Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion docs/source/en/quantization/compressed_tensors.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,16 +64,49 @@ print(f"{mem_params/2**30:.4f} GB")

## Loading modes

A compressed-tensors checkpoint stores its weights compressed (fp8, or packed int4/int8). How they are executed is up to two [`CompressedTensorsConfig`] arguments.
A compressed-tensors checkpoint stores its weights compressed. [`CompressedTensorsConfig`] provides the following loading modes.

| Configuration | Weights after loading | Execution |
|---------------|-----------------------|-----------|
| default | kept in the compressed-tensors format: every serialized tensor (`weight_packed`, `weight_scale`, `weight_zero_point`, ...) loads as stored | compressed-tensors owns the layers and decompresses the model on the first forward pass |
| `dequantize=True` | decompressed while loading into the model dtype (e.g. BF16) | a plain dense model with no `quantization_scheme` left, so w8a8 activations aren't quantized either; it can be fine-tuned or saved in that dtype |
| `use_optimized_inference=True` | kept quantized | layers whose scheme has a kernel run through it, currently W8A8 fp8; inference only |
| `weight_only=True` (NVFP4 only) | NVFP4 bytes and scales kept in torchao tensors | BF16 activations, with activation quantization explicitly disabled; inference only |

With the default, [`~PreTrainedModel.save_pretrained`] writes the compressed tensors back unchanged, so a loaded model saves in the same compressed-tensors format.

## NVFP4 weight-only loading

Pass `weight_only=True` to reuse compressed-tensors `nvfp4-pack-quantized` checkpoints on supported devices without native NVFP4 GEMMs. Packed weights and block scales are preserved in torchao's `NVFP4Tensor` without requantization. Only NVFP4 is supported. Install `compressed-tensors>=0.15.0` and a compatible `torchao>=0.16.0` build exposing `torchao.prototype.mx_formats.nvfp4_tensor.NVFP4Tensor`.

> [!WARNING]
> This mode disables input activation quantization (W4A4 becomes W4A16), so outputs can differ from the original deployment. Torchao dequantizes each Linear weight on every forward call and performs BF16 Linear: this is not a fused FP4 GEMM and does not imply a speedup.

```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, CompressedTensorsConfig

model_id = "RedHatAI/Qwen3-14B-NVFP4"
model = AutoModelForCausalLM.from_pretrained(
model_id,
quantization_config=CompressedTensorsConfig(weight_only=True),
dtype=torch.bfloat16,
device_map="xpu", # Or a single CUDA device, e.g. "cuda:0".
)
tokenizer = AutoTokenizer.from_pretrained(model_id)
inputs = tokenizer("The capital of France is", return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, max_new_tokens=8, do_sample=False)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
```

All quantized groups must contain static, symmetric float4 `tensor_group` weights with group size 16 and absent or local-dynamic NVFP4 input quantization. Targets and ignore patterns select ordinary `torch.nn.Linear` modules; unquantized modules load normally. FP8 block scales are preserved, FP32 global weight scales are inverted for torchao, and optional input global scales are validated but unused.

Memory planning accounts for packed weights and scales; temporary dequantization tensors and the KV cache require additional memory.

Use `dtype=torch.bfloat16` and one device (`device_map="xpu"`, `"cuda:0"`, or `"cpu"`; omitted means CPU). Unsupported: automatic placement, CPU/disk offload, mixed quantized formats, tied quantized weights, KV-cache quantization, sparsity, transforms, training, QAT, compilation, and saving the loaded quantized model. Any model-level `WeightConverter` is rejected, even for unquantized modules; weight renamings remain supported.

`weight_only` cannot be combined with `dequantize` or `use_optimized_inference` and is not saved in checkpoint metadata: set it on each load. Leave it unset for the default behavior, or use `dequantize=True` alone for a dense model that can be fine-tuned or saved.

## FP8 kernel acceleration

Pass `use_optimized_inference=True` to keep an FP8 compressed-tensors model in FP8 and run its matmuls through hardware-accelerated FP8 kernels ([torch.nn.functional.scaled_mm](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_mm.html), which dispatches to `torch._scaled_mm_v2`; older torch versions fall back to `torch._scaled_mm`), instead of dequantizing the weights back to BF16. Keeping weights in FP8 throughout inference lowers memory usage and speeds up computation. This is inference only, so leave it off to fine-tune.
Expand Down
68 changes: 68 additions & 0 deletions src/transformers/integrations/compressed_tensors.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,74 @@
logger = logging.get_logger(__name__)


class CompressedTensorsNVFP4Deserialize(ConversionOps):
"""Import compressed-tensors NVFP4 bytes and scales into torchao without requantizing."""

def __init__(self, hf_quantizer):
self.hf_quantizer = hf_quantizer

def convert(self, input_dict, source_patterns, model=None, full_layer_name=None, **kwargs):
from torchao.prototype.mx_formats.nvfp4_tensor import NVFP4Tensor

if model is None or full_layer_name is None:
raise ValueError("NVFP4 deserialization requires a model and a full layer name.")
serialized_names = dict(zip(source_patterns, self.hf_quantizer.serialized_names["weight"]))
tensors = {}
for name, value in input_dict.items():
if isinstance(value, list):
if len(value) != 1:
raise ValueError(f"Expected one tensor for {full_layer_name}: {name}.")
value = value[0]
tensors[serialized_names[name]] = value

module_name, _, _ = full_layer_name.rpartition(".")
module = model.get_submodule(module_name)
required = {"weight_packed", "weight_scale", "weight_global_scale"}
allowed = required | {"input_global_scale"}
if not required <= tensors.keys() or tensors.keys() - allowed:
raise ValueError(
f"Invalid NVFP4 tensors for {module_name}: missing {sorted(required - tensors.keys())}, "
f"unexpected {sorted(tensors.keys() - allowed)}."
)
packed = tensors["weight_packed"]
scales = tensors["weight_scale"]
global_scale = tensors["weight_global_scale"]
n, k = module.out_features, module.in_features
if packed.dtype != torch.uint8 or packed.shape != (n, k // 2):
raise ValueError(f"{module_name}.weight_packed must be uint8 with shape {(n, k // 2)}.")
if scales.dtype != torch.float8_e4m3fn or scales.shape != (n, k // 16):
raise ValueError(f"{module_name}.weight_scale must be float8_e4m3fn with shape {(n, k // 16)}.")
for name in ("weight_global_scale", "input_global_scale"):
if name not in tensors:
continue
scale = tensors[name]
if (
scale.dtype != torch.float32
or scale.shape != (1,)
or not torch.isfinite(scale).all()
or not (scale > 0).all()
):
raise ValueError(f"{module_name}.{name} must be a positive finite float32 tensor with shape (1,).")
scales_float = scales.float()
if not torch.isfinite(scales_float).all() or (scales_float < 0).any():
raise ValueError(f"{module_name}.weight_scale must contain nonnegative finite values.")
# CT divides by its global scale; torchao multiplies by its per-tensor scale.
per_tensor_scale = global_scale.reshape(()).reciprocal()
if not torch.isfinite(per_tensor_scale):
raise ValueError(f"{module_name}.weight_global_scale has a nonfinite reciprocal.")
weight = NVFP4Tensor(
packed.contiguous(),
scales.contiguous(),
block_size=16,
orig_dtype=torch.bfloat16,
per_tensor_scale=per_tensor_scale,
is_swizzled_scales=False,
use_triton_kernel=False,
act_quant_kwargs=None,
)
return {full_layer_name: nn.Parameter(weight, requires_grad=False)}


def get_experts_scheme(quantization_config):
"""Resolve which config group quantizes the MoE experts. Mixed configs quantize
different layers with different schemes (e.g. Kimi: FP8 attention + INT4 experts), so
Expand Down
Loading
Loading