Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / back / insert_compatibility_l2normalization.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 numpy as np
18 import networkx as nx
19 from mo.ops.op import Op
20 from mo.graph.graph import Graph
21 from mo.back.replacement import BackReplacementPattern
22
23
24 class CompatibilityL2NormalizationPattern(BackReplacementPattern):
25
26     enabled = True
27
28     def pattern(self):
29         return dict(
30             nodes=[
31                 ('l2_normalization', dict(op='Normalize'))
32             ],
33             edges=[])
34
35     def replace_pattern(self, graph: Graph, match: dict):
36         """
37         Adds Normalize layer weights, which are required by Inference Engine, 
38         but do not always exist in MXNet model. 
39         
40         L2Normalization is mapped to Normalize layer
41         so we need to generate Normalize weights filled with ones.
42         
43         Parameters
44         ----------
45         graph : Graph
46            Graph with loaded model.
47          match : dict
48            Patterns which were found in graph structure.
49         """
50         l2_normalization_node = match['l2_normalization']
51         if len(l2_normalization_node.in_nodes()) < 2:
52             value = np.full([l2_normalization_node.in_node(0).shape[1]], 1.0, dtype=np.float32)
53             weights_node = Op.create_input_data_node(graph, name=l2_normalization_node['name'] + '_weights', value=value)
54             graph.create_edge(weights_node, l2_normalization_node, out_port=0, in_port=1, edge_attrs={'bin': 'weights'})