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
[OVC] Introduce torch.export in convert_model as non-default (#34471)
Maxim Vafin2908f218935e
diff --git a/docs/articles_en/openvino-workflow/model-preparation/convert-model-pytorch.rst b/docs/articles_en/openvino-workflow/model-preparation/convert-model-pytorch.rstindex 9a00aee059f..2a64976bffa 100644--- a/docs/articles_en/openvino-workflow/model-preparation/convert-model-pytorch.rst+++ b/docs/articles_en/openvino-workflow/model-preparation/convert-model-pytorch.rst@@ -198,6 +198,58 @@ Here is an example of how to convert a model obtained with ``torch.export``:exported_model = export(model, (torch.randn(1, 3, 224, 224),))ov_model = convert_model(exported_model)+Using the ``dynamo`` parameter+++++++++++++++++++++++++++++++++Instead of calling ``torch.export.export`` manually, you can pass ``dynamo=True`` to+``openvino.convert_model`` and it will use ``torch.export`` internally. This approach+requires ``example_input`` and PyTorch >= 2.6:++.. code-block:: py+ :force:++ import torch+ import openvino as ov+ from torchvision.models import resnet50, ResNet50_Weights++ model = resnet50(weights=ResNet50_Weights.DEFAULT)+ model.eval()+ ov_model = ov.convert_model(model, example_input=torch.randn(1, 3, 224, 224), dynamo=True)++By default, the exported model has fully static shapes taken from ``example_input``.+To make certain dimensions dynamic, combine ``dynamo=True`` with the ``input`` parameter.+Dimensions marked as ``-1`` become dynamic, while fixed values remain static:++.. code-block:: py+ :force:++ from openvino import PartialShape++ # Only the batch dimension is dynamic+ ov_model = ov.convert_model(+ model,+ example_input=torch.randn(1, 3, 224, 224),+ dynamo=True,+ input=PartialShape([-1, 3, 224, 224]),+ )++You can also specify constrained dimensions using ``Dimension`` with min/max bounds.+This maps to ``torch.export.Dim`` with explicit constraints, enabling tighter shape+validation during export:++.. code-block:: py+ :force:++ from openvino import Dimension, PartialShape++ # Batch between 1 and 8, spatial dims between 128 and 512+ ov_model = ov.convert_model(+ model,+ example_input=torch.randn(1, 3, 224, 224),+ dynamo=True,+ input=PartialShape([Dimension(1, 8), 3, Dimension(128, 512), Dimension(128, 512)]),+ )+Converting a PyTorch Model from Disk####################################diff --git a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.pyindex 976d7e89251..bb59e003d23 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py@@ -263,7 +263,9 @@ class TorchFXPythonDecoder (BaseFXDecoder):self.input_types.append(BaseFXDecoder.get_type_for_value(arg))@classmethod- def from_exported_program(cls, exported_program: torch.export.ExportedProgram) -> "TorchFXPythonDecoder":+ def from_exported_program(+ cls, exported_program: torch.export.ExportedProgram, dynamic_shapes=True+ ) -> "TorchFXPythonDecoder":"""Create a TorchFXPythonDecoder instance from an exported PyTorch program."""from packaging import versionif version.parse(torch.__version__) >= version.parse("2.6"):@@ -284,7 +286,7 @@ class TorchFXPythonDecoder (BaseFXDecoder):exported_program = exported_program.run_decompositions(decomp_table=decomp)gm = exported_program.module()logger.debug(gm.code)- return cls(gm, dynamic_shapes=True)+ return cls(gm, dynamic_shapes=dynamic_shapes)@staticmethoddef get_found_shape(value) -> str:diff --git a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py b/tests/layer_tests/py_frontend_tests/test_torch_frontend.pyindex 08a7d90a7d6..498576f5370 100644--- a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py+++ b/tests/layer_tests/py_frontend_tests/test_torch_frontend.py@@ -1148,3 +1148,646 @@ def test_inlined_inputs():model.eval()model = orig_compile(model, backend="openvino", options={"testing": 1})model()+++# --- dynamo (torch.export) tests ---++def _torch_version_at_least(version_str):+ from packaging.version import parse+ return parse(torch.__version__.split('+')[0].split('dev')[0]) >= parse(version_str)++[email protected](not _torch_version_at_least("2.6"),+ reason="Dim.AUTO requires PyTorch >= 2.6")+class TestBuildDynamicShapes:+ """Unit tests for _build_dynamic_shapes covering many input combinations."""++ @staticmethod+ def _make_spec(shape):+ """Create an _InputCutInfo with the given PartialShape."""+ from openvino.tools.ovc.cli_parser import _InputCutInfo+ return _InputCutInfo(name=None, shape=PartialShape(shape))++ # ── input_specs=None → always None ──────────────────────────────++ def test_no_specs_returns_none_single_input(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ example_input = (torch.randn(2, 3),)+ result = _build_dynamic_shapes(example_input)+ assert result is None++ def test_no_specs_returns_none_multi_input(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ example_input = (torch.randn(4,), torch.randn(4,))+ result = _build_dynamic_shapes(example_input)+ assert result is None++ def test_no_specs_returns_none_dict_input(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ example_input = {"x": torch.randn(2, 3), "y": torch.randn(2, 3)}+ result = _build_dynamic_shapes(example_input)+ assert result is None++ def test_no_specs_returns_none_single_tensor(self):+ """Bare tensor (not wrapped in tuple) with no specs."""+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ example_input = torch.randn(2, 3, 4)+ result = _build_dynamic_shapes(example_input)+ assert result is None++ # ── All dims dynamic (-1) ───────────────────────────────────────++ def test_all_dims_dynamic_1d(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = (torch.randn(5),)+ inp = [self._make_spec([-1])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert isinstance(result, tuple)+ assert result[0] == {0: Dim.AUTO}++ def test_all_dims_dynamic_2d(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = (torch.randn(2, 3),)+ inp = [self._make_spec([-1, -1])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] == {0: Dim.AUTO, 1: Dim.AUTO}++ def test_all_dims_dynamic_4d(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = (torch.randn(1, 3, 224, 224),)+ inp = [self._make_spec([-1, -1, -1, -1])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] == {0: Dim.AUTO, 1: Dim.AUTO, 2: Dim.AUTO, 3: Dim.AUTO}++ # ── Only batch dynamic ──────────────────────────────────────────++ def test_batch_only_dynamic_4d(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = (torch.randn(2, 3, 32, 32),)+ inp = [self._make_spec([-1, 3, 32, 32])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] == {0: Dim.AUTO}++ def test_batch_only_dynamic_3d(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = (torch.randn(4, 10, 512),)+ inp = [self._make_spec([-1, 10, 512])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] == {0: Dim.AUTO}++ # ── Mixed dynamic / static dims ─────────────────────────────────++ def test_batch_and_seqlen_dynamic(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = (torch.randn(1, 128, 768),)+ inp = [self._make_spec([-1, -1, 768])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] == {0: Dim.AUTO, 1: Dim.AUTO}++ def test_only_spatial_dynamic(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = (torch.randn(1, 3, 64, 64),)+ inp = [self._make_spec([1, 3, -1, -1])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] == {2: Dim.AUTO, 3: Dim.AUTO}++ def test_only_middle_dim_dynamic(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = (torch.randn(4, 10, 16),)+ inp = [self._make_spec([4, -1, 16])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] == {1: Dim.AUTO}++ # ── All static dims → None per input ────────────────────────────++ def test_all_static_returns_none_for_input(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ example_input = (torch.randn(2, 3, 4),)+ inp = [self._make_spec([2, 3, 4])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result is not None # tuple is returned (not None), but element is None+ assert result[0] is None++ # ── Multiple inputs ─────────────────────────────────────────────++ def test_two_inputs_both_dynamic(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = (torch.randn(2, 8), torch.randn(2, 8))+ inp = [self._make_spec([-1, 8]), self._make_spec([-1, 8])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] == {0: Dim.AUTO}+ assert result[1] == {0: Dim.AUTO}++ def test_two_inputs_one_dynamic_one_static(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = (torch.randn(2, 3, 32, 32), torch.randn(2, 10))+ inp = [self._make_spec([-1, 3, 32, 32]), self._make_spec([2, 10])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] == {0: Dim.AUTO}+ assert result[1] is None++ def test_three_inputs_mixed(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = (torch.randn(1, 128, 64), torch.randn(1, 128, 64), torch.randn(1, 128, 64))+ inp = [self._make_spec([-1, -1, 64])] * 3+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ for i in range(3):+ assert result[i] == {0: Dim.AUTO, 1: Dim.AUTO}++ # ── Dict inputs ─────────────────────────────────────────────────++ def test_dict_input_single_dynamic(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = {"x": torch.randn(4, 16), "y": torch.randn(4, 16)}+ inp = [self._make_spec([-1, 16]), self._make_spec([-1, 16])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result["x"] == {0: Dim.AUTO}+ assert result["y"] == {0: Dim.AUTO}++ def test_dict_input_mixed_shapes(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = {"image": torch.randn(1, 3, 64, 64), "mask": torch.randn(1, 1, 64, 64)}+ inp = [self._make_spec([-1, 3, -1, -1]), self._make_spec([-1, 1, -1, -1])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result["image"] == {0: Dim.AUTO, 2: Dim.AUTO, 3: Dim.AUTO}+ assert result["mask"] == {0: Dim.AUTO, 2: Dim.AUTO, 3: Dim.AUTO}++ def test_dict_input_all_static(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ example_input = {"a": torch.randn(2, 3), "b": torch.randn(2, 3)}+ inp = [self._make_spec([2, 3]), self._make_spec([2, 3])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result["a"] is None+ assert result["b"] is None++ # ── List inputs (auto-converted to tuple) ───────────────────────++ def test_list_input(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = [torch.randn(3, 5)]+ inp = [self._make_spec([-1, 5])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] == {0: Dim.AUTO}++ # ── Bare single tensor input ────────────────────────────────────++ def test_bare_tensor_input(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = torch.randn(2, 10)+ inp = [self._make_spec([-1, 10])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] == {0: Dim.AUTO}++ # ── Scalar tensor → None ────────────────────────────────────────++ def test_scalar_tensor_returns_none(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ example_input = (torch.tensor(3.14),)+ inp = [self._make_spec([])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] is None++ # ── Spec with None shape ────────────────────────────────────────++ def test_spec_with_none_shape(self):+ """Spec that has shape=None should not produce dynamic dims."""+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from openvino.tools.ovc.cli_parser import _InputCutInfo+ example_input = (torch.randn(2, 3),)+ inp = [_InputCutInfo(name=None, shape=None)]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] is None++ # ── More specs than inputs (extra specs ignored) ────────────────++ def test_extra_specs_ignored(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = (torch.randn(2, 4),)+ inp = [self._make_spec([-1, 4]), self._make_spec([-1, 8])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] == {0: Dim.AUTO}++ # ── Fewer specs than inputs (missing specs → None) ──────────────++ def test_fewer_specs_than_inputs(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = (torch.randn(2, 4), torch.randn(2, 4))+ inp = [self._make_spec([-1, 4])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] == {0: Dim.AUTO}+ assert result[1] is None # no spec → static++ # ── High-dimensional tensors ────────────────────────────────────++ def test_5d_tensor(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = (torch.randn(2, 3, 16, 224, 224),)+ inp = [self._make_spec([-1, 3, -1, 224, 224])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] == {0: Dim.AUTO, 2: Dim.AUTO}++ def test_6d_tensor_all_dynamic(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = (torch.randn(1, 2, 3, 4, 5, 6),)+ inp = [self._make_spec([-1, -1, -1, -1, -1, -1])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] == {0: Dim.AUTO, 1: Dim.AUTO, 2: Dim.AUTO,+ 3: Dim.AUTO, 4: Dim.AUTO, 5: Dim.AUTO}++ # ── Multiple inputs with different ranks ────────────────────────++ def test_inputs_different_ranks(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = (torch.randn(8), torch.randn(4, 8), torch.randn(2, 4, 8))+ inp = [self._make_spec([-1]), self._make_spec([-1, -1]), self._make_spec([-1, -1, -1])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] == {0: Dim.AUTO}+ assert result[1] == {0: Dim.AUTO, 1: Dim.AUTO}+ assert result[2] == {0: Dim.AUTO, 1: Dim.AUTO, 2: Dim.AUTO}++ # ── Spec shape shorter than tensor rank (extra dims stay static)++ def test_spec_shorter_than_tensor(self):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = (torch.randn(2, 3, 32, 32),)+ inp = [self._make_spec([-1, 3])] # only covers first 2 of 4 dims+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ # Only dim 0 is -1 in spec, dim 1 is 3 (static), dims 2,3 not in spec → static+ assert result[0] == {0: Dim.AUTO}++ # ── Dimension constraints (min/max bounds) ──────────────────────++ def test_constrained_batch_dim(self):+ """Dimension(1, 10) → Dim with min=1, max=10."""+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from openvino import Dimension+ from torch.export import Dim+ example_input = (torch.randn(2, 3, 32, 32),)+ inp = [self._make_spec([Dimension(1, 10), 3, 32, 32])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ d = result[0][0]+ assert d is not Dim.AUTO+ assert d.min == 1+ assert d.max == 10++ def test_constrained_lower_bound_only(self):+ """Dimension(1, -1) → Dim with min=1, unbounded max."""+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from openvino import Dimension+ from torch.export import Dim+ example_input = (torch.randn(4, 16),)+ inp = [self._make_spec([Dimension(1, -1), 16])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ d = result[0][0]+ assert d is not Dim.AUTO+ assert d.min == 1++ def test_constrained_upper_bound_only(self):+ """Dimension(0, 100) → Dim with max=100."""+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from openvino import Dimension+ from torch.export import Dim+ example_input = (torch.randn(4, 16),)+ inp = [self._make_spec([Dimension(0, 100), 16])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ d = result[0][0]+ assert d is not Dim.AUTO+ assert d.max == 100++ def test_constrained_mixed_with_fully_dynamic(self):+ """Mix constrained dims, fully dynamic dims, and static dims."""+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from openvino import Dimension+ from torch.export import Dim+ example_input = (torch.randn(1, 3, 64, 64),)+ inp = [self._make_spec([Dimension(1, 8), 3, -1, -1])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ # dim 0: constrained+ assert result[0][0] is not Dim.AUTO+ assert result[0][0].min == 1+ assert result[0][0].max == 8+ # dims 2,3: fully dynamic+ assert result[0][2] is Dim.AUTO+ assert result[0][3] is Dim.AUTO+ # dim 1 (static 3) not present+ assert 1 not in result[0]++ def test_constrained_all_dims(self):+ """All dims have constraints."""+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from openvino import Dimension+ example_input = (torch.randn(2, 8),)+ inp = [self._make_spec([Dimension(1, 4), Dimension(4, 16)])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0][0].min == 1+ assert result[0][0].max == 4+ assert result[0][1].min == 4+ assert result[0][1].max == 16++ def test_constrained_multiple_inputs(self):+ """Two inputs, each with different constraints."""+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from openvino import Dimension+ from torch.export import Dim+ example_input = (torch.randn(2, 8), torch.randn(2, 16))+ inp = [self._make_spec([Dimension(1, 4), 8]),+ self._make_spec([-1, Dimension(8, 32)])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ # Input 0: dim 0 constrained+ assert result[0][0].min == 1+ assert result[0][0].max == 4+ # Input 1: dim 0 fully dynamic, dim 1 constrained+ assert result[1][0] is Dim.AUTO+ assert result[1][1].min == 8+ assert result[1][1].max == 32++ def test_constrained_dict_input(self):+ """Dict input with constrained dimensions."""+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from openvino import Dimension+ from torch.export import Dim+ example_input = {"x": torch.randn(2, 3), "y": torch.randn(2, 3)}+ inp = [self._make_spec([Dimension(1, 8), 3]),+ self._make_spec([-1, 3])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ # "x": dim 0 constrained+ assert result["x"][0].min == 1+ assert result["x"][0].max == 8+ # "y": dim 0 fully dynamic+ assert result["y"][0] is Dim.AUTO++ def test_constrained_all_static_still_none(self):+ """Static Dimension values should be treated same as plain ints."""+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from openvino import Dimension+ example_input = (torch.randn(2, 3),)+ inp = [self._make_spec([Dimension(2), Dimension(3)])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] is None++ # ── Parametrized: many rank / dynamic-dim combos ────────────────++ @pytest.mark.parametrize("ndim,dyn_dims", [+ (1, [0]),+ (2, [0]),+ (2, [1]),+ (2, [0, 1]),+ (3, [0]),+ (3, [2]),+ (3, [0, 2]),+ (4, [0]),+ (4, [0, 2, 3]),+ (4, [0, 1, 2, 3]),+ (5, [0, 2]),+ ])+ def test_parametrized_dynamic_dims(self, ndim, dyn_dims):+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ tensor_shape = [(d + 2) for d in range(ndim)]+ example_input = (torch.randn(*tensor_shape),)+ inp = [self._make_spec([(-1 if d in dyn_dims else (d + 2)) for d in range(ndim)])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ if dyn_dims:+ assert result[0] == {d: Dim.AUTO for d in dyn_dims}+ else:+ assert result[0] is None++ # ── Nested tuple inputs (e.g. past_key_values) ─────────────────++ def test_nested_tuple_single_layer(self):+ """past_key_values with one layer: ((key, value),)."""+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ x = torch.randn(2, 4)+ past_kv = ((torch.randn(2, 4, 3, 8), torch.randn(2, 4, 3, 8)),)+ example_input = (x, past_kv)+ # 3 flat specs: x, key, value+ inp = [self._make_spec([-1, 4]),+ self._make_spec([-1, 4, 3, 8]),+ self._make_spec([-1, 4, 3, 8])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ # Result must mirror nested structure: (dims_x, ((dims_k, dims_v),))+ assert result[0] == {0: Dim.AUTO}+ assert result[1][0][0] == {0: Dim.AUTO}+ assert result[1][0][1] == {0: Dim.AUTO}++ def test_nested_tuple_two_layers(self):+ """past_key_values with two layers: ((k0, v0), (k1, v1))."""+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ x = torch.randn(1, 16)+ past_kv = (+ (torch.randn(1, 8, 5, 64), torch.randn(1, 8, 5, 64)),+ (torch.randn(1, 8, 5, 64), torch.randn(1, 8, 5, 64)),+ )+ example_input = (x, past_kv)+ # 5 flat specs+ inp = [self._make_spec([-1, 16]),+ self._make_spec([-1, 8, -1, 64]),+ self._make_spec([-1, 8, -1, 64]),+ self._make_spec([-1, 8, -1, 64]),+ self._make_spec([-1, 8, -1, 64])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] == {0: Dim.AUTO}+ for layer in range(2):+ for kv in range(2):+ d = result[1][layer][kv]+ assert 0 in d and 2 in d+ assert d[0] is Dim.AUTO+ assert d[2] is Dim.AUTO++ def test_nested_tuple_static_specs(self):+ """Nested inputs with all-static specs → None per leaf."""+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ x = torch.randn(2, 4)+ past_kv = ((torch.randn(2, 4, 3, 8),),)+ example_input = (x, past_kv)+ inp = [self._make_spec([2, 4]),+ self._make_spec([2, 4, 3, 8])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] is None+ assert result[1][0][0] is None++ def test_nested_list_input(self):+ """List containing tensors (auto-converted by pytree)."""+ from openvino.tools.ovc.moc_frontend.pytorch_frontend_utils import _build_dynamic_shapes+ from torch.export import Dim+ example_input = (torch.randn(2, 4), [torch.randn(2, 8), torch.randn(2, 8)])+ inp = [self._make_spec([-1, 4]),+ self._make_spec([-1, 8]),+ self._make_spec([-1, 8])]+ result = _build_dynamic_shapes(example_input, input_specs=inp)+ assert result[0] == {0: Dim.AUTO}+ assert result[1][0] == {0: Dim.AUTO}+ assert result[1][1] == {0: Dim.AUTO}+++class TestConvertModelDynamo:+ """Tests for convert_model with dynamo=True (torch.export path)."""++ def test_basic(self):+ from openvino import convert_model, compile_model++ class SimpleModel(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.linear = torch.nn.Linear(16, 32)++ def forward(self, x):+ return torch.nn.functional.relu(self.linear(x))++ model = SimpleModel()+ example = (torch.randn(2, 16),)++ with torch.no_grad():+ ref = model(*example)++ ov_model = convert_model(model, example_input=example, dynamo=True)+ assert ov_model is not None++ cm = compile_model(ov_model, "CPU", default_cfg)+ res = cm([e.numpy() for e in example])+ np.testing.assert_allclose(res[0], ref.numpy(), atol=1e-4, rtol=1e-4)++ def test_multi_input(self):+ from openvino import convert_model, compile_model++ class MultiInputModel(torch.nn.Module):+ def forward(self, x, y):+ return x + y, x * y++ model = MultiInputModel()+ example = (torch.randn(2, 8), torch.randn(2, 8))++ with torch.no_grad():+ ref = model(*example)++ ov_model = convert_model(model, example_input=example, dynamo=True)+ assert ov_model is not None++ cm = compile_model(ov_model, "CPU", default_cfg)+ res = cm([e.numpy() for e in example])+ np.testing.assert_allclose(res[0], ref[0].numpy(), atol=1e-5, rtol=1e-5)+ np.testing.assert_allclose(res[1], ref[1].numpy(), atol=1e-5, rtol=1e-5)++ def test_dynamic_shapes(self):+ from openvino import convert_model, compile_model++ class DynModel(torch.nn.Module):+ def forward(self, x):+ return x * 2.0++ model = DynModel()+ example = (torch.randn(2, 4),)++ # No 'input' provided → fully static export+ ov_model = convert_model(model, example_input=example, dynamo=True)+ assert ov_model is not None++ input_shape = ov_model.input(0).get_partial_shape()+ assert input_shape.is_static, (+ f"Expected static shape without 'input', got {input_shape}")++ # With 'input' specifying dynamic dims → dynamic export+ ov_model_dyn = convert_model(+ model, example_input=example, dynamo=True,+ input=(PartialShape([-1, -1]),))+ assert ov_model_dyn is not None++ input_shape_dyn = ov_model_dyn.input(0).get_partial_shape()+ assert input_shape_dyn.is_dynamic, (+ f"Expected dynamic shape with 'input', got {input_shape_dyn}")++ # Inference with different shapes should work+ cm = compile_model(ov_model_dyn, "CPU", default_cfg)+ for shape in [(1, 4), (3, 4), (5, 8)]:+ inp = np.random.randn(*shape).astype(np.float32)+ res = cm([inp])+ np.testing.assert_allclose(res[0], inp * 2.0, atol=1e-5, rtol=1e-5)++ def test_no_example_input_raises(self):+ from openvino import convert_model++ class Dummy(torch.nn.Module):+ def forward(self, x):+ return x++ with pytest.raises(Exception, match="example_input is required when dynamo=True"):+ convert_model(Dummy(), dynamo=True)++ def test_dict_example_input(self):+ from openvino import convert_model, compile_model++ class DictModel(torch.nn.Module):+ def forward(self, a, b):+ return a - b++ model = DictModel()+ example = {"a": torch.randn(3, 5), "b": torch.randn(3, 5)}++ with torch.no_grad():+ ref = model(**example)++ ov_model = convert_model(model, example_input=example, dynamo=True)+ assert ov_model is not None++ cm = compile_model(ov_model, "CPU", default_cfg)+ res = cm([v.numpy() for v in example.values()])+ np.testing.assert_allclose(res[0], ref.numpy(), atol=1e-5, rtol=1e-5)++ def test_input_shapes_constrain_dynamism(self):+ """When 'input' specifies shapes, only -1 dims become dynamic."""+ from openvino import convert_model, compile_model++ class ConvModel(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.conv = torch.nn.Conv2d(3, 8, 3, padding=1)++ def forward(self, x):+ return self.conv(x)++ model = ConvModel()+ example = (torch.randn(1, 3, 32, 32),)++ # Only batch dim is dynamic (-1), spatial dims are fixed+ ov_model = convert_model(+ model, example_input=example, dynamo=True,+ input=(PartialShape([-1, 3, 32, 32]),))+ assert ov_model is not None++ ps = ov_model.input(0).get_partial_shape()+ # Batch dim should be dynamic+ assert ps[0].is_dynamic, f"Expected dynamic batch dim, got {ps}"+ # Channel and spatial dims should be static+ assert ps[1].get_length() == 3+ assert ps[2].get_length() == 32+ assert ps[3].get_length() == 32++ # Inference with different batch sizes should work+ cm = compile_model(ov_model, "CPU", default_cfg)+ for batch in [1, 2, 4]:+ inp = np.random.randn(batch, 3, 32, 32).astype(np.float32)+ res = cm([inp])+ assert res[0].shape[0] == batchdiff --git a/tests/model_hub_tests/pytorch/test_easyocr.py b/tests/model_hub_tests/pytorch/test_easyocr.pyindex 6bd3fe6c93b..1af89fcf5ed 100644--- a/tests/model_hub_tests/pytorch/test_easyocr.py+++ b/tests/model_hub_tests/pytorch/test_easyocr.py@@ -4,6 +4,7 @@import platformimport pytestimport torch+from openvino import PartialShapefrom torch_utils import TestTorchConvertModel@@ -14,10 +15,15 @@ torch.manual_seed(0)class TestEasyOCRConvertModel(TestTorchConvertModel):def load_model(self, model_name, model_link):import easyocr+ is_export = getattr(self, "mode", None) == "export"if model_name == "detector":model = easyocr.Reader(["en"], quantize=False).detectorself.example = (torch.rand(1, 3, 608, 800),)- self.inputs = (torch.rand(1, 3, 608, 800),)+ if is_export:+ self.dynamo_input = (PartialShape([1, 3, -1, -1]),)+ self.inputs = (torch.rand(1, 3, 480, 640),)+ else:+ self.inputs = (torch.rand(1, 3, 608, 800),)elif model_name == "recognizer":model = easyocr.Reader(["en"], quantize=False).recognizerself.example = (torch.rand(1, 1, 64, 320), torch.rand(1, 33))@@ -33,3 +39,12 @@ class TestEasyOCRConvertModel(TestTorchConvertModel):if platform.machine() in ['arm', 'armv7l', 'aarch64', 'arm64', 'ARM64']:pytest.skip("EasyOCR models are not enabled on ARM")self.run(name, None, ie_device)++ @pytest.mark.precommit+ @pytest.mark.nightly+ @pytest.mark.parametrize("name", ["detector", "recognizer"])+ def test_convert_model_export(self, name, ie_device):+ if platform.machine() in ['arm', 'armv7l', 'aarch64', 'arm64', 'ARM64']:+ pytest.skip("EasyOCR models are not enabled on ARM")+ self.mode = "export"+ self.run(name, None, ie_device)diff --git a/tests/model_hub_tests/pytorch/test_lightglue.py b/tests/model_hub_tests/pytorch/test_lightglue.pyindex cdf62334837..6a33236cd4c 100644--- a/tests/model_hub_tests/pytorch/test_lightglue.py+++ b/tests/model_hub_tests/pytorch/test_lightglue.py@@ -8,6 +8,7 @@ import tempfileimport pytestimport torch+from openvino import PartialShapefrom torch_utils import TestTorchConvertModel@@ -29,14 +30,32 @@ class TestLightGlueModel(TestTorchConvertModel):m = LightGlue(extractor_type)- def get_example():- dummy_kpts0 = torch.randn(size=[1, 1580, 2], dtype=torch.float32)- dummy_kpts1 = torch.randn(size=[1, 3401, 2], dtype=torch.float32)- dummy_desc0 = torch.randn(size=[1, 1580, 256], dtype=torch.float32)- dummy_desc1 = torch.randn(size=[1, 3401, 256], dtype=torch.float32)- return (dummy_kpts0, dummy_kpts1, dummy_desc0, dummy_desc1)- self.example = get_example()- self.inputs = get_example()+ self.example = (+ torch.randn(size=[1, 1580, 2], dtype=torch.float32),+ torch.randn(size=[1, 3401, 2], dtype=torch.float32),+ torch.randn(size=[1, 1580, 256], dtype=torch.float32),+ torch.randn(size=[1, 3401, 256], dtype=torch.float32),+ )+ if getattr(self, "mode", None) == "export":+ self.dynamo_input = (+ PartialShape([1, -1, 2]),+ PartialShape([1, -1, 2]),+ PartialShape([1, -1, 256]),+ PartialShape([1, -1, 256]),+ )+ self.inputs = (+ torch.randn(size=[1, 1200, 2], dtype=torch.float32),+ torch.randn(size=[1, 2800, 2], dtype=torch.float32),+ torch.randn(size=[1, 1200, 256], dtype=torch.float32),+ torch.randn(size=[1, 2800, 256], dtype=torch.float32),+ )+ else:+ self.inputs = (+ torch.randn(size=[1, 1580, 2], dtype=torch.float32),+ torch.randn(size=[1, 3401, 2], dtype=torch.float32),+ torch.randn(size=[1, 1580, 256], dtype=torch.float32),+ torch.randn(size=[1, 3401, 256], dtype=torch.float32),+ )return mdef teardown_class(self):@@ -46,3 +65,8 @@ class TestLightGlueModel(TestTorchConvertModel):@pytest.mark.nightlydef test_convert_model(self, ie_device):self.run("lightglue", "superpoint", ie_device)++ @pytest.mark.nightly+ def test_convert_model_export(self, ie_device):+ self.mode = "export"+ self.run("lightglue", "superpoint", ie_device)diff --git a/tests/model_hub_tests/pytorch/test_timm.py b/tests/model_hub_tests/pytorch/test_timm.pyindex b8f91c9c800..faac2930a80 100644--- a/tests/model_hub_tests/pytorch/test_timm.py+++ b/tests/model_hub_tests/pytorch/test_timm.py@@ -121,8 +121,11 @@ class TestTimmConvertModel(TestTorchConvertModel):self.example = (torch.randn([2] + shape),)self.inputs = (torch.randn([3] + shape),)if getattr(self, "mode", None) == "export":- batch = torch.export.Dim("batch", min=1, max=3)- self.export_kwargs = {"dynamic_shapes": {"x": {0: batch}}}+ from openvino import PartialShape+ self.dynamo_input = (PartialShape([-1] + shape),)+ # Use same batch as example because the FX decoder does not+ # fully propagate symbolic batch through reshape ops yet.+ self.inputs = (torch.randn([2] + shape),)return mdef infer_fw_model(self, model_obj, inputs):diff --git a/tests/model_hub_tests/pytorch/test_torchvision_models.py b/tests/model_hub_tests/pytorch/test_torchvision_models.pyindex ac02fb1cd56..66a425d7308 100644--- a/tests/model_hub_tests/pytorch/test_torchvision_models.py+++ b/tests/model_hub_tests/pytorch/test_torchvision_models.py@@ -84,8 +84,10 @@ class TestTorchHubConvertModel(TestTorchConvertModel):if (getattr(self, "mode", None) == "export"and "raft" not in model_nameand not model_name.startswith("vit_")):- batch = torch.export.Dim("batch", min=1, max=3)- self.export_kwargs = {"dynamic_shapes": [{0: batch}]}+ from openvino import PartialShape, Dimension+ shape = list(self.example[0].shape)+ shape[0] = Dimension(1, 3)+ self.dynamo_input = (PartialShape(shape),)return mdef infer_fw_model(self, model_obj, inputs):diff --git a/tests/model_hub_tests/pytorch/torch_utils.py b/tests/model_hub_tests/pytorch/torch_utils.pyindex aeb172fb12d..5aadcd414b5 100644--- a/tests/model_hub_tests/pytorch/torch_utils.py+++ b/tests/model_hub_tests/pytorch/torch_utils.py@@ -65,26 +65,15 @@ class TestTorchConvertModel(TestConvertModel):def convert_model_impl(self, model_obj):if hasattr(self, "mode") and self.mode == "export":- from torch.export import export- from packaging import version-- model_obj.eval()- graph = Noneexport_kwargs = {}- if getattr(self, "export_kwargs", None):- export_kwargs = self.export_kwargs- if isinstance(self.example, dict):- pt_res = model_obj(**self.example)- graph = export(model_obj, args=tuple(), kwargs=self.example, **export_kwargs)- else:- pt_res = model_obj(*self.example)- graph = export(model_obj, self.example, **export_kwargs)- ov_model = convert_model(graph, verbose=True)-- if isinstance(pt_res, dict):- for i, k in enumerate(pt_res.keys()):- ov_model.outputs[i].get_tensor().set_names({k})- ov_model.validate_nodes_and_infer_types()+ if getattr(self, "dynamo_input", None):+ export_kwargs["input"] = self.dynamo_input+ ov_model = convert_model(model_obj,+ example_input=self.example,+ verbose=True,+ dynamo=True,+ **export_kwargs,+ )else:ov_model = convert_model(model_obj,example_input=self.example,diff --git a/tools/ovc/openvino/tools/ovc/convert.py b/tools/ovc/openvino/tools/ovc/convert.pyindex 2c9d6608f68..c3734b54499 100644--- a/tools/ovc/openvino/tools/ovc/convert.py+++ b/tools/ovc/openvino/tools/ovc/convert.py@@ -21,6 +21,7 @@ def convert_model(extension: [str, pathlib.Path, list, Any] = None,verbose: bool = False,share_weights: bool = True,+ dynamo: bool = False,) -> Model:"""Converts the model from original framework to OpenVino Model.@@ -95,6 +96,15 @@ def convert_model(then mmap is used to allocate weights directly from file. If input model isruntime object, then original memory regions allocated in the original modelare reused for weights in the converted model.+ :param dynamo:+ Export a PyTorch torch.nn.Module using torch.export instead of+ torch.jit.trace. Requires example_input and PyTorch >= 2.6.+ Default is False.+ The resulting model uses static shapes derived from example_input by default.+ To enable dynamic dimensions, combine with the input parameter:+ dimensions set to -1 or Dimension(-1) become fully dynamic+ (torch.export.Dim.AUTO), and bounded dimensions such as Dimension(1, 10)+ are exported with explicit min/max constraints.Returns:openvino.Modeldiff --git a/tools/ovc/openvino/tools/ovc/convert_impl.py b/tools/ovc/openvino/tools/ovc/convert_impl.pyindex 814e5cd6319..a96a8760e61 100644--- a/tools/ovc/openvino/tools/ovc/convert_impl.py+++ b/tools/ovc/openvino/tools/ovc/convert_impl.py@@ -454,8 +454,17 @@ def _convert(cli_parser: argparse.ArgumentParser, args, python_api_used):model_framework = Noneinp_model_is_object = input_model_is_object(args['input_model']) if python_api_used else False+ if not inp_model_is_object and args.get("dynamo", False):+ log.warning("dynamo=True is only supported for PyTorch nn.Module objects, "+ "but the provided model is a file path. "+ "The dynamo parameter will be ignored.")+if inp_model_is_object:model_framework = check_model_object(args)+ if args.get("dynamo", False) and model_framework != "pytorch":+ log.warning("dynamo=True is only supported for PyTorch models, "+ "but the provided model is detected as '{}'. "+ "The dynamo parameter will be ignored.".format(model_framework))if model_framework == "pytorch":example_inputs = Noneif 'example_input' in args and args['example_input'] is not None:diff --git a/tools/ovc/openvino/tools/ovc/moc_frontend/pytorch_frontend_utils.py b/tools/ovc/openvino/tools/ovc/moc_frontend/pytorch_frontend_utils.pyindex 69276ad634d..44e440889c5 100644--- a/tools/ovc/openvino/tools/ovc/moc_frontend/pytorch_frontend_utils.py+++ b/tools/ovc/openvino/tools/ovc/moc_frontend/pytorch_frontend_utils.py@@ -9,7 +9,7 @@ import numpy as np# pylint: disable=no-name-in-module,import-errorfrom openvino import Tensor, PartialShape-from openvino.tools.ovc.cli_parser import single_input_to_input_cut_info, _InputCutInfo+from openvino.tools.ovc.cli_parser import input_to_input_cut_info, single_input_to_input_cut_info, _InputCutInfofrom openvino.tools.ovc.error import Error@@ -21,6 +21,131 @@ def extract_module_extensions(args):return {extension.module: extension for extension in extensions if isinstance(extension, ModuleExtension)}+def _build_dynamic_shapes(inputs, input_specs=None):+ """Build dynamic_shapes for torch.export.export.++ If input_specs (list of _InputCutInfo from the 'input' parameter) is provided+ and contains shapes, dimensions marked as -1 (fully dynamic) get Dim.AUTO,+ dimensions with min/max constraints (e.g. Dimension(1, 10)) get+ Dim("dI_D", min=..., max=...), and fixed dimensions stay static.+ When no specs are given returns None so that torch.export.export produces+ a fully static graph.++ The input_specs list is flat (one spec per leaf tensor), while inputs may+ contain nested tuples/lists (e.g. past_key_values). pytree is used to+ flatten inputs, pair each leaf with its spec, and then unflatten the+ result back into the original structure that torch.export expects.+ """+ import torch+ from torch.export import Dim+ from torch.utils._pytree import tree_flatten, tree_unflatten++ if input_specs is None:+ return None++ def _dims_for_tensor(tensor, spec_shape, input_idx):+ """Return a per-dim dict mapping dim index to Dim hint.++ - Fully dynamic dims (-1) → Dim.AUTO+ - Constrained dims (min, max) → Dim("dI_D", min=..., max=...)+ - Static dims → omitted (stays static)+ """+ if not isinstance(tensor, torch.Tensor) or tensor.ndim == 0:+ return None+ if spec_shape is None:+ return None+ dims = {}+ for d in range(tensor.ndim):+ if d >= len(spec_shape):+ continue+ sd = spec_shape[d]+ if isinstance(sd, tuple):+ # Constrained dimension with (min, max) bounds+ min_val, max_val = sd+ kwargs = {}+ if min_val > 0:+ kwargs['min'] = min_val+ if max_val != -1: # -1 means unbounded+ kwargs['max'] = max_val+ dims[d] = Dim(f"d{input_idx}_{d}", **kwargs)+ elif sd == -1:+ dims[d] = Dim.AUTO+ # If no dynamic dims, return None+ if not dims:+ return None+ return dims++ # Resolve spec shapes (list of dim descriptors aligned to flat leaves).+ # Each dim is: int (static), -1 (fully dynamic), or (min, max) tuple.+ def _get_spec_shapes():+ shapes = []+ for spec in input_specs:+ if spec is None or getattr(spec, 'shape', None) is None or not spec.shape.rank.is_static:+ shapes.append(None)+ continue+ dims = []+ for i in range(spec.shape.rank.get_length()):+ dim = spec.shape.get_dimension(i)+ if dim.is_static:+ dims.append(dim.get_length())+ elif dim.get_min_length() == 0 and dim.get_max_length() == -1:+ dims.append(-1) # Fully dynamic (unbounded)+ else:+ dims.append((dim.get_min_length(), dim.get_max_length())) # Constrained+ shapes.append(dims)+ return shapes++ spec_shapes = _get_spec_shapes()++ # Flatten the (possibly nested) inputs to get leaf tensors and the+ # tree structure. Build a flat list of per-leaf dim specs, then+ # unflatten back so that dynamic_shapes mirrors the input structure+ # exactly as torch.export.export requires.+ if isinstance(inputs, torch.Tensor):+ inputs = (inputs,)++ flat_leaves, tree_spec = tree_flatten(inputs)++ flat_dim_specs = []+ for i, leaf in enumerate(flat_leaves):+ ss = spec_shapes[i] if i < len(spec_shapes) else None+ flat_dim_specs.append(_dims_for_tensor(leaf, ss, i))++ return tree_unflatten(flat_dim_specs, tree_spec)+++def _export_torch_model(model, inputs, input_specs=None):+ """Export a torch.nn.Module using torch.export.export with Dim.AUTO dynamic shapes."""+ import torch++ model.eval()+ dynamic_shapes = _build_dynamic_shapes(inputs, input_specs=input_specs)++ # Normalize inputs to a tuple for torch.export.export+ if isinstance(inputs, dict):+ export_args = ()+ export_kwargs = inputs+ else:+ if isinstance(inputs, torch.Tensor):+ export_args = (inputs,)+ elif isinstance(inputs, (list, tuple)):+ export_args = tuple(inputs)+ else:+ export_args = (inputs,)+ export_kwargs = None++ if export_kwargs is not None:+ export_args_dict = dict(args=export_args, kwargs=export_kwargs)+ else:+ export_args_dict = dict(args=export_args)++ if dynamic_shapes is not None:+ export_args_dict["dynamic_shapes"] = dynamic_shapes++ exported_program = torch.export.export(model, **export_args_dict)+ return exported_program++def get_pytorch_decoder(model, example_inputs, args):try:from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder@@ -47,9 +172,22 @@ def get_pytorch_decoder(model, example_inputs, args):"supported directly. Please upgrade nncf or ""export to ONNX first.")inputs = prepare_torch_inputs(example_inputs)+ use_dynamo = args.get("dynamo", False)if not isinstance(model, (TorchScriptPythonDecoder, TorchFXPythonDecoder)):if hasattr(torch, "export") and isinstance(model, (torch.export.ExportedProgram)):decoder = TorchFXPythonDecoder.from_exported_program(model)+ elif use_dynamo and isinstance(model, torch.nn.Module):+ if inputs is None:+ raise Error("example_input is required when dynamo=True")+ # Extract user-provided input shape specs to constrain dynamic dims.+ # Normalize raw user input (PartialShape, list, etc.) to list of _InputCutInfo+ # because _build_dynamic_shapes expects _InputCutInfo objects with .shape attribute.+ raw_input = args.get('input', None) or None+ input_specs = input_to_input_cut_info(raw_input) if raw_input is not None else None+ exported_program = _export_torch_model(model, inputs, input_specs=input_specs)+ has_dynamic = input_specs is not None+ decoder = TorchFXPythonDecoder.from_exported_program(+ exported_program, dynamic_shapes=has_dynamic)else:decoder = TorchScriptPythonDecoder(model,@@ -193,6 +331,10 @@ def extract_input_info_from_example(args, inputs):name = example[0]example = example[1]shape = PartialShape([-1] * example.ndim) if hasattr(example, "ndim") else PartialShape.dynamic()+ if getattr(args, 'dynamo', False):+ # For dynamo mode, use concrete shapes from example; dynamic dims+ # are only introduced when the user explicitly provides 'input'.+ shape = PartialShape(list(example.shape)) if hasattr(example, "shape") else shapedtype = getattr(example, "dtype", type(example))dtype = pt_to_ov_type_map.get(str(dtype))if name:diff --git a/tools/ovc/unit_tests/ovc/utils/cli_parser_test.py b/tools/ovc/unit_tests/ovc/utils/cli_parser_test.pyindex 8c752e85624..0bea974164d 100644--- a/tools/ovc/unit_tests/ovc/utils/cli_parser_test.py+++ b/tools/ovc/unit_tests/ovc/utils/cli_parser_test.py@@ -491,7 +491,7 @@ class TestConvertModelParamsParsing(unittest.TestCase):def test_mo_convert_params_parsing(self):ref_params = {'Optional parameters:': {'input_model', 'input', 'output', 'example_input',- 'extension', 'verbose', 'share_weights'},+ 'extension', 'verbose', 'share_weights', 'dynamo'},}params = get_mo_convert_params()