Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / front / tf / FlattenToReshape.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 from extensions.front.Pack import Pack
22 from extensions.front.tf.nearest_neighbor_upsampling import NearestNeighborUpsampling
23 from mo.front.common.partial_infer.utils import int64_array
24 from mo.front.common.replacement import FrontReplacementSubgraph
25 from mo.graph.graph import Graph
26
27
28 def is_value_is_constant(val: np.ndarray, const: [int, float]):
29     if val.ndim > 1:
30         return False
31     if val.ndim == 1 and len(val) > 1:
32         return False
33     return val.item() == const
34
35
36 class FlattenToReshapeableReshape(FrontReplacementSubgraph):
37     """
38     The TensorFlow implementation of the Flatten operation is not reshape-able because the batch size is hardcoded
39     during te constant propagation. This transform sets the 'dim' attribute for the Reshape to [0, -1].
40     """
41     enabled = True
42
43     def run_after(self):
44         return [NearestNeighborUpsampling]
45
46     def run_before(self):
47         return [Pack]
48
49     def pattern(self):
50         return dict(
51             nodes=[
52                 ('shape', dict(op='Shape')),
53                 ('strided_slice', dict(op='StridedSlice')),
54                 ('pack', dict(op='Pack')),
55                 ('const', dict(op='Const')),
56                 ('reshape', dict(op='Reshape')),
57             ],
58             edges=[
59                 ('shape', 'strided_slice', {'in': 0}),
60                 ('strided_slice', 'pack', {'in': 0}),
61                 ('const', 'pack', {'in': 1}),
62                 ('pack', 'reshape', {'in': 1}),
63             ])
64
65     @staticmethod
66     def replace_sub_graph(graph: Graph, match: dict):
67         strided_slice_node = match['strided_slice']
68         const_node = match['const']
69         reshape_node = match['reshape']
70         pack_node = match['pack']
71
72         if not const_node.has_valid('value') or not is_value_is_constant(const_node.value, -1):
73             log.debug('The pattern does not correspond to flatten. The second reshape dimension is not -1. It is {}'.
74                       format(const_node.soft_get('value')))
75             return
76         if len(pack_node.in_nodes()) != 2:
77             log.debug('The pattern does not correspond to flatten. The "Pack" operation produces tensor with 3 items '
78                       'but should produce just 2.')
79             return
80
81         expected_values = [0, 1, 1]  # expected values to a StridedSlice to get the batch size
82         for ind in range(3):
83             if not strided_slice_node.in_node(ind + 1).has_valid('value') or \
84                     not is_value_is_constant(strided_slice_node.in_node(ind + 1).value, expected_values[ind]):
85                 log.debug('The pattern does not correspond to flatten because of the input with index {}. The value is '
86                           '"{}".'.format(ind, strided_slice_node.soft_get('value')))
87                 return
88
89         graph.remove_edge(pack_node.id, reshape_node.id)
90         reshape_node['dim'] = int64_array([0, -1])
91         log.debug('The node "{}" is actually a Flatten node'.format(reshape_node.soft_get('name')))