Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / front / tf / ArgMaxReshape.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 import numpy as np
19
20 from mo.front.common.replacement import FrontReplacementOp
21 from mo.graph.graph import Node, Graph
22 from mo.ops.squeeze import Squeeze
23
24
25 class ArgMaxReshape(FrontReplacementOp):
26     """
27     The TensorFlow version of ArgMax removes the reduction axis, but Inference Engine ones doesn't. So this pass adds
28     Squeeze to remove the reduction dimension.
29     """
30     op = "ArgMax"
31     enabled = True
32
33     def nodes_to_remove(self, graph: Graph, match: dict):
34         # do not remove matched node
35         return []
36
37     def replace_op(self, graph: Graph, node: Node):
38         squeeze_op = Squeeze(graph, dict())
39         squeeze_op.attrs['old_infer'] = squeeze_op.attrs['infer']
40         squeeze_op.attrs['infer'] = __class__.do_infer
41
42         squeeze_node = squeeze_op.create_node([], dict(name=node.name + '/Squeeze'))
43         node.insert_node_after(squeeze_node)
44         return []
45
46     @staticmethod
47     def do_infer(node: Node):
48         """
49         The infer function for Squeeze that get's axis for reduction from the ArgMax node
50         """
51         argmax_node = node.in_node(0).in_node(0)
52         assert argmax_node.type == 'ArgMax'
53         if not argmax_node.has('axis'):
54             log.error('The node "{}" does not have attribute "axis"'.format(argmax_node.name))
55             return
56         node['squeeze_dims'] = np.array([argmax_node.axis])
57         node.old_infer(node)