Skip to content

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

[PT FE] Support AWQ models obtained by compressed-tensors (#36455)

Maxim Vafin6a6e7473b20e
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/compressed_tensors.py b/src/bindings/python/src/openvino/frontend/pytorch/compressed_tensors.py
new file mode 100644
index 00000000000..03510a89c36
--- /dev/null
+++ b/src/bindings/python/src/openvino/frontend/pytorch/compressed_tensors.py
@@ -0,0 +1,110 @@
+# -*- coding: utf-8 -*-
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+import torch
+from openvino.frontend.pytorch import ModuleExtension
+
+log = logging.getLogger(__name__)
+
+
+def build_extensions(for_export: bool = False) -> dict[Any, Any]:
+ """Build a ``ModuleExtension`` mapping for compressed-tensors ``CompressedLinear``.
+
+ Converts int4 pack-quantized weights directly to ``ov_ext::ct_gemm``, preserving
+ weights as OV i4 (symmetric) or u4 (asymmetric) constants without decompressing
+ to float first. All unpacking and dequantization graph construction happens in
+ the C++ PyTorch frontend translator.
+
+ Supports symmetric and asymmetric group-quantized int4 (``num_bits=4``,
+ ``strategy="group"``). An exception is raised for unsupported configurations
+ so that they are never silently skipped.
+
+ Args:
+ for_export: When ``True``, scalar arguments (``group_size``, ``sym``)
+ are passed as plain Python values, as required by ``torch.export``.
+ When ``False`` (TorchScript default), they are wrapped in ``torch.tensor``.
+
+ Returns:
+ Dict mapping the ``CompressedLinear`` class to a ``ModuleExtension``, or an
+ empty dict if the ``compressed_tensors`` package is not installed.
+ """
+ try:
+ from compressed_tensors.linear.compressed_linear import CompressedLinear
+ except ImportError:
+ log.warning(
+ "compressed_tensors package not found; "
+ "CompressedLinear extensions will not be registered."
+ )
+ return {}
+
+ def _convert(
+ module: Any,
+ target_op: Any,
+ *args: Any,
+ **kwargs: Any,
+ ) -> torch.Tensor:
+ weight_args = getattr(
+ getattr(module, "quantization_scheme", None), "weights", None
+ )
+ if weight_args is None:
+ raise ValueError(
+ "CompressedLinear module is missing quantization_scheme.weights; "
+ "cannot export to OpenVINO int4."
+ )
+
+ num_bits = getattr(weight_args, "num_bits", None)
+ symmetric = getattr(weight_args, "symmetric", None)
+ strategy = getattr(weight_args, "strategy", None)
+ group_size = getattr(weight_args, "group_size", None)
+
+ if num_bits != 4:
+ raise ValueError(
+ f"Unsupported num_bits={num_bits} in compressed-tensors module. "
+ "Only num_bits=4 is supported."
+ )
+ if symmetric is None:
+ raise ValueError(
+ "CompressedLinear module is missing quantization_scheme.weights.symmetric."
+ )
+ if strategy != "group":
+ raise ValueError(
+ f"Unsupported strategy={strategy!r} in compressed-tensors module. "
+ "Only strategy='group' is supported."
+ )
+ if group_size is None:
+ raise ValueError(
+ "CompressedLinear module is missing quantization_scheme.weights.group_size."
+ )
+
+ sym_val = bool(symmetric)
+ gs = group_size if for_export else torch.tensor(group_size)
+ sym = sym_val if for_export else torch.tensor(sym_val)
+
+ # Pass raw CT buffers directly — all unpacking happens in C++ translate_linear_ct.
+ # weight_packed: [out, in//8] int32 (8 nibbles/int32, low-nibble first)
+ # weight_scale: [out, n_groups] float32
+ # weight_zero_point: [out//8, n_groups] int32 (asym only, same nibble packing)
+ bias = getattr(module, "bias", None)
+ if sym_val:
+ return target_op(args[0], module.weight_packed, module.weight_scale,
+ gs, sym, None, bias)
+ else:
+ return target_op(args[0], module.weight_packed, module.weight_scale,
+ gs, sym, module.weight_zero_point, bias)
+
+ return {
+ CompressedLinear: ModuleExtension(
+ CompressedLinear,
+ "ov_ext::ct_gemm",
+ convert=_convert,
+ evaluate=lambda module, *args, **kwargs: torch.full(
+ (*args[0].shape[:-1], module.out_features), 0.5,
+ dtype=torch.float32, device=args[0].device),
+ )
+ }
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/ov_custom_ops.py b/src/bindings/python/src/openvino/frontend/pytorch/ov_custom_ops.py
index bc980aa6429..65715d6f011 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/ov_custom_ops.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/ov_custom_ops.py
@@ -145,4 +145,52 @@ def _gptq_gemm_cpu(
return out.to(data.dtype)
+# ──────────────────────────────────────────────────────────────────────
+# ov_ext::ct_gemm (input, weight_packed, weight_scale, group_size,
+# sym, weight_zero_point?, bias?) → Tensor
+#
+# Compressed-tensors pack-quantized int4 gemm.
+# weight_packed: [out_features, in_features // 8] int32
+# 8 nibbles per int32, low nibble first.
+# Nibble values = q_uint = q_int8 + 8 ∈ [0, 15].
+# weight_scale: [out_features, n_groups] float32
+# weight_zero_point: [out_features // 8, n_groups] int32 (asym only)
+# Same nibble packing, values = zp_uint ∈ [0, 15].
+# sym=True → i4 weights, no zero-point subtraction.
+# sym=False → u4 weights, zero-point subtracted before scaling.
+# ──────────────────────────────────────────────────────────────────────
+_ov_ext_lib.define(
+ "ct_gemm(Tensor input, Tensor weight_packed, Tensor weight_scale, "
+ "int group_size, bool sym, Tensor? weight_zero_point, "
+ "Tensor? bias) -> Tensor")
+
+
[email protected](_ov_ext_lib, "ct_gemm", "Meta")
+def _ct_gemm_meta(
+ data: torch.Tensor, weight_packed: torch.Tensor,
+ _weight_scale: torch.Tensor, _group_size: int, _sym: bool,
+ _weight_zero_point: torch.Tensor | None, _bias: torch.Tensor | None,
+) -> torch.Tensor:
+ out_features = weight_packed.shape[0] # weight_packed shape: [out_features, in_features // 8]
+ return torch.empty(
+ *data.shape[:-1], out_features,
+ dtype=data.dtype, device="meta")
+
+
[email protected](_ov_ext_lib, "ct_gemm", "CPU")
+def _ct_gemm_cpu(
+ data: torch.Tensor, weight_packed: torch.Tensor,
+ _weight_scale: torch.Tensor, _group_size: int, _sym: bool,
+ _weight_zero_point: torch.Tensor | None, bias: torch.Tensor | None,
+) -> torch.Tensor:
+ # Placeholder – actual dequantisation happens in the C++ OV translator.
+ out_features = weight_packed.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)
+
+
log.debug("Registered ov_ext custom ops for torch.export")
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/quantized.py b/src/bindings/python/src/openvino/frontend/pytorch/quantized.py
index 8c2d1edc979..e44e6f32433 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/quantized.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/quantized.py
@@ -11,7 +11,7 @@ from collections.abc import Callable
from typing import Any
import torch
-from openvino.frontend.pytorch import ModuleExtension, gptq
+from openvino.frontend.pytorch import ModuleExtension, compressed_tensors, gptq
from openvino.frontend.pytorch.patch_model import (
patch_model, unpatch_model, patch_model_for_export)
@@ -128,6 +128,8 @@ def _build_quantized_extensions(
# GPTQ is handled separately — not via ModuleExtension for TorchScript,
# and via attribute-based patching for torch.export (see _patch_gptq_for_export).
return None
+ elif quant_type == "compressed-tensors":
+ return compressed_tensors.build_extensions(for_export) # type: ignore
else:
raise RuntimeError(f"Unknown quantization type: {quant_type}.")
return extensions
diff --git a/src/frontends/pytorch/src/op/linear.cpp b/src/frontends/pytorch/src/op/linear.cpp
index 73bdbe51b52..7d17a4cf755 100644
--- a/src/frontends/pytorch/src/op/linear.cpp
+++ b/src/frontends/pytorch/src/op/linear.cpp
@@ -8,6 +8,7 @@
#include "openvino/op/matmul.hpp"
#include "openvino/op/reshape.hpp"
#include "openvino/op/shape_of.hpp"
+#include "openvino/op/transpose.hpp"
#include "utils.hpp"
namespace ov {
@@ -336,6 +337,150 @@ OutputVector translate_linear_bitnet(const NodeContext& context) {
return {matmul};
};
+namespace {
+
+// compressed-tensors pack-quantized int4:
+// weight_packed [out, in//8] int32: 8 nibbles per int32, nibble k at bits [k*4+3:k*4].
+// weight_scale [out, n_groups] float32.
+// weight_zero_point [out//8, n_groups] int32 (asymmetric only, same nibble packing).
+//
+// Symmetric → i4 weight constant (subtract 8 from each nibble), no zero-point node.
+// Asymmetric → u4 weight constant (nibbles as-is), u4 zero-point constant.
+//
+// Output shape [n_groups, group_size, out_features] so that it broadcasts correctly
+// with scales/zero_points shaped [n_groups, 1, out_features].
+Output<Node> unpack_ct_weight(const Output<Node>& c, bool sym, size_t group_size) {
+ auto constant = ov::as_type_ptr<v0::Constant>(c.get_node_shared_ptr());
+ FRONT_END_OP_CONVERSION_CHECK(constant, "weight_packed must be Constant.");
+ FRONT_END_OP_CONVERSION_CHECK(constant->get_byte_size() == shape_size(constant->get_shape()) * sizeof(uint32_t),
+ "CT weight_packed storage size does not match expected int32 packing.");
+ const auto* src = constant->get_data_ptr<uint32_t>();
+ const auto initial_shape = constant->get_shape();
+ FRONT_END_OP_CONVERSION_CHECK(initial_shape.size() == 2, "Only 2D weight_packed constants are supported.");
+ const size_t out_features = initial_shape[0];
+ const size_t in_div8 = initial_shape[1]; // in_features / 8
+ const size_t in_features = in_div8 * 8;
+ FRONT_END_OP_CONVERSION_CHECK(group_size > 0 && in_features % group_size == 0,
+ "CT group_size must divide in_features.");
+ const size_t n_groups = in_features / group_size;
+ // Output shape: [n_groups, group_size, out_features] — compatible with scales [n_groups, 1, out_features].
+ // Row-major layout of [n_groups, group_size, out_features] equals [in_features, out_features],
+ // so the write index for element (o, i) is i * out_features + o.
+ const element::Type out_type = sym ? element::i4 : element::u4;
+ auto new_const = std::make_shared<v0::Constant>(out_type, Shape{n_groups, group_size, out_features}, 0);
+ auto* dst = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(new_const->get_data_ptr()));
+ for (size_t o = 0; o < out_features; ++o) {
+ for (size_t b = 0; b < in_div8; ++b) {
+ uint32_t val = src[o * in_div8 + b];
+ for (size_t k = 0; k < 8; ++k) {
+ uint8_t nibble = static_cast<uint8_t>((val >> (k * 4)) & 0xFU);
+ if (sym) {
+ // Re-bias: q_uint - 8 gives signed in [-8, 7], store as i4
+ nibble = static_cast<uint8_t>((nibble - 8U) & 0xFU);
+ }
+ // Transposed index: weight[o, i] → grouped[i, o] (row-major)
+ set_u4(dst, (b * 8 + k) * out_features + o, nibble);
+ }
+ }
+ }
+ new_const->set_friendly_name(constant->get_friendly_name());
+ return new_const;
+}
+
+// Unpack CT zero_point [out//8, n_groups] int32 → [n_groups, 1, out] u4 constant.
+// Each int32 holds 8 nibbles: nibble k corresponds to output row (out8_idx*8 + k).
+// Output shape [n_groups, 1, out_features] is broadcast-compatible with weight [n_groups, group_size, out].
+Output<Node> unpack_ct_zp(const Output<Node>& c, size_t out_features) {
+ auto constant = ov::as_type_ptr<v0::Constant>(c.get_node_shared_ptr());
+ FRONT_END_OP_CONVERSION_CHECK(constant, "weight_zero_point must be Constant.");
+ FRONT_END_OP_CONVERSION_CHECK(constant->get_byte_size() == shape_size(constant->get_shape()) * sizeof(uint32_t),
+ "CT weight_zero_point storage size does not match expected int32 packing.");
+ const auto* src = constant->get_data_ptr<uint32_t>();
+ const auto initial_shape = constant->get_shape();
+ FRONT_END_OP_CONVERSION_CHECK(initial_shape.size() == 2, "Only 2D weight_zero_point constants are supported.");
+ const size_t n_out8 = initial_shape[0];
+ const size_t n_groups = initial_shape[1];
+ FRONT_END_OP_CONVERSION_CHECK(n_out8 * 8 == out_features, "CT weight_zero_point dim0*8 must equal out_features.");
+ // Output: [n_groups, 1, out_features] u4 — matches scale layout for broadcast
+ auto new_const = std::make_shared<v0::Constant>(element::u4, Shape{n_groups, 1, out_features}, 0);
+ auto* dst = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(new_const->get_data_ptr()));
+ for (size_t b = 0; b < n_out8; ++b) {
+ const size_t o_base = b * 8;
+ for (size_t g = 0; g < n_groups; ++g) {
+ uint32_t val = src[b * n_groups + g];
+ for (size_t k = 0; k < 8; ++k) {
+ uint8_t nibble = static_cast<uint8_t>((val >> (k * 4)) & 0xFU);
+ // Index in [n_groups, 1, out_features]: g * out_features + (o_base + k)
+ set_u4(dst, g * out_features + o_base + k, nibble);
+ }
+ }
+ }
+ new_const->set_friendly_name(constant->get_friendly_name());
+ return new_const;
+}
+
+} // namespace
+
+OutputVector translate_linear_ct(const NodeContext& context) {
+ // ov_ext::ct_gemm(input, weight_packed, weight_scale, group_size, sym,
+ // weight_zero_point?, bias?)
+ num_inputs_check(context, 5, 7);
+ auto x = context.get_input(0);
+ auto weight_packed = context.get_input(1);
+ auto scales = context.get_input(2);
+ const auto group_size = context.const_input<int64_t>(3);
+ const auto sym = context.const_input<bool>(4);
+
+ const auto wp_shape = weight_packed.get_shape();
+ FRONT_END_OP_CONVERSION_CHECK(wp_shape.size() == 2, "weight_packed must be 2D.");
+ const size_t out_features = wp_shape[0];
+ const size_t in_features = wp_shape[1] * 8;
+ FRONT_END_OP_CONVERSION_CHECK(group_size > 0 && static_cast<size_t>(group_size) <= in_features &&
+ in_features % static_cast<size_t>(group_size) == 0,
+ "CT group_size must divide in_features.");
+ const size_t n_groups = in_features / static_cast<size_t>(group_size);
+
+ // Unpack weights: [n_groups, group_size, out] i4 (sym) or u4 (asym)
+ auto new_weight = unpack_ct_weight(weight_packed, sym, static_cast<size_t>(group_size));
+
+ // Scales: [out, n_groups] → transpose to [n_groups, out] → reshape to [n_groups, 1, out]
+ FRONT_END_OP_CONVERSION_CHECK(scales.get_partial_shape().is_static(), "weight_scale must have a static shape.");
+ const auto scales_shape = scales.get_shape();
+ FRONT_END_OP_CONVERSION_CHECK(
+ scales_shape.size() == 2 && scales_shape[0] == out_features && scales_shape[1] == n_groups,
+ "CT weight_scale shape must be [out_features, n_groups].");
+ auto new_scales_shape = v0::Constant::create(
+ element::i32,
+ {3},
+ std::vector<int64_t>{static_cast<int64_t>(n_groups), 1, static_cast<int64_t>(out_features)});
+ auto perm = v0::Constant::create(element::i32, {2}, std::vector<int32_t>{1, 0});
+ auto scales_T = context.mark_node(std::make_shared<v1::Transpose>(scales, perm));
+ auto new_scales = context.mark_node(std::make_shared<v1::Reshape>(scales_T, new_scales_shape, false));
+
+ // Reshape dequantised weight to [in_features, out_features] for matmul
+ auto out_shape = v0::Constant::create(
+ element::i32,
+ {2},
+ std::vector<int32_t>{static_cast<int32_t>(in_features), static_cast<int32_t>(out_features)});
+
+ Output<Node> new_zp;
+ if (!sym) {
+ FRONT_END_OP_CONVERSION_CHECK(!context.input_is_none(5), "CT asymmetric gemm requires weight_zero_point.");
+ new_zp = unpack_ct_zp(context.get_input(5), out_features);
+ }
+ auto weight = low_precision_subgraph(context, x, new_weight, new_zp, new_scales, out_shape);
+
+ auto matmul = context.mark_node(std::make_shared<v0::MatMul>(x, weight, false, false));
+ if (!context.input_is_none(6)) {
+ auto bias = context.get_input(6);
+ 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_bmm_ext(const NodeContext& context) {
// ov_ext::bmm - batch matrix multiplication for 16-bit models
// schema: ov_ext::bmm(Tensor batch1, Tensor batch2) -> Tensor
diff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cpp
index 58d04314a26..cb8cca2bf62 100644
--- a/src/frontends/pytorch/src/op_table.cpp
+++ b/src/frontends/pytorch/src/op_table.cpp
@@ -371,6 +371,7 @@ OP_CONVERTER(translate_conv1d_ext);
OP_CONVERTER(translate_embedding_ext);
OP_CONVERTER(translate_linear_awq);
OP_CONVERTER(translate_linear_bitnet);
+OP_CONVERTER(translate_linear_ct);
OP_CONVERTER(translate_linear_ext);
OP_CONVERTER(translate_linear_gptq);
} // namespace op
@@ -804,6 +805,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::ct_gemm", op::translate_linear_ct},
{"ov_ext::gptq_gemm", op::translate_linear_gptq},
{"ov_ext::bmm", op::translate_bmm_ext},
{"ov_ext::embedding", op::translate_embedding_ext},
@@ -1183,6 +1185,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_fx() {
// 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.ct_gemm.default", op::translate_linear_ct},
{"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},
diff --git a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py b/tests/layer_tests/py_frontend_tests/test_torch_frontend.py
index 4fa01b85ac1..69d91f2a8d9 100644
--- a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py
+++ b/tests/layer_tests/py_frontend_tests/test_torch_frontend.py
@@ -2721,3 +2721,257 @@ def test_dynamo_auto_patches_gptq():
# Verify output shape
assert ov_model.output(0).get_partial_shape()[-1].get_length() == out_features
+
+
+# ──────────────────────────────────────────────────────────────────────
+# compressed-tensors (NeuralMagic) export pipeline tests
+# ──────────────────────────────────────────────────────────────────────
+
+def _make_fake_ct_model(in_features=32, out_features=64, group_size=32, symmetric=True):
+ """Return ``(model, x, FakeCompressedLinear)`` for compressed-tensors tests.
+
+ The fake module exposes all attributes consumed by
+ ``compressed_tensors.build_extensions``:
+
+ * ``weight_packed`` – int32, shape ``[out, in//8]``
+ * ``weight_scale`` – float32, shape ``[out, n_groups]``
+ * ``weight_zero_point`` – int32, shape ``[out//8, n_groups]`` (asymmetric only)
+ * ``quantization_scheme`` – object with ``.weights.num_bits``,
+ ``.weights.symmetric``, ``.weights.strategy``,
+ ``.weights.group_size``
+ * ``out_features`` – plain int
+ * ``bias`` – None
+
+ The outer ``CTModel`` has ``config.quantization_config.quant_method``
+ set to ``"compressed-tensors"`` so that ``detect_quantized_model``
+ returns the right type.
+ """
+ rng = torch.Generator().manual_seed(0)
+ n_groups = in_features // group_size
+ _group_size = group_size # captured before class definition to avoid class-scope NameError
+ _symmetric = symmetric
+
+ class FakeWeightArgs:
+ num_bits = 4
+ symmetric = _symmetric
+ strategy = "group"
+ group_size = _group_size
+
+ class FakeScheme:
+ weights = FakeWeightArgs()
+
+ class FakeQuantConfig:
+ quant_method = "compressed-tensors"
+
+ class FakeConfig:
+ quantization_config = FakeQuantConfig()
+
+ class FakeCompressedLinear(torch.nn.Module):
+ """Minimal stand-in for ``compressed_tensors.linear.CompressedLinear``."""
+
+ def __init__(self):
+ super().__init__()
+ self.out_features = out_features
+ self.in_features = in_features
+ self.register_buffer(
+ "weight_packed",
+ torch.randint(
+ -(2 ** 31), 2 ** 31,
+ (out_features, in_features // 8),
+ dtype=torch.int32,
+ generator=rng,
+ ),
+ )
+ self.register_buffer(
+ "weight_scale",
+ torch.randn(out_features, n_groups, dtype=torch.float32, generator=rng),
+ )
+ if not _symmetric:
+ self.register_buffer(
+ "weight_zero_point",
+ torch.randint(
+ -(2 ** 31), 2 ** 31,
+ (out_features // 8, n_groups),
+ dtype=torch.int32,
+ generator=rng,
+ ),
+ )
+ self.quantization_scheme = FakeScheme()
+ self.bias = None
+
+ def forward(self, x):
+ return torch.zeros(*x.shape[:-1], self.out_features, dtype=x.dtype)
+
+ class CTModel(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.config = FakeConfig()
+ self.linear = FakeCompressedLinear()
+
+ def forward(self, x):
+ return self.linear(x)
+
+ model = CTModel()
+ x = torch.randn(2, in_features, generator=rng)
+ return model, x, FakeCompressedLinear
+
+
+def _inject_fake_ct_module(fake_linear_class):
+ """Inject a stub ``compressed_tensors`` package into ``sys.modules`` so that
+ ``compressed_tensors.build_extensions`` resolves ``CompressedLinear`` to
+ ``fake_linear_class``.
+
+ Returns a dict of the previous ``sys.modules`` state for the touched keys so
+ the caller can restore it (pass to ``_restore_ct_modules``).
+ """
+ import types
+ _CT_KEYS = [
+ "compressed_tensors",
+ "compressed_tensors.linear",
+ "compressed_tensors.linear.compressed_linear",
+ ]
+ prior = {k: sys.modules.get(k) for k in _CT_KEYS}
+
+ fake_ct_pkg = prior["compressed_tensors"] or types.ModuleType("compressed_tensors")
+ fake_linear_mod = types.ModuleType("compressed_tensors.linear.compressed_linear")
+ fake_linear_mod.CompressedLinear = fake_linear_class
+ sys.modules.setdefault("compressed_tensors", fake_ct_pkg)
+ sys.modules["compressed_tensors.linear"] = types.ModuleType("compressed_tensors.linear")
+ sys.modules["compressed_tensors.linear.compressed_linear"] = fake_linear_mod
+ return prior
+
+
+def _restore_ct_modules(prior):
+ """Restore ``sys.modules`` entries saved by ``_inject_fake_ct_module``."""
+ for key, value in prior.items():
+ if value is None:
+ sys.modules.pop(key, None)
+ else:
+ sys.modules[key] = value
+
+
+def test_compressed_tensors_build_extensions_returns_non_empty():
+ """``build_extensions()`` returns a non-empty dict keyed by ``CompressedLinear``."""
+ from openvino.frontend.pytorch.compressed_tensors import build_extensions
+ from openvino.frontend.pytorch import ModuleExtension
+
+ _, _, FakeCompressedLinear = _make_fake_ct_model()
+ prior = _inject_fake_ct_module(FakeCompressedLinear)
+ try:
+ extensions = build_extensions(for_export=False)
+ assert extensions, "build_extensions() returned an empty dict"
+ assert FakeCompressedLinear in extensions, \
+ "CompressedLinear class not in extensions dict"
+ assert isinstance(extensions[FakeCompressedLinear], ModuleExtension)
+ finally:
+ _restore_ct_modules(prior)
+
+
+def test_compressed_tensors_convert_keeps_u4():
+ """TorchScript conversion of a compressed-tensors model must keep 4-bit
+ (i4/u4) weight constants — weights must NOT be decompressed to float.
+
+ The ``TorchScriptPythonDecoder`` auto-detects the quant type via
+ ``detect_quantized_model`` and patches the model internally, so no manual
+ ``patch_model`` call is needed here.
+ """
+ from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder
+
+ model, x, FakeCompressedLinear = _make_fake_ct_model()
+ prior = _inject_fake_ct_module(FakeCompressedLinear)
+ try:
+ decoder = TorchScriptPythonDecoder(model, example_input=(x,))
+ fe = FrontEndManager().load_by_framework("pytorch")
+ ov_model = fe.convert(fe.load(decoder))
+ assert ov_model is not None
+
+ four_bit_consts = [
+ op for op in ov_model.get_ops()
+ if op.get_type_name() == "Constant"
+ and op.get_output_element_type(0) in (Type.i4, Type.u4)
+ ]
+ assert four_bit_consts, \
+ "Expected a packed 4-bit (i4/u4) weight constant in the OV model"
+ finally:
+ _restore_ct_modules(prior)
+
+
[email protected](sys.platform.lower().startswith("win"), reason="CVS-174725")
+def test_compressed_tensors_export_pipeline():
+ """``patch_quantized_for_export`` + ``torch.export`` + ``convert_model``
+ must produce a valid OV model and preserve ``ov_ext.ct_gemm`` in the
+ exported graph."""
+ from openvino import convert_model, compile_model
+ from openvino.frontend.pytorch.quantized import (
+ patch_quantized_for_export, unpatch_quantized_for_export)
+ import openvino.frontend.pytorch.ov_custom_ops # noqa: F401
+
+ model, x, FakeCompressedLinear = _make_fake_ct_model()
+ prior = _inject_fake_ct_module(FakeCompressedLinear)
+ try:
+ patch_quantized_for_export(model)
+ try:
+ with torch.no_grad():
+ ep = torch.export.export(model, (x,))
+
+ ops = [str(n.target) for n in ep.module().graph.nodes if n.op == "call_function"]
+ assert "ov_ext.ct_gemm.default" in ops, \
+ f"ov_ext.ct_gemm not found in exported graph. Ops: {ops}"
+
+ ov_model = convert_model(ep)
+ assert ov_model is not None
+ cm = compile_model(ov_model, "CPU", default_cfg)
+ res = cm([x.numpy()])
+ assert res[0].shape == (2, 64)
+ finally:
+ unpatch_quantized_for_export(model)
+
+ for _, m in model.named_modules():
+ assert not hasattr(m, "_openvino_quantized_patch_orig_forward")
+ finally:
+ _restore_ct_modules(prior)
+
+
+def test_dynamo_auto_patches_compressed_tensors():
+ """``convert_model(dynamo=True)`` must auto-patch a compressed-tensors model
+ and produce a valid OV model with the expected output shape."""
+ from openvino import convert_model
+
+ model, x, FakeCompressedLinear = _make_fake_ct_model()
+ prior = _inject_fake_ct_module(FakeCompressedLinear)
+ try:
+ ov_model = convert_model(model, example_input=[x], dynamo=True)
+ assert ov_model is not None
+
+ for _, m in model.named_modules():
+ assert not hasattr(m, "_openvino_quantized_patch_orig_forward")
+
+ assert ov_model.output(0).get_partial_shape()[-1].get_length() == 64
+ finally:
+ _restore_ct_modules(prior)
+
+
+def test_compressed_tensors_convert_asym_keeps_u4():
+ """TorchScript conversion of an asymmetric compressed-tensors model must
+ keep u4 weight constants — the zero-point and packed weights must NOT be
+ decompressed to float.
+ """
+ from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder
+
+ model, x, FakeCompressedLinear = _make_fake_ct_model(symmetric=False)
+ prior = _inject_fake_ct_module(FakeCompressedLinear)
+ try:
+ decoder = TorchScriptPythonDecoder(model, example_input=(x,))
+ fe = FrontEndManager().load_by_framework("pytorch")
+ ov_model = fe.convert(fe.load(decoder))
+ assert ov_model is not None
+
+ u4_consts = [
+ op for op in ov_model.get_ops()
+ if op.get_type_name() == "Constant"
+ and op.get_output_element_type(0) == Type.u4
+ ]
+ assert u4_consts, \
+ "Expected u4 weight constants in the OV model for asymmetric CT gemm"
+ finally:
+ _restore_ct_modules(prior)
diff --git a/tests/model_hub_tests/pytorch/envs/llm.txt b/tests/model_hub_tests/pytorch/envs/llm.txt
index aa1de5617bb..69865ec2884 100644
--- a/tests/model_hub_tests/pytorch/envs/llm.txt
+++ b/tests/model_hub_tests/pytorch/envs/llm.txt
@@ -26,3 +26,6 @@ peft==0.18.1; platform_system == "Linux" and platform_machine == "x86_64" and py
# optimum (required by transformers' GptqHfQuantizer for GPTQ model loading)
optimum==2.1.0; python_version < "3.12"
+
+# compressed-tensors (required for compressed-tensors quantized models, e.g. cyankiwi/Qwen3.5-4B-AWQ-4bit)
+compressed-tensors==0.17.1
diff --git a/tests/model_hub_tests/pytorch/test_llm.py b/tests/model_hub_tests/pytorch/test_llm.py
index f401824fc5a..f0d5b2e2616 100644
--- a/tests/model_hub_tests/pytorch/test_llm.py
+++ b/tests/model_hub_tests/pytorch/test_llm.py
@@ -22,6 +22,40 @@ def is_quantized_model(config):
return quantization_config and quantization_config["quant_method"] in ["gptq", "awq"]
+def is_compressed_tensors_model(config):
+ config_dict = config.to_dict() if not isinstance(config, dict) else config
+ quantization_config = config_dict.get("quantization_config", None)
+ return bool(quantization_config and quantization_config.get("quant_method") == "compressed-tensors")
+
+
+def patch_compressed_tensors():
+ """Prevent ``CompressedTensorsHfQuantizer`` from decompressing weights so
+ that the packed ``weight_packed`` buffers survive model loading.
+
+ Returns the original method to be restored by ``unpatch_compressed_tensors``.
+ """
+ try:
+ from transformers.quantizers.quantizer_compressed_tensors import (
+ CompressedTensorsHfQuantizer)
+ orig = CompressedTensorsHfQuantizer._process_model_after_weight_loading
+ CompressedTensorsHfQuantizer._process_model_after_weight_loading = (
+ lambda self, model, **kwargs: model)
+ return orig
+ except ImportError:
+ return None
+
+
+def unpatch_compressed_tensors(orig):
+ if orig is None:
+ return
+ try:
+ from transformers.quantizers.quantizer_compressed_tensors import (
+ CompressedTensorsHfQuantizer)
+ CompressedTensorsHfQuantizer._process_model_after_weight_loading = orig
+ except ImportError:
+ pass
+
+
def patch_gptq():
orig_cuda_is_available = torch.cuda.is_available
orig_cuda_is_bf16_supported = torch.cuda.is_bf16_supported
@@ -376,6 +410,7 @@ class TestLLMModel(TestTorchConvertModel):
def setup_class(self):
self.infer_timeout = 1800
self.cuda_available, self.gptq_postinit, self.awq_postinit, self.orig_gemm_forward, self.orig_default_dtype = None, None, None, None, None
+ self.ct_postinit = None
self.export_mode = False
@retry(3, exceptions=(OSError,), delay=1)
@@ -389,9 +424,15 @@ class TestLLMModel(TestTorchConvertModel):
except Exception:
config = {}
model_kwargs = {}
- is_quant = is_quantized_model(config)
+ is_ct = is_compressed_tensors_model(config)
+ is_gptq_awq = is_quantized_model(config)
+ is_quant = is_ct or is_gptq_awq
- if is_quant:
+ if is_ct:
+ self.ct_postinit = patch_compressed_tensors()
+ model_kwargs["dtype"] = torch.float32
+ self.ov_config = {"DYNAMIC_QUANTIZATION_GROUP_SIZE": "0"}
+ elif is_gptq_awq:
self.cuda_available, self.gptq_postinit, self.awq_postinit, self.orig_gemm_forward, self.orig_default_dtype = patch_gptq()
model_kwargs["dtype"] = torch.float32
self.ov_config = {"DYNAMIC_QUANTIZATION_GROUP_SIZE": "0"}
@@ -575,6 +616,10 @@ class TestLLMModel(TestTorchConvertModel):
if self.cuda_available is not None:
unpatch_gptq(self.cuda_available, self.gptq_postinit, self.awq_postinit, self.orig_gemm_forward, self.orig_default_dtype)
self.cuda_available, self.gptq_postinit, self.awq_postinit, self.orig_gemm_forward, self.orig_default_dtype = None, None, None, None, None
+ # restore after compressed-tensors patching
+ if self.ct_postinit is not None:
+ unpatch_compressed_tensors(self.ct_postinit)
+ self.ct_postinit = None
super().teardown_method()
@staticmethod
@@ -599,6 +644,8 @@ class TestLLMModel(TestTorchConvertModel):
("opt_gptq", "katuni4ka/opt-125m-gptq"),
("llama", "TinyLlama/TinyLlama-1.1B-Chat-v1.0"),
("llama_awq", "casperhansen/tinyllama-1b-awq"),
+ ("llama_compressed_tensors",
+ "optimum-intel-internal-testing/tiny-random-llama-compressed-tensors"),
])
return models
@@ -620,7 +667,9 @@ class TestLLMModel(TestTorchConvertModel):
("bloom_gptq", "sbolouki/bloom-1b7-gptq"),
("cohere_gptq", "shuyuej/aya-23-8B-GPTQ"),
("mbart_gptq", "Shivam098/opt-translation"),
- ("llama_awq", "TheBloke/open-llama-3b-v2-wizard-evol-instuct-v2-196k-AWQ")
+ ("llama_awq", "TheBloke/open-llama-3b-v2-wizard-evol-instuct-v2-196k-AWQ"),
+ ("qwen3_compressed_tensors",
+ "cyankiwi/Qwen3.5-4B-AWQ-4bit"), # repo name is misleading; config has quant_method=compressed-tensors
])
@pytest.mark.nightly
def test_convert_model_nightly(self, name, type, ie_device):