Publishing R3
[platform/upstream/dldt.git] / model-optimizer / extensions / front / LRNReplacer.py
1 """
2  Copyright (c) 2017-2018 Intel Corporation
3
4  Lic    ensed 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
20 from mo.front.common.replacement import FrontReplacementOp
21 from mo.ops.lin_op import Mul
22 from mo.ops.const import Const
23
24
25 class LRNReplacer(FrontReplacementOp):
26     op = 'LRN'
27     enabled = True
28
29     def replace_sub_graph(self, graph: nx.MultiDiGraph, match: dict):
30         node = match['op']
31
32         if not node.has_valid('bias') or (node.has_valid('bias') and node.bias == 1):
33             return
34
35         # Calculate scale value & create Const op
36         scale_value = np.array(1. / (pow(node.bias, node.beta)))
37         node.alpha /= node.bias
38         const_node = Const(graph, dict(value=scale_value, shape=scale_value.shape))
39
40         # Get all outputs for LRN layer
41         out_nodes = [node for node in node.out_nodes().values()]
42
43         # Create Mul node with inputs
44         mul_node = Mul(graph, dict(name=node.id + "/Mul_"))
45         mnode = mul_node.create_node(inputs=[node, const_node.create_node()])
46
47         # Move edges from LRN to Mul node
48         for out_node in out_nodes:
49             edge_attrs = graph.get_edge_data(node.id, out_node.id)[0]
50             graph.remove_edge(node.id, out_node.id)
51             graph.add_edges_from([(mnode.id, out_node.id, edge_attrs)])