Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / middle / NormalizePad.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
19 from mo.graph.graph import Graph
20 from mo.middle.passes.eliminate import remove_op_node_with_data_node
21 from mo.middle.replacement import MiddleReplacementPattern
22
23
24 class NormalizePad(MiddleReplacementPattern):
25     """
26     The replacer finds all Pad operations and remove inputs with index 1 and 2. These inputs contain padding values
27     for each input tensor dimension and optionally the pad value for case of padding with a 'constant' mode.
28
29     The Pad layer is removed if all padding values are equal to 0.
30     """
31     enabled = True
32
33     def run_after(self):
34         from extensions.middle.pass_separator import MiddleStart
35         return [MiddleStart]
36
37     def run_before(self):
38         from extensions.middle.pass_separator import MiddleFinish
39         return [MiddleFinish]
40
41     def pattern(self):
42         return dict(
43             nodes=[
44                 ('pad', dict(kind='op', op='Pad'))
45             ],
46             edges=[]
47         )
48
49     def replace_pattern(self, graph: Graph, match: dict):
50         node = match['pad']
51         for port, input_node in node.in_nodes().items():
52             if port != 0:
53                 graph.remove_edge(input_node.id, node.id)
54
55         # remove Pad operation if all pads are equal to 0
56         if np.all(node.pads == 0):
57             remove_op_node_with_data_node(graph, node)