18d687fbc0b726411fec09b4cfba83683e5451af
[platform/upstream/dldt.git] / model-optimizer / extensions / middle / UselessStridedSlice.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 logging as log
18
19 import networkx as nx
20 import numpy as np
21
22 from extensions.middle.ConvertGroupedStridedSlice import ConvertGroupedStridedSlice
23 from extensions.middle.SliceConverter import ConvertSlice
24 from mo.graph.graph import erase_node
25 from mo.middle.replacement import MiddleReplacementPattern
26
27
28 class UselessStridedSliceEraser(MiddleReplacementPattern):
29     enabled = True
30
31     def run_before(self):
32         return [ConvertGroupedStridedSlice]
33
34     def run_after(self):
35         return [ConvertSlice]
36
37     def pattern(self):
38         return dict(
39             nodes=[('strided_slice', dict(kind='op', op='StridedSlice'))],
40             edges=[]
41         )
42
43     def replace_pattern(self, graph: nx.MultiDiGraph, match: dict):
44         output_data_node = match['strided_slice'].out_node(0)
45         input_data_node = match['strided_slice'].in_node(0)
46         if np.array_equal(input_data_node.shape, output_data_node.shape) and \
47                 all(elem.step == 1 for elem in match['strided_slice'].slices):
48             log.info("Useless StridedSlice op '{}' has been detected".format(match['strided_slice'].id))
49             # remove inputs to Strided Slice so it has just one input with data so we can use 'erase_node' function
50             graph.remove_edge(match['strided_slice'].in_node(1).id, match['strided_slice'].id)
51             graph.remove_edge(match['strided_slice'].in_node(2).id, match['strided_slice'].id)
52             graph.remove_edge(match['strided_slice'].in_node(3).id, match['strided_slice'].id)
53
54             erase_node(match['strided_slice'])
55             erase_node(output_data_node)