Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / back / CreateConstNodes.py
1 """
2  Copyright (c) 2018-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 from mo.back.replacement import BackReplacementPattern
17 from mo.front.extractor import update_ie_fields
18 from mo.graph.graph import *
19
20
21 class CreateConstNodesReplacement(BackReplacementPattern):
22     enabled = False
23
24     @staticmethod
25     def pattern():
26         return dict(
27             nodes=[
28                 ('data', dict(kind='data'))
29             ],
30             edges=[]
31         )
32
33     @staticmethod
34     def _check_bin_attrs(node):
35         """Check that at least one output edge from node without 'bin' attribute."""
36         out_edges = node.out_edges()
37         bin_in_out_ports = ['bin' in edge for edge in out_edges]
38         out_node = [node.has('op') and node.op == 'OpOutput' for node in node.out_nodes()]
39         return np.any(out_node) or not np.all(bin_in_out_ports)
40
41     @staticmethod
42     def _check_that_node_from_body(node):
43         """Check that all output edges from node have 'internal_port_id'
44         (that shows that this node is from TI body)"""
45         n_ports = len(node.out_edges())
46         internal_port_in_out_ports = ['internal_port_id' in edge for edge in node.out_edges()]
47         return np.all(internal_port_in_out_ports) and n_ports
48
49     def replace_pattern(self, graph: Graph, match: dict):
50         """
51             Adds layers with type 'Const' that produce blob from 'bin' file. The pass finds data nodes with one output which
52             doesn't have edge with 'bin' attribute (or with two outputs and at least one output havent 'bin' attr)
53             and generate Const op node before the node and data node before the Const node. The data node before 'Const'
54             node is needed because the op node dumps input tensors to bin file.
55         """
56         node = match['data']
57         if len(node.in_nodes()) > 0:
58             return
59
60         if self._check_bin_attrs(node):
61             if node.has_valid('value'):
62                 const_node_name = graph.unique_id(node.id + '_const')
63                 log.debug("Added Const node '{}'".format(const_node_name))
64                 graph.add_node(const_node_name, name=const_node_name, type='Const', kind='op', op='Const',
65                                precision="FP32")
66                 update_ie_fields(node.graph.node[const_node_name])
67                 graph.add_edges_from([(const_node_name, node.id, {'out': 0})])
68
69                 copy_data_node_name = graph.unique_id(node.id + '_copy_')
70                 graph.add_node(copy_data_node_name, kind='data', precision="FP32", shape=np.array(node.shape),
71                                value=np.array(node.value))
72
73                 if node.has_valid('force_precision'):
74                     Node(graph, copy_data_node_name)['force_precision'] = node.force_precision
75                     Node(graph, const_node_name)['force_precision'] = node.force_precision
76                 graph.add_edges_from([(copy_data_node_name, const_node_name, {'in': 0, 'bin': 'custom'})])
77             elif not self._check_that_node_from_body(node):
78                 log.debug('node = {}'.format(node.graph.node[node.id]))
79                 raise Error(
80                     'Discovered data node without inputs and value, node.name = {}, consumer.name = {}. ' +
81                     refer_to_faq_msg(23),
82                     node.soft_get('name'),
83                     node.out_node().soft_get('name') if len(node.out_nodes()) else "<no consumer>"
84                 )