Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / mo / front / caffe / extractors / batchnorm.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.partial_infer.elemental import copy_shape_infer
21
22
23 def batch_norm_ext(pb_layer, pb_model):
24     """
25     Extracts properties of the BatchNorm layer.
26     In case of scale, scale is merged into mean and variance
27     Args:
28         pl: proto layer, contains own properties of the layer, i.e epsilon
29         ml: caffemodel layer, contains blobs with 0: mean, 1: variance, (opt)2: scale
30
31     Returns:
32         attrs object with type, partial inference function and mean/variance properties.
33     """
34     assert pb_layer, 'Protobuf layer can not be empty'
35     param = pb_layer.batch_norm_param
36     attrs = {
37         'op': 'BatchNormalization',
38         'type': 'BatchNormalization',
39         'epsilon': param.eps,
40         'infer': copy_shape_infer
41     }
42
43     if not pb_model:
44         return attrs
45
46     blobs = pb_model.blobs
47     assert len(blobs) >= 2, 'BatchNorm accepts not less then two input blobs'
48     mean = np.array(blobs[0].data)
49     variance = np.array(blobs[1].data)
50
51     if len(blobs) == 3:
52         scale = blobs[2].data[0]
53         if scale != 0:
54             scale = 1.0 / scale
55         mean *= scale
56         variance *= scale
57
58     embed_input(attrs, 1, 'mean', mean, 'biases')
59     embed_input(attrs, 2, 'variance', variance, 'weights')
60
61     return attrs