1 // This file is part of OpenCV project.
2 // It is subject to the license terms in the LICENSE file found in the top-level directory
3 // of this distribution and at http://opencv.org/license.html.
5 // Copyright (C) 2018, Intel Corporation, all rights reserved.
6 // Third party copyrights are property of their respective owners.
10 #include "tf_graph_simplifier.hpp"
12 namespace cv { namespace dnn {
13 CV__DNN_EXPERIMENTAL_NS_BEGIN
15 using ::google::protobuf::RepeatedField;
16 using ::google::protobuf::MapPair;
18 class Subgraph // Interface to match and replace TensorFlow subgraphs.
21 // Add a node to be matched in the origin graph. Specify ids of nodes that
22 // are expected to be inputs. Returns id of a newly added node.
23 // TODO: Replace inputs to std::vector<int> in C++11
24 int addNodeToMatch(const std::string& op, int input_0 = -1, int input_1 = -1,
25 int input_2 = -1, int input_3 = -1)
27 int nodeInputs[] = {input_0, input_1, input_2, input_3};
29 for (int i = 0; i < 4; ++i)
31 numInputs += (int)(nodeInputs[i] != -1);
33 return addNodeToMatch(op, std::vector<int>(&nodeInputs[0], &nodeInputs[0] + numInputs));
36 int addNodeToMatch(const std::string& op, const std::vector<int>& inputs_)
38 for (int i = 0; i < inputs_.size(); ++i)
40 CV_Assert(inputs_[i] < (int)nodes.size());
43 inputs.push_back(inputs_);
44 return nodes.size() - 1;
47 // Specify resulting node. All the matched nodes in subgraph excluding
48 // input nodes will be fused into this single node.
49 // TODO: Replace inputs to std::vector<int> in C++11
50 void setFusedNode(const std::string& op, int input_0 = -1, int input_1 = -1,
51 int input_2 = -1, int input_3 = -1, int input_4 = -1,
54 int nodeInputs[] = {input_0, input_1, input_2, input_3, input_4, input_5};
56 for (int i = 0; i < 6; ++i)
58 CV_Assert(nodeInputs[i] < (int)nodes.size());
59 numInputs += (int)(nodeInputs[i] != -1);
61 setFusedNode(op, std::vector<int>(&nodeInputs[0], &nodeInputs[0] + numInputs));
64 void setFusedNode(const std::string& op, const std::vector<int>& inputs_)
66 fusedNodeInputs = inputs_;
69 for (int i = 0; i < nodes.size(); ++i)
71 if (std::find(fusedNodeInputs.begin(), fusedNodeInputs.end(), i) == fusedNodeInputs.end() &&
73 nodesToFuse.push_back(i);
77 static const tensorflow::NodeDef& getInputNode(const tensorflow::GraphDef& net,
78 const tensorflow::NodeDef& node,
81 CV_Assert(inpId < node.input_size());
82 std::string name = node.input(inpId);
83 const int numNodes = net.node_size();
84 for (int i = 0; i < numNodes; ++i)
86 if (net.node(i).name() == name)
89 CV_Error(Error::StsParseError, "Input node with name " + name + " not found");
90 return net.node(0); // just return something
93 // Match TensorFlow subgraph starting from <nodeId> with a set of nodes to be fused.
94 // Const nodes are skipped during matching. Returns true if nodes are matched and can be fused.
95 virtual bool match(const tensorflow::GraphDef& net, int nodeId, std::vector<int>& matchedNodesIds)
97 matchedNodesIds.clear();
98 matchedNodesIds.reserve(nodesToFuse.size());
100 int numNodes = net.node_size();
101 for (int i = 0; i < nodesToFuse.size(); ++i)
103 while (nodeId < numNodes && net.node(nodeId).op() == "Const")
107 if (nodeId > numNodes - 1)
110 const tensorflow::NodeDef& node = net.node(nodeId);
112 if (node.op() != nodes[nodesToFuse[i]])
115 std::vector<int>& inputNodes = inputs[nodesToFuse[i]];
116 if (inputNodes.size() != node.input_size())
118 for (int j = 0; j < inputNodes.size(); ++j)
120 if (nodes[inputNodes[j]].empty()) // Unknown input node type.
122 const tensorflow::NodeDef& inpNode = getInputNode(net, node, j);
123 if (inpNode.op() != nodes[inputNodes[j]])
127 matchedNodesIds.push_back(nodeId);
133 // Fuse matched subgraph.
134 void replace(tensorflow::GraphDef& net, const std::vector<int>& matchedNodesIds)
136 // Extract names of input nodes.
137 std::vector<std::string> inputsNames(fusedNodeInputs.size());
138 for (int i = 0; i < fusedNodeInputs.size(); ++i)
141 // Find input node name looking at inputs of fused nodes.
142 for (int j = 0; j < matchedNodesIds.size() && inpName.empty(); ++j)
144 const tensorflow::NodeDef &node = net.node(matchedNodesIds[j]);
145 std::vector<int>& inpIndices = inputs[nodesToFuse[j]];
147 CV_Assert(node.input_size() == inpIndices.size());
148 for (int k = 0; k < inpIndices.size(); ++k)
150 if (inpIndices[k] == fusedNodeInputs[i])
152 inpName = node.input(k);
157 CV_Assert(!inpName.empty());
158 inputsNames[i] = inpName;
161 // Remove matched nodes except the last one. Indices in ascending order are expected.
162 tensorflow::NodeDef* node = net.mutable_node(matchedNodesIds.back());
163 for (int i = matchedNodesIds.size() - 2; i >= 0; --i)
164 net.mutable_node()->DeleteSubrange(matchedNodesIds[i], 1);
166 // Modify the last node to be a fused one.
167 node->set_op(fusedNodeOp);
169 for (int i = 0; i < inputsNames.size(); ++i)
171 node->add_input(inputsNames[i]);
174 std::vector<tensorflow::NodeDef*> inputNodes(inputsNames.size());
175 for (int i = 0; i < inputsNames.size(); ++i)
177 inputNodes[i] = (tensorflow::NodeDef*)&getInputNode(net, *node, i);
179 finalize(net, node, inputNodes);
182 virtual void finalize(tensorflow::GraphDef&, tensorflow::NodeDef*,
183 std::vector<tensorflow::NodeDef*>&) {}
186 std::vector<std::string> nodes; // Nodes to be matched in the origin graph.
187 std::vector<std::vector<int> > inputs; // Connections of an every node to it's inputs.
189 std::string fusedNodeOp; // Operation name of resulting fused node.
190 std::vector<int> nodesToFuse; // Set of nodes to be fused.
191 std::vector<int> fusedNodeInputs; // Inputs of fused node.
194 class BatchNormSubgraph : public Subgraph
199 int input = addNodeToMatch("");
200 int epsilon = addNodeToMatch("Const");
201 int moving_variance = addNodeToMatch("Const");
202 int moving_mean = addNodeToMatch("Const");
203 int beta = addNodeToMatch("Const");
204 int gamma = addNodeToMatch("Const");
205 int add = addNodeToMatch("Add", moving_variance, epsilon);
206 int rsqrt = addNodeToMatch("Rsqrt", add);
207 int mul = addNodeToMatch("Mul", rsqrt, gamma);
208 int mul_1 = addNodeToMatch("Mul", input, mul);
209 int mul_2 = addNodeToMatch("Mul", moving_mean, mul);
210 int sub = addNodeToMatch("Sub", beta, mul_2);
211 addNodeToMatch("Add", mul_1, sub);
213 setFusedNode("FusedBatchNorm", input, gamma, beta, moving_mean, moving_variance, epsilon);
216 virtual void finalize(tensorflow::GraphDef&, tensorflow::NodeDef* fusedNode,
217 std::vector<tensorflow::NodeDef*>& inputNodes) CV_OVERRIDE
219 Mat epsMat = getTensorContent(inputNodes.back()->attr().at("value").tensor());
220 CV_Assert(epsMat.total() == 1, epsMat.type() == CV_32FC1);
222 fusedNode->mutable_input()->RemoveLast();
223 fusedNode->clear_attr();
224 tensorflow::AttrValue epsilon;
225 epsilon.set_f(epsMat.at<float>(0));
226 fusedNode->mutable_attr()->insert(MapPair<std::string, tensorflow::AttrValue>("epsilon", epsilon));
230 class BatchNormNoGammaSubgraph : public Subgraph
233 BatchNormNoGammaSubgraph()
235 int input = addNodeToMatch("");
236 int epsilon = addNodeToMatch("Const");
237 int moving_variance = addNodeToMatch("Const");
238 int moving_mean = addNodeToMatch("Const");
239 int beta = addNodeToMatch("Const");
240 int add = addNodeToMatch("Add", moving_variance, epsilon);
241 int rsqrt = addNodeToMatch("Rsqrt", add);
242 int mul = addNodeToMatch("Mul", input, rsqrt);
243 int mul_1 = addNodeToMatch("Mul", moving_mean, rsqrt);
244 int sub = addNodeToMatch("Sub", beta, mul_1);
245 addNodeToMatch("Add", mul, sub);
247 // There is a fake reference to beta that will be replaced to a new gamma tensor.
248 setFusedNode("FusedBatchNorm", input, beta, beta, moving_mean, moving_variance, epsilon);
251 virtual void finalize(tensorflow::GraphDef& net, tensorflow::NodeDef* fusedNode,
252 std::vector<tensorflow::NodeDef*>& inputNodes) CV_OVERRIDE
254 Mat epsMat = getTensorContent(inputNodes.back()->attr().at("value").tensor());
255 CV_Assert(epsMat.total() == 1, epsMat.type() == CV_32FC1);
257 fusedNode->mutable_input()->RemoveLast();
258 fusedNode->clear_attr();
259 tensorflow::AttrValue epsilon;
260 epsilon.set_f(epsMat.at<float>(0));
261 fusedNode->mutable_attr()->insert(MapPair<std::string, tensorflow::AttrValue>("epsilon", epsilon));
263 tensorflow::NodeDef* gamma = net.add_node();
264 gamma->set_op("Const");
265 gamma->set_name(fusedNode->name() + "/gamma");
266 // Just put a single value to recognize this node as Const.
267 gamma->mutable_attr()->insert(MapPair<std::string, tensorflow::AttrValue>("value", epsilon));
268 fusedNode->set_input(1, gamma->name());
272 // tf.contrib.layers.flatten
273 class FlattenSubgraph : public Subgraph
278 int input = addNodeToMatch("");
279 int shape = addNodeToMatch("Const");
280 int stack = addNodeToMatch("Const");
281 int stack_1 = addNodeToMatch("Const");
282 int stack_2 = addNodeToMatch("Const");
283 int strided_slice = addNodeToMatch("StridedSlice", shape, stack, stack_1, stack_2);
284 int shape_pack = addNodeToMatch("Const");
285 int pack = addNodeToMatch("Pack", strided_slice, shape_pack);
286 addNodeToMatch("Reshape", input, pack);
288 setFusedNode("Flatten", input);
292 // tf.contrib.layers.flatten in case of unknown batch size
293 class FlattenShapeSubgraph : public Subgraph
296 FlattenShapeSubgraph()
298 int input = addNodeToMatch("");
299 int shape = addNodeToMatch("Shape", input);
300 int stack = addNodeToMatch("Const");
301 int stack_1 = addNodeToMatch("Const");
302 int stack_2 = addNodeToMatch("Const");
303 int strided_slice = addNodeToMatch("StridedSlice", shape, stack, stack_1, stack_2);
304 int shape_pack = addNodeToMatch("Const");
305 int pack = addNodeToMatch("Pack", strided_slice, shape_pack);
306 addNodeToMatch("Reshape", input, pack);
308 setFusedNode("Flatten", input);
313 class SoftMaxKerasSubgraph : public Subgraph
316 SoftMaxKerasSubgraph()
318 int input = addNodeToMatch("");
319 int maxReductionIndices = addNodeToMatch("Const");
320 int smMax = addNodeToMatch("Max", input, maxReductionIndices);
321 int smSub = addNodeToMatch("Sub", input, smMax);
322 int smExp = addNodeToMatch("Exp", smSub);
323 int sumReductionIndices = addNodeToMatch("Const");
324 int smSum = addNodeToMatch("Sum", smExp, sumReductionIndices);
325 addNodeToMatch("RealDiv", smExp, smSum);
327 setFusedNode("Softmax", input);
331 class ReLU6KerasSubgraph : public Subgraph
336 int input = addNodeToMatch("");
337 int relu = addNodeToMatch("Relu", input);
338 int maxValue = addNodeToMatch("Const");
339 int clipValue = addNodeToMatch("Const");
340 int minimum = addNodeToMatch("Minimum", relu, maxValue);
341 addNodeToMatch("Maximum", minimum, clipValue);
343 setFusedNode("Relu6", input);
346 virtual bool match(const tensorflow::GraphDef& net, int nodeId, std::vector<int>& matchedNodesIds) CV_OVERRIDE
348 if (!Subgraph::match(net, nodeId, matchedNodesIds))
350 Mat maxValue = getTensorContent(net.node(nodeId + 1).attr().at("value").tensor());
351 return maxValue.type() == CV_32FC1 && maxValue.total() == 1 && maxValue.at<float>(0) == 6;
355 // Keras' reshape stores output shape in separate Const nodes by one value.
356 // Need to merge them into a single Const node.
357 class ReshapeKerasSubgraph : public Subgraph
360 ReshapeKerasSubgraph(int _numOutDims) : numOutDims(_numOutDims)
362 int input = addNodeToMatch("");
363 int shape = addNodeToMatch("Shape", input);
364 int stack = addNodeToMatch("Const");
365 int stack_1 = addNodeToMatch("Const");
366 int stack_2 = addNodeToMatch("Const");
367 int strided_slice = addNodeToMatch("StridedSlice", shape, stack, stack_1, stack_2);
369 std::vector<int> ids(1 + numOutDims);
370 ids[0] = strided_slice;
371 for (int i = 0; i < numOutDims; ++i)
372 ids[1 + i] = addNodeToMatch("Const");
373 int pack = addNodeToMatch("Pack", ids);
374 addNodeToMatch("Reshape", input, pack);
377 setFusedNode("Reshape", ids);
380 virtual void finalize(tensorflow::GraphDef&, tensorflow::NodeDef* fusedNode,
381 std::vector<tensorflow::NodeDef*>& inputNodes) CV_OVERRIDE
383 std::vector<int> shape(numOutDims + 1); // batch size in Keras is implicit.
385 for (int i = 0; i < numOutDims; ++i)
387 shape[1 + i] = inputNodes[1 + i]->attr().at("value").tensor().int_val(0);
389 tensorflow::TensorProto* shapeTensor = inputNodes[1]->mutable_attr()->at("value").mutable_tensor();
390 fusedNode->mutable_input()->DeleteSubrange(2, numOutDims - 1);
392 shapeTensor->clear_int_val();
393 for (int i = 0; i < shape.size(); ++i)
395 shapeTensor->add_int_val(shape[i]);
403 void simplifySubgraphs(tensorflow::GraphDef& net)
405 std::vector<Ptr<Subgraph> > subgraphs;
406 subgraphs.push_back(Ptr<Subgraph>(new BatchNormSubgraph()));
407 subgraphs.push_back(Ptr<Subgraph>(new BatchNormNoGammaSubgraph()));
408 subgraphs.push_back(Ptr<Subgraph>(new FlattenSubgraph()));
409 subgraphs.push_back(Ptr<Subgraph>(new FlattenShapeSubgraph()));
410 subgraphs.push_back(Ptr<Subgraph>(new SoftMaxKerasSubgraph()));
411 subgraphs.push_back(Ptr<Subgraph>(new ReLU6KerasSubgraph()));
412 subgraphs.push_back(Ptr<Subgraph>(new ReshapeKerasSubgraph(3)));
414 int numNodes = net.node_size();
415 std::vector<int> matchedNodesIds;
416 for (int i = 0; i < numNodes; ++i)
418 for (int j = 0; j < subgraphs.size(); ++j)
420 if (subgraphs[j]->match(net, i, matchedNodesIds))
422 subgraphs[j]->replace(net, matchedNodesIds);
423 numNodes -= matchedNodesIds.size() - 1; // #matchedNodes removed and one added.
430 void RemoveIdentityOps(tensorflow::GraphDef& net)
432 typedef std::map<String, String> IdentityOpsMap;
433 IdentityOpsMap identity_ops;
435 std::vector<int> identity_ops_idx;
437 int layersCount = net.node_size();
438 for (int li = 0; li < layersCount; li++)
440 const tensorflow::NodeDef &layer = net.node(li);
441 String type = layer.op();
443 if (type == "Identity" || type == "Dropout") {
444 identity_ops_idx.push_back(li);
445 identity_ops[layer.name()] = layer.input(0);
449 for (int li = 0; li < layersCount; li++)
451 tensorflow::NodeDef* layer = net.mutable_node(li);
452 for (int input_id = 0; input_id < layer->input_size(); input_id++) {
453 String input_op_name = layer->input(input_id);
454 IdentityOpsMap::iterator it = identity_ops.find(input_op_name);
456 if (it != identity_ops.end()) {
457 layer->set_input(input_id, it->second);
462 std::sort(identity_ops_idx.begin(), identity_ops_idx.end());
464 int removed_nodes = 0;
465 for(size_t i = 0; i < identity_ops_idx.size(); i++) {
466 int start_id = identity_ops_idx[i] - removed_nodes;
467 net.mutable_node()->DeleteSubrange(start_id, 1);
472 Mat getTensorContent(const tensorflow::TensorProto &tensor)
474 std::string content = tensor.tensor_content();
475 switch (tensor.dtype())
477 case tensorflow::DT_FLOAT:
479 if (!content.empty())
480 return Mat(1, content.size() / sizeof(float), CV_32FC1, (void*)content.c_str()).clone();
483 const RepeatedField<float>& field = tensor.float_val();
484 CV_Assert(!field.empty());
485 return Mat(1, field.size(), CV_32FC1, (void*)field.data()).clone();
488 case tensorflow::DT_DOUBLE:
490 if (!content.empty())
491 return Mat(1, content.size() / sizeof(double), CV_64FC1, (void*)content.c_str()).clone();
494 const RepeatedField<double>& field = tensor.double_val();
495 CV_Assert(!field.empty());
496 return Mat(1, field.size(), CV_64FC1, (void*)field.data()).clone();
499 case tensorflow::DT_INT32:
501 if (!content.empty())
502 return Mat(1, content.size() / sizeof(int32_t), CV_32SC1, (void*)content.c_str()).clone();
505 const RepeatedField<int32_t>& field = tensor.int_val();
506 CV_Assert(!field.empty());
507 return Mat(1, field.size(), CV_32SC1, (void*)field.data()).clone();
510 case tensorflow::DT_HALF:
513 if (!content.empty())
515 static const int kHalfSize = 2;
516 halfs = Mat(1, content.size() / kHalfSize, CV_16UC1, (void*)content.c_str());
520 const RepeatedField<int32_t>& field = tensor.half_val();
521 CV_Assert(!field.empty());
522 Mat ints(1, field.size(), CV_32SC1, (void*)field.data());
523 ints.convertTo(halfs, CV_16UC1);
525 // Reinterpret as a signed shorts just for a convertFp16 call.
526 Mat halfsSigned(halfs.size(), CV_16SC1, halfs.data);
527 Mat floats(halfs.size(), CV_32FC1);
528 convertFp16(halfsSigned, floats);
531 case tensorflow::DT_QUINT8:
533 CV_Assert(!content.empty());
534 return Mat(1, content.size(), CV_8UC1, (void*)content.c_str()).clone();
537 CV_Error(Error::StsError, "Tensor's data type is not supported");
543 CV__DNN_EXPERIMENTAL_NS_END
544 }} // namespace dnn, namespace cv
546 #endif // HAVE_PROTOBUF