Files
openvino/model-optimizer/extensions/back/CropToStridedSlice.py
T
Pavel Esir 22169a05b9 [MO] StridedSlice improvements (#4139)
* fix ss

* successfully converted

* successfully run moved infer and normalizer unit-tests

* successfully rewritten StridedSlice infer unittests

* int64 array

* Successfully converter crash-when-loading, xj_feauture and toy nets (cherry-picked maxpoolV4 and tf_broadcast_ext)

* successfully moved PermuteAttrs to general mechanism

* successfully converted xj_feauture and crash when loading with the new rewritten SS infer

* fixed get_shape_from_slice and moved to common utils

* fixed extending masks and some other

* some refactoring

* fixed extending masks in extractor, fixed licence year and some other code clearing

* corrected a couple of unittests

* fox permute for 5 rank slice and 4 rank inputs/

* WIP

* Added comments

* fixed StridedSlice in ProposalMutation.py

* rechecked shape_infer unittests added some new cases

* added shape_infer unit-tests after StridedSliceNormalizer pass and Permute unit-tests

* corrected unittests

* Applied review comments

* general permutations for inputs implemented, corrected ellipsis unrolling when shrink_axis is at the beginning, some other corrections

* removed code duplication in infer and normalizer, moved 'slices' attr normalizing to StridedSliceNormalizer.py

* removed some code duplication and other minor improvements

* Added tests

* minor corrections

* wider range of unittests added (froze the number)

* review comments applied

* enabled skipped unit-test

* comment corrections

* applied review comments: changed op -> type, added some asserts, corrected comments and other minor corrections

* sorted inputs, updated Supported_Frameworks_Layers.md, some minor
2021-02-16 11:48:49 +03:00

128 lines
5.5 KiB
Python

"""
Copyright (C) 2018-2021 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import numpy as np
from extensions.back.ForceStrictPrecision import ForceStrictPrecision
from extensions.ops.elementwise import Add
from mo.back.replacement import BackReplacementPattern
from mo.front.common.partial_infer.utils import int64_array
from mo.graph.graph import Graph, Node
from mo.ops.const import Const
from mo.ops.shape import Shape
from mo.ops.strided_slice import StridedSlice
class CropToStridedSlice(BackReplacementPattern):
enabled = True
force_clean_up = True
def run_before(self):
return [ForceStrictPrecision]
@staticmethod
def pattern():
return dict(
nodes=[
('crop', dict(type='Crop'))
],
edges=[]
)
@staticmethod
def mask_normalizer(shape_rank: int, axes: np.ndarray, values: np.ndarray):
mask = np.zeros(shape_rank, dtype=np.int64)
for i, axis in enumerate(axes):
mask[axis] = values[i]
return mask
@staticmethod
def list_to_ndarray(val):
return np.array(val) if np.array(val).ndim != 0 else np.array([val])
def replace_pattern(self, graph: Graph, match: [str, Node]):
node = match['crop']
assert node.has_valid('axis')
node_axis = self.list_to_ndarray(node.axis)
in_shape = node.in_port(0).data.get_shape()
shape_rank = in_shape.size
axis_mask = int64_array([1 if i in node_axis else 0 for i in range(shape_rank)])
begin_mask = axis_mask.copy()
end_mask = axis_mask.copy()
ss = StridedSlice(graph, {'name': node.soft_get('name', node.id) + '/strided_slice', 'begin_mask': begin_mask,
'end_mask': end_mask,
'new_axis_mask': np.zeros(len(end_mask)),
'shrink_axis_mask': np.zeros(len(end_mask)),
'ellipsis_mask': np.zeros(len(end_mask))}).create_node()
if len(node.in_nodes()) == 2 and node.has_valid('offset'):
# Crop Type 1
begin = Const(graph, {'value': self.mask_normalizer(shape_rank, node_axis, node.offset),
'name': ss.name + '/begin'}).create_node()
shape = Shape(graph, {'name': ss.name + '/shape_of_crop'}).create_node()
end = Add(graph, {'name': ss.name + '/end'}).create_node()
node.in_port(1).get_connection().get_source().connect(shape.in_port(0))
node.in_port(1).disconnect()
shape.out_port(0).connect(end.in_port(0))
begin.out_port(0).connect(end.in_port(1))
elif node.has_valid('dim') and node.has_valid('offset'):
# Crop Type 2
node_dim = self.list_to_ndarray(node.dim)
node_offset = self.list_to_ndarray(node.offset)
assert node_dim.size == node_offset.size == node_axis.size
begin = Const(graph, {'value': self.mask_normalizer(shape_rank, node_axis, node_offset),
'name': ss.name + '/begin'}).create_node()
end_values = np.array([node_offset[i] + node_dim[i] for i in range(len(node_dim))])
end = Const(graph, {'value': self.mask_normalizer(shape_rank, node_axis, end_values),
'name': ss.name + '/end'}).create_node()
elif node.has_valid('crop_begin') and node.has_valid('crop_end'):
# Crop Type 3
node_crop_begin = self.list_to_ndarray(node.crop_begin)
node_crop_end = self.list_to_ndarray(node.crop_end)
assert len(node_crop_begin) == len(node_crop_end) == len(node_axis)
begin = Const(graph, {'value': self.mask_normalizer(shape_rank, node_axis, node_crop_begin),
'name': ss.name + '/begin'}).create_node()
shape = Shape(graph, {'name': ss.name + '/shape'}).create_node()
end = Add(graph, {'name': ss.name + '/end'}).create_node()
const = Const(graph, {'value': -1 * self.mask_normalizer(shape_rank, node_axis, node_crop_end),
'name': ss.name + '/const'}).create_node()
node.in_port(0).get_connection().get_source().connect(shape.in_port(0))
shape.out_port(0).connect(end.in_port(0))
const.out_port(0).connect(end.in_port(1))
else:
raise Exception("Unknown type of Crop")
source = node.in_port(0).get_connection().get_source()
stride = Const(graph, {'value': np.ones(shape_rank, dtype=np.int64),
'name': ss.name + '/stride'}).create_node()
source.connect(ss.in_port(0))
begin.out_port(0).connect(ss.in_port(1))
end.out_port(0).connect(ss.in_port(2))
stride.out_port(0).connect(ss.in_port(3))
node.in_port(0).disconnect()
node.out_port(0).get_connection().set_source(ss.out_port(0))
ss['force_precision_in_ports'] = {1: 'int64', 2: 'int64', 3: 'int64'}