2 Copyright (c) 2018-2019 Intel Corporation
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
8 http://www.apache.org/licenses/LICENSE-2.0
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.
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
26 class BNToScaleShift(FrontReplacementOp):
28 Replaces BN layer with ScaleShift.
33 def replace_op(self, graph: Graph, node: Node):
34 attrs = {'name': node.id + "/ScaleShift_"}
36 param = graph.node[node.id]['pb'].bn_param
37 pb_model = graph.node[node.id]['model_pb']
38 blobs = pb_model.blobs
41 raise Error("Incorrect number of blobs in BN layer {}".format(node.id))
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)
48 gamma = gamma + np.repeat(param.eps, gamma.shape)
50 scale = 1.0 / np.sqrt(gamma) * mean
51 shift = var - betta * scale
53 embed_input(attrs, 1, 'scale', scale, 'weights')
54 embed_input(attrs, 2, 'bias', shift, 'biases')
56 ss = ScaleShiftOp(graph, attrs)
57 scale_shift = ss.create_node([node.in_node(0)])
59 return [scale_shift.id]