Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / mo / middle / passes / l2normalization.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.front.extractor import add_attrs_props
20 from mo.front.extractor import update_ie_fields
21 from mo.graph.graph import Node, Graph
22 from mo.middle.pattern_match import apply_pattern
23
24
25 def l2_norm_to_norm_action(graph: Graph, match: dict):
26     input_data_name = match['input'].node
27     output_data_name = match['l2_normalize_data'].node
28
29     if not match['maximum_y_data'].has_valid('value'):
30         return 1
31     if match['maximum_y_data'].value.shape != ():
32         return 1
33     y = match['maximum_y_data'].value
34
35     normalize_id = graph.unique_id()
36     graph.add_node(normalize_id,
37                    **add_attrs_props(
38                        dict(kind='op', precision="FP32", type='Normalize', name=str(graph.unique_id('normalize')),
39                             op='Normalize', shape=None, eps=str(y), across_spatial=str(0), channel_shared=str(0),
40                             data_type=None, infer=None, in_ports_count=2, out_ports_count=1)))
41     normalize_data_id = graph.unique_id()
42
43     graph.add_node(normalize_data_id, **add_attrs_props(graph.node[output_data_name]))
44     update_ie_fields(graph.node[normalize_id])
45     weights_id = graph.unique_id('weights_')
46     graph.add_node(weights_id, **add_attrs_props(
47         dict(kind='data', precision="FP32", name=weights_id, value=None, shape=None, data_type=None, infer=None)))
48     wnode = Node(graph, weights_id)
49     wnode['value'] = np.ones(shape=match['input'].shape[-1],
50                              dtype=match['input'].data_type)  # TODO feature dim instead of -1
51     wnode['shape'] = np.array(wnode['value'].shape)
52     output_edges = list(graph.out_edges(output_data_name, data=True))
53     graph.remove_edges_from([
54         (input_data_name, match['l2_normalize'].id),
55         (input_data_name, match['square'].id)
56     ])
57     graph.remove_edges_from(list(graph.out_edges(output_data_name)))
58     graph.remove_node(output_data_name)
59     graph.add_edge(input_data_name, normalize_id, **{'in': 0})
60     graph.add_edge(weights_id, normalize_id, **{'in': 1, 'bin': 'weights'})
61     graph.add_edge(normalize_id, normalize_data_id, **{'out': 0})
62     for data, owner, attr in output_edges:
63         graph.add_edge(normalize_data_id, owner, **attr)
64
65
66 def l2_norm_to_norm(graph: Graph):
67     apply_pattern(
68         graph,
69         nodes=[
70             ('input', dict(kind='data')),
71             ('l2_normalize', dict(kind='op', op='Mul')),
72             ('l2_normalize_data', dict(kind='data')),
73             ('maximum', dict(kind='op', op='Maximum')),
74             ('maximum_data', dict(kind='data')),
75             ('maximum_y_data', dict(kind='data')),
76             ('rsqrt', dict(kind='op', op='Rsqrt')),
77             ('rsqrt_data', dict(kind='data')),
78             ('square', dict(kind='op', op='Square')),
79             ('square_data', dict(kind='data')),
80             ('sum', dict(kind='op', op='Reduce', reduce_type='sum')),
81             ('sum_data', dict(kind='data')),
82         ],
83         edges=[
84             ('input', 'square'),
85             ('square', 'square_data'),
86             ('square_data', 'sum'),
87             ('sum', 'sum_data'),
88             ('maximum_y_data', 'maximum'),
89             ('sum_data', 'maximum'),
90             ('maximum', 'maximum_data'),
91             ('maximum_data', 'rsqrt'),
92             ('rsqrt', 'rsqrt_data'),
93             ('rsqrt_data', 'l2_normalize'),
94             ('input', 'l2_normalize'),
95             ('l2_normalize', 'l2_normalize_data'),
96         ],
97         action=l2_norm_to_norm_action
98     )