Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / front / caffe / bn_test.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 import numpy as np
17 import unittest
18
19 from extensions.front.caffe.bn import BNToScaleShift
20 from mo.graph.graph import Node
21 from mo.utils.unittest.extractors import FakeParam
22 from mo.utils.unittest.graph import build_graph_with_edge_attrs
23
24
25 class FakeBNProtoLayer:
26     def __init__(self, val):
27         self.bn_param = val
28
29
30 class FakeBNBinLayer:
31     def __init__(self, val):
32         self.blobs = val
33
34
35 class TestBNReplacer(unittest.TestCase):
36     def test_bn(self):
37         bn_pb = FakeBNProtoLayer(FakeParam('eps', 0.0001))
38         mean = [1, 2.5, 3]
39         var = [0.5, 0.1, 1.2]
40         scale = [2.3, 3.4, 4.5]
41         shift = [0.8, 0.6, 0.4]
42         bn_bin = FakeBNBinLayer([FakeParam('data', mean),
43                                  FakeParam('data', var),
44                                  FakeParam('data', scale),
45                                  FakeParam('data', shift)])
46         nodes = {
47             'node_1': {'kind': 'op', 'type': 'Identity', 'op': 'Placeholder'},
48             'bn': {'type': 'BN', 'kind': 'op', 'op': 'BN',
49                    'pb': bn_pb,
50                    'model_pb': bn_bin},
51             'node_2': {'kind': 'op', 'type': 'Identity', 'op': 'Placeholder'}}
52         edges = [
53             ('node_1', 'bn', {'in': 0}),
54             ('bn', 'node_2', {'in': 0})]
55         graph = build_graph_with_edge_attrs(nodes, edges)
56         node = Node(graph, 'bn')
57         replacer = BNToScaleShift()
58         replacer.replace_op(graph, node)
59
60         scale_node = [node for node, attrs in list(graph.nodes(data=True)) if attrs['type'] == 'ScaleShift']
61         self.assertEqual(len(scale_node), 1)
62
63         scale_ref = np.array([1.11796412, 3.2272172, 4.74282367])
64         shift_ref = np.array([-2.07131747, -10.87253847, -20.14270653])
65         for i in range(len(mean)):
66             self.assertAlmostEqual(graph.node[scale_node[0]]['scale'][i], scale_ref[i])
67             self.assertAlmostEqual(graph.node[scale_node[0]]['bias'][i], shift_ref[i])