2 Copyright (c) 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.
18 from mo.back.replacement import BackReplacementPattern
19 from mo.graph.graph import Graph, Node
20 from mo.middle.pattern_match import for_each_sub_graph_recursively
23 class ReshapeMutation(BackReplacementPattern):
30 nodes=[('reshape', {'kind': 'op', 'type': 'Reshape'})],
35 def replace_pattern(graph: Graph, match: dict):
36 reshape = match['reshape']
37 if hasattr(reshape, 'dim') and reshape.dim is not None:
38 reshape_inputs = reshape.in_nodes()
39 value = np.array(reshape.dim)
40 shape = np.array(value.shape)
41 del reshape.graph.node[reshape.id]['dim']
43 if 1 in reshape_inputs:
44 reshape_inputs[1].value = value
45 reshape_inputs[1].shape = shape
47 const_id = graph.unique_id(reshape.id + '/DimData')
48 graph.add_node(const_id,
49 **{'kind': 'data', 'value': value, 'shape': shape, 'name': reshape.id + '/DimData'})
50 graph.add_edge(const_id, reshape.id, **{'in': 1})
53 class DisableReshapeMutationInTensorIterator(BackReplacementPattern):
58 return [ReshapeMutation]
61 def add_supported_attrs_to_node(node: Node, params: list):
62 node.graph.node[node.id].update({
65 [('id', lambda node: node.node), 'name', 'precision', 'type'],
72 def reshapes_with_two_inputs_to_reshape_with_dim(self, graph: Graph):
73 reshapes = graph.get_op_nodes(op='Reshape')
75 for reshape in reshapes:
76 in_nodes = reshape.in_nodes()
78 if len(in_nodes) == 1:
80 assert len(in_nodes) == 2, "Reshape operation should have 2 inputs or 1 input and `dim` attribute"
82 reshape['dim'] = reshape.in_port(1).get_connection().data.get_value()
83 reshape.in_port(1).disconnect()
85 params = [('dim', lambda node: ','.join(map(str, node['dim'])))]
86 self.add_supported_attrs_to_node(reshape, params)
88 def find_and_replace_pattern(self, graph: Graph):
89 for_each_sub_graph_recursively(graph, self.reshapes_with_two_inputs_to_reshape_with_dim)