Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / middle / GemmResolver.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 from mo.front.common.partial_infer.utils import mark_input_bins, assign_dims_to_weights, int64_array
18 from mo.graph.graph import Graph
19 from mo.middle.replacement import MiddleReplacementPattern
20 from mo.ops.op import PermuteAttrs
21
22
23 class GemmResolver(MiddleReplacementPattern):
24     enabled = True
25     graph_condition = [lambda graph: graph.graph['fw'] != 'tf']
26
27     def run_before(self):
28         from extensions.middle.NormalizeFullyConnected import NormalizeFullyConnected
29         return [NormalizeFullyConnected]
30
31     def run_after(self):
32         from extensions.middle.pass_separator import MiddleStart
33         return [MiddleStart]
34
35     def pattern(self):
36         return dict(
37             nodes=[
38                 ('input_0', dict(kind='data')),
39                 ('input_1', dict(kind='data')),
40                 ('fc', dict(op='MatMul')),
41                 ('fc_data', dict(kind='data'))],
42             edges=[
43                 ('input_0', 'fc', {'in': 0}),
44                 ('input_1', 'fc', {'in': 1}),
45                 ('fc', 'fc_data')
46             ]
47         )
48
49     def replace_pattern(self, graph: Graph, match: dict):
50         if not match['input_0'].has_valid('value') and not match['input_1'].has_valid('value') or \
51                 not match['input_0'].has_valid('value') and match['input_1'].has_valid('value') and match[
52             'input_1'].shape.size > 2:
53             match['fc']['type'] = 'GEMM'
54         elif not match['input_0'].has_valid('value') and match['input_1'].has_valid('value'):
55             match['fc']['type'] = 'FullyConnected'
56             node = match['fc']
57             mark_input_bins(node)
58             weights_node = match['input_1']
59             assign_dims_to_weights(weights_node, None, 0, 1, 2)
60             PermuteAttrs.set_permutation(weights_node, node, PermuteAttrs.Permutation(perm=int64_array([1, 0]),
61                                                                                       inv=int64_array([0, 1])))
62             weights_shape = weights_node.shape
63
64             node['out-size'] = weights_shape[1]