Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / front / mxnet / ssd_pattern_remove_transpose.py
1 """
2  Copyright (c) 2017-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 networkx as nx
18
19 from extensions.front.mxnet.ssd_pattern_flatten_softmax_activation import SsdPatternFlattenSoftmaxActivation
20 from extensions.front.mxnet.ssd_pattern_remove_flatten import SsdPatternRemoveFlatten
21 from extensions.front.mxnet.ssd_pattern_remove_reshape import SsdPatternRemoveReshape
22 from mo.front.common.replacement import FrontReplacementSubgraph
23 from mo.graph.graph import Graph
24
25
26 class SsdPatternRemoveTranspose(FrontReplacementSubgraph):
27     enabled = True
28
29     def run_before(self):
30         return [SsdPatternFlattenSoftmaxActivation, SsdPatternRemoveFlatten, SsdPatternRemoveReshape]
31
32     def pattern(self):
33         return dict(
34             nodes=[
35                 ('transpose', dict(op='transpose')),
36                 ('softmax_activation', dict(op='SoftMax')),
37                 ('multi_box_detection', dict(op='_contrib_MultiBoxDetection'))
38             ],
39             edges=[
40                 ('transpose', 'softmax_activation', {'in': 0}),
41                 ('softmax_activation', 'multi_box_detection', {'in': 1}),
42             ]
43         )
44
45     def replace_sub_graph(self, graph: Graph, match: dict):
46         """
47         Need to find each occurrence of pattern:
48         transpose -> SoftmaxActivation -> _contrib_MultiBoxDetection
49         remove transpose layer to secure the order of weights in SoftMax to be the same as IE expects
50         IE expects weights to be in following order: class-wise values for each priorbox.
51         priorboxes change the quickest
52
53         Parameters
54         ----------
55         graph : Graph
56            Graph with loaded model.
57          match : dict
58            Patterns which were found in graph structure.
59         """
60         transpose_node = match['transpose']
61         softmax_activation = match['softmax_activation']
62         transpose_in_node = transpose_node.in_node(0)
63
64         graph.remove_edge(transpose_in_node.id, transpose_node.id)
65         graph.remove_edge(transpose_node.id, softmax_activation.id)
66         graph.remove_node(transpose_node.id)
67         graph.create_edge(transpose_in_node, softmax_activation)