Publishing R5 content (#72)
[platform/upstream/dldt.git] / model-optimizer / extensions / back / kaldi_remove_memory_output.py
1 """
2  Copyright (c) 2018 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 networkx as nx
18
19 from mo.back.replacement import BackReplacementPattern
20
21
22 class KaldiRemoveMemoryOutputBackReplacementPattern(BackReplacementPattern):
23     enabled = False
24
25     @staticmethod
26     def pattern():
27         return dict(
28             nodes=[
29                 ('memory_node', dict(kind='op', op='Memory')),
30                 ('data_node', dict(kind='data'))
31             ],
32             edges=[
33                 ('memory_node', 'data_node', {'out': 0})
34             ]
35         )
36
37     @staticmethod
38     def replace_pattern(graph: nx.MultiDiGraph, match: dict):
39         """
40         Need to find the pattern: Memory -> Data -> OpOutput
41
42         It is needed to make Memory nodes appear in IR,
43         but they are output nodes by default and we remove the OpOutput node after each output memory.
44
45         DO NOT use graph clean up after it
46         otherwise Memory nodes would be removed as they are not on the path from input to output
47
48         Parameters
49         ----------
50         graph : nx.MultiDiGraph
51            Graph with loaded model.
52         match : dict
53            Patterns which were found in graph structure.
54         """
55         memory = match['memory_node']
56         data = match['data_node']
57
58         # Those Memory nodes that are not output ones, should not be replaced
59         if not data.has_and_set('is_output'):
60             return
61         graph.remove_edge(memory.id, data.id)
62         graph.remove_node(data.id)