Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / back / ReshapeMutation.py
1 """
2  Copyright (c) 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 numpy as np
17
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
21
22
23 class ReshapeMutation(BackReplacementPattern):
24     enabled = True
25     force_clean_up = True
26
27     @staticmethod
28     def pattern():
29         return dict(
30             nodes=[('reshape', {'kind': 'op', 'type': 'Reshape'})],
31             edges=[],
32         )
33
34     @staticmethod
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']
42
43             if 1 in reshape_inputs:
44                 reshape_inputs[1].value = value
45                 reshape_inputs[1].shape = shape
46             else:
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})
51
52
53 class DisableReshapeMutationInTensorIterator(BackReplacementPattern):
54     enabled = True
55     force_clean_up = True
56
57     def run_after(self):
58         return [ReshapeMutation]
59
60     @staticmethod
61     def add_supported_attrs_to_node(node: Node, params: list):
62         node.graph.node[node.id].update({
63             'IE': [(
64                 'layer',
65                 [('id', lambda node: node.node), 'name', 'precision', 'type'],
66                 [
67                     ('data', params, []),
68                     '@ports',
69                     '@consts'])]
70         })
71
72     def reshapes_with_two_inputs_to_reshape_with_dim(self, graph: Graph):
73         reshapes = graph.get_op_nodes(op='Reshape')
74
75         for reshape in reshapes:
76             in_nodes = reshape.in_nodes()
77
78             if len(in_nodes) == 1:
79                 continue
80             assert len(in_nodes) == 2, "Reshape operation should have 2 inputs or 1 input and `dim` attribute"
81
82             reshape['dim'] = reshape.in_port(1).get_connection().data.get_value()
83             reshape.in_port(1).disconnect()
84
85             params = [('dim', lambda node: ','.join(map(str, node['dim'])))]
86             self.add_supported_attrs_to_node(reshape, params)
87
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)