2 Copyright (c) 2018-2019 Intel Corporation
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
8 http://www.apache.org/licenses/LICENSE-2.0
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.
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
28 def is_value_is_constant(val: np.ndarray, const: [int, float]):
31 if val.ndim == 1 and len(val) > 1:
33 return val.item() == const
36 class FlattenToReshapeableReshape(FrontReplacementSubgraph):
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].
44 return [NearestNeighborUpsampling]
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')),
59 ('shape', 'strided_slice', {'in': 0}),
60 ('strided_slice', 'pack', {'in': 0}),
61 ('const', 'pack', {'in': 1}),
62 ('pack', 'reshape', {'in': 1}),
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']
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')))
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.')
81 expected_values = [0, 1, 1] # expected values to a StridedSlice to get the batch size
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')))
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')))