Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[PT FE] Patch built-in functions such as divmod (#30067)

Roman Kazantsev6cdc048d71d1
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/patch_functions.py b/src/bindings/python/src/openvino/frontend/pytorch/patch_functions.py
new file mode 100644
index 00000000000..527e18e3cd2
--- /dev/null
+++ b/src/bindings/python/src/openvino/frontend/pytorch/patch_functions.py
@@ -0,0 +1,47 @@
+# -*- coding: utf-8 -*-
+# Copyright (C) 2018-2025 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+import builtins
+import torch
+from typing import Any, Tuple, Optional, Type
+
+originals_map = {
+ "divmod": builtins.divmod
+}
+
+
+def patched_divmod(lhs: Any, rhs: Any) -> Tuple[Any, Any]:
+ # TorchScript tracing outputs torch.Tensor for `x.shape[-1]` instead of scalar.
+ # For example, it leads to TypeError issue during tracing of `divmod(x.shape[-1], 5)`
+ # since builtin `divmod()` expects both scalar inputs.
+ # So the patch for `divmod` is required to adjust operands to scalar type
+ if isinstance(lhs, torch.Tensor):
+ lhs = lhs.item()
+ if isinstance(rhs, torch.Tensor):
+ rhs = rhs.item()
+ return originals_map["divmod"](lhs, rhs)
+
+
+patches_map = {
+ "divmod": patched_divmod,
+}
+
+
+class FunctionsPatcher:
+ """Patch different Python functions including built-in routines such as divmod().
+
+ For example, TorchScript is unable to trace divmod() with torch.Tensor input type.
+ """
+ def __enter__(self) -> None:
+ for name, new_fn in patches_map.items():
+ setattr(builtins, name, new_fn)
+
+ def __exit__(self,
+ exc_type: Optional[Type[BaseException]],
+ exc_val: Optional[BaseException],
+ exc_tb: Optional[Any]
+ ) -> None:
+ for name, _ in patches_map.items():
+ original_fn = originals_map[name]
+ setattr(builtins, name, original_fn)
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py
index e1b8ee9f29f..82649ca28b4 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/ts_decoder.py
@@ -26,6 +26,8 @@ from openvino.frontend.pytorch.utils import (
from openvino import opset11 as ops
from openvino.frontend.pytorch import quantized, patch_model
from openvino.frontend.pytorch.module_extension import ModuleExtension
+from openvino.frontend.pytorch.patch_functions import FunctionsPatcher
+
log = logging.getLogger(__name__)
@@ -167,8 +169,9 @@ class TorchScriptPythonDecoder(Decoder):
if trace_kwargs is None:
trace_kwargs = {}
try:
- scripted = torch.jit.trace(
- pt_module, **input_parameters, strict=False, **trace_kwargs)
+ with FunctionsPatcher():
+ scripted = torch.jit.trace(
+ pt_module, **input_parameters, strict=False, **trace_kwargs)
finally:
if patched:
quantized.unpatch_quantized(pt_module)
diff --git a/tests/layer_tests/pytorch_tests/test_divmod.py b/tests/layer_tests/pytorch_tests/test_divmod.py
new file mode 100644
index 00000000000..19d1bda06e3
--- /dev/null
+++ b/tests/layer_tests/pytorch_tests/test_divmod.py
@@ -0,0 +1,71 @@
+# Copyright (C) 2018-2025 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+import numpy.testing as npt
+import openvino as ov
+import pytest
+import torch
+
+
+# do not test via PytorchLayerTest since PytorchLayerTest triggers own TorchScript tracing
+# this test validates TorchScript patched inside ov.convert_model
+class TestBuiltinDivmod():
+ class divmod_on_assert_path(torch.nn.Module):
+ # test divmod() on assert path that is omitted in ov::Model
+ def forward(self, x):
+ divisor, rem = divmod(x.shape[-1], 7)
+ assert rem == 0, x.shape
+ assert divisor > 0 and (divisor & (divisor - 1)) == 0, (divisor, x.shape)
+ new_shape = tuple(x.shape[:-1]) + (-1, 7)
+ return x.reshape(new_shape)
+
+ class divmod_on_compute_path(torch.nn.Module):
+ # test divmod() on assert path that is omitted in ov::Model
+ def forward(self, x):
+ divisor, rem = divmod(x.shape[0], 5)
+ divisor = torch.tensor(divisor, dtype=torch.int32)
+ rem = torch.tensor(rem, dtype=torch.int32)
+ return divisor, rem
+
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ def test_divmod_on_assert_path(self, ie_device, precision):
+ fw_model = self.divmod_on_assert_path()
+ inputs = torch.randn(2, 3, 28)
+
+ example_input = inputs
+ ov_model = ov.convert_model(input_model=fw_model, example_input=example_input)
+ if ie_device == 'GPU' and precision == 'FP32':
+ config = {'INFERENCE_PRECISION_HINT': 'f32'}
+ else:
+ config = {}
+ compiled_model = ov.Core().compile_model(ov_model, ie_device, config)
+
+ fw_res = fw_model(example_input)
+ ov_res = compiled_model(example_input)[0]
+
+ npt.assert_allclose(fw_res.numpy(), ov_res)
+
+ @pytest.mark.parametrize("x_shape", [[1], [2], [3], [4], [5], [6]])
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ def test_divmod_on_compute_path(self, ie_device, precision, x_shape):
+ fw_model = self.divmod_on_compute_path()
+ x = torch.randn(x_shape)
+
+ example_input = x
+ ov_model = ov.convert_model(input_model=fw_model,
+ input=[ov.PartialShape([-1])],
+ example_input=example_input)
+
+ if ie_device == 'GPU' and precision == 'FP32':
+ config = {'INFERENCE_PRECISION_HINT': 'f32'}
+ else:
+ config = {}
+ compiled_model = ov.Core().compile_model(ov_model, ie_device, config)
+
+ fw_div, fw_rem = fw_model(example_input)
+ ov_res = compiled_model(example_input)
+ ov_div, ov_rem = ov_res[0], ov_res[1]
+ npt.assert_allclose(fw_div.numpy(), ov_div)
+ npt.assert_allclose(fw_rem.numpy(), ov_rem)