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