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 div rounding_mode="trunc" and support aten::trunc (#38753)
Muhammad Usman Mateen01aef77b9ba5
diff --git a/src/frontends/pytorch/src/op/div.cpp b/src/frontends/pytorch/src/op/div.cppindex 1d1ef139af2..8b3162a48a2 100644--- a/src/frontends/pytorch/src/op/div.cpp+++ b/src/frontends/pytorch/src/op/div.cpp@@ -41,14 +41,14 @@ OutputVector translate_div_common(const NodeContext& context,is_python_scalar_input(context, 0),is_python_scalar_input(context, 1));}- auto res = context.mark_node(std::make_shared<v1::Divide>(x, y, true));+ // Without python division, integer division already rounds toward zero, as "trunc" requires.+ auto res = context.mark_node(std::make_shared<v1::Divide>(x, y, rounding_mode != "trunc"));// TODO: ticket 103296; Temporarily disable ConvertDivide transformationdisable_divide_conversion(res);if (rounding_mode == "floor") {res = context.mark_node(std::make_shared<v0::Floor>(res));} else if (rounding_mode == "trunc") {- const auto convert = context.mark_node(std::make_shared<v0::Convert>(res, element::i32));- res = context.mark_node(std::make_shared<v1::ConvertLike>(convert, x));+ res = trunc_toward_zero(context, res).get_node_shared_ptr();}if (inplace)context.mutate_input(0, res);diff --git a/src/frontends/pytorch/src/op/trunc.cpp b/src/frontends/pytorch/src/op/trunc.cppnew file mode 100644index 00000000000..6a57bd35eab--- /dev/null+++ b/src/frontends/pytorch/src/op/trunc.cpp@@ -0,0 +1,17 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/frontend/pytorch/node_context.hpp"+#include "utils.hpp"++namespace ov::frontend::pytorch::op {++OutputVector translate_trunc(const NodeContext& context) {+ // aten::trunc(Tensor self) -> Tensor+ // aten::trunc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)+ num_inputs_check(context, 1, 2);+ return {trunc_toward_zero(context, context.get_input(0))};+};++} // namespace ov::frontend::pytorch::opdiff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cppindex c80dd622646..857b61db311 100644--- a/src/frontends/pytorch/src/op_table.cpp+++ b/src/frontends/pytorch/src/op_table.cpp@@ -278,6 +278,7 @@ OP_CONVERTER(translate_transformer_encoder_layer_fwd);OP_CONVERTER(translate_transpose);OP_CONVERTER(translate_tril);OP_CONVERTER(translate_triu);+OP_CONVERTER(translate_trunc);OP_CONVERTER(translate_type_as);OP_CONVERTER(translate_tuple_index);OP_CONVERTER(translate_tuple_unpack);@@ -779,6 +780,8 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::transpose", op::quantizable_op<op::translate_transpose>},{"aten::tril", op::translate_tril},{"aten::triu", op::translate_triu},+ {"aten::trunc", op::optional_out<op::translate_trunc, 1>},+ {"aten::trunc_", op::inplace_op<op::translate_trunc>},{"aten::type_as", op::translate_type_as},// aten::unbind - Supported in limited set of patterns{"aten::unflatten", op::translate_unflatten},diff --git a/src/frontends/pytorch/src/utils.cpp b/src/frontends/pytorch/src/utils.cppindex 6813cd41f22..322bae11d7a 100644--- a/src/frontends/pytorch/src/utils.cpp+++ b/src/frontends/pytorch/src/utils.cpp@@ -12,12 +12,15 @@#include "openvino/frontend/sequence_mark.hpp"#include "openvino/op/add.hpp"#include "openvino/op/broadcast.hpp"+#include "openvino/op/ceiling.hpp"#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/convert_promote_types.hpp"#include "openvino/op/divide.hpp"+#include "openvino/op/floor.hpp"#include "openvino/op/gather.hpp"#include "openvino/op/gather_nd.hpp"+#include "openvino/op/less.hpp"#include "openvino/op/logical_not.hpp"#include "openvino/op/loop.hpp"#include "openvino/op/matmul.hpp"@@ -681,6 +684,15 @@ Output<Node> get_input_with_floating_type(const NodeContext& context, size_t idxreturn x;}+Output<Node> trunc_toward_zero(const NodeContext& context, const Output<Node>& x) {+ auto zero = context.mark_node(v0::Constant::create(element::i32, Shape{}, {0}));+ zero = context.mark_node(std::make_shared<v1::ConvertLike>(zero, x));+ auto is_negative = context.mark_node(std::make_shared<v1::Less>(x, zero));+ auto ceil = context.mark_node(std::make_shared<v0::Ceiling>(x));+ auto floor = context.mark_node(std::make_shared<v0::Floor>(x));+ return context.mark_node(std::make_shared<v1::Select>(is_negative, ceil, floor));+}+Output<Node> get_input_as_i32(const NodeContext& context, size_t idx) {auto x = context.get_input(static_cast<int>(idx));// Handle SequenceMark (list construct) - concatenate elementsdiff --git a/src/frontends/pytorch/src/utils.hpp b/src/frontends/pytorch/src/utils.hppindex 7f2278f9e3d..9a64ca27e74 100644--- a/src/frontends/pytorch/src/utils.hpp+++ b/src/frontends/pytorch/src/utils.hpp@@ -154,6 +154,9 @@ Output<Node> try_constfold(const Output<Node>& x);Output<Node> get_input_with_floating_type(const NodeContext& context, size_t idx);+/// \brief Rounds toward zero, keeping infinities and NaN. Integer inputs are returned unchanged.+Output<Node> trunc_toward_zero(const NodeContext& context, const Output<Node>& x);+Output<Node> get_input_as_i32(const NodeContext& context, size_t idx);Output<Node> get_input_concat_if_list(const NodeContext& context, size_t idx);diff --git a/tests/layer_tests/pytorch_tests/test_div.py b/tests/layer_tests/pytorch_tests/test_div.pyindex d9b99bfd914..3178c9cf62f 100644--- a/tests/layer_tests/pytorch_tests/test_div.py+++ b/tests/layer_tests/pytorch_tests/test_div.py@@ -51,6 +51,56 @@ class TestDiv(PytorchLayerTest):ie_device, precision, ir_version, use_convert_model=True)+class TestDivTrunc(PytorchLayerTest):+ def _prepare_input(self):+ return (self.input_array, self.other_array)++ def create_model(self):+ class aten_div(torch.nn.Module):+ def forward(self, input_tensor, other_tensor):+ return torch.div(input_tensor, other_tensor, rounding_mode="trunc")++ return aten_div(), "aten::div"++ @pytest.mark.parametrize(("input_array", "other_array"), [+ # quotients outside the i32 range, infinities and NaN+ [np.array([1e10, -1e10, 3e9, np.inf, -np.inf, np.nan, -7.5, 0.5], dtype=np.float32),+ np.array([3, 3, 1, 2, 2, 1, 2, -2], dtype=np.float32)],+ [np.array([-7, 7, -9, 9, -1], dtype=np.int64),+ np.array([2, -2, 4, 4, 3], dtype=np.int64)],+ ])+ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.precommit_torch_export+ def test_div_trunc(self, input_array, other_array, ie_device, precision, ir_version):+ if precision == "FP16" and input_array.dtype == np.float32:+ pytest.skip("Values exceed the f16 range")+ self.input_array = input_array+ self.other_array = other_array+ self._test(*self.create_model(), ie_device, precision, ir_version)+++class TestDivTruncConstant(PytorchLayerTest):+ def _prepare_input(self):+ return (np.zeros(3, dtype=np.int64),)++ def create_model(self):+ class aten_div(torch.nn.Module):+ def forward(self, x):+ a = torch.tensor([-7, 7, -9])+ b = torch.tensor([2, -2, 4])+ return torch.div(a, b, rounding_mode="trunc") + x++ return aten_div(), "aten::div"++ @pytest.mark.nightly+ @pytest.mark.precommit+ @pytest.mark.precommit_torch_export+ def test_div_trunc_constant(self, ie_device, precision, ir_version):+ # Constant folding follows the Divide spec, so the division must not use python division here+ self._test(*self.create_model(), ie_device, precision, ir_version, freeze_model=False)++class TestDivTypes(PytorchLayerTest):def _prepare_input(self):diff --git a/tests/layer_tests/pytorch_tests/test_unary_ops.py b/tests/layer_tests/pytorch_tests/test_unary_ops.pyindex 53796a6f6d2..33997a1e2f2 100644--- a/tests/layer_tests/pytorch_tests/test_unary_ops.py+++ b/tests/layer_tests/pytorch_tests/test_unary_ops.py@@ -29,6 +29,8 @@ OPS = {"aten::ceil_": torch.ceil_,"aten::floor": torch.floor,"aten::floor_": torch.floor_,+ "aten::trunc": torch.trunc,+ "aten::trunc_": torch.trunc_,"aten::sigmoid": torch.sigmoid,"aten::sigmoid_": torch.sigmoid_,"aten::reciprocal": torch.reciprocal,@@ -169,6 +171,8 @@ class TestUnaryOp(PytorchLayerTest):"aten::ceil_","aten::floor","aten::floor_",+ "aten::trunc",+ "aten::trunc_","aten::sigmoid","aten::reciprocal","aten::log",@@ -262,6 +266,7 @@ class TestUnaryOp(PytorchLayerTest):"aten::relu","aten::ceil","aten::floor",+ "aten::trunc","aten::sigmoid","aten::reciprocal","aten::log",