Add a section of how to link IE with CMake project (#99)
[platform/upstream/dldt.git] / model-optimizer / mo / middle / passes / shared_weights_duplication.py
1 """
2  Copyright (c) 2018 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 networkx as nx
18 import numpy as np
19
20 from mo.graph.graph import Node
21 from mo.ops.op import Op
22 from mo.utils.error import Error
23
24
25 def duplicate_shared_weights(graph: nx.MultiDiGraph):
26     """
27     This function finds all const data nodes that have more that one consumer and then duplicate them
28     """
29     data_nodes = [Node(graph, id) for id in graph.nodes() if Node(graph, id).soft_get('kind') == 'data']
30     for node in data_nodes:
31         # Check that node has const values and more than one consumer
32         if len(node.out_nodes()) > 1 and node.value is not None:
33             # Here we delete all edges between base node and it's consumers (except first), and then duplicate this
34             # node to connect with other consumers
35             while len(node.out_nodes()) > 1:
36                 out_node = node.out_node(1)
37
38                 if len(graph.get_edge_data(node.id, out_node.id)) != 1:
39                     raise Error('There is more than one edge from {} node to {} node.'.format(node.id, out_node.id))
40                 e_attrs = graph.get_edge_data(node.id, out_node.id)[0]
41
42                 graph.remove_edge(node.id, out_node.id)
43                 data = Op.create_input_data_node(graph, "Copy_{}".format(node.id), np.array(node.value), graph.node[node.id])
44
45                 graph.add_edges_from([(data.id, out_node.id, e_attrs)])