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