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] Implement patch for quantized models in torch.export path (#35281)
Maxim Vafin35e816af721a
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.pyindex ea73ee13862..aa3b974f49d 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/fx_decoder.py@@ -288,6 +288,78 @@ class TorchFXPythonDecoder (BaseFXDecoder):logger.debug(gm.code)return cls(gm, dynamic_shapes=dynamic_shapes)+ @classmethod+ def from_model(+ cls, model: torch.nn.Module, example_inputs,+ dynamic_shapes=None,+ ) -> "TorchFXPythonDecoder":+ """Export a model and create a decoder, auto-patching quantized models.++ This is the ``torch.export`` counterpart of TorchScriptPythonDecoder's+ auto-patching of quantized models. The method patches the model before+ ``torch.export.export`` so that custom ``ov_ext`` ops are captured in+ the FX graph, then unpatches afterwards.++ :param model: The ``torch.nn.Module`` to export and decode.+ :param example_inputs: Example inputs for ``torch.export.export``.+ :param dynamic_shapes: Dynamic shapes specification built by+ ``_build_dynamic_shapes`` for ``torch.export.export``, or ``None``+ for a fully static graph.+ """+ from openvino.frontend.pytorch import quantized++ quant_patched = False+ if quantized.detect_quantized_model(model) is not None:+ try:+ quantized.patch_quantized_for_export(model)+ quant_patched = True+ except Exception as error:+ logger.warning(+ "Failed patching quantized model for torch.export. "+ "Conversion of the model will likely be unsuccessful or incorrect",+ exc_info=error)+ try:+ quantized.unpatch_quantized_for_export(model)+ except Exception:+ pass+ quant_patched = False++ try:+ exported_program = cls._export(model, example_inputs, dynamic_shapes)+ finally:+ if quant_patched:+ quantized.unpatch_quantized_for_export(model)++ return cls.from_exported_program(+ exported_program, dynamic_shapes=dynamic_shapes is not None)++ @staticmethod+ def _export(model, inputs, dynamic_shapes=None):+ """Export a torch.nn.Module using torch.export.export."""+ model.eval()++ 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 = {"args": export_args, "kwargs": export_kwargs}+ else:+ export_args_dict = {"args": export_args}++ if dynamic_shapes is not None:+ export_args_dict["dynamic_shapes"] = dynamic_shapes++ return torch.export.export(model, **export_args_dict)+@staticmethoddef get_found_shape(value) -> str:# If input is a tensor, read the shape from meta datadiff --git a/src/bindings/python/src/openvino/frontend/pytorch/ov_custom_ops.py b/src/bindings/python/src/openvino/frontend/pytorch/ov_custom_ops.pynew file mode 100644index 00000000000..bc980aa6429--- /dev/null+++ b/src/bindings/python/src/openvino/frontend/pytorch/ov_custom_ops.py@@ -0,0 +1,148 @@+# -*- coding: utf-8 -*-+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++"""Register OpenVINO custom ops via torch.library for use with torch.export.++When converting quantized PyTorch models, module forwards are replaced with+calls to these custom ops. During ``torch.export``, the ops appear as+``call_function`` nodes in the FX graph (e.g. ``ov_ext.awq_gemm.default``)+and are later translated by the C++ PyTorch frontend.++Import this module to trigger registration::++ import openvino.frontend.pytorch.ov_custom_ops # noqa: F401+"""++from __future__ import annotations++import logging++import torch++log = logging.getLogger(__name__)++# ──────────────────────────────────────────────────────────────────────+# Module-level library handle for ov_ext operator schema registration+# ──────────────────────────────────────────────────────────────────────+_ov_ext_lib = torch.library.Library("ov_ext", "DEF")+++# ──────────────────────────────────────────────────────────────────────+# ov_ext::awq_gemm (input, qweight, qzeros, scales, group_size,+# w_bit, bias?) → Tensor+# ──────────────────────────────────────────────────────────────────────+_ov_ext_lib.define(+ "awq_gemm(Tensor input, Tensor qweight, Tensor qzeros, "+ "Tensor scales, int group_size, int w_bit, "+ "Tensor? bias) -> Tensor")++[email protected](_ov_ext_lib, "awq_gemm", "Meta")+def _awq_gemm_meta(+ data: torch.Tensor, qweight: torch.Tensor, _qzeros: torch.Tensor,+ _scales: torch.Tensor, _group_size: int, w_bit: int,+ _bias: torch.Tensor | None,+) -> torch.Tensor:+ pack_num = 32 // w_bit+ out_features = qweight.shape[1] * pack_num+ return torch.empty(+ *data.shape[:-1], out_features,+ dtype=data.dtype, device="meta")++[email protected](_ov_ext_lib, "awq_gemm", "CPU")+def _awq_gemm_cpu(+ data: torch.Tensor, qweight: torch.Tensor, _qzeros: torch.Tensor,+ _scales: torch.Tensor, _group_size: int, w_bit: int,+ bias: torch.Tensor | None,+) -> torch.Tensor:+ # Placeholder – actual dequantisation happens in the C++ OV translator.+ # This fallback produces the right shape for tracing / testing.+ pack_num = 32 // w_bit+ out_features = qweight.shape[1] * pack_num+ out = torch.zeros(+ *data.shape[:-1], out_features,+ dtype=torch.float32, device=data.device)+ if bias is not None:+ out = out + bias.float()+ return out.to(data.dtype)+++# ──────────────────────────────────────────────────────────────────────+# ov_ext::bit_linear (input, weight, weight_scale, bias?) → Tensor+# ──────────────────────────────────────────────────────────────────────+_ov_ext_lib.define(+ "bit_linear(Tensor input, Tensor weight, Tensor weight_scale, "+ "Tensor? bias) -> Tensor")++[email protected](_ov_ext_lib, "bit_linear", "Meta")+def _bit_linear_meta(+ data: torch.Tensor, weight: torch.Tensor, _weight_scale: torch.Tensor,+ _bias: torch.Tensor | None,+) -> torch.Tensor:+ # BitNet weight packing: out_features is weight.shape[0]+ out_features = weight.shape[0]+ return torch.empty(+ *data.shape[:-1], out_features,+ dtype=data.dtype, device="meta")++[email protected](_ov_ext_lib, "bit_linear", "CPU")+def _bit_linear_cpu(+ data: torch.Tensor, weight: torch.Tensor, _weight_scale: torch.Tensor,+ bias: torch.Tensor | None,+) -> torch.Tensor:+ out_features = weight.shape[0]+ out = torch.zeros(+ *data.shape[:-1], out_features,+ dtype=torch.float32, device=data.device)+ if bias is not None:+ out = out + bias.float()+ return out.to(data.dtype)+++# ──────────────────────────────────────────────────────────────────────+# ov_ext::gptq_gemm (input, qweight, qzeros, scales, group_size,+# w_bit, sym, bias?) → Tensor+# ──────────────────────────────────────────────────────────────────────+_ov_ext_lib.define(+ "gptq_gemm(Tensor input, Tensor qweight, Tensor qzeros, "+ "Tensor scales, int group_size, int w_bit, bool sym, "+ "Tensor? bias) -> Tensor")++[email protected](_ov_ext_lib, "gptq_gemm", "Meta")+def _gptq_gemm_meta(+ data: torch.Tensor, qweight: torch.Tensor, _qzeros: torch.Tensor,+ _scales: torch.Tensor, _group_size: int, w_bit: int, _sym: bool,+ _bias: torch.Tensor | None,+) -> torch.Tensor:+ # qweight is [in_features / pack_num, out_features] — dim 1 is the raw+ # output width (packing is along the input dimension only).+ out_features = qweight.shape[1]+ return torch.empty(+ *data.shape[:-1], out_features,+ dtype=data.dtype, device="meta")++[email protected](_ov_ext_lib, "gptq_gemm", "CPU")+def _gptq_gemm_cpu(+ data: torch.Tensor, qweight: torch.Tensor, _qzeros: torch.Tensor,+ _scales: torch.Tensor, _group_size: int, w_bit: int, _sym: bool,+ bias: torch.Tensor | None,+) -> torch.Tensor:+ # Placeholder – actual dequantisation happens in the C++ OV translator.+ # qweight is [in_features / pack_num, out_features] — dim 1 is the raw+ # output width (packing is along the input dimension only).+ out_features = qweight.shape[1]+ out = torch.zeros(+ *data.shape[:-1], out_features,+ dtype=torch.float32, device=data.device)+ if bias is not None:+ out = out + bias.float()+ return out.to(data.dtype)+++log.debug("Registered ov_ext custom ops for torch.export")diff --git a/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py b/src/bindings/python/src/openvino/frontend/pytorch/patch_model.pyindex e9f26dcd646..9dce2b01310 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/patch_model.py@@ -169,19 +169,60 @@ def _unpatch_torch_functions():del _patched_torch_functions[key]-def __make_16bit_traceable(model: torch.nn.Module,- orig_forward_name: str = "_openvino_module_extension_patch_orig_forward",- patch_condition=None):- """Prepare a 16-bit PyTorch model for tracing with OpenVINO.+def patch_model_for_export(model, module_extensions, orig_forward_name):+ """Patch model modules for ``torch.export`` by replacing forwards with ``torch.ops.ov_ext.*`` calls.- - Replace known list of modules with ModuleExtension.- - Patch torch functions (bmm, baddbmm, etc.) for MoE and similar models.- - Convert other modules with weights to FP32.+ Unlike ``patch_model`` (which uses ``torch.autograd.Function`` / ``torch.jit.ignore``+ for TorchScript tracing), this function creates forwards that call registered+ ``torch.library`` custom ops so that ``torch.export`` captures them as+ ``call_function`` nodes in the FX graph."""- supported = {torch.float16, torch.bfloat16, torch.float8_e4m3fn, torch.float8_e5m2}+ import openvino.frontend.pytorch.ov_custom_ops # noqa: F401 – triggers registration++ def _resolve_target_op(extension):+ """Map an ``ov_ext::*`` target-op name to the corresponding ``torch.ops.ov_ext.*`` callable."""+ # extension.target_op is e.g. "ov_ext::linear"+ parts = extension.target_op.split("::")+ if len(parts) == 2 and parts[0] == "ov_ext":+ op_fn = getattr(torch.ops.ov_ext, parts[1], None)+ if op_fn is not None:+ return op_fn+ raise RuntimeError(+ f"Cannot resolve torch.library op for target_op='{extension.target_op}'. "+ "Make sure it is registered in openvino.frontend.pytorch.ov_custom_ops.")- # Patch torch functions for operations like bmm used in MoE models- _patch_torch_functions()+ def module_patcher(module, name):+ extension = None+ if module in module_extensions:+ extension = module_extensions[module]+ elif module.__class__ in module_extensions:+ extension = module_extensions[module.__class__]+ elif name in module_extensions:+ extension = module_extensions[name]++ if extension and extension.condition(module):+ log.debug("Patching module %s for torch.export", module)+ target_op = _resolve_target_op(extension)++ def new_forward(*args, **kwargs):+ return extension.convert(module, target_op, *args, **kwargs)++ new_forward = functools.wraps(module.forward)(new_forward)+ setattr(module, orig_forward_name, module.forward)+ module.forward = new_forward++ for name, module in model.named_modules():+ if hasattr(module, orig_forward_name):+ log.debug("Unexpectedly found already patched module %s while applying "+ "ModuleExtension for torch.export during PyTorch model conversion. "+ "Result of the conversion maybe broken.", name)+ continue+ module_patcher(module, name)+++def _get_16bit_extensions(patch_condition=None):+ """Return a dict of ModuleExtension entries for known 16-bit module types."""+ supported = {torch.float16, torch.bfloat16, torch.float8_e4m3fn, torch.float8_e5m2}if patch_condition is None:def patch_condition(module):@@ -221,6 +262,22 @@ def __make_16bit_traceable(model: torch.nn.Module,condition=patch_condition)except ImportError:pass+ return extensions, supported+++def __make_16bit_traceable(model: torch.nn.Module,+ orig_forward_name: str = "_openvino_module_extension_patch_orig_forward",+ patch_condition=None):+ """Prepare a 16-bit PyTorch model for tracing with OpenVINO.++ - Replace known list of modules with ModuleExtension.+ - Patch torch functions (bmm, baddbmm, etc.) for MoE and similar models.+ - Convert other modules with weights to FP32.+ """+ # Patch torch functions for operations like bmm used in MoE models+ _patch_torch_functions()++ extensions, supported = _get_16bit_extensions(patch_condition)patch_model(model, extensions, orig_forward_name)for _, module in model.named_modules():if (module.__class__ not in extensionsdiff --git a/src/bindings/python/src/openvino/frontend/pytorch/quantized.py b/src/bindings/python/src/openvino/frontend/pytorch/quantized.pyindex 1ac905b919f..8c2d1edc979 100644--- a/src/bindings/python/src/openvino/frontend/pytorch/quantized.py+++ b/src/bindings/python/src/openvino/frontend/pytorch/quantized.py@@ -2,13 +2,23 @@# Copyright (C) 2018-2026 Intel Corporation# SPDX-License-Identifier: Apache-2.0-from typing import Optional+from __future__ import annotations+++import functools+import logging+from collections.abc import Callable+from typing import Any+import torchfrom openvino.frontend.pytorch import ModuleExtension, gptq-from openvino.frontend.pytorch.patch_model import patch_model, unpatch_model+from openvino.frontend.pytorch.patch_model import (+ patch_model, unpatch_model, patch_model_for_export)+log = logging.getLogger(__name__)-def detect_quantized_model(model: torch.nn.Module) -> Optional[str]:++def detect_quantized_model(model: torch.nn.Module) -> str | None:"""Detects the quantization method used in a given PyTorch model.Args:@@ -34,20 +44,67 @@ def patch_quantized(model: torch.nn.Module) -> None:Raises:RuntimeError: If the quantization type is unknown."""+ quant_type = detect_quantized_model(model)+ if quant_type == "gptq":+ model._openvino_gptq_patched = True # type: ignore[assignment]+ gptq.patch_model(model) # type: ignore+ return++ extensions = _build_quantized_extensions(quant_type)+ patch_model(model, extensions,+ "_openvino_quantized_patch_orig_forward") # type: ignore+++def unpatch_quantized(model: torch.nn.Module) -> None:+ """Reverts the patching applied to a quantized PyTorch model.++ Args:+ model (torch.nn.Module): The model to unpatch.+ """+ if getattr(model, "_openvino_gptq_patched", False):+ gptq.unpatch_model(model) # type: ignore+ del model._openvino_gptq_patched+ else:+ unpatch_model(model,+ "_openvino_quantized_patch_orig_forward") # type: ignore+++def _build_quantized_extensions(+ quant_type: str | None, for_export: bool = False,+) -> dict[Any, ModuleExtension] | None:+ """Build ModuleExtension dict for the given quantization type.++ Args:+ quant_type: Quantization method string ("awq", "bitnet", etc.).+ for_export: If True, pass group_size/w_bit as plain ints for+ ``torch.export``. If False (default), wrap them in+ ``torch.tensor`` so they appear as graph inputs in+ TorchScript tracing.++ Returns the extensions dict (may be empty if the required package is+ not installed). Raises ``RuntimeError`` for unknown quant types.+ """def fp32_tensor(*shape: int) -> torch.Tensor:return torch.full(shape, 0.5, dtype=torch.float32)- quant_type = detect_quantized_model(model)- extensions = {}+ extensions: dict[Any, ModuleExtension] = {}if quant_type == "awq":try:from awq.modules.linear import WQLinear_GEMM++ def _awq_convert(+ module: Any, target_op: Callable[..., torch.Tensor],+ *args: Any, **kwargs: Any,+ ) -> torch.Tensor:+ gs = module.group_size if for_export else torch.tensor(module.group_size)+ wb = module.w_bit if for_export else torch.tensor(module.w_bit)+ return target_op(+ args[0], module.qweight, module.qzeros, module.scales,+ gs, wb, module.bias)+extensions[WQLinear_GEMM] = ModuleExtension(WQLinear_GEMM, "ov_ext::awq_gemm",- convert=lambda module, target_op, *args, **kwargs: target_op(- args[0], module.qweight, module.qzeros, module.scales,- torch.tensor(module.group_size),- torch.tensor(module.w_bit), module.bias),+ convert=_awq_convert,evaluate=lambda module, *args, **kwargs: fp32_tensor(*args[0].shape[:-1], module.out_features)) # type: ignoreexcept ImportError:@@ -68,25 +125,96 @@ def patch_quantized(model: torch.nn.Module) -> None:except ImportError:passelif quant_type == "gptq":- model._openvino_gptq_patched = True # type: ignore[assignment]- gptq.patch_model(model) # type: ignore- return+ # GPTQ is handled separately — not via ModuleExtension for TorchScript,+ # and via attribute-based patching for torch.export (see _patch_gptq_for_export).+ return Noneelse:raise RuntimeError(f"Unknown quantization type: {quant_type}.")+ return extensions- patch_model(model, extensions,- "_openvino_quantized_patch_orig_forward") # type: ignore+# ──────────────────────────────────────────────────────────────────────+# torch.export–compatible patching+# ──────────────────────────────────────────────────────────────────────-def unpatch_quantized(model: torch.nn.Module) -> None:- """Reverts the patching applied to a quantized PyTorch model.+def patch_quantized_for_export(model: torch.nn.Module) -> None:+ """Patch a quantized model for ``torch.export`` using ``torch.library`` custom ops.++ This is the ``torch.export`` counterpart of ``patch_quantized``.++ Args:+ model (torch.nn.Module): The model to patch.++ Raises:+ RuntimeError: If the quantization type is unknown or unsupported.+ """+ quant_type = detect_quantized_model(model)++ if quant_type == "gptq":+ _patch_gptq_for_export(model)+ return++ extensions = _build_quantized_extensions(quant_type, for_export=True)+ patch_model_for_export(model, extensions,+ "_openvino_quantized_patch_orig_forward") # type: ignore+++def _detect_gptq_sym(model: torch.nn.Module) -> bool:+ """Detect whether a GPTQ model uses symmetric quantization."""+ config = getattr(model, "config", None)+ if config is None and hasattr(model, "model"):+ config = getattr(model.model, "config", None)+ if config is not None and hasattr(config, "quantization_config"):+ return bool(getattr(config.quantization_config, "sym", False))+ return False+++def _patch_gptq_for_export(model: torch.nn.Module) -> None:+ """Patch GPTQ modules for ``torch.export`` using ``ov_ext::gptq_gemm``.++ Unlike AWQ/BitNet which use ``ModuleExtension``, GPTQ modules are+ discovered by attribute (``QUANT_TYPE``) since there is no common base+ class across AutoGPTQ backends.+ """+ import openvino.frontend.pytorch.ov_custom_ops # noqa: F401++ sym = _detect_gptq_sym(model)+ target_op = torch.ops.ov_ext.gptq_gemm++ for name, module in model.named_modules():+ if hasattr(module, "_openvino_quantized_patch_orig_forward"):+ log.debug("Skipping already-patched GPTQ module %s", name)+ continue+ if not hasattr(module, "QUANT_TYPE"):+ continue+ if module.QUANT_TYPE not in gptq.supported_quant_types:+ raise ValueError(+ f"Unsupported QUANT_TYPE == {module.QUANT_TYPE} in module "+ f"{name}. Supported types: {gptq.supported_quant_types}")+ if module.bits != 4:+ raise ValueError(+ f"Unsupported bits == {module.bits} in module {name}, "+ "only bits == 4 is supported.")++ module._openvino_quantized_patch_orig_forward = module.forward++ def _make_forward(mod: torch.nn.Module) -> Callable[..., torch.Tensor]:+ @functools.wraps(mod.forward)+ def new_forward(*args: Any, **kwargs: Any) -> torch.Tensor:+ return target_op(+ args[0], mod.qweight, mod.qzeros, mod.scales,+ mod.group_size, mod.bits, sym,+ mod.bias)+ return new_forward++ module.forward = _make_forward(module)+++def unpatch_quantized_for_export(model: torch.nn.Module) -> None:+ """Revert patching applied by ``patch_quantized_for_export``.Args:model (torch.nn.Module): The model to unpatch."""- if getattr(model, "_openvino_gptq_patched", False):- gptq.unpatch_model(model) # type: ignore- del model._openvino_gptq_patched- else:- unpatch_model(model,- "_openvino_quantized_patch_orig_forward") # type: ignore+ unpatch_model(model,+ "_openvino_quantized_patch_orig_forward") # type: ignorediff --git a/src/frontends/pytorch/src/op/linear.cpp b/src/frontends/pytorch/src/op/linear.cppindex dc112d628e3..81370973a03 100644--- a/src/frontends/pytorch/src/op/linear.cpp+++ b/src/frontends/pytorch/src/op/linear.cpp@@ -65,6 +65,15 @@ OutputVector translate_linear_ext(const NodeContext& context) {namespace {+// Write a u4 value at a given linear index in a packed u4 buffer.+inline void set_u4(uint8_t* data, size_t idx, uint8_t val) {+ size_t byte_idx = idx / 2;+ if (idx & 1)+ data[byte_idx] = (data[byte_idx] & 0x0F) | static_cast<uint8_t>((val & 0x0F) << 4);+ else+ data[byte_idx] = (data[byte_idx] & 0xF0) | (val & 0x0F);+}+Output<Node> low_precision_subgraph(const NodeContext& context,const Output<Node>& x,const Output<Node>& weights,@@ -104,6 +113,8 @@ uint32_t rearrange_awq_bits(uint32_t num) {Output<Node> rearrange_constant(const Output<Node>& c, uint32_t groups) {auto constant = ov::as_type_ptr<v0::Constant>(c.get_node_shared_ptr());FRONT_END_OP_CONVERSION_CHECK(constant, "weight must be Constant.");+ FRONT_END_OP_CONVERSION_CHECK(constant->get_byte_size() == shape_size(constant->get_shape()) * sizeof(uint32_t),+ "AWQ constant storage size does not match expected int32 packing.");auto src = constant->get_data_ptr<uint32_t>();auto initial_shape = constant->get_shape();FRONT_END_OP_CONVERSION_CHECK(initial_shape.size() == 2, "Only 2D constants are supported.");@@ -123,6 +134,66 @@ Output<Node> rearrange_constant(const Output<Node>& c, uint32_t groups) {new_qweight->set_friendly_name(constant->get_friendly_name());return new_qweight;}++// GPTQ packs 8 u4 values per int32 along the INPUT dimension.+// Each int32 at [i, j] holds u4 values for rows i*8..i*8+7 at column j.+// This is a transpose of the inner dims: [K, N, 8] u4 → [K, 8, N] u4.+Output<Node> unpack_gptq_qweight(const Output<Node>& c, int64_t group_size) {+ auto constant = ov::as_type_ptr<v0::Constant>(c.get_node_shared_ptr());+ FRONT_END_OP_CONVERSION_CHECK(constant, "qweight must be Constant.");+ FRONT_END_OP_CONVERSION_CHECK(constant->get_byte_size() == shape_size(constant->get_shape()) * sizeof(uint32_t),+ "GPTQ qweight storage size does not match expected int32 packing.");+ auto src = constant->get_data_ptr<uint32_t>();+ auto initial_shape = constant->get_shape();+ FRONT_END_OP_CONVERSION_CHECK(initial_shape.size() == 2, "Only 2D qweight constants are supported.");+ const size_t K = initial_shape[0]; // in_features / 8+ const size_t N = initial_shape[1]; // out_features+ const size_t in_features = K * 8;+ FRONT_END_OP_CONVERSION_CHECK(group_size > 0, "GPTQ group_size must be greater than 0.");+ FRONT_END_OP_CONVERSION_CHECK(static_cast<size_t>(group_size) <= in_features,+ "GPTQ group_size must not exceed in_features.");+ const size_t group_size_u = static_cast<size_t>(group_size);+ FRONT_END_OP_CONVERSION_CHECK(in_features % group_size_u == 0, "GPTQ in_features must be divisible by group_size.");+ const size_t n_groups = in_features / group_size_u;+ auto new_shape = Shape{n_groups, group_size_u, N};+ auto new_const = std::make_shared<v0::Constant>(element::u4, new_shape, 0);+ auto dst = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(new_const->get_data_ptr()));+ for (size_t i = 0; i < K; ++i) {+ for (size_t j = 0; j < N; ++j) {+ uint32_t val = src[i * N + j];+ for (size_t k = 0; k < 8; ++k) {+ set_u4(dst, (i * 8 + k) * N + j, (val >> (k * 4)) & 0xF);+ }+ }+ }+ new_const->set_friendly_name(constant->get_friendly_name());+ return new_const;+}++// GPTQ qzeros: packs 8 u4 values per int32 along the OUTPUT dimension.+// Byte layout matches u4 layout directly — single-pass copy with +1 offset.+Output<Node> unpack_gptq_qzeros(const Output<Node>& c) {+ auto constant = ov::as_type_ptr<v0::Constant>(c.get_node_shared_ptr());+ FRONT_END_OP_CONVERSION_CHECK(constant, "qzeros must be Constant.");+ FRONT_END_OP_CONVERSION_CHECK(constant->get_byte_size() == shape_size(constant->get_shape()) * sizeof(uint32_t),+ "GPTQ qzeros storage size does not match expected int32 packing.");+ auto src = reinterpret_cast<const uint8_t*>(constant->get_data_ptr());+ auto initial_shape = constant->get_shape();+ FRONT_END_OP_CONVERSION_CHECK(initial_shape.size() == 2, "Only 2D qzeros constants are supported.");+ auto new_shape = Shape{initial_shape[0], 1, initial_shape[1] * 8};+ auto new_const = std::make_shared<v0::Constant>(element::u4, new_shape);+ auto dst = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(new_const->get_data_ptr()));+ // Apply +1 offset per u4 value while copying (GPTQ stores zp-1)+ const size_t n_bytes = shape_size(initial_shape) * sizeof(uint32_t);+ for (size_t i = 0; i < n_bytes; ++i) {+ uint8_t lo = (src[i] & 0x0F) + 1;+ uint8_t hi = ((src[i] >> 4) & 0x0F) + 1;+ dst[i] = (lo & 0x0F) | static_cast<uint8_t>((hi & 0x0F) << 4);+ }+ new_const->set_friendly_name(constant->get_friendly_name());+ return new_const;+}+} // namespaceOutputVector translate_linear_awq(const NodeContext& context) {@@ -159,6 +230,58 @@ OutputVector translate_linear_awq(const NodeContext& context) {return {matmul};};+OutputVector translate_linear_gptq(const NodeContext& context) {+ // ov_ext::gptq_gemm(input, qweight, qzeros, scales, group_size, bits, sym, bias?)+ num_inputs_check(context, 7, 8);+ auto x = context.get_input(0);+ auto qweight = context.get_input(1);+ auto qzeros = context.get_input(2);+ auto scales = context.get_input(3);+ auto group_size = context.const_input<int64_t>(4);+ auto bits = context.const_input<int64_t>(5);+ auto sym = context.const_input<bool>(6);++ FRONT_END_OP_CONVERSION_CHECK(bits == 4, "Only 4-bit GPTQ is supported.");++ // qweight: [in_features/8, out_features] int32 → [n_groups, group_size, out_features] u4+ auto new_qweight = unpack_gptq_qweight(qweight, group_size);++ Output<Node> new_qzeros;+ if (sym) {+ // Symmetric quantisation: zero point is always 8 (midpoint of u4 range)+ new_qzeros = context.mark_node(v0::Constant::create(element::u4, Shape{}, std::vector<uint8_t>{8}));+ } else {+ // qzeros: [n_groups, out_features/8] int32 → [n_groups, 1, out_features] u4 (with +1 offset)+ new_qzeros = unpack_gptq_qzeros(qzeros);+ }++ FRONT_END_OP_CONVERSION_CHECK(scales.get_partial_shape().is_static(), "Scales must be constant.");+ auto scales_shape = scales.get_shape();+ FRONT_END_OP_CONVERSION_CHECK(scales_shape.size() == 2,+ "GPTQ scales input is expected to be 2D, but got rank ",+ scales_shape.size(),+ ".");+ auto new_scales_shape =+ v0::Constant::create(element::i32, {3}, std::vector<uint64_t>{scales_shape[0], 1, scales_shape[1]});+ auto new_scales = context.mark_node(std::make_shared<v1::Reshape>(scales, new_scales_shape, false));+ // Reshape dequantised weight to [in_features, out_features] for matmul+ auto qweight_shape = qweight.get_shape();+ auto out_shape =+ v0::Constant::create(element::i32, {2}, std::vector<int32_t>{static_cast<int32_t>(qweight_shape[0] * 8), -1});+ auto weight = low_precision_subgraph(context, x, new_qweight, new_qzeros, new_scales, out_shape);++ auto matmul = context.mark_node(std::make_shared<v0::MatMul>(x, weight, false, false));+ if (!context.input_is_none(7)) {+ auto bias = context.get_input(7);++ if (bias.get_element_type() == element::f16 || bias.get_element_type() == element::bf16) {+ bias = context.mark_node(std::make_shared<v1::ConvertLike>(bias, x));+ }+ matmul = context.mark_node(std::make_shared<v1::Add>(matmul, bias));+ }+ return {matmul};+};+OutputVector translate_linear_bitnet(const NodeContext& context) {num_inputs_check(context, 3, 4);const auto x = context.get_input(0);diff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cppindex 0f018836755..40c033b5d7d 100644--- a/src/frontends/pytorch/src/op_table.cpp+++ b/src/frontends/pytorch/src/op_table.cpp@@ -370,6 +370,7 @@ OP_CONVERTER(translate_embedding_ext);OP_CONVERTER(translate_linear_awq);OP_CONVERTER(translate_linear_bitnet);OP_CONVERTER(translate_linear_ext);+OP_CONVERTER(translate_linear_gptq);} // namespace op// Supported ops for TorchScript@@ -791,6 +792,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {{"aten::zeros_like", op::translate_zeros_like},{"ov_ext::awq_gemm", op::translate_linear_awq},{"ov_ext::bit_linear", op::translate_linear_bitnet},+ {"ov_ext::gptq_gemm", op::translate_linear_gptq},{"ov_ext::bmm", op::translate_bmm_ext},{"ov_ext::embedding", op::translate_embedding_ext},{"ov_ext::conv1d", op::translate_conv1d_ext},@@ -1165,6 +1167,10 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_fx() {{"quantized_decomposed.dequantize_per_channel.default", op::skip_node},{"inlined.constant.default", op::translate_constant}, // this is a custom ov type{"inlined.list.default", op::translate_list_construct}, // this is a custom list type+ // OpenVINO extension ops registered via torch.library for torch.export+ {"ov_ext.awq_gemm.default", op::translate_linear_awq},+ {"ov_ext.bit_linear.default", op::translate_linear_bitnet},+ {"ov_ext.gptq_gemm.default", op::translate_linear_gptq},// Higher-order operations from torch.export (torch.cond, torch.while_loop, etc.){"cond", op::translate_cond_fx},{"while_loop", op::translate_while_loop_fx},diff --git a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py b/tests/layer_tests/py_frontend_tests/test_torch_frontend.pyindex 498576f5370..035a71ca8f6 100644--- a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py+++ b/tests/layer_tests/py_frontend_tests/test_torch_frontend.py@@ -1791,3 +1791,432 @@ class TestConvertModelDynamo:inp = np.random.randn(batch, 3, 32, 32).astype(np.float32)res = cm([inp])assert res[0].shape[0] == batch++# ──────────────────────────────────────────────────────────────────────+# Tests for torch.export path with ov_ext custom ops (quantized models)+# ──────────────────────────────────────────────────────────────────────+++def test_ov_ext_ops_meta_dispatch():+ """Verify quantized ov_ext ops produce correct shapes and dtypes on meta device."""+ import openvino.frontend.pytorch.ov_custom_ops # noqa: F401++ # awq_gemm+ r = torch.ops.ov_ext.awq_gemm(+ torch.empty(2, 64, dtype=torch.float16, device="meta"),+ torch.empty(64, 16, device="meta"),+ torch.empty(2, 16, device="meta"),+ torch.empty(2, 128, device="meta"),+ 32, 4, None)+ assert r.shape == (2, 128) and r.dtype == torch.float16++ # bit_linear+ r = torch.ops.ov_ext.bit_linear(+ torch.empty(2, 3, 32, dtype=torch.bfloat16, device="meta"),+ torch.empty(64, 32, device="meta"),+ torch.empty(64, device="meta"), None)+ assert r.shape == (2, 3, 64) and r.dtype == torch.bfloat16++ # gptq_gemm — qweight is [in_features/8, out_features]+ r = torch.ops.ov_ext.gptq_gemm(+ torch.empty(2, 64, dtype=torch.float16, device="meta"),+ torch.empty(8, 16, device="meta"),+ torch.empty(2, 2, device="meta"),+ torch.empty(2, 16, device="meta"),+ 32, 4, False, None)+ assert r.shape == (2, 16) and r.dtype == torch.float16+++def test_ov_ext_awq_gemm_output_shape():+ """ov_ext.awq_gemm produces correct output shape."""+ import openvino.frontend.pytorch.ov_custom_ops # noqa: F401+ batch, in_f, w_bit, group_size = 2, 64, 4, 32+ pack_num = 32 // w_bit+ packed_out = 16 # out_features = packed_out * pack_num = 128+ data = torch.randn(batch, in_f)+ qweight = torch.randint(0, 255, (in_f, packed_out), dtype=torch.int32)+ qzeros = torch.randint(0, 255, (in_f // group_size, packed_out), dtype=torch.int32)+ scales = torch.randn(in_f // group_size, packed_out * pack_num)+ result = torch.ops.ov_ext.awq_gemm(data, qweight, qzeros, scales, group_size, w_bit, None)+ assert result.shape == (batch, packed_out * pack_num)+++def test_ov_ext_bit_linear_output_shape():+ """ov_ext.bit_linear produces correct output shape."""+ import openvino.frontend.pytorch.ov_custom_ops # noqa: F401+ out_features = 64+ data = torch.randn(2, 3, 32)+ weight = torch.randn(out_features, 32)+ weight_scale = torch.randn(out_features)+ result = torch.ops.ov_ext.bit_linear(data, weight, weight_scale, None)+ assert result.shape == (2, 3, out_features)+++def test_ov_ext_gptq_gemm_output_shape():+ """ov_ext.gptq_gemm produces correct output shape."""+ import openvino.frontend.pytorch.ov_custom_ops # noqa: F401+ batch, in_f, w_bit, group_size = 2, 64, 4, 32+ pack_num = 32 // w_bit+ out_features = 64+ data = torch.randn(batch, in_f)+ # GPTQ packs along input dim: qweight = [in_features/pack_num, out_features]+ qweight = torch.randint(0, 255, (in_f // pack_num, out_features), dtype=torch.int32)+ # qzeros packs along output dim: qzeros = [n_groups, out_features/pack_num]+ qzeros = torch.randint(0, 255, (in_f // group_size, out_features // pack_num), dtype=torch.int32)+ scales = torch.randn(in_f // group_size, out_features)+ # Asymmetric+ result = torch.ops.ov_ext.gptq_gemm(data, qweight, qzeros, scales,+ group_size, w_bit, False, None)+ assert result.shape == (batch, out_features)+ # Symmetric+ result_sym = torch.ops.ov_ext.gptq_gemm(data, qweight, qzeros, scales,+ group_size, w_bit, True, None)+ assert result_sym.shape == (batch, out_features)++[email protected](sys.platform.lower().startswith("win"), reason="CVS-174725")+def test_gptq_export_pipeline():+ """Patch a GPTQ model with patch_quantized_for_export, export, convert, verify."""+ try:+ from auto_gptq.nn_modules.qlinear.qlinear_cuda_old import (+ QuantLinear as GPTQQuantLinear)+ except ImportError:+ pytest.skip("auto_gptq not installed")++ from openvino import convert_model, compile_model+ from openvino.frontend.pytorch.quantized import (+ patch_quantized_for_export, unpatch_quantized_for_export)++ rng = torch.Generator().manual_seed(42)+ in_features, out_features, group_size, bits = 32, 64, 32, 4+ pack_num = 32 // bits++ class FakeQuantConfig:+ quant_method = "gptq"+ sym = False++ class FakeConfig:+ quantization_config = FakeQuantConfig()++ class GPTQModel(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.config = FakeConfig()+ self.linear = GPTQQuantLinear(+ bits, group_size, in_features, out_features, True)+ # Fill with random quantized data+ self.linear.qweight = torch.nn.Parameter(+ torch.randint(0, 2**31, (in_features // pack_num, out_features),+ dtype=torch.int32, generator=rng),+ requires_grad=False)+ self.linear.qzeros = torch.nn.Parameter(+ torch.randint(0, 2**31, (in_features // group_size,+ out_features // pack_num),+ dtype=torch.int32, generator=rng),+ requires_grad=False)+ self.linear.scales = torch.nn.Parameter(+ torch.randn(in_features // group_size, out_features,+ dtype=torch.float16, generator=rng),+ requires_grad=False)+ self.linear.bias = torch.nn.Parameter(+ torch.randn(out_features, dtype=torch.float16, generator=rng),+ requires_grad=False)++ def forward(self, x):+ return self.linear(x)++ model = GPTQModel()+ x = torch.randn(1, in_features, generator=rng)++ patch_quantized_for_export(model)+ try:+ with torch.no_grad():+ ep = torch.export.export(model, (x,))+ # Verify custom op in graph+ ops = [str(n.target) for n in ep.module().graph.nodes if n.op == "call_function"]+ assert "ov_ext.gptq_gemm.default" in ops++ ov_model = convert_model(ep)+ assert ov_model+ cm = compile_model(ov_model, "CPU", default_cfg)+ res = cm([x.numpy()])+ assert res[0].shape == (1, out_features)+ finally:+ unpatch_quantized_for_export(model)++ # Verify model was unpatched+ for _, m in model.named_modules():+ assert not hasattr(m, "_openvino_quantized_patch_orig_forward")+++# ──────────────────────────────────────────────────────────────────────+# Tests for dynamo=True auto-patching of quantized models+# ──────────────────────────────────────────────────────────────────────++def test_dynamo_auto_patches_quantized_awq():+ """Verify convert_model(dynamo=True) auto-patches AWQ quantized models."""+ try:+ from awq.modules.linear import WQLinear_GEMM+ except ImportError:+ pytest.skip("awq not installed")++ from openvino import convert_model++ class FakeQuantConfig:+ quant_method = "awq"++ class FakeConfig:+ quantization_config = FakeQuantConfig()++ # Build a model with a WQLinear_GEMM submodule+ class FakeAWQModel(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.config = FakeConfig()+ in_f, out_f, w_bit, group_size = 64, 128, 4, 32+ pack_num = 32 // w_bit+ self.linear = WQLinear_GEMM(w_bit, group_size, in_f, out_f, bias=False, dev="cpu")+ # Provide properly shaped fake weights+ self.linear.qweight = torch.nn.Parameter(+ torch.randint(0, 255, (in_f, out_f // pack_num), dtype=torch.int32),+ requires_grad=False)+ self.linear.qzeros = torch.nn.Parameter(+ torch.randint(0, 255, (in_f // group_size, out_f // pack_num), dtype=torch.int32),+ requires_grad=False)+ self.linear.scales = torch.nn.Parameter(+ torch.randn(in_f // group_size, out_f), requires_grad=False)++ def forward(self, x):+ return self.linear(x)++ model = FakeAWQModel()+ example_input = torch.randn(2, 64)+ ov_model = convert_model(model, example_input=[example_input], dynamo=True)+ assert ov_model is not None++ # Verify the model was unpatched (no leftover attributes)+ for _, m in model.named_modules():+ assert not hasattr(m, "_openvino_quantized_patch_orig_forward")++ # Verify model has expected output shape+ assert ov_model.output(0).get_partial_shape()[-1].get_length() == 128+++def test_dynamo_auto_patches_gptq_graceful_fallback():+ """Verify convert_model(dynamo=True) handles GPTQ model with plain Linear (no QUANT_TYPE)."""+ from openvino import convert_model++ class FakeQuantConfig:+ quant_method = "gptq"++ class FakeConfig:+ quantization_config = FakeQuantConfig()++ class FakeGPTQModel(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.config = FakeConfig()+ self.linear = torch.nn.Linear(4, 2)++ def forward(self, x):+ return self.linear(x)++ model = FakeGPTQModel()+ example_input = torch.randn(2, 4)+ # Model uses plain Linear (no QUANT_TYPE), so GPTQ patching finds+ # nothing to patch and the model exports as-is+ ov_model = convert_model(model, example_input=[example_input], dynamo=True)+ assert ov_model is not None+++# ──────────────────────────────────────────────────────────────────────+# BitNet export pipeline tests+# ──────────────────────────────────────────────────────────────────────+[email protected](sys.platform.lower().startswith("win"), reason="CVS-174725")+def test_bitnet_export_pipeline():+ """Patch a BitNet model with patch_quantized_for_export, export, convert, verify."""+ from openvino import convert_model, compile_model+ from openvino.frontend.pytorch.quantized import (+ patch_quantized_for_export, unpatch_quantized_for_export)+ from transformers.integrations.bitnet import AutoBitLinear, pack_weights+ from transformers import PretrainedConfig, BitNetQuantConfig++ rng = torch.Generator().manual_seed(42)+ size = (32, 64)++ class BitNetModel(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.config = PretrainedConfig(+ quantization_config=BitNetQuantConfig(linear_class="autobitlinear"))+ self.linear = AutoBitLinear(size[0], size[1], bias=True, use_rms_norm=True)+ w = torch.randint(-1, 2, (size[1], size[0]), dtype=torch.float32, generator=rng)+ self.linear.weight = torch.nn.Parameter(w)+ self.linear.original_weight = pack_weights(self.linear.weight.data.clone())++ def forward(self, x):+ return self.linear(x)++ model = BitNetModel()+ x = torch.randn(1, size[0], generator=rng)+ with torch.no_grad():+ res_ref = model(x)++ patch_quantized_for_export(model)+ try:+ with torch.no_grad():+ ep = torch.export.export(model, (x,))+ # Verify custom ops in graph+ ops = [str(n.target) for n in ep.module().graph.nodes if n.op == "call_function"]+ assert "ov_ext.bit_linear.default" in ops++ ov_model = convert_model(ep)+ assert ov_model+ cm = compile_model(ov_model, "CPU", default_cfg)+ res = cm([x.numpy()])+ rtol, atol = 1e-4, 1e-4+ if platform.machine() in ('arm', 'armv7l', 'aarch64', 'arm64', 'ARM64'):+ rtol, atol = 0.5, 0.1+ np.testing.assert_allclose(res[0], res_ref.numpy(), rtol=rtol, atol=atol)+ finally:+ unpatch_quantized_for_export(model)++ # Verify model was unpatched+ for _, m in model.named_modules():+ assert not hasattr(m, "_openvino_quantized_patch_orig_forward")++[email protected](sys.platform.lower().startswith("win"), reason="CVS-174725")+def test_dynamo_auto_patches_bitnet():+ """Verify convert_model(dynamo=True) auto-patches BitNet quantized models."""+ from openvino import convert_model+ from transformers.integrations.bitnet import AutoBitLinear, pack_weights+ from transformers import PretrainedConfig, BitNetQuantConfig++ rng = torch.Generator().manual_seed(42)+ size = (32, 64)++ class BitNetModel(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.config = PretrainedConfig(+ quantization_config=BitNetQuantConfig(linear_class="autobitlinear"))+ self.linear = AutoBitLinear(size[0], size[1], bias=True, use_rms_norm=True)+ w = torch.randint(-1, 2, (size[1], size[0]), dtype=torch.float32, generator=rng)+ self.linear.weight = torch.nn.Parameter(w)+ self.linear.original_weight = pack_weights(self.linear.weight.data.clone())++ def forward(self, x):+ return self.linear(x)++ model = BitNetModel()+ x = torch.randn(1, size[0], generator=rng)+ ov_model = convert_model(model, example_input=[x], dynamo=True)+ assert ov_model is not None++ # Verify the model was unpatched+ for _, m in model.named_modules():+ assert not hasattr(m, "_openvino_quantized_patch_orig_forward")++ # Verify output shape+ assert ov_model.output(0).get_partial_shape()[-1].get_length() == size[1]+++def test_dynamo_auto_patches_gptq_converts_without_quantized_ops():+ """Verify convert_model(dynamo=True) with GPTQ produces valid model (no quant ops)."""+ from openvino import convert_model, compile_model++ class FakeQuantConfig:+ quant_method = "gptq"++ class FakeConfig:+ quantization_config = FakeQuantConfig()++ class FakeGPTQModel(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.config = FakeConfig()+ self.linear = torch.nn.Linear(16, 8)++ def forward(self, x):+ return self.linear(x)++ model = FakeGPTQModel()+ x = torch.randn(2, 16)+ with torch.no_grad():+ res_ref = model(x)++ # GPTQ patching fails gracefully; model is still exported as plain linear+ ov_model = convert_model(model, example_input=[x], dynamo=True)+ assert ov_model is not None++ # Verify the model was not patched (no leftover attributes)+ for _, m in model.named_modules():+ assert not hasattr(m, "_openvino_quantized_patch_orig_forward")++ # Verify output is numerically correct (plain linear, no quantization)+ cm = compile_model(ov_model, "CPU", default_cfg)+ res = cm([x.numpy()])+ np.testing.assert_allclose(res[0], res_ref.numpy(), atol=1e-5)++[email protected](sys.platform.lower().startswith("win"), reason="CVS-174725")+def test_dynamo_auto_patches_gptq():+ """Verify convert_model(dynamo=True) auto-patches GPTQ quantized models."""+ try:+ from auto_gptq.nn_modules.qlinear.qlinear_cuda_old import (+ QuantLinear as GPTQQuantLinear)+ except ImportError:+ pytest.skip("auto_gptq not installed")++ from openvino import convert_model++ rng = torch.Generator().manual_seed(42)+ in_features, out_features, group_size, bits = 32, 64, 32, 4+ pack_num = 32 // bits++ class FakeQuantConfig:+ quant_method = "gptq"+ sym = False++ class FakeConfig:+ quantization_config = FakeQuantConfig()++ class GPTQModel(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.config = FakeConfig()+ self.linear = GPTQQuantLinear(+ bits, group_size, in_features, out_features, True)+ self.linear.qweight = torch.nn.Parameter(+ torch.randint(0, 2**31, (in_features // pack_num, out_features),+ dtype=torch.int32, generator=rng),+ requires_grad=False)+ self.linear.qzeros = torch.nn.Parameter(+ torch.randint(0, 2**31, (in_features // group_size,+ out_features // pack_num),+ dtype=torch.int32, generator=rng),+ requires_grad=False)+ self.linear.scales = torch.nn.Parameter(+ torch.randn(in_features // group_size, out_features,+ dtype=torch.float16, generator=rng),+ requires_grad=False)+ self.linear.bias = torch.nn.Parameter(+ torch.randn(out_features, dtype=torch.float16, generator=rng),+ requires_grad=False)++ def forward(self, x):+ return self.linear(x)++ model = GPTQModel()+ x = torch.randn(1, in_features, generator=rng)+ ov_model = convert_model(model, example_input=[x], dynamo=True)+ assert ov_model is not None++ # Verify the model was unpatched+ for _, m in model.named_modules():+ assert not hasattr(m, "_openvino_quantized_patch_orig_forward")++ # Verify output shape+ assert ov_model.output(0).get_partial_shape()[-1].get_length() == out_featuresdiff --git a/tests/model_hub_tests/pytorch/test_llm.py b/tests/model_hub_tests/pytorch/test_llm.pyindex 3621cfc6f0a..922b606c421 100644--- a/tests/model_hub_tests/pytorch/test_llm.py+++ b/tests/model_hub_tests/pytorch/test_llm.py@@ -82,7 +82,7 @@ def patch_gptq():x = x.to(torch.float16)out = dequantize_gemm(qweight, qzeros, scales, w_bit, group_size)- out = torch.matmul(x, out)+ out = torch.matmul(x, out.to(x.dtype))out = out + bias if bias is not None else outout = out.reshape(out_shape)@@ -123,6 +123,9 @@ def flattenize_tuples(list_input):for r in list_input:if isinstance(r, (tuple, list)):unpacked_pt_res.extend(flattenize_tuples(r))+ elif hasattr(r, 'to_legacy_cache'):+ # DynamicCache → legacy tuple of (key, value) tuples+ unpacked_pt_res.extend(flattenize_tuples(r.to_legacy_cache()))else:unpacked_pt_res.append(r)return unpacked_pt_res@@ -144,6 +147,7 @@ class TestLLMModel(TestTorchConvertModel):def setup_class(self):self.infer_timeout = 1800self.cuda_available, self.gptq_postinit, self.orig_gemm_forward = None, None, None+ self.export_mode = False@retry(3, exceptions=(OSError,), delay=1)def load_model(self, name, type):@@ -204,6 +208,9 @@ class TestLLMModel(TestTorchConvertModel):res = []for k in filtered_keys:v = inputs[k]+ # DynamicCache (newer transformers) → legacy tuple for flattening+ if hasattr(v, 'to_legacy_cache'):+ v = v.to_legacy_cache()if isinstance(v, tuple):v_flatten = flattenize_outputs(v)if k == "past_key_values":@@ -218,7 +225,46 @@ class TestLLMModel(TestTorchConvertModel):fw_outputs = model_obj(**inputs)return flattenize_outputs(fw_outputs)+ def infer_ov_model(self, ov_model, inputs, ie_device):+ if self.export_mode:+ return self._infer_ov_model_export(ov_model, ie_device)+ return super().infer_ov_model(ov_model, inputs, ie_device)++ def compare_results(self, fw_outputs, ov_outputs):+ if self.export_mode and isinstance(fw_outputs, (list, tuple)):+ # In export mode, only compare the first output (logits).+ # KV cache outputs diverge for quantized models because+ # FW and OV dequantization paths differ.+ return super().compare_results([fw_outputs[0]], [ov_outputs[0]])+ return super().compare_results(fw_outputs, ov_outputs)++ def _infer_ov_model_export(self, ov_model, ie_device):+ """Build inputs dict by OV model input names for the export path.++ FX export flattens nested structures (e.g. past_key_values tuples)+ into individual named inputs, so we match OV input names against+ the flattened example data.+ """+ from openvino import Core+ from torch.utils._pytree import tree_flatten++ example = getattr(self, "inputs", self.example)+ flat_values, _ = tree_flatten(example)+ flat_np = [to_numpy(v) if isinstance(v, torch.Tensor) else v+ for v in flat_values]++ ov_inputs = {}+ for i, inp in enumerate(ov_model.inputs):+ if i < len(flat_np):+ ov_inputs[i] = flat_np[i]++ core = Core()+ compiled = core.compile_model(ov_model, ie_device, self.ov_config)+ return compiled(ov_inputs)+def convert_model_impl(self, model_obj):+ if self.export_mode:+ return self._convert_model_export(model_obj)is_patched = Falseif getattr(self.model.config, "torch_dtype", None) in [torch.float16, torch.bfloat16]:patch(self.model)@@ -232,7 +278,50 @@ class TestLLMModel(TestTorchConvertModel):# model_obj.float()return ovm+ def _convert_model_export(self, model_obj):+ from torch.export import export+ from openvino import convert_model+ from openvino.frontend.pytorch.quantized import (+ detect_quantized_model,+ patch_quantized_for_export,+ unpatch_quantized_for_export,+ )++ is_quant_patched = False++ quant_type = detect_quantized_model(self.model)+ if quant_type:+ patch_quantized_for_export(self.model)+ is_quant_patched = True++ try:+ # Initialize model after patching+ self.model(**self.example)++ with torch.no_grad():+ exported = export(+ self.model,+ args=tuple(),+ kwargs=self.example,+ strict=False,+ )+ # Restore CUDA mocks before convert_model because+ # run_decompositions() tries to preserve CUDA RNG state+ # and fails when CUDA is mocked but not really available.+ # Only restore CUDA check functions — the AWQ GEMM forward+ # must stay patched for infer_fw_model.+ if self.cuda_available is not None:+ (torch.cuda.is_available,+ torch.cuda.is_bf16_supported,+ torch.cuda.get_device_capability) = self.cuda_available+ ovm = convert_model(exported, verbose=True)+ finally:+ if is_quant_patched:+ unpatch_quantized_for_export(self.model)+ return ovm+def teardown_method(self):+ self.export_mode = False# restore after gptq patchingif self.cuda_available is not None:unpatch_gptq(self.cuda_available, self.gptq_postinit, self.orig_gemm_forward)@@ -246,6 +335,11 @@ class TestLLMModel(TestTorchConvertModel):with torch.no_grad():pkv = model(**for_pkv)[1]+ # Newer transformers return DynamicCache; convert to legacy tuple format+ # so that the example dict contains plain tensors for both TS and FX paths.+ if hasattr(pkv, "to_legacy_cache"):+ pkv = pkv.to_legacy_cache()+return pkv, for_pkv["attention_mask"]def get_supported_precommit_models():@@ -310,3 +404,17 @@ class TestLLMModel(TestTorchConvertModel):])def test_convert_model_very_large(self, name, type, ie_device):self.run(model_name=name, model_link=type, ie_device=ie_device)++ def get_supported_export_precommit_models():+ if platform.machine() in ['arm', 'armv7l', 'aarch64', 'arm64', 'ARM64']:+ return []+ return [+ ("llama_awq", "casperhansen/tinyllama-1b-awq"),+ ]++ @pytest.mark.parametrize("type,name", get_supported_export_precommit_models())+ @pytest.mark.precommit+ @pytest.mark.nightly+ def test_export_model_precommit(self, name, type, ie_device):+ self.export_mode = True+ self.run(model_name=name, model_link=type, ie_device=ie_device)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 44e440889c5..1522f4284a1 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@@ -114,38 +114,6 @@ def _build_dynamic_shapes(inputs, input_specs=None):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@@ -184,10 +152,11 @@ def get_pytorch_decoder(model, example_inputs, args):# because _build_dynamic_shapes expects _InputCutInfo objects with .shape attribute.raw_input = args.get('input', None) or Noneinput_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)+ dynamic_shapes = _build_dynamic_shapes(inputs, input_specs=input_specs)+ decoder = TorchFXPythonDecoder.from_model(+ model,+ example_inputs=inputs,+ dynamic_shapes=dynamic_shapes)else:decoder = TorchScriptPythonDecoder(model,