Skip to content

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

[PT FE] Support compressed-tensors >= 0.17 modern Linear layout (#36690)

Maxim Vafin49f50f981601
diff --git a/src/bindings/python/src/openvino/frontend/pytorch/compressed_tensors.py b/src/bindings/python/src/openvino/frontend/pytorch/compressed_tensors.py
index 03510a89c36..d8b7b48f573 100644
--- a/src/bindings/python/src/openvino/frontend/pytorch/compressed_tensors.py
+++ b/src/bindings/python/src/openvino/frontend/pytorch/compressed_tensors.py
@@ -14,16 +14,22 @@ log = logging.getLogger(__name__)
def build_extensions(for_export: bool = False) -> dict[Any, Any]:
- """Build a ``ModuleExtension`` mapping for compressed-tensors ``CompressedLinear``.
+ """Build a ``ModuleExtension`` mapping for compressed-tensors pack-quantized weights.
- 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.
+ Converts int4 pack-quantized ``nn.Linear`` and ``nn.Embedding`` weights directly to
+ ``ov_ext::ct_gemm`` / ``ov_ext::ct_embedding``, 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.
+ ``strategy="group"``). Any packed module with an unsupported configuration
+ (float formats such as nvfp4/mxfp4, other bit widths, non-group strategy) is
+ still matched and raises a precise error, so it is never silently exported as dense.
+
+ Handles two compressed-tensors variants:
+ - Legacy (< 0.17): ``CompressedLinear`` subclass with ``weight_packed`` buffer.
+ - Modern (>= 0.17): plain ``torch.nn.Linear`` / ``torch.nn.Embedding`` with
+ ``weight_packed`` parameter and ``quantization_scheme`` set by ``apply_quantization_config``.
Args:
for_export: When ``True``, scalar arguments (``group_size``, ``sym``)
@@ -31,80 +37,154 @@ def build_extensions(for_export: bool = False) -> dict[Any, Any]:
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.
+ Dict mapping module class(es) to ``ModuleExtension`` objects, or an empty
+ dict if the ``compressed_tensors`` package is not installed.
"""
try:
- from compressed_tensors.linear.compressed_linear import CompressedLinear
+ import compressed_tensors # noqa: F401
except ImportError:
log.warning(
"compressed_tensors package not found; "
- "CompressedLinear extensions will not be registered."
+ "pack-quantized 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."
- )
-
+ # CompressionFormat is the canonical source of the format string, but fall
+ # back to the literal so a stripped-down install (or a test stub) still works.
+ try:
+ from compressed_tensors.config.base import CompressionFormat
+ pack_quantized_fmt = CompressionFormat.pack_quantized.value
+ except ImportError:
+ pack_quantized_fmt = "pack-quantized"
+
+ def _get_weight_args(module: Any) -> Any:
+ return getattr(getattr(module, "quantization_scheme", None), "weights", None)
+
+ def _is_ct_pack_quantized(module: Any) -> bool:
+ """Match any compressed-tensors module carrying packed quantized weights.
+
+ Intentionally permissive: modules that carry ``weight_packed`` but use a
+ configuration we cannot convert (wrong bit width, float type, ...) are
+ still matched here so that ``_validate_weights`` can raise a precise
+ error instead of the module being silently exported as dense float.
+ """
+ return hasattr(module, "weight_packed") and _get_weight_args(module) is not None
+
+ def _validate_weights(module: Any, weight_args: Any) -> tuple[bool, int]:
+ """Validate the weight quantization config, returning ``(sym, group_size)``.
+
+ Raises ``ValueError`` with a precise reason for any unsupported config so
+ it is never silently skipped. Only int4 group pack-quantized is supported.
+ """
+ # compressed-tensors stores these as ``str, Enum`` members; unwrap ``.value``
+ # to the underlying string (``getattr(x, "value", x)`` also handles plain
+ # strings / None and keeps mypy happy about the union type).
+ fmt = getattr(getattr(module, "quantization_scheme", None), "format", None)
+ w_type = getattr(weight_args, "type", None)
+ w_type = str(getattr(w_type, "value", w_type))
num_bits = getattr(weight_args, "num_bits", None)
symmetric = getattr(weight_args, "symmetric", None)
strategy = getattr(weight_args, "strategy", None)
+ strategy = getattr(strategy, "value", strategy)
group_size = getattr(weight_args, "group_size", None)
+ name = type(module).__name__
+ # ``scheme.format`` is only populated on the compress/decompress path; the
+ # plain model-load path (and older CT / legacy CompressedLinear) leave it
+ # None while still being valid pack-quantized. So enforce it only when set;
+ # the type/num_bits/strategy checks below robustly reject float formats
+ # (nvfp4/mxfp4 use type="float") and other unsupported configs regardless.
+ fmt_str = getattr(fmt, "value", fmt)
+ if fmt_str is not None and fmt_str != pack_quantized_fmt:
+ raise ValueError(
+ f"Unsupported compressed-tensors format={fmt_str!r} on {name}. "
+ f"Only {pack_quantized_fmt!r} is supported by OpenVINO.")
+ if w_type != "int":
+ raise ValueError(
+ f"Unsupported compressed-tensors weight type={w_type!r} on {name}. "
+ "Only integer pack-quantized weights are supported (float "
+ "formats such as nvfp4/mxfp4 are not).")
if num_bits != 4:
raise ValueError(
- f"Unsupported num_bits={num_bits} in compressed-tensors module. "
- "Only num_bits=4 is supported."
- )
+ f"Unsupported num_bits={num_bits} on {name}. Only num_bits=4 is supported.")
if symmetric is None:
- raise ValueError(
- "CompressedLinear module is missing quantization_scheme.weights.symmetric."
- )
+ raise ValueError(f"{name} 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."
- )
+ f"Unsupported strategy={strategy!r} on {name}. 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)
+ raise ValueError(f"{name} is missing quantization_scheme.weights.group_size.")
+ return bool(symmetric), group_size
+
+ def _packed_args(module: Any, weight_args: Any) -> tuple[Any, Any, Any, Any, Any]:
+ """Common CT buffers → ``(weight_packed, weight_scale, gs, sym, zero_point)``.
+
+ Buffers are passed raw; all unpacking happens in the C++ translator.
+ weight_packed: [rows, cols//8] int32 (8 nibbles/int32, low-nibble first)
+ weight_scale: [rows, n_groups] float32
+ weight_zero_point: [rows//8, n_groups] int32 (asymmetric only, same packing)
+ """
+ sym_val, group_size = _validate_weights(module, weight_args)
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)
+ weight_scale = getattr(module, "weight_scale", None)
+ if weight_scale is None:
+ raise ValueError(f"{type(module).__name__} is missing weight_scale buffer.")
+ zero_point = None
+ if not sym_val:
+ zero_point = getattr(module, "weight_zero_point", None)
+ if zero_point is None:
+ raise ValueError(
+ f"asymmetric {type(module).__name__} is missing weight_zero_point buffer.")
+ return module.weight_packed, weight_scale, gs, sym, zero_point
+
+ def _convert_linear(module: Any, target_op: Any, *args: Any, **kwargs: Any) -> torch.Tensor:
+ weight_args = _get_weight_args(module)
+ wp, ws, gs, sym, zp = _packed_args(module, weight_args)
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),
+ return target_op(args[0], wp, ws, gs, sym, zp, bias)
+
+ def _convert_embedding(module: Any, target_op: Any, *args: Any, **kwargs: Any) -> torch.Tensor:
+ weight_args = _get_weight_args(module)
+ wp, ws, gs, sym, zp = _packed_args(module, weight_args)
+ return target_op(wp, ws, gs, sym, args[0], zp)
+
+ def _evaluate_linear(module: Any, *args: Any, **kwargs: Any) -> torch.Tensor:
+ return torch.full(
+ (*args[0].shape[:-1], module.out_features), 0.5,
+ dtype=torch.float32, device=args[0].device)
+
+ def _evaluate_embedding(module: Any, *args: Any, **kwargs: Any) -> torch.Tensor:
+ return torch.full(
+ (*args[0].shape, module.embedding_dim), 0.5,
+ dtype=torch.float32, device=args[0].device)
+
+ extensions: dict[Any, Any] = {}
+
+ # Modern compressed-tensors (>= 0.17): plain nn.Linear / nn.Embedding, gated by condition.
+ extensions[torch.nn.Linear] = ModuleExtension(
+ torch.nn.Linear, "ov_ext::ct_gemm",
+ convert=_convert_linear, evaluate=_evaluate_linear,
+ condition=_is_ct_pack_quantized,
+ )
+ extensions[torch.nn.Embedding] = ModuleExtension(
+ torch.nn.Embedding, "ov_ext::ct_embedding",
+ convert=_convert_embedding, evaluate=_evaluate_embedding,
+ condition=_is_ct_pack_quantized,
+ )
+
+ # Legacy compressed-tensors (< 0.17): CompressedLinear subclass (absent in newer releases).
+ try:
+ from compressed_tensors.linear.compressed_linear import CompressedLinear
+ legacy_linear_cls = CompressedLinear
+ except ImportError:
+ legacy_linear_cls = None
+
+ # Skip the alias case so it can't clobber the conditioned modern nn.Linear entry.
+ if legacy_linear_cls is not None and legacy_linear_cls is not torch.nn.Linear:
+ extensions[legacy_linear_cls] = ModuleExtension(
+ legacy_linear_cls, "ov_ext::ct_gemm",
+ convert=_convert_linear, evaluate=_evaluate_linear,
)
- }
+
+ return extensions
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 65715d6f011..eed80e84c27 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
@@ -193,4 +193,45 @@ def _ct_gemm_cpu(
return out.to(data.dtype)
+# ──────────────────────────────────────────────────────────────────────
+# ov_ext::ct_embedding (weight_packed, weight_scale, group_size,
+# sym, indices, weight_zero_point?) → Tensor
+#
+# Compressed-tensors pack-quantized int4 embedding lookup.
+# Same weight packing as ct_gemm; weight_packed is [num_embeddings,
+# embedding_dim // 8] int32. Output is [*indices.shape, embedding_dim].
+# weight_zero_point is kept last (trailing optional) so TorchScript does
+# not drop it from the middle of the positional args in the symmetric case.
+# ──────────────────────────────────────────────────────────────────────
+_ov_ext_lib.define(
+ "ct_embedding(Tensor weight_packed, Tensor weight_scale, "
+ "int group_size, bool sym, Tensor indices, "
+ "Tensor? weight_zero_point) -> Tensor")
+
+
[email protected](_ov_ext_lib, "ct_embedding", "Meta")
+def _ct_embedding_meta(
+ weight_packed: torch.Tensor, _weight_scale: torch.Tensor,
+ _group_size: int, _sym: bool, indices: torch.Tensor,
+ _weight_zero_point: torch.Tensor | None,
+) -> torch.Tensor:
+ embedding_dim = weight_packed.shape[1] * 8
+ return torch.empty(
+ *indices.shape, embedding_dim,
+ dtype=torch.float32, device="meta")
+
+
[email protected](_ov_ext_lib, "ct_embedding", "CPU")
+def _ct_embedding_cpu(
+ weight_packed: torch.Tensor, _weight_scale: torch.Tensor,
+ _group_size: int, _sym: bool, indices: torch.Tensor,
+ _weight_zero_point: torch.Tensor | None,
+) -> torch.Tensor:
+ # Placeholder – actual dequantisation happens in the C++ OV translator.
+ embedding_dim = weight_packed.shape[1] * 8
+ return torch.zeros(
+ *indices.shape, embedding_dim,
+ dtype=torch.float32, device=indices.device)
+
+
log.debug("Registered ov_ext custom ops for torch.export")
diff --git a/src/frontends/pytorch/src/op/embedding.cpp b/src/frontends/pytorch/src/op/embedding.cpp
index 02db5ef65cd..0e69b6956b0 100644
--- a/src/frontends/pytorch/src/op/embedding.cpp
+++ b/src/frontends/pytorch/src/op/embedding.cpp
@@ -6,7 +6,9 @@
#include "openvino/op/constant.hpp"
#include "openvino/op/convert.hpp"
#include "openvino/op/gather.hpp"
+#include "openvino/op/transpose.hpp"
#include "utils.hpp"
+#include "utils_quantize.hpp"
namespace ov {
namespace frontend {
@@ -42,6 +44,32 @@ OutputVector translate_embedding_ext(const NodeContext& context) {
return {context.mark_node(std::make_shared<ov::op::v8::Gather>(data, indices, axis_0))};
};
+OutputVector translate_embedding_ct(const NodeContext& context) {
+ // ov_ext::ct_embedding(weight_packed, weight_scale, group_size, sym,
+ // indices, weight_zero_point?)
+ // compressed-tensors pack-quantized int4 embedding lookup.
+ num_inputs_check(context, 5, 6);
+ auto weight_packed = context.get_input(0);
+ auto scales = context.get_input(1);
+ const auto group_size = context.const_input<int64_t>(2);
+ const auto sym = context.const_input<bool>(3);
+ auto indices = context.get_input(4);
+
+ Output<Node> zp;
+ if (!sym) {
+ FRONT_END_OP_CONVERSION_CHECK(!context.input_is_none(5), "CT asymmetric embedding requires weight_zero_point.");
+ zp = context.get_input(5);
+ }
+ // Dequantized as [embedding_dim, num_embeddings]; scales drive the output type (f32).
+ auto table = dequantize_ct_weight(context, weight_packed, scales, sym, group_size, scales, zp);
+ // Transpose to the [num_embeddings, embedding_dim] lookup table and gather rows.
+ auto perm = ov::op::v0::Constant::create(element::i32, {2}, std::vector<int32_t>{1, 0});
+ table = context.mark_node(std::make_shared<ov::op::v1::Transpose>(table, perm));
+ indices = context.mark_node(std::make_shared<ov::op::v0::Convert>(indices, element::i32));
+ auto axis_0 = ov::op::v0::Constant::create(element::i32, Shape{}, {0});
+ return {context.mark_node(std::make_shared<ov::op::v8::Gather>(table, indices, axis_0))};
+};
+
} // namespace op
} // namespace pytorch
} // namespace frontend
diff --git a/src/frontends/pytorch/src/op/linear.cpp b/src/frontends/pytorch/src/op/linear.cpp
index 7d17a4cf755..76ee285db28 100644
--- a/src/frontends/pytorch/src/op/linear.cpp
+++ b/src/frontends/pytorch/src/op/linear.cpp
@@ -2,14 +2,13 @@
// SPDX-License-Identifier: Apache-2.0
//
-#include "openvino/decompositions/low_precision_dequantize.hpp"
#include "openvino/frontend/pytorch/node_context.hpp"
#include "openvino/op/add.hpp"
+#include "openvino/op/convert.hpp"
#include "openvino/op/matmul.hpp"
#include "openvino/op/reshape.hpp"
-#include "openvino/op/shape_of.hpp"
-#include "openvino/op/transpose.hpp"
#include "utils.hpp"
+#include "utils_quantize.hpp"
namespace ov {
namespace frontend {
@@ -74,19 +73,6 @@ inline void set_u4(uint8_t* data, size_t idx, uint8_t val) {
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,
- const Output<Node>& zero_points,
- const Output<Node>& scales,
- const Output<Node>& out_shape) {
- ov::pass::NodeRegistry reg;
- auto weight = ov::decomposition::low_precision_dequantize(reg, weights, scales, zero_points, out_shape);
- weight = reg.make<v1::ConvertLike>(weight, x);
- context.mark_nodes(reg.get());
- return weight;
-}
-
uint32_t rearrange_awq_bits(uint32_t num) {
uint32_t result = 0;
uint32_t mask = 0xF;
@@ -337,90 +323,6 @@ 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?)
@@ -431,44 +333,13 @@ OutputVector translate_linear_ct(const NodeContext& context) {
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;
+ Output<Node> 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);
+ zp = context.get_input(5);
}
- auto weight = low_precision_subgraph(context, x, new_weight, new_zp, new_scales, out_shape);
+ // [in_features, out_features]
+ auto weight = dequantize_ct_weight(context, weight_packed, scales, sym, group_size, x, zp);
auto matmul = context.mark_node(std::make_shared<v0::MatMul>(x, weight, false, false));
if (!context.input_is_none(6)) {
diff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cpp
index cb8cca2bf62..008d7d0d1f7 100644
--- a/src/frontends/pytorch/src/op_table.cpp
+++ b/src/frontends/pytorch/src/op_table.cpp
@@ -372,6 +372,7 @@ OP_CONVERTER(translate_embedding_ext);
OP_CONVERTER(translate_linear_awq);
OP_CONVERTER(translate_linear_bitnet);
OP_CONVERTER(translate_linear_ct);
+OP_CONVERTER(translate_embedding_ct);
OP_CONVERTER(translate_linear_ext);
OP_CONVERTER(translate_linear_gptq);
} // namespace op
@@ -806,6 +807,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {
{"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::ct_embedding", op::translate_embedding_ct},
{"ov_ext::gptq_gemm", op::translate_linear_gptq},
{"ov_ext::bmm", op::translate_bmm_ext},
{"ov_ext::embedding", op::translate_embedding_ext},
@@ -1186,6 +1188,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_fx() {
{"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.ct_embedding.default", op::translate_embedding_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/src/frontends/pytorch/src/utils_quantize.cpp b/src/frontends/pytorch/src/utils_quantize.cpp
index ff08c67286a..a227aa21e6b 100644
--- a/src/frontends/pytorch/src/utils_quantize.cpp
+++ b/src/frontends/pytorch/src/utils_quantize.cpp
@@ -5,6 +5,7 @@
#include "utils_quantize.hpp"
#include "openvino/core/validation_util.hpp"
+#include "openvino/decompositions/low_precision_dequantize.hpp"
#include "openvino/frontend/pytorch/node_context.hpp"
#include "openvino/op/bitwise_and.hpp"
#include "openvino/op/broadcast.hpp"
@@ -16,6 +17,8 @@
#include "openvino/op/reshape.hpp"
#include "openvino/op/scatter_elements_update.hpp"
#include "openvino/op/subtract.hpp"
+#include "openvino/op/transpose.hpp"
+#include "openvino/pass/node_registry.hpp"
#include "transformations/utils/utils.hpp"
namespace ov {
@@ -282,6 +285,159 @@ std::shared_ptr<Node> u4_compression_stack(const OutputVector& list_elems, int64
return new_const;
}
+Output<Node> low_precision_subgraph(const NodeContext& context,
+ const Output<Node>& x,
+ const Output<Node>& weights,
+ const Output<Node>& zero_points,
+ const Output<Node>& scales,
+ const Output<Node>& out_shape) {
+ ov::pass::NodeRegistry reg;
+ auto weight = ov::decomposition::low_precision_dequantize(reg, weights, scales, zero_points, out_shape);
+ weight = reg.make<v1::ConvertLike>(weight, x);
+ context.mark_nodes(reg.get());
+ return weight;
+}
+
+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);
+}
+
+// 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
+
+Output<Node> dequantize_ct_weight(const NodeContext& context,
+ const Output<Node>& weight_packed,
+ const Output<Node>& scales,
+ bool sym,
+ int64_t group_size,
+ const Output<Node>& like,
+ const Output<Node>& zero_point_packed) {
+ 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 rows = wp_shape[0];
+ const size_t inner = wp_shape[1] * 8;
+ FRONT_END_OP_CONVERSION_CHECK(
+ group_size > 0 && static_cast<size_t>(group_size) <= inner && inner % static_cast<size_t>(group_size) == 0,
+ "CT group_size must divide the packed inner dimension.");
+ const size_t n_groups = inner / static_cast<size_t>(group_size);
+
+ // Unpack weights: [n_groups, group_size, rows] i4 (sym) or u4 (asym)
+ auto new_weight = unpack_ct_weight(weight_packed, sym, static_cast<size_t>(group_size));
+
+ // Scales: [rows, n_groups] → transpose to [n_groups, rows] → reshape to [n_groups, 1, rows]
+ 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] == rows && scales_shape[1] == n_groups,
+ "CT weight_scale shape must be [rows, 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>(rows)});
+ 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 [inner, rows]
+ auto out_shape =
+ v0::Constant::create(element::i32,
+ {2},
+ std::vector<int32_t>{static_cast<int32_t>(inner), static_cast<int32_t>(rows)});
+
+ Output<Node> new_zp;
+ if (!sym) {
+ FRONT_END_OP_CONVERSION_CHECK(zero_point_packed.get_node_shared_ptr(),
+ "CT asymmetric quantization requires weight_zero_point.");
+ new_zp = unpack_ct_zp(zero_point_packed, rows);
+ }
+ return low_precision_subgraph(context, like, new_weight, new_zp, new_scales, out_shape);
+}
+
} // namespace pytorch
} // namespace frontend
} // namespace ov
diff --git a/src/frontends/pytorch/src/utils_quantize.hpp b/src/frontends/pytorch/src/utils_quantize.hpp
index 5f59e127879..762164ddd82 100644
--- a/src/frontends/pytorch/src/utils_quantize.hpp
+++ b/src/frontends/pytorch/src/utils_quantize.hpp
@@ -193,6 +193,33 @@ OutputVector quantizable_op(const NodeContext& context) {
*/
std::shared_ptr<Node> u4_compression_stack(const OutputVector& list_elems, int64_t axis);
+/**
+ * Build a low-precision dequantization subgraph: dequantize `weights` (i4/u4/u2) with `zero_points`
+ * and `scales`, reshape to `out_shape`, and cast to the element type of `x`. Used by the AWQ / GPTQ /
+ * BitNet / compressed-tensors weight-only quantized translators.
+ */
+Output<Node> low_precision_subgraph(const NodeContext& context,
+ const Output<Node>& x,
+ const Output<Node>& weights,
+ const Output<Node>& zero_points,
+ const Output<Node>& scales,
+ const Output<Node>& out_shape);
+
+/**
+ * Dequantize compressed-tensors pack-quantized weights to a dense [inner, rows] tensor
+ * (converted to the element type of `like`). Shared by ct_gemm (linear) and ct_embedding.
+ * weight_packed: [rows, inner//8] int32
+ * scales: [rows, n_groups] float32
+ * zero_point_packed: [rows//8, n_groups] int32 (asymmetric only; empty for symmetric)
+ */
+Output<Node> dequantize_ct_weight(const NodeContext& context,
+ const Output<Node>& weight_packed,
+ const Output<Node>& scales,
+ bool sym,
+ int64_t group_size,
+ const Output<Node>& like,
+ const Output<Node>& zero_point_packed);
+
} // namespace pytorch
} // namespace frontend
} // namespace ov
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 69d91f2a8d9..c8d04e2f39d 100644
--- a/tests/layer_tests/py_frontend_tests/test_torch_frontend.py
+++ b/tests/layer_tests/py_frontend_tests/test_torch_frontend.py
@@ -2753,12 +2753,14 @@ def _make_fake_ct_model(in_features=32, out_features=64, group_size=32, symmetri
class FakeWeightArgs:
num_bits = 4
+ type = "int"
symmetric = _symmetric
strategy = "group"
group_size = _group_size
class FakeScheme:
weights = FakeWeightArgs()
+ format = "pack-quantized"
class FakeQuantConfig:
quant_method = "compressed-tensors"
@@ -2816,6 +2818,67 @@ def _make_fake_ct_model(in_features=32, out_features=64, group_size=32, symmetri
return model, x, FakeCompressedLinear
+def _make_fake_ct_embedding_model(num_embeddings=64, embedding_dim=32, group_size=32,
+ symmetric=True, ct_format="pack-quantized"):
+ """Return ``(model, idx)`` with a pack-quantized ``nn.Embedding``.
+
+ Mirrors the modern (>= 0.17) layout: a plain ``nn.Embedding`` carrying
+ ``weight_packed`` / ``weight_scale`` (+ ``weight_zero_point`` when asymmetric)
+ and a ``quantization_scheme`` with ``format`` set. ``ct_format`` can be
+ overridden to exercise the unsupported-config error path.
+ """
+ rng = torch.Generator().manual_seed(0)
+ n_groups = embedding_dim // group_size
+ _group_size, _symmetric, _fmt = group_size, symmetric, ct_format
+
+ class FakeWeightArgs:
+ num_bits = 4
+ type = "int"
+ symmetric = _symmetric
+ strategy = "group"
+ group_size = _group_size
+
+ class FakeScheme:
+ weights = FakeWeightArgs()
+ format = _fmt
+
+ class FakeQuantConfig:
+ quant_method = "compressed-tensors"
+
+ class FakeConfig:
+ quantization_config = FakeQuantConfig()
+
+ def _make_embedding():
+ # Modern CT layer is a *plain* nn.Embedding (matched by exact class), with
+ # the dense weight replaced by packed buffers + a quantization_scheme.
+ emb = torch.nn.Embedding(num_embeddings, embedding_dim)
+ del emb.weight
+ emb.register_buffer("weight_packed", torch.randint(
+ -(2 ** 31), 2 ** 31, (num_embeddings, embedding_dim // 8),
+ dtype=torch.int32, generator=rng))
+ emb.register_buffer("weight_scale", torch.randn(
+ num_embeddings, n_groups, dtype=torch.float32, generator=rng))
+ if not _symmetric:
+ emb.register_buffer("weight_zero_point", torch.randint(
+ -(2 ** 31), 2 ** 31, (num_embeddings // 8, n_groups),
+ dtype=torch.int32, generator=rng))
+ emb.quantization_scheme = FakeScheme()
+ # Placeholder forward so tracing produces a valid result before patching.
+ emb.forward = lambda idx: torch.zeros(*idx.shape, embedding_dim, dtype=torch.float32)
+ return emb
+
+ class CTModel(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.config = FakeConfig()
+ self.emb = _make_embedding()
+
+ def forward(self, idx):
+ return self.emb(idx)
+
+ return CTModel(), torch.randint(0, num_embeddings, (2, 4))
+
+
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
@@ -2975,3 +3038,68 @@ def test_compressed_tensors_convert_asym_keeps_u4():
"Expected u4 weight constants in the OV model for asymmetric CT gemm"
finally:
_restore_ct_modules(prior)
+
+
+def test_compressed_tensors_embedding_keeps_i4():
+ """A pack-quantized ``nn.Embedding`` must convert to a Gather over an i4
+ weight constant — the embedding table must NOT be decompressed to float."""
+ from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder
+
+ model, idx = _make_fake_ct_embedding_model()
+ prior = _inject_fake_ct_module(torch.nn.Linear) # embedding path needs only the CT pkg present
+ try:
+ decoder = TorchScriptPythonDecoder(model, example_input=(idx,))
+ fe = FrontEndManager().load_by_framework("pytorch")
+ ov_model = fe.convert(fe.load(decoder))
+ assert ov_model is not None
+
+ op_types = [op.get_type_name() for op in ov_model.get_ops()]
+ assert "Gather" in op_types, "Expected a Gather for the embedding lookup"
+ 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 weight constant for CT embedding"
+ finally:
+ _restore_ct_modules(prior)
+
+
+def test_compressed_tensors_unsupported_format_raises():
+ """An unsupported compressed-tensors format must raise (never silently export
+ the module as dense float)."""
+ from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder
+
+ model, idx = _make_fake_ct_embedding_model(ct_format="nvfp4-pack-quantized")
+ prior = _inject_fake_ct_module(torch.nn.Linear)
+ try:
+ with pytest.raises(Exception, match="nvfp4-pack-quantized"):
+ decoder = TorchScriptPythonDecoder(model, example_input=(idx,))
+ fe = FrontEndManager().load_by_framework("pytorch")
+ fe.convert(fe.load(decoder))
+ finally:
+ _restore_ct_modules(prior)
+
+
+def test_compressed_tensors_missing_format_still_converts():
+ """A valid pack-quantized module whose ``quantization_scheme.format`` is None
+ (the plain model-load path, older CT, and the legacy CompressedLinear path all
+ leave it unset) must still convert — the format check is lenient when unset."""
+ from openvino.frontend.pytorch.ts_decoder import TorchScriptPythonDecoder
+
+ model, idx = _make_fake_ct_embedding_model(ct_format=None)
+ prior = _inject_fake_ct_module(torch.nn.Linear)
+ try:
+ decoder = TorchScriptPythonDecoder(model, example_input=(idx,))
+ 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 weight constant when format is None"
+ finally:
+ _restore_ct_modules(prior)
diff --git a/tests/model_hub_tests/pytorch/test_llm.py b/tests/model_hub_tests/pytorch/test_llm.py
index f0d5b2e2616..c25300e3408 100644
--- a/tests/model_hub_tests/pytorch/test_llm.py
+++ b/tests/model_hub_tests/pytorch/test_llm.py
@@ -29,10 +29,11 @@ def is_compressed_tensors_model(config):
def patch_compressed_tensors():
- """Prevent ``CompressedTensorsHfQuantizer`` from decompressing weights so
- that the packed ``weight_packed`` buffers survive model loading.
+ """Stop CompressedTensorsHfQuantizer from decompressing so weight_packed survives loading.
- Returns the original method to be restored by ``unpatch_compressed_tensors``.
+ In compressed-tensors >= 0.17 both ``_process_model_after_weight_loading`` and the
+ ``add_decompress_hook`` forward pre-hook would dequantize before conversion, so we no-op
+ both. Returns the originals for ``unpatch_compressed_tensors``.
"""
try:
from transformers.quantizers.quantizer_compressed_tensors import (
@@ -40,20 +41,50 @@ def patch_compressed_tensors():
orig = CompressedTensorsHfQuantizer._process_model_after_weight_loading
CompressedTensorsHfQuantizer._process_model_after_weight_loading = (
lambda self, model, **kwargs: model)
- return orig
except ImportError:
- return None
+ return None, None
+
+ orig_add_decompress_hook = None
+ try:
+ from compressed_tensors import ModelCompressor
+ orig_add_decompress_hook = ModelCompressor.add_decompress_hook
+ ModelCompressor.add_decompress_hook = lambda self, model: None
+ except ImportError:
+ pass
+
+ return orig, orig_add_decompress_hook
def unpatch_compressed_tensors(orig):
- if orig is None:
- return
+ orig_process, orig_add_decompress_hook = orig
+ if orig_process is not None:
+ try:
+ from transformers.quantizers.quantizer_compressed_tensors import (
+ CompressedTensorsHfQuantizer)
+ CompressedTensorsHfQuantizer._process_model_after_weight_loading = orig_process
+ except ImportError:
+ pass
+
+ if orig_add_decompress_hook is not None:
+ try:
+ from compressed_tensors import ModelCompressor
+ ModelCompressor.add_decompress_hook = orig_add_decompress_hook
+ except ImportError:
+ pass
+
+
+def decompress_compressed_tensors_model(model):
+ """Decompress a CT model in-place to get a framework reference forward.
+
+ Called only after OV conversion; pack-quantized CT modules have no working CPU forward
+ of their own, so this is the only way to a valid baseline once decompression is suppressed.
+ """
try:
- from transformers.quantizers.quantizer_compressed_tensors import (
- CompressedTensorsHfQuantizer)
- CompressedTensorsHfQuantizer._process_model_after_weight_loading = orig
+ from compressed_tensors import ModelCompressor
except ImportError:
- pass
+ return
+ compressor = ModelCompressor.from_compression_config(model.config.quantization_config)
+ compressor.decompress_model(model)
def patch_gptq():
@@ -411,6 +442,7 @@ class TestLLMModel(TestTorchConvertModel):
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.is_ct = False
self.export_mode = False
@retry(3, exceptions=(OSError,), delay=1)
@@ -430,6 +462,7 @@ class TestLLMModel(TestTorchConvertModel):
if is_ct:
self.ct_postinit = patch_compressed_tensors()
+ self.is_ct = True
model_kwargs["dtype"] = torch.float32
self.ov_config = {"DYNAMIC_QUANTIZATION_GROUP_SIZE": "0"}
elif is_gptq_awq:
@@ -445,6 +478,11 @@ class TestLLMModel(TestTorchConvertModel):
# dequantized weights) before any forward pass, to prevent gptqmodel
# from repacking weights and to keep bitwise ops out of the graph.
_replace_awq_with_linear(self.model)
+ if is_ct:
+ # CT has no packed forward; patch to ov_ext::ct_gemm before any forward so
+ # weight_packed survives to tracing. Restored in teardown_method.
+ from openvino.frontend.pytorch.quantized import patch_quantized
+ patch_quantized(self.model)
if is_quant:
model = self.model
else:
@@ -561,6 +599,12 @@ class TestLLMModel(TestTorchConvertModel):
ovm = super().convert_model_impl(self.model)
if is_patched:
unpatch(self.model, "_openvino_module_extension_patch_orig_forward")
+ if self.is_ct:
+ # Undo the ov_ext::ct_gemm trampolines (which return placeholders), then
+ # decompress so infer_fw_model gets a real reference forward.
+ from openvino.frontend.pytorch.quantized import unpatch_quantized
+ unpatch_quantized(self.model)
+ decompress_compressed_tensors_model(self.model)
return ovm
def _convert_model_export(self, model_obj):
@@ -620,6 +664,11 @@ class TestLLMModel(TestTorchConvertModel):
if self.ct_postinit is not None:
unpatch_compressed_tensors(self.ct_postinit)
self.ct_postinit = None
+ if self.is_ct and getattr(self, "model", None) is not None:
+ # Safety net in case conversion raised before the decoder's own unpatch ran.
+ from openvino.frontend.pytorch.quantized import unpatch_quantized
+ unpatch_quantized(self.model)
+ self.is_ct = False
super().teardown_method()
@staticmethod