Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / middle / ChangePlaceholderTypes.py
1 """
2  Copyright (c) 2019 Intel Corporation
3
4  Licensed under the Apache License, Version 2.0 (the "License");
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7
8       http://www.apache.org/licenses/LICENSE-2.0
9
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15 """
16
17 import logging as log
18
19 from mo.graph.graph import Graph, Node
20 from mo.middle.passes.fusing.helpers import get_next_operation
21 from mo.middle.replacement import MiddleReplacementPattern
22 from mo.utils.error import Error
23 from mo.utils.utils import refer_to_faq_msg
24
25
26 class ChangePlaceholderTypes(MiddleReplacementPattern):
27     enabled = True
28     graph_condition = [lambda graph: graph.graph['fw'] == 'tf']
29     force_clean_up = True
30
31     def run_after(self):
32         return []
33
34     def run_before(self):
35         from extensions.middle.ScaleInput import ScaleInput
36         return [ScaleInput]
37
38     @staticmethod
39     def change_node_type(node: Node, new_type: type):
40         node.graph.node[node.id]['pb'].attr['dtype'].type = new_type
41
42     @staticmethod
43     def is_node_casts_to_float(node: Node):
44         from tensorflow.core.framework import types_pb2 as tf_types  # pylint: disable=no-name-in-module
45         attrs = node.graph.node[node.id]
46         return 'pb' in attrs and attrs['pb'].op == 'Cast' and attrs['pb'].attr['DstT'].type == tf_types.DT_FLOAT
47
48     @staticmethod
49     def remove_node_preserving_edges(pl_node: Node, nodes: list):
50         graph = pl_node.graph
51         pl_node_data = pl_node.out_node()
52
53         # Disconnect Placeholder data node from Cast nodes
54         for out_node in pl_node.out_node().out_nodes():
55             graph.remove_edge(pl_node_data.id, out_node.id)
56
57         # Move edges from Cast data nodes to Placeholder data node
58         for cast_node in nodes:
59             # it is necessary to create a list from the result of function "graph.out_edges()" because we modify
60             # the graph during iteration over the list. networkx version 2.1 raises error without creating a list
61             for u, v, d in list(graph.out_edges(cast_node.out_node().id, data=True)):
62                 graph.remove_edge(u, v)
63                 graph.add_edges_from([(pl_node_data.id, v, d)])
64
65     @staticmethod
66     def is_node_gather(node: Node):
67         attrs = node.graph.node[node.id]
68         return 'pb' in attrs and attrs['pb'].op == 'GatherV2' and attrs['precision'] == 'FP32'
69
70     def find_and_replace_pattern(self, graph: Graph):
71         from tensorflow.core.framework import types_pb2 as tf_types  # pylint: disable=no-name-in-module
72         for node_name, node_attrs in list(graph.nodes(data=True)):
73             node = Node(graph, node_name)
74             pb = node_attrs.get('pb')
75             if pb is not None and pb.op == 'Placeholder' and pb.attr['dtype'].type != tf_types.DT_FLOAT:
76                 log.info('Placeholder "{}" has type that is different from DT_FLOAT'.format(node_name))
77                 next_ops = get_next_operation(node)
78                 # check that all output nodes are nodes of type 'ToFloat'
79                 if all([ChangePlaceholderTypes.is_node_casts_to_float(op) and
80                         len(op.in_nodes()) == 1 for op in next_ops]):
81                     ChangePlaceholderTypes.change_node_type(node, tf_types.DT_FLOAT)
82                     ChangePlaceholderTypes.remove_node_preserving_edges(node, next_ops)  # remove 'Cast' nodes
83
84                 elif all([ChangePlaceholderTypes.is_node_gather(op) for op in next_ops] for op in next_ops):
85                     ChangePlaceholderTypes.change_node_type(node, tf_types.DT_FLOAT)
86
87                 else:
88                     raise Error(
89                         ('Cannot convert type of placeholder "{}" because not all of its outputs are "Cast" to float '
90                          'operations: {}. ' +
91                          refer_to_faq_msg(49)),
92                         node.soft_get('name'),
93                         [op.soft_get('name') for op in next_ops]
94                     )