OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[PT FE] Fix aten::arange defult dtype (#32425)
Maxim Vafinfb4a025db9e9
diff --git a/src/frontends/pytorch/src/op/arange.cpp b/src/frontends/pytorch/src/op/arange.cppindex e20d8171053..79302b84496 100644--- a/src/frontends/pytorch/src/op/arange.cpp+++ b/src/frontends/pytorch/src/op/arange.cpp@@ -18,13 +18,49 @@ namespace op {using namespace ov::op;+namespace {+OutputVector make_arange(const NodeContext& context,+ const Output<Node>& start,+ const Output<Node>& end,+ const Output<Node>& step,+ const element::Type& dtype,+ const Output<Node>& ref_tensor = {}) {+ auto range_dtype = element::i64;+ auto is_real_tensor = [](const auto& o) {+ return o.get_element_type().is_real();+ };+ auto is_dynamic_tensor = [](const auto& o) {+ return o.get_element_type().is_dynamic();+ };+ if ((dtype.is_dynamic() || dtype.is_real()) &&+ (is_real_tensor(start) || is_real_tensor(end) || is_real_tensor(step))) {+ range_dtype = element::f32;+ }+ if (is_dynamic_tensor(start) || is_dynamic_tensor(end) || is_dynamic_tensor(step)) {+ // use f32 in dynamic case+ range_dtype = element::f32;+ }+ if (ref_tensor.get_node_shared_ptr() && ref_tensor.get_element_type().is_static() &&+ ref_tensor.get_element_type().is_integral()) {+ // target type is integer, so use int Range+ range_dtype = element::i64;+ }+ auto range = context.mark_node(std::make_shared<v4::Range>(start, end, step, range_dtype));+ if (ref_tensor.get_node_shared_ptr()) {+ range = context.mark_node(std::make_shared<v1::ConvertLike>(range, ref_tensor));+ } else if (dtype != range_dtype && dtype.is_static()) {+ range = context.mark_node(std::make_shared<v0::Convert>(range, dtype));+ }+ return {std::move(range)};+}+} // namespace+OutputVector translate_arange(const NodeContext& context) {- auto zero = context.mark_node(v0::Constant::create(element::i32, Shape{}, {0}));- auto one = context.mark_node(v0::Constant::create(element::i32, Shape{}, {1}));+ const auto zero = context.mark_node(v0::Constant::create(element::i32, Shape{}, {0}));+ const auto one = context.mark_node(v0::Constant::create(element::i32, Shape{}, {1}));int dtype_port = -1;- auto dtype = element::f32;- bool dtype_applied = false;- auto num_inputs = context.get_input_size();+ auto dtype = element::dynamic;+ const auto num_inputs = context.get_input_size();ov::Output<Node> end;ov::Output<Node> out_tensor;ov::Output<Node> start = zero;@@ -33,54 +69,62 @@ OutputVector translate_arange(const NodeContext& context) {if (num_inputs == 2) {// aten::arange(Scalar end, tensor out)end = context.get_input(0);- out_tensor = context.input_is_none(1) ? end : context.get_input(1);+ if (!context.input_is_none(1)) {+ out_tensor = context.get_input(1);+ }} else if (num_inputs == 4) {// aten::arange(Scalar start, Scalar end, Scalar step, Tensor out)start = context.get_input(0);end = context.get_input(1);step = context.get_input(2);- out_tensor = context.input_is_none(3) ? end : context.get_input(3);+ if (!context.input_is_none(3)) {+ out_tensor = context.get_input(3);+ }} else if (num_inputs == 5) {// aten::arange(Scalar end, ScalarType dtype, Layout, Device, bool pin_memory)end = context.get_input(0);- out_tensor = end;- dtype_port = 1;+ if (!context.input_is_none(1)) {+ dtype_port = 1;+ }} else if (num_inputs == 6) {// aten::arange(Scalar start, Scalar end, ScalarType dtype, Layout, Device, bool pin_memory)start = context.get_input(0);end = context.get_input(1);- out_tensor = end;dtype_port = 2;- dtype_applied = true;} else if (num_inputs == 7) {// aten::arange(Scalar start, Scalar end, Scalar step, ScalarType dtype, Layout, Device, bool pin_memory)start = context.get_input(0);end = context.get_input(1);step = context.get_input(2);- out_tensor = end;dtype_port = 3;- dtype_applied = true;} else {PYTORCH_OP_CONVERSION_CHECK(false, "Not expected number of inputs for ", context.get_op_type());}- if (dtype_port >= 0 && !context.input_is_none(dtype_port)) {- if (ov::as_type_ptr<v0::Constant>(context.get_input_from_visible_context(dtype_port).get_node_shared_ptr())) {- dtype = convert_dtype(context.const_input<int64_t>(dtype_port));- dtype_applied = true;- } else if (const auto& fw_node =- cast_fw_node(context.get_input(dtype_port).get_node_shared_ptr(), "prim::dtype")) {- out_tensor = fw_node->input_value(0);- dtype_applied = false;+ if (!out_tensor.get_node_shared_ptr() && dtype_port >= 0) {+ if (context.input_is_none(dtype_port)) {+ // dtype=None and not provided behave differently, so we rely on output type if we can+ const auto dtype_val = simplified_type_interpret(context.get_output_type(0));+ if (dtype_val.is<element::Type>()) {+ dtype = dtype_val.as<element::Type>();+ }+ if (dtype.is_dynamic()) {+ // convert to default torch dtype (see torch.get_default_dtype())+ dtype = element::f32;+ }} else {- PYTORCH_OP_CONVERSION_CHECK(false, "Couldn't get dtype input");+ if (ov::as_type_ptr<v0::Constant>(+ context.get_input_from_visible_context(dtype_port).get_node_shared_ptr())) {+ dtype = convert_dtype(context.const_input<int64_t>(dtype_port));+ } else if (const auto& fw_node =+ cast_fw_node(context.get_input(dtype_port).get_node_shared_ptr(), "prim::dtype")) {+ out_tensor = fw_node->input_value(0);+ } else {+ PYTORCH_OP_CONVERSION_CHECK(false, "Couldn't get dtype input");+ }}}- auto range = context.mark_node(std::make_shared<v4::Range>(start, end, step, dtype));- if (!dtype_applied) {- range = context.mark_node(std::make_shared<v1::ConvertLike>(range, out_tensor));- }- return {range};-};+ return make_arange(context, start, end, step, dtype, out_tensor);+}OutputVector translate_arange_fx(const NodeContext& context) {auto zero = context.mark_node(v0::Constant::create(element::i32, Shape{}, {0}));@@ -92,8 +136,8 @@ OutputVector translate_arange_fx(const NodeContext& context) {ov::Output<Node> step = one;if (num_inputs == 1) {- // arange = torch.ops.aten.arange.default(_local_scalar_dense, dtype = torch.int8, device = device(type='cpu'),- // pin_memory = False);+ // arange = torch.ops.aten.arange.default(_local_scalar_dense, dtype = torch.int8, device =+ // device(type='cpu'), pin_memory = False);end = context.get_input(0);} else if (num_inputs == 2) {start = context.get_input(0);diff --git a/tests/layer_tests/pytorch_tests/test_arange.py b/tests/layer_tests/pytorch_tests/test_arange.pyindex bba8257781c..992c56778cc 100644--- a/tests/layer_tests/pytorch_tests/test_arange.py+++ b/tests/layer_tests/pytorch_tests/test_arange.py@@ -2,11 +2,199 @@# SPDX-License-Identifier: Apache-2.0import pytest+import numpy as npfrom pytorch_layer_test_class import PytorchLayerTest, skip_check, skip_if_export+import torchclass TestArange(PytorchLayerTest):+ def _prepare_input(self, start=None, end=None, step=None, ref_value=None, out=None):+ args = tuple(a for a in [start, end, step,+ ref_value, out] if a is not None)+ return args++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("end", [np.array(1), np.array(2), np.array(3.)])+ def test_arange_end(self, ie_device, precision, ir_version, end):+ class aten_arange_end(torch.nn.Module):+ def forward(self, end):+ return torch.arange(end)++ self._test(aten_arange_end(), None, "aten::arange",+ ie_device, precision, ir_version, trace_model=True,+ kwargs_to_prepare_input={"end": end})++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("end", [np.array(1), np.array(2), np.array(3.)])+ @pytest.mark.parametrize("dtype", [None, torch.float32, torch.float64,+ torch.int8, torch.int32, torch.int64])+ def test_arange_end_dtype(self, ie_device, precision, ir_version, end, dtype):+ class aten_arange_end_dtype(torch.nn.Module):+ def __init__(self, dtype):+ super().__init__()+ self.dtype = dtype++ def forward(self, end):+ return torch.arange(end, dtype=self.dtype)++ self._test(aten_arange_end_dtype(dtype), None, "aten::arange",+ ie_device, precision, ir_version, trace_model=True,+ kwargs_to_prepare_input={"end": end})++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("end", [np.array(1), np.array(2), np.array(3.)])+ @pytest.mark.parametrize("dtype", [torch.float32, torch.float64,+ torch.int8, torch.int32, torch.int64])+ def test_arange_end_prim_dtype(self, ie_device, precision, ir_version, end, dtype):+ class aten_arange_end_prim_dtype(torch.nn.Module):+ def forward(self, end, ref):+ return torch.arange(end, dtype=ref.dtype)++ self._test(aten_arange_end_prim_dtype(), None, ["aten::arange", "prim::dtype"],+ ie_device, precision, ir_version,+ kwargs_to_prepare_input={"end": end,+ "ref_value": torch.tensor(1, dtype=dtype).numpy()})++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("start,end", [(np.array(0), np.array(1)),+ (np.array(-1), np.array(1)),+ (np.array(0.4), np.array(2.4)),+ (np.array(16777215), np.array(16777247))])+ def test_arange_start_end(self, ie_device, precision, ir_version, start, end):+ class aten_arange_start_end(torch.nn.Module):+ def forward(self, start, end):+ return torch.arange(start, end)++ self._test(aten_arange_start_end(), None, "aten::arange",+ ie_device, precision, ir_version, trace_model=True,+ kwargs_to_prepare_input={"start": start, "end": end})++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("start,end", [(np.array(0), np.array(1)),+ (np.array(-1), np.array(1)),+ (np.array(0.4), np.array(2.4)),+ (np.array(16777215), np.array(16777247))])+ @pytest.mark.parametrize("dtype", [None, torch.float32, torch.float64,+ torch.int8, torch.int32, torch.int64])+ def test_arange_start_end_dtype(self, ie_device, precision, ir_version, start, end, dtype):+ if dtype == torch.int8 and start > 127:+ pytest.skip("int8 range is not supported in openvino")++ class aten_arange_start_end_dtype(torch.nn.Module):+ def __init__(self, dtype):+ super().__init__()+ self.dtype = dtype++ def forward(self, start, end):+ return torch.arange(start, end, dtype=self.dtype)++ self._test(aten_arange_start_end_dtype(dtype), None, "aten::arange",+ ie_device, precision, ir_version, trace_model=True,+ kwargs_to_prepare_input={"start": start, "end": end})++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("start,end", [+ (np.array(0), np.array(1)),+ (np.array(-1), np.array(1)),+ (np.array(0.4), np.array(2.4)),+ pytest.param(np.array(16777215), np.array(16777247), marks=pytest.mark.xfail(reason="unsupported for dynamic case"))])+ @pytest.mark.parametrize("dtype", [torch.float32, torch.float64,+ torch.int8, torch.int32, torch.int64])+ def test_arange_start_end_prim_dtype(self, ie_device, precision, ir_version, start, end, dtype):+ if dtype == torch.int8 and start > 127:+ pytest.skip("int8 range is not supported in openvino")++ class aten_arange_start_end_prim_dtype(torch.nn.Module):+ def forward(self, start, end, ref):+ return torch.arange(start, end, dtype=ref.dtype)++ self._test(aten_arange_start_end_prim_dtype(), None, ["aten::arange", "prim::dtype"],+ ie_device, precision, ir_version,+ kwargs_to_prepare_input={"start": start, "end": end,+ "ref_value": torch.tensor(1, dtype=dtype).numpy()})++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("start,end,step", [+ (np.array(0), np.array(1), np.array(1)),+ (np.array(-2), np.array(1), np.array(1.25)),+ (np.array(1), np.array(-5), np.array(-1)),+ (np.array(1), np.array(10), np.array(2)),+ (np.array(-1), np.array(-5), np.array(-2)),+ (np.array(16777215), np.array(16777247), np.array(1))])+ def test_arange_start_end_step(self, ie_device, precision, ir_version, start, end, step):+ class aten_arange_start_end_step(torch.nn.Module):+ def forward(self, start, end, step):+ return torch.arange(start, end, step)++ self._test(aten_arange_start_end_step(), None, "aten::arange",+ ie_device, precision, ir_version, trace_model=True,+ kwargs_to_prepare_input={"start": start, "end": end, "step": step})++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("start,end,step", [+ (np.array(0), np.array(1), np.array(1)),+ (np.array(-2), np.array(1), np.array(1.25)),+ (np.array(1), np.array(-5), np.array(-1)),+ (np.array(1), np.array(10), np.array(2)),+ (np.array(-1), np.array(-5), np.array(-2)),+ (np.array(16777215), np.array(16777247), np.array(1))])+ @pytest.mark.parametrize("dtype", [None, torch.float32, torch.float64,+ torch.int8, torch.int32, torch.int64])+ def test_arange_start_end_step_dtype(self, ie_device, precision, ir_version,+ start, end, step, dtype):+ if dtype == torch.int8 and start > 127:+ pytest.skip("int8 range is not supported in openvino")++ class aten_arange_start_end_step_dtype(torch.nn.Module):+ def __init__(self, dtype):+ super().__init__()+ self.dtype = dtype++ def forward(self, start, end, step):+ return torch.arange(start, end, step, dtype=self.dtype)++ self._test(aten_arange_start_end_step_dtype(dtype), None, "aten::arange",+ ie_device, precision, ir_version, trace_model=True,+ kwargs_to_prepare_input={"start": start, "end": end, "step": step})++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.parametrize("start,end,step", [+ (np.array(0), np.array(1), np.array(1)),+ (np.array(-2), np.array(1), np.array(1.25)),+ (np.array(1), np.array(-5), np.array(-1)),+ (np.array(1), np.array(10), np.array(2)),+ (np.array(-1), np.array(-5), np.array(-2)),+ pytest.param(np.array(16777215), np.array(16777247), np.array(1), marks=pytest.mark.xfail(reason="unsupported for dynamic case"))])+ @pytest.mark.parametrize("dtype", [torch.float32, torch.float64,+ torch.int8, torch.int32, torch.int64])+ def test_arange_start_end_step_prim_dtype(self, ie_device, precision, ir_version,+ start, end, step, dtype):+ class aten_arange_start_end_step_prim_dtype(torch.nn.Module):+ def __init__(self, dtype):+ super().__init__()+ self.dtype = dtype++ def forward(self, start, end, step, ref):+ ref = ref.to(self.dtype)+ return torch.arange(start, end, step, dtype=ref.dtype)++ self._test(aten_arange_start_end_step_prim_dtype(dtype), None, ["aten::arange", "prim::dtype"],+ ie_device, precision, ir_version,+ kwargs_to_prepare_input={"start": start, "end": end, "step": step,+ "ref_value": torch.tensor(1, dtype=dtype).numpy()})+++class TestArangeLegacy(PytorchLayerTest):def _prepare_input(self, end, start=None, step=None, dtype="int64", ref_dtype=None):import numpy as npif start is None and step is None:@@ -120,7 +308,7 @@ class TestArange(PytorchLayerTest):@pytest.mark.parametrize("use_out", [skip_check(True), False])def test_arange_end_only(self, dtype, end, use_out, ie_device, precision, ir_version):self._test(*self.create_model(dtype, 1, use_out), ie_device, precision, ir_version,- kwargs_to_prepare_input={"end": end})+ kwargs_to_prepare_input={"end": end}, trace_model=True)@pytest.mark.nightly@pytest.mark.parametrize("dtype", [None, "float32", "float64", "int32", "int64", "int8"])