otbTensorflowGraphOperations.cxx 6.41 KB
Newer Older
remi cresson's avatar
remi cresson committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*=========================================================================

  Copyright (c) Remi Cresson (IRSTEA). All rights reserved.


     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbTensorflowGraphOperations.h"

namespace otb {
namespace tf {

//
// Restore a model from a path
//
void RestoreModel(const std::string path, tensorflow::SavedModelBundle & bundle)
{
  tensorflow::Tensor checkpointPathTensor(tensorflow::DT_STRING, tensorflow::TensorShape());
  checkpointPathTensor.scalar<std::string>()() = path;
  std::vector<std::pair<std::string, tensorflow::Tensor>> feed_dict =
  {{bundle.meta_graph_def.saver_def().filename_tensor_name(), checkpointPathTensor}};
  auto status = bundle.session->Run(feed_dict, {}, {bundle.meta_graph_def.saver_def().restore_op_name()}, nullptr);
  if (!status.ok())
    {
    itkGenericExceptionMacro("Can't restore the input model: " << status.ToString() );
    }
}

//
// Restore a model from a path
//
void SaveModel(const std::string path, tensorflow::SavedModelBundle & bundle)
{
  tensorflow::Tensor checkpointPathTensor(tensorflow::DT_STRING, tensorflow::TensorShape());
  checkpointPathTensor.scalar<std::string>()() = path;
  std::vector<std::pair<std::string, tensorflow::Tensor>> feed_dict =
  {{bundle.meta_graph_def.saver_def().filename_tensor_name(), checkpointPathTensor}};
  auto status = bundle.session->Run(feed_dict, {}, {bundle.meta_graph_def.saver_def().save_tensor_name()}, nullptr);
  if (!status.ok())
    {
    itkGenericExceptionMacro("Can't restore the input model: " << status.ToString() );
    }
}

//
// Load a session and a graph from a folder
//
void LoadModel(const std::string path, tensorflow::SavedModelBundle & bundle)
{

  tensorflow::RunOptions runoptions;
  runoptions.set_trace_level(tensorflow::RunOptions_TraceLevel_FULL_TRACE);
  auto status = tensorflow::LoadSavedModel(tensorflow::SessionOptions(), runoptions,
      path, {tensorflow::kSavedModelTagServe}, &bundle);
  if (!status.ok())
    {
    itkGenericExceptionMacro("Can't load the input model: " << status.ToString() );
    }

}

//
// Load a graph from a .meta file
//
tensorflow::GraphDef LoadGraph(std::string filename)
{
  tensorflow::MetaGraphDef meta_graph_def;
  auto status = tensorflow::ReadBinaryProto(tensorflow::Env::Default(), filename, &meta_graph_def);
  if (!status.ok())
    {
    itkGenericExceptionMacro("Can't load the input model: " << status.ToString() );
    }

  return meta_graph_def.graph_def();
}

//
// Get the following attributes of the specified tensors (by name) of a graph:
// - shape
// - datatype
// Here we assume that the node's output is a tensor
//
void GetTensorAttributes(const tensorflow::GraphDef & graph, std::vector<std::string> & tensorsNames,
    std::vector<tensorflow::TensorShapeProto> & shapes, std::vector<tensorflow::DataType> & dataTypes)
{
  // Allocation
  shapes.clear();
  shapes.reserve(tensorsNames.size());
  dataTypes.clear();
  dataTypes.reserve(tensorsNames.size());

  // Get infos
  for (std::vector<std::string>::iterator nameIt = tensorsNames.begin();
      nameIt != tensorsNames.end(); ++nameIt)
  {
    bool found = false;
    for (int i = 0 ; i < graph.node_size() ; i++)
    {
      tensorflow::NodeDef node = graph.node(i);


      if (node.name().compare((*nameIt)) == 0)
      {
        found = true;
Cresson Remi's avatar
Cresson Remi committed
108
109
110

        // Set default to DT_FLOAT
        tensorflow::DataType ts_dt = tensorflow::DT_FLOAT;
remi cresson's avatar
remi cresson committed
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192

        // Default (input?) tensor type
        auto test_is_output = node.attr().find("T");
        if (test_is_output != node.attr().end())
        {
          ts_dt = node.attr().at("T").type();
        }
        auto test_has_dtype = node.attr().find("dtype");
        if (test_has_dtype != node.attr().end())
        {
          ts_dt = node.attr().at("dtype").type();
        }
        auto test_output_type = node.attr().find("output_type");
        if (test_output_type != node.attr().end())
        {
          // if there is an output type, we take it instead of the
          // datatype of the input tensor
          ts_dt = node.attr().at("output_type").type();
        }
        dataTypes.push_back(ts_dt);

        // Get the tensor's shape
        // Here we assure it's a tensor, with 1 shape
        tensorflow::TensorShapeProto ts_shp = node.attr().at("_output_shapes").list().shape(0);
        shapes.push_back(ts_shp);
      }
    }

    if (!found)
    {
      itkGenericExceptionMacro("Tensor name \"" << (*nameIt) << "\" not found" );
    }

  }

}

//
// Print a lot of stuff about the specified nodes of the graph
//
void PrintNodeAttributes(const tensorflow::GraphDef & graph, std::vector<std::string> & nodesNames)
{
  std::cout << "Go through graph:" << std::endl;
  std::cout << "#\tname" << std::endl;
  for (int i = 0 ; i < graph.node_size() ; i++)
  {
    tensorflow::NodeDef node = graph.node(i);
    std::cout << i << "\t" << node.name() << std::endl;

    for (std::vector<std::string>::iterator nameIt = nodesNames.begin();
        nameIt != nodesNames.end(); ++nameIt)
    {
      if (node.name().compare((*nameIt)) == 0)
      {
        std::cout << "Node " << i << " : " << std::endl;
        std::cout << "\tName: " << node.name() << std::endl;
        std::cout << "\tinput_size() : " << node.input_size() << std::endl;
        std::cout << "\tPrintDebugString --------------------------------";
        std::cout << std::endl;
        node.PrintDebugString();
        std::cout << "\t-------------------------------------------------" << std::endl;

        // display all attributes of the node
        std::cout << "\tAttributes of the node: " << std::endl;
        for (auto attr = node.attr().begin() ; attr != node.attr().end() ; attr++)
        {
          std::cout << "\t\tKey :" << attr->first << std::endl;
          std::cout << "\t\tValue.value_case() :" << attr->second.value_case() << std::endl;
          std::cout << "\t\tPrintDebugString --------------------------------";
          std::cout << std::endl;
          attr->second.PrintDebugString();
          std::cout << "\t\t-------------------------------------------------" << std::endl;
          std::cout << std::endl;
        } // next attribute
      } // node name match
    } // next node name
  } // next node of the graph

}

} // end namespace tf
} // end namespace otb