Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / mo / ops / deconvolution.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 import numpy as np
19
20 from mo.front.common.partial_infer.utils import int64_array, float_array, mark_input_bins, assign_dims_to_weights, \
21     tf_window_op_pad_infer
22 from mo.front.onnx.extractors.utils import get_backend_pad
23 from mo.front.extractor import spatial_getter
24 from mo.utils.error import Error
25 from mo.graph.graph import Node, Graph
26 from mo.ops.op import Op, PermuteAttrs
27
28
29 class Deconvolution(Op):
30     op = 'Deconvolution'
31
32     def __init__(self, graph: Graph, attrs: dict):
33         super().__init__(graph, {
34             'kind': 'op',
35             'type': __class__.op,
36             'op': __class__.op,
37             'infer': __class__.infer,
38             'in_ports_count': 3,
39             'out_ports_count': 1,
40         }, attrs)
41
42     def backend_attrs(self):
43         return [
44            'auto_pad',
45            'group',
46            ('strides', lambda node: ','.join(map(str, node['stride'][node.spatial_dims]))),
47            ('kernel', lambda node: ','.join(map(str, node['kernel_spatial']))),
48
49            ('pads_begin', lambda node: ','.join(map(str, get_backend_pad(node.pad, node.spatial_dims, 0)))),
50            ('pads_end', lambda node: ','.join(map(str, get_backend_pad(node.pad, node.spatial_dims, 1)))),
51            'output'
52         ]
53
54     def backend_attrs_v2(self):
55         return [
56             spatial_getter('stride-x', 'stride', 1),
57             spatial_getter('stride-y', 'stride', 0),
58
59             ('kernel-x', lambda node: node.kernel_spatial[1]),
60             ('kernel-y', lambda node: node.kernel_spatial[0]),
61
62             spatial_getter('pad-x', 'pad', 1, lambda x: x[0]),
63             spatial_getter('pad-y', 'pad', 0, lambda x: x[0]),
64             spatial_getter('pad-r', 'pad', 1, lambda x: x[1]),
65             spatial_getter('pad-b', 'pad', 0, lambda x: x[1]),
66
67             'auto_pad',
68             'output',
69             'group',
70         ]
71
72
73     @staticmethod
74     def infer(node: Node):
75         """
76         Deconvolution has an input argument that explicitly determines output shape, so in contrast
77         to the forward Conv2d we shouldn't infer output shape. We just use this output shape as
78         an input shape and pass it to our utilities that computes numeric values for padding.
79         They also deliver output shape that is interpreted here as input shape for convolution.
80         We need to check that the real input shape and shape inferred by those utility functions match.
81         """
82         output_shape = np.array(node.in_node(0).value)
83         kernel_shape = node.in_node(1).shape
84         node['kernel_shape'] = kernel_shape
85         if output_shape is None or kernel_shape is None or node.spatial_dims is None or node.stride is None:
86             return
87
88         if not node.has_valid('kernel_spatial_idx'):
89             node['kernel_spatial_idx'] = np.delete([x for x in range(len(kernel_shape))], (node.input_feature_channel, node.output_feature_channel))
90
91         spatial_dims = node.spatial_dims
92         output_spatial = np.array(output_shape[spatial_dims])
93         stride_spatial = np.array(node.stride[spatial_dims])
94         node['kernel_spatial'] = np.array(kernel_shape[node.kernel_spatial_idx])
95         node.pad_spatial_shape, input_spatial_for_check = tf_window_op_pad_infer(
96             output_spatial, node.kernel_spatial, stride_spatial, node.auto_pad)
97
98         assert all(input_spatial_for_check == node.in_node(2).shape[spatial_dims])
99
100         pad = np.zeros((len(output_shape), 2), dtype=np.int64)
101         pad[spatial_dims] = node.pad_spatial_shape
102         node.pad = pad
103
104         node.output = output_shape[node.channel_dims][0]
105         node.output_shape = output_shape
106         node.out_node().shape = output_shape
107
108         mark_input_bins(node, ['weights'], 1)
109         assign_dims_to_weights(node.in_node(1), node.kernel_spatial_idx, node.input_feature_channel,
110                                node.output_feature_channel, len(kernel_shape))
111
112         # cut shape input at port 0, it is already consumed
113         node.graph.remove_edge(node.in_node(0).id, node.id)
114
115         # reconnect input tensor from port 2 to port 0
116         node.in_edge(2)['in'] = 0
117
118         # OK, now we are sure this is a supported Deconvolution layer
119         node.type = 'Deconvolution'
120         node.op = 'Deconv2D'
121
122         # Add permute_attrs
123         PermuteAttrs.create_permute_attrs(node, attrs=[('pad', 'input:0'),
124                                                        ('stride', 'input:0'),
125                                                        ('output_shape', 'input:0'),
126                                                        ('batch_dims', 'input:0'),
127                                                        ('channel_dims', 'input:0'),
128                                                        ('spatial_dims', 'input:0'),
129
130                                                        ('kernel_shape', 'input:1'),
131                                                        ('kernel_spatial_idx', 'input:1'),
132                                                        ('input_feature_channel', 'input:1'),
133                                                        ('output_feature_channel', 'input:1'),
134                                                        ])
135
136         PermuteAttrs.set_permutation(node.in_node(1), node,
137                                      node.get_weights_permute if node.has_valid('get_weights_permute') else None)