Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / front / caffe / bn.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.caffe.extractors.utils import embed_input
20 from mo.front.common.replacement import FrontReplacementOp
21 from mo.graph.graph import Node, Graph
22 from mo.ops.scale_shift import ScaleShiftOp
23 from mo.utils.error import Error
24
25
26 class BNToScaleShift(FrontReplacementOp):
27     """
28     Replaces BN layer with ScaleShift.
29     """
30     op = "BN"
31     enabled = True
32
33     def replace_op(self, graph: Graph, node: Node):
34         attrs = {'name': node.id + "/ScaleShift_"}
35
36         param = graph.node[node.id]['pb'].bn_param
37         pb_model = graph.node[node.id]['model_pb']
38         blobs = pb_model.blobs
39
40         if len(blobs) != 4:
41             raise Error("Incorrect number of blobs in BN layer {}".format(node.id))
42
43         mean = np.array(blobs[0].data)
44         var = np.array(blobs[1].data)
45         betta = np.array(blobs[2].data)
46         gamma = np.array(blobs[3].data)
47
48         gamma = gamma + np.repeat(param.eps, gamma.shape)
49
50         scale = 1.0 / np.sqrt(gamma) * mean
51         shift = var - betta * scale
52
53         embed_input(attrs, 1, 'scale', scale, 'weights')
54         embed_input(attrs, 2, 'bias', shift, 'biases')
55
56         ss = ScaleShiftOp(graph, attrs)
57         scale_shift = ss.create_node([node.in_node(0)])
58
59         return [scale_shift.id]