Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / mo / ops / reduce.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 logging as log
18
19 import numpy as np
20
21 from mo.front.common.partial_infer.utils import int64_array
22 from mo.graph.graph import Node, Graph
23 from mo.ops.op import Op
24 from mo.utils.error import Error
25
26
27 class Reduce(Op):
28     enabled = False
29
30     reduce_method_map = {
31         'max': np.max,
32         'mean': np.mean,
33         'sum': np.sum,
34     }
35
36     def __init__(self, graph: Graph, attrs: dict):
37         super().__init__(graph, {
38             'op': 'Reduce',
39             'reduce_type': None,
40             'infer': __class__.infer,
41             'in_ports_count': 2,
42             'out_ports_count': 1,
43         }, attrs)
44
45     @staticmethod
46     def infer(node: Node):
47         if len(node.in_nodes()) == 2:
48             reduction_indices_data = node.in_node(1)
49             if reduction_indices_data.has_valid('value'):
50                 node['axis'] = reduction_indices_data.value
51             else:
52                 raise Error("Can not deduce `reduction_indices` for node {}. It should be deduced out of first port "
53                             "input due to absence of value in this node".format(node.id))
54             node.graph.remove_edge(reduction_indices_data.id, node.id)
55
56         input_node = node.in_node()
57         input_shape = np.array(node.in_node().shape, dtype=np.int64)
58         output_node = node.out_node()
59
60         # In case if axis is None it means that reduction comes along each dimension
61         if node.axis is None:
62             node.axis = int64_array(list(range(len(input_shape))))
63
64         if not node.has_valid('reduce_type'):
65             log.error('Reduce type for node {} not specified!'.format(node.id))
66             return
67
68         reduce_type = node.reduce_type
69         if input_node.has_valid('value'):
70             if reduce_type.lower() in ['mean', 'max']:
71                 # Value and Shape propagation for constant path
72                 output_node.value = Reduce.reduce_method_map[reduce_type.lower()](input_node.value,
73                                                                                   axis=tuple(node.axis),
74                                                                                   keepdims=node.keep_dims)
75                 output_node.shape = np.array(output_node.value.shape, dtype=np.int64)
76             else:
77                 log.error('Reduce type {} is not supported for node {}'.format(reduce_type, node.id))
78                 return
79         else:
80             used_dims = np.zeros(len(input_shape), dtype=np.bool)
81             output_shape = input_shape
82
83             if node.axis.size == 1:
84                 node.axis = int64_array([node.axis.item()])
85
86             for dim in node.axis:
87                 used_dims[dim] = True
88                 output_shape[dim] = 1
89
90             # In case if keep dims == False, we should remove all 1 dims that was used in reduction
91             if not node.keep_dims:
92                 output_shape = output_shape[np.invert(used_dims)]
93
94             output_node.shape = output_shape