7cfdb1570700416a8edaf2d22931bbba4cf091bb
[platform/upstream/dldt.git] / model-optimizer / mo / front / common / partial_infer / eltwise.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
17 import networkx as nx
18 import numpy as np
19
20 from mo.front.common.partial_infer.utils import int64_array
21 from mo.graph.graph import Node
22
23
24 def eltwise_infer(node, op=None, **kwargs):
25     raw_inputs = [(inp, attr) for inp, attr in node.get_sorted_inputs()
26                   if 'control_flow_edge' not in attr or not attr['control_flow_edge']]
27     inputs = [Node(node.graph, inp) for inp, attr in raw_inputs]
28     shapes = [node.graph.node[inp]['shape'] for inp, attr in raw_inputs]
29     values = [node.graph.node[inp]['value'] for inp, attr in raw_inputs]
30
31     # infer output shape based on input shapes without op involvement
32     # based on repeated application of rules https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html
33
34     if any([s is None for s in shapes]):
35         # nothing is known
36         return
37
38     max_dims = None
39     for id, s in enumerate(shapes):
40         if max_dims is None or len(s) > max_dims:
41             max_dims = len(s)
42
43     # Make all input shapes of the same size by adding 1's
44     axis = node.axis if node.has_valid('axis') else None
45     for id, item in enumerate(zip(shapes, values)):
46         shape, value = item
47         if len(shape) != max_dims and len(shape) > 0 and axis is not None:
48             new_shape = shape
49
50             # Extend shape with 1's
51             for cnt in range(axis + len(shape), max_dims):
52                 new_shape = np.append(new_shape, 1)
53
54             shapes[id] = new_shape
55
56             # Save shape for further transformation that applies this shapes for input nodes
57             # We set new_shape attribute on edge for given input node
58             edge_attrs = node.graph.get_edge_data(inputs[id].id, node.id)[0]
59
60             nx.set_edge_attributes(G=node.graph,
61                                    values={(inputs[id].id, node.id, 0): new_shape},
62                                    name='new_shape')
63
64             # Reshape value to correctly calculate output shape
65             if values[id] is not None:
66                 values[id] = np.reshape(values[id], new_shape)
67
68     extended_shapes = int64_array([np.concatenate((np.ones(max_dims - len(s), dtype=np.int64), s)) for s in shapes])
69     # ugly but clear solution
70     output_shape = extended_shapes[0]
71     for si in range(1, len(extended_shapes)):
72         for ei in range(max_dims):
73             mind = min(output_shape[ei], extended_shapes[si][ei])
74             maxd = max(output_shape[ei], extended_shapes[si][ei])
75             if mind == -1:
76                 output_shape[ei] = -1
77             elif mind == 1:
78                 output_shape[ei] = maxd
79             elif mind != maxd:
80                 output_shape[ei] = -1
81     node.out_node().shape = output_shape
82
83     if op is None or any([v is None for v in values]):
84         return
85
86     if len(values) <= 2:
87         node.out_node().value = op(*values, **kwargs)
88     else:
89         node.out_node().value = values[0]
90         for i in range(len(values) - 1):
91             node.out_node().value = op(node.out_node().value, values[i + 1])
92
93
94 def bias_add_infer(node, op):
95     if node.in_port(0).data.get_value() is not None and node.in_port(1).data.get_value() is not None and op is not None:
96         node.out_port(0).data.set_value(op(node.in_port(0).data.get_value(), node.in_port(1).data.get_value()))
97     else:
98         node.out_port(0).data.set_shape(node.in_port(0).data.get_shape())