2 Copyright (c) 2018-2019 Intel Corporation
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
8 http://www.apache.org/licenses/LICENSE-2.0
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.
21 from mo.front.common.partial_infer.utils import int64_array
22 from mo.graph.graph import Node
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]
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
35 if any([s is None for s in shapes]):
40 for id, s in enumerate(shapes):
41 if max_dims is None or len(s) > max_dims:
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)):
48 if len(shape) != max_dims and len(shape) > 0 and axis is not None:
51 # Extend shape with 1's
52 for cnt in range(axis + len(shape), max_dims):
53 new_shape = np.append(new_shape, 1)
55 shapes[id] = new_shape
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]
61 nx.set_edge_attributes(G=node.graph,
62 values={(inputs[id].id, node.id, 0): new_shape},
65 # Reshape value to correctly calculate output shape
66 if values[id] is not None:
67 values[id] = np.reshape(values[id], new_shape)
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])
79 output_shape[ei] = maxd
82 node.out_node().shape = output_shape
84 if op is None or any([v is None for v in values]):
87 node.out_node().value = op(*values, **kwargs)