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.
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
25 class NormalizeFullyConnected(MiddleReplacementPattern):
27 graph_condition = [lambda graph: graph.graph['fw'] == 'onnx']
30 from extensions.middle.GemmToFullyConnected import GemmToFullyConnected
31 return [GemmToFullyConnected]
34 from extensions.middle.pass_separator import MiddleFinish
40 ('fc', dict(kind='op', type='FullyConnected')),
41 ('fc_output', dict(kind='data'))],
42 edges=[('fc', 'fc_output')],
45 def replace_pattern(self, graph: Graph, match: dict):
47 This pass normalize FC layer
50 (2,16,512)-->FC->(2,16,101) => (2,16,512)-->Reshape-->(32,512)-->FC-->(32,101)-->Reshape-->(2,16,101)
54 fc_weights = fc.in_node(1)
55 fc_output = match['fc_output']
56 fc_input = fc.in_node()
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]:
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)})
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]
72 graph.remove_edge(fc_input.id, fc.id)
73 graph.remove_edge(fc.id, fc_output.id)
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)
79 new_fc_output = Op.create_data_node(graph, fc, {'shape': fc_out_shape}, edge_attrs=output_edge_attrs)
81 second_reshape.create_node_with_data(inputs=[new_fc_output], data_nodes=fc_output)