Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / middle / SliceConverter.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.const import Const
22 from mo.ops.crop import Crop
23 from mo.ops.strided_slice import StridedSlice
24
25
26 def convert_negative_indices(indices: np.array, shape: np.array):
27     for ind, value in enumerate(indices):
28         if value < 0:
29             indices[ind] += shape[ind]
30
31
32 class ConvertSlice(MiddleReplacementPattern):
33     """
34     This class convert Slice operation to Crop or Split depends on parameters
35     """
36
37     enabled = True
38     op = "Slice"
39
40     def run_after(self):
41         from extensions.middle.pass_separator import MiddleStart
42         return [MiddleStart]
43
44     def pattern(self):
45         return dict(
46             nodes=[
47                 ('slice', dict(kind='op', op='Slice'))
48             ],
49             edges=[]
50         )
51
52     def replace_pattern(self, graph: Graph, match: dict):
53         node = match['slice']
54         # Caffe case
55         if not node.has_valid('start') or not node.has_valid('end'):
56             return
57
58         begin = node.start
59         end = node.end
60         axis = node.axis if node.has_valid('axis') else range(begin.size)
61         
62
63         input = node.in_node(0)
64         output_data = node.out_node()
65
66         # Check whether operation use only one axis or not
67         axes_begin = np.zeros(len(input.shape), dtype=np.int32)
68         axes_end = np.zeros(len(input.shape), dtype=np.int32)
69         begin_ext = np.zeros(len(input.shape), dtype=np.int32)
70         end_ext = np.zeros(len(input.shape), dtype=np.int32)
71         dims = 0
72         axes = np.zeros(begin.size)
73         for i in range(len(axis)):
74             if begin[i] != 0 or end[i] < input.shape[i]:
75                 dims += 1
76                 axes[i] = 1
77                 if begin[i] != 0:
78                     axes_begin[axis[i]] = 1
79                     begin_ext[axis[i]] = begin[i]
80                 if end[i] < input.shape[i]:
81                     axes_end[axis[i]] = 1
82                     end_ext[axis[i]] = end[i]
83         axes = np.array(axes, dtype=bool)
84
85         if dims == 1 or dims == 0:
86             # If Slice use only one axis or no axis, than
87             # convert Slice to StridedSlice
88             ss = StridedSlice(graph, dict(new_axis_mask=np.zeros(len(output_data.shape), dtype=np.int32),
89                                           shrink_axis_mask=np.zeros(len(output_data.shape), dtype=np.int32),
90                                           ellipsis_mask=np.zeros(len(output_data.shape), dtype=np.int32),
91                                           begin_mask=axes_begin,
92                                           end_mask=axes_end))
93
94             convert_negative_indices(begin_ext, input.shape)
95             convert_negative_indices(end_ext, input.shape)
96
97             begin_node = Const(graph, {'name': 'begin', 'value': begin_ext, 'force_precision': 'I32'}).create_node_with_data()
98             end_node = Const(graph, {'name': 'end', 'value': end_ext, 'force_precision': 'I32'}).create_node_with_data()
99
100             ss.create_node_with_data(inputs=[input, begin_node, end_node], data_nodes=[output_data])
101             # Remove unnecessary edges from and to to Slice vertex
102             graph.remove_edge(input.id, node.id)
103             graph.remove_edge(node.id, output_data.id)
104         else:
105             # If Slice use more than one axis use Crop layer
106             crop = Crop(graph, dict(axis=np.arange(begin.size)[axes],
107                                     offset=begin[axes]))
108             # creating node with data
109             crop.create_node_with_data(inputs=[input], data_nodes=[output_data])
110
111             # Remove unnecessary edges from and to to Slice vertex
112             graph.remove_edge(input.id, node.id)
113             graph.remove_edge(node.id, output_data.id)