Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / mo / ops / reshape.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 math
17
18 import numpy as np
19
20 from mo.front.common.partial_infer.elemental import single_output_infer
21 from mo.front.common.partial_infer.reshape import tf_reshape_shape_infer
22 from mo.graph.graph import Node, Graph
23 from mo.ops.op import Op
24 from mo.utils.error import Error
25
26
27 class Reshape(Op):
28     op = 'Reshape'
29     enabled = True
30
31     def __init__(self, graph: Graph, attrs: dict):
32         super().__init__(graph, {
33             'kind': 'op',
34             'type': __class__.op,
35             'op': __class__.op,
36             'in_ports_count': 2,
37             'out_ports_count': 1,
38             'infer': lambda node: single_output_infer(node, tf_reshape_shape_infer,
39                                                       lambda node: np.reshape(node.in_node().value,
40                                                                               node.out_node().shape))
41         }, attrs)
42
43     @staticmethod
44     def kaldi_infer(node: Node):
45         in_node = node.in_node().in_node()  # prev_layer_node -> data -> this_node
46         input_shape = node.in_node().shape
47         # Kaldi Reshape hugely depends on the layers that precedes or succeeds
48         # Convolution/Pooling layers. Therefore there are 4 cases with different
49         # partial inference.
50         batch = input_shape[0]
51         if in_node.op in ['Convolution', 'Pooling', 'Permute']:
52             output_spatial = np.array([batch, np.prod(input_shape[1:])], dtype=np.int64)
53             return Reshape.set_shape_and_dim(node, output_spatial)
54         # Supports ONLY NCHW and NH layouts
55         if len(input_shape) not in [4, 2]:
56             raise Error('Reshape in Kaldi support only 1d or 3d shapes')
57         spatial_shape = input_shape[1]
58         if len(input_shape) in [4]:
59             spatial_shape = input_shape[2:3]
60         out_node = node.out_node().out_node()
61         if out_node.op == 'Convolution':
62             output_spatial = np.array(
63                 [batch, math.ceil(spatial_shape / out_node.patch_stride), 1, out_node.patch_stride], dtype=np.int64)
64             return Reshape.set_shape_and_dim(node, output_spatial)
65         elif out_node.op == 'Pooling':
66             if out_node.pool_step is None:
67                 out_node.stride = np.array([1, 1, out_node.window[-1], out_node.window[-1]], dtype=np.int64)
68             output_spatial = np.array(
69                 [batch, out_node.pool_stride, 1, math.ceil(spatial_shape / out_node.pool_stride)], dtype=np.int64)
70             return Reshape.set_shape_and_dim(node, output_spatial)
71
72     @staticmethod
73     def set_shape_and_dim(node: Node, reshape_dim):
74         Reshape.update_node_stat(node, {'dim': reshape_dim})
75         node.out_node().shape = reshape_dim