Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / middle / NormalizeFullyConnected.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 numpy as np
18
19 from mo.graph.graph import Graph
20 from mo.middle.replacement import MiddleReplacementPattern
21 from mo.ops.op import Op
22 from mo.ops.reshape import Reshape
23
24
25 class NormalizeFullyConnected(MiddleReplacementPattern):
26     enabled = True
27     graph_condition = [lambda graph: graph.graph['fw'] == 'onnx']
28
29     def run_after(self):
30         from extensions.middle.GemmToFullyConnected import GemmToFullyConnected
31         return [GemmToFullyConnected]
32
33     def run_before(self):
34         from extensions.middle.pass_separator import MiddleFinish
35         return [MiddleFinish]
36
37     def pattern(self):
38         return dict(
39             nodes=[
40                 ('fc', dict(kind='op', type='FullyConnected')),
41                 ('fc_output', dict(kind='data'))],
42             edges=[('fc', 'fc_output')],
43         )
44
45     def replace_pattern(self, graph: Graph, match: dict):
46         """
47             This pass normalize FC layer
48             Example:
49
50             (2,16,512)-->FC->(2,16,101)    =>    (2,16,512)-->Reshape-->(32,512)-->FC-->(32,101)-->Reshape-->(2,16,101)
51
52         """
53         fc = match['fc']
54         fc_weights = fc.in_node(1)
55         fc_output = match['fc_output']
56         fc_input = fc.in_node()
57
58         input_shape = fc.in_node().shape
59         if len(input_shape) <= 2 or np.prod(fc_input.shape[1:]) == fc_weights.shape[fc_weights.input_channel_dim]:
60             return
61
62         # Insert Reshape to normalize input for FC layer that should be in [N,C] layout
63         first_reshape_shape = np.array([np.prod(input_shape[0:-1]), input_shape[-1]], dtype=np.int64)
64         second_reshape_shape = np.array([*input_shape[0:-1], fc['out-size']], dtype=np.int64)
65         fc_out_shape = np.array([np.prod(input_shape[0:-1]), fc['out-size']], dtype=np.int64)
66         first_reshape = Reshape(graph, {'dim': np.array(first_reshape_shape)})
67         second_reshape = Reshape(graph, {'dim': np.array(second_reshape_shape)})
68
69         input_edge_attrs = graph.get_edge_data(fc_input.id, fc.id)[0]
70         output_edge_attrs = graph.get_edge_data(fc.id, fc_output.id)[0]
71
72         graph.remove_edge(fc_input.id, fc.id)
73         graph.remove_edge(fc.id, fc_output.id)
74
75         # Insert Reshapes before and after FullyConnected layer
76         reshape_data = first_reshape.create_node_with_data(inputs=[fc_input])
77         graph.add_edge(reshape_data.id, fc.id, **input_edge_attrs)
78
79         new_fc_output = Op.create_data_node(graph, fc, {'shape': fc_out_shape}, edge_attrs=output_edge_attrs)
80
81         second_reshape.create_node_with_data(inputs=[new_fc_output], data_nodes=fc_output)