Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / mo / front / common / weights.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 logging as log
18
19 import numpy as np
20
21
22 def swap_weights_xy(nodes: list):
23     """
24     The function changes weights of the nodes from the 'nodes' list which are used with calculations with coordinates of
25     some objects. The function should be used when it is necessary to virtually change the layout of data from XY to YX.
26     The node from the 'nodes' list should be some sort of convolution node or matrix multiplication.
27     The function also swaps weights in the following Add and BiasAdd operations.
28     :param nodes: list of Node objects to change the weights in them.
29     :return: None
30     """
31     for node in nodes:
32         weights_node = node.in_node(1)
33         if weights_node.has_and_set('swap_xy_count'):
34             weights_node['swap_xy_count'] += 1
35             log.debug('Increasing value for attribute "swap_xy_count" to {} for node {}'.format(
36                 weights_node['swap_xy_count'], weights_node.name))
37             continue
38         weights_node['swap_xy_count'] = 1
39         log.debug('Swapping weights for node "{}"'.format(node.name))
40         reshaped_weights = weights_node.value.reshape((-1, 2))
41         new_swapped_weights = np.concatenate((reshaped_weights[:, 1:2], reshaped_weights[:, 0:1]), 1)
42         new_swapped_weights = new_swapped_weights.reshape(weights_node.shape)
43         weights_node.shape = np.array(new_swapped_weights.shape, dtype=np.int64)
44         weights_node.value = new_swapped_weights
45         # biases
46         for m in node.out_node().out_nodes():
47             if m.has_valid('op') and m.op in ['Add', 'BiasAdd']:
48                 biases = m.in_node(1).value  # biases are weights of the (Bias)Add op
49                 # swap Y and X to the regular order that the IE expects
50                 reshaped_biases = biases.reshape((-1, 2))
51                 swapped_biases = np.concatenate((reshaped_biases[:, 1:2], reshaped_biases[:, 0:1]), 1)
52                 # reshaping back to the original shape
53                 swapped_biases = swapped_biases.reshape(biases.shape)
54                 m.in_node(1).shape = np.array(swapped_biases.shape, dtype=np.int64)
55                 m.in_node(1).value = swapped_biases