From 23baea8fe2d3514f1caef5656c5e3e1ea5d2e9f0 Mon Sep 17 00:00:00 2001 From: Eryk Roch Rybak Date: Tue, 24 Nov 2026 13:58:05 +0200 Subject: [PATCH 1/4] Add opt-in NVFP4 weight-only loading for compressed-tensors Import compressed-tensors NVFP4 bytes and scales into torchao with explicit BF16 activations, preserving packed weights without requantization. Adapt reciprocal global scales, allow absent input scales, and use scoped converters for base-model prefix handling. Limit the path to ordinary dense Linear modules on one device, account for packed storage during memory planning, and document unsupported operations. Keep the existing loading routes opt-out by default. Expose is_qat_trainable as a boolean property as expected by the trainer, with a regression assertion for the existing compressed route. Include compact CPU/accelerator loading and validation tests. --- .../en/quantization/compressed_tensors.md | 37 ++- .../integrations/compressed_tensors.py | 75 +++++ .../quantizer_compressed_tensors.py | 162 +++++++++- src/transformers/utils/quantization_config.py | 71 ++++- .../test_nvfp4.py | 279 ++++++++++++++++++ 5 files changed, 615 insertions(+), 9 deletions(-) create mode 100644 tests/quantization/compressed_tensors_integration/test_nvfp4.py diff --git a/docs/source/en/quantization/compressed_tensors.md b/docs/source/en/quantization/compressed_tensors.md index c45df3a480a6..a59d908a0c65 100644 --- a/docs/source/en/quantization/compressed_tensors.md +++ b/docs/source/en/quantization/compressed_tensors.md @@ -64,16 +64,51 @@ 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 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 load a compressed-tensors `nvfp4-pack-quantized` checkpoint into torchao's `NVFP4Tensor`. This mode preserves the original packed weights and block scales without requantizing or converting the entire model to BF16. Install `compressed-tensors>=0.15.0` and a compatible `torchao>=0.16.0` build exposing `torchao.prototype.mx_formats.nvfp4_tensor.NVFP4Tensor`. + +> [!WARNING] +> This is an explicit change from W4A4 to W4A16: the checkpoint's input activation quantization is disabled, so outputs can differ from its original deployment. The current torchao weight-only path dequantizes each Linear weight for every forward call, then performs BF16 Linear. It is not a native or fused FP4 GEMM, and this loading mode does not imply a speedup. Temporary dequantization allocations also contribute to peak memory. + +```python +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer, CompressedTensorsConfig + +model_id = "RedHatAI/Qwen3-14B-NVFP4" +revision = "cc120e7bc68557313002275d51db65096ca24303" +model = AutoModelForCausalLM.from_pretrained( + model_id, + revision=revision, + 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, revision=revision) +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)) +``` + +Supported checkpoints contain static, symmetric float4 `tensor_group` weights with group size 16, optionally with local-dynamic NVFP4 input activation quantization. All quantized groups must use this format. Targets and ignore patterns select ordinary `torch.nn.Linear` modules; unquantized modules, such as embeddings and the output head, retain the normal loading path. Block scales use `float8_e4m3fn`, and the compressed-tensors FP32 global scale is inverted to obtain torchao's multiplicative per-tensor scale. Input global scales are optional; when present, they are validated and consumed but not used for inference. + +Allocator planning accounts for the packed weights and their block/global scales rather than the logical BF16 weight size. Temporary dequantization tensors and the KV cache still require additional memory. + +This mode requires `dtype=torch.bfloat16` and an explicit whole-model device (`device_map="xpu"`, `"cuda:0"`, or `"cpu"`). Omitting `device_map` loads on CPU, which is useful for small correctness tests. Automatic device placement, CPU/disk offload, mixed quantized formats, tied quantized weights, KV-cache quantization, sparsity, and transforms are not supported. Models requiring any model-level `WeightConverter` (including fused/grouped conversions for MoE experts) are rejected, even when the conversion only affects unquantized modules; weight renamings remain supported. Training, QAT, compilation, and saving the loaded quantized model are not supported either. + +`weight_only` cannot be combined with `dequantize` or `use_optimized_inference`. Like the other compressed-tensors loading options, it is not written into checkpoint metadata. Set it explicitly each time you load the original checkpoint. Leave it unset to retain the existing compressed-tensors 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. diff --git a/src/transformers/integrations/compressed_tensors.py b/src/transformers/integrations/compressed_tensors.py index 543214f35dd0..8c6cca3f70f7 100644 --- a/src/transformers/integrations/compressed_tensors.py +++ b/src/transformers/integrations/compressed_tensors.py @@ -24,6 +24,81 @@ 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): + 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) + if module_name not in self.hf_quantizer.nvfp4_modules: + raise ValueError(f"NVFP4 conversion was requested for unselected module {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 k % 16 or 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)} and K divisible by 16." + ) + 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)}.") + if any(tensor.device != packed.device for tensor in tensors.values()) or packed.device.type == "meta": + raise ValueError(f"All NVFP4 tensors for {module_name} must be materialized on the same device.") + if module.weight.dtype != torch.bfloat16: + raise ValueError(f"NVFP4 weight-only module {module_name} requires BF16.") + 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 = self.hf_quantizer.nvfp4_tensor_class( + 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 diff --git a/src/transformers/quantizers/quantizer_compressed_tensors.py b/src/transformers/quantizers/quantizer_compressed_tensors.py index 6f6644c23fa8..61d743b506ea 100644 --- a/src/transformers/quantizers/quantizer_compressed_tensors.py +++ b/src/transformers/quantizers/quantizer_compressed_tensors.py @@ -12,9 +12,16 @@ # See the License for the specific language governing permissions and # limitations under the License. +import re from copy import deepcopy -from ..utils import is_compressed_tensors_available, is_torch_available, is_torch_greater_or_equal, logging +from ..utils import ( + is_compressed_tensors_available, + is_torch_available, + is_torch_greater_or_equal, + is_torchao_available, + logging, +) from ..utils.quantization_config import CompressedTensorsConfig from .base import HfQuantizer @@ -22,8 +29,8 @@ if is_torch_available(): import torch - from ..core_model_loading import WeightConverter - from ..integrations.compressed_tensors import CompressedTensorsDequantize + from ..core_model_loading import WeightConverter, build_glob_alternation + from ..integrations.compressed_tensors import CompressedTensorsDequantize, CompressedTensorsNVFP4Deserialize logger = logging.get_logger(__name__) @@ -44,6 +51,9 @@ class CompressedTensorsHfQuantizer(HfQuantizer): row-wise FP8 kernels (`torch.nn.functional.scaled_mm`) via `CompressedTensorsFP8Linear`, when FP8 matmul hardware is available (CUDA SM89+, XPU, or MPS with torch >= 2.15). This is opt-in and inference only. + With `weight_only=True`, NVFP4 checkpoints use torchao weights with BF16 activations. + This changes activation precision, does not select a fused kernel, and is inference only. + Otherwise the model goes through the regular compressed-tensors route: `dequantize=True` dequantizes the weights at load time, while `dequantize=False` leaves them compressed and lets compressed-tensors decompress them on the first forward pass. @@ -60,6 +70,12 @@ def __init__(self, quantization_config: CompressedTensorsConfig, **kwargs): # duplicate logging. quantization_config.post_init() + self.use_nvfp4_weight_only = quantization_config.weight_only + self.use_fp8_kernel = quantization_config.use_optimized_inference + self.nvfp4_modules: set[str] = set() + self.nvfp4_base_model_prefix = "" + if self.use_nvfp4_weight_only: + self.serialized_names = {"weight": [*self.serialized_names["weight"], "input_global_scale"]} from compressed_tensors.compressors import ModelCompressor self.compressor = ModelCompressor.from_compression_config(quantization_config) @@ -71,6 +87,36 @@ def validate_environment(self, *args, **kwargs): "`pip install compressed-tensors>=0.15.0`" ) + if self.use_nvfp4_weight_only: + # NVFP4Tensor renamed `_is_swizzled_scales` in torchao 0.16. + if not is_torchao_available(min_version="0.16.0"): + raise ImportError( + "NVFP4 weight-only loading requires torchao>=0.16.0. " + "Install a compatible build with `pip install 'torchao>=0.16.0'`." + ) + try: + from torchao.prototype.mx_formats.nvfp4_tensor import NVFP4Tensor + except ImportError as error: + raise ImportError( + "NVFP4 weight-only loading requires a torchao build providing " + "`torchao.prototype.mx_formats.nvfp4_tensor.NVFP4Tensor`. Upgrade torchao." + ) from error + self.nvfp4_tensor_class = NVFP4Tensor + device_map = kwargs.get("device_map") + if device_map is not None: + if not isinstance(device_map, dict) or set(device_map) != {""}: + raise ValueError("NVFP4 weight-only loading requires an explicit whole-model device_map.") + device = device_map[""] + if device == "disk" or torch.device(device).type not in ("cpu", "cuda", "xpu"): + raise ValueError( + "NVFP4 weight-only loading supports a single CPU, CUDA or XPU device, without offload." + ) + logger.warning_once( + "NVFP4 weight-only loading disables activation quantization and uses BF16 activations (W4A16). " + "Torchao currently dequantizes weights for each Linear call; this is not a fused FP4 kernel." + ) + return + # `use_optimized_inference` has been resolved against the checkpoint by # `CompressedTensorsConfig.post_init`; what is left to check is whether the hardware can run # the kernels. When it cannot, the model goes through the regular compressed-tensors route. @@ -88,7 +134,71 @@ def validate_environment(self, *args, **kwargs): ) self.use_fp8_kernel = False + def update_dtype(self, dtype): + if self.use_nvfp4_weight_only and dtype != torch.bfloat16: + raise ValueError("NVFP4 weight-only loading requires `dtype=torch.bfloat16`.") + return dtype + + def param_element_size(self, model, param_name: str, param: "torch.Tensor") -> float: + module_name, _, attribute = param_name.rpartition(".") + if self.use_nvfp4_weight_only and attribute == "weight" and module_name in self.nvfp4_modules: + # Packed FP4, one FP8 scale per 16 weights, and one FP32 global scale per Linear. + return 0.5 + 1 / 16 + 4 / param.numel() + return super().param_element_size(model, param_name, param) + def _process_model_before_weight_loading(self, model, **kwargs): + if self.use_nvfp4_weight_only: + from compressed_tensors.utils.match import match_named_modules + + if getattr(model.config, "distributed_config", None) is not None: + raise ValueError("NVFP4 weight-only loading does not support tensor or expert parallelism.") + config = self.quantization_config.quantization_config + if config is None: + raise ValueError("NVFP4 weight-only loading requires a checkpoint quantization config.") + self.nvfp4_modules = set() + self.nvfp4_base_model_prefix = getattr(model, "base_model_prefix", "") + fp32_pattern = None + if model._keep_in_fp32_modules_strict: + fp32_pattern, _, _ = build_glob_alternation(list(model._keep_in_fp32_modules_strict)) + for group in config.config_groups.values(): + for name, module in match_named_modules(model, group.targets, ignore=config.ignore): + if type(module) is not torch.nn.Linear: + raise ValueError( + f"NVFP4 weight-only loading supports ordinary nn.Linear modules only: {name}." + ) + if ( + module.in_features <= 0 + or module.out_features <= 0 + or module.in_features % 16 + or module.weight.dtype != torch.bfloat16 + ): + raise ValueError( + f"NVFP4 module {name} requires BF16 weights, positive dimensions and in_features divisible by 16." + ) + if fp32_pattern is not None and fp32_pattern.search(f"{name}.weight"): + raise ValueError( + f"NVFP4 weight-only loading cannot quantize an FP32-preserved weight: {name}." + ) + self.nvfp4_modules.add(name) + if not self.nvfp4_modules: + raise ValueError("No Linear modules matched the NVFP4 weight-only targets and ignore patterns.") + tied_weights = getattr(model, "all_tied_weights_keys", {}) + tied_quantized = {f"{name}.weight" for name in self.nvfp4_modules} & ( + set(tied_weights) | set(tied_weights.values()) + ) + if tied_quantized: + raise ValueError( + f"NVFP4 weight-only loading does not support tied quantized weights: {sorted(tied_quantized)}." + ) + selected_weights = {id(model.get_submodule(name).weight) for name in self.nvfp4_modules} + seen = set() + for name, parameter in model.named_parameters(remove_duplicate=False): + if id(parameter) in selected_weights: + if id(parameter) in seen: + raise ValueError(f"NVFP4 weight-only loading does not support tied quantized weights: {name}.") + seen.add(id(parameter)) + # No CT wrappers or companion parameters: the deserializer constructs the torchao weights. + return if self.quantization_config.dequantize: # The model stays dense: the `dequantize` load operation runs on every checkpoint weight return @@ -118,30 +228,66 @@ def _process_model_before_weight_loading(self, model, **kwargs): if self.quantization_config.is_quantization_compressed: self.compressor.compress_model(model=model) + def _process_model_after_weight_loading(self, model, **kwargs): + if self.use_nvfp4_weight_only: + missing = [ + name + for name in self.nvfp4_modules + if not isinstance(model.get_submodule(name).weight, self.nvfp4_tensor_class) + ] + if missing: + raise ValueError(f"Missing NVFP4 packed weights for selected modules: {missing}.") + return model + @property def is_trainable(self): # The FP8 kernel path is inference-only; load with `dequantize=True` to fine-tune. - return not self.use_fp8_kernel + return not (self.use_fp8_kernel or self.use_nvfp4_weight_only) @property def is_compileable(self) -> bool: - return True + return not self.use_nvfp4_weight_only + @property def is_qat_trainable(self) -> bool: """Loaded Models can carry out quantization aware training""" - if self.use_fp8_kernel: + if self.use_fp8_kernel or self.use_nvfp4_weight_only: return False # models need to be decompressed carry out qat return self.quantization_config.dequantize or not self.quantization_config.is_quantization_compressed def is_serializable(self) -> bool: """Models quantized using compressed tensors can be saved to disk""" - return True + return not self.use_nvfp4_weight_only + + def update_weight_conversions(self, weight_conversions, model): + if self.use_nvfp4_weight_only: + if any(isinstance(converter, WeightConverter) for converter in weight_conversions): + raise ValueError( + "NVFP4 weight-only loading does not support model-level WeightConverters, " + "including fused or grouped weight conversions, even for unquantized modules." + ) + return weight_conversions + self.get_weight_conversions() + return super().update_weight_conversions(weight_conversions, model) def get_weight_conversions(self): """On the FP8 kernel path, a generic converter reshapes the checkpoint ``weight_scale`` tensors into the row-wise kernel layout once at load time — see :class:`ConvertFP8LinearScale`.""" + if self.use_nvfp4_weight_only: + converters = [] + for name in sorted(self.nvfp4_modules): + name = name.removeprefix(f"{self.nvfp4_base_model_prefix}.") + converter = WeightConverter( + source_patterns=[rf"^{re.escape(name)}\.{param}$" for param in self.serialized_names["weight"]], + target_patterns=[f"{name}.weight"], + operations=[CompressedTensorsNVFP4Deserialize(self)], + ) + # Match exact module names with or without the checkpoint's base-model prefix. + converter.scope_prefix = "" + converter.base_model_prefix = self.nvfp4_base_model_prefix + converters.append(converter) + return converters if not self.use_fp8_kernel: return super().get_weight_conversions() @@ -168,5 +314,7 @@ def get_weight_conversions(self): } def get_load_operations(self): + if self.use_nvfp4_weight_only: + return {"deserialize": CompressedTensorsNVFP4Deserialize} # No `deserialize`: the serialized tensors load as is into the params compressed-tensors creates return {"dequantize": CompressedTensorsDequantize} diff --git a/src/transformers/utils/quantization_config.py b/src/transformers/utils/quantization_config.py index e8e399738ad4..65e2dfb33c9f 100644 --- a/src/transformers/utils/quantization_config.py +++ b/src/transformers/utils/quantization_config.py @@ -1121,6 +1121,11 @@ class CompressedTensorsConfig(QuantizationConfigMixin): have kernels for keep their quantized weights and run through those kernels (currently W8A8 FP8, on CUDA SM89+, XPU, or MPS with torch >= 2.15). Inference only, and opt-in: without it the model goes through the regular compressed-tensors route. Ignored when `dequantize=True`. + weight_only (`bool`, *optional*, defaults to `False`): + Load packed NVFP4 weights into torchao with BF16 activations, explicitly disabling the checkpoint's + activation quantization. Supports dense Linear layers only and requires torchao. This is an + inference-only loading mode, not a promise of accelerated FP4 computation. Cannot be combined with + `dequantize=True` or `use_optimized_inference=True`. """ def __init__( @@ -1135,6 +1140,7 @@ def __init__( run_compressed: bool | None = None, dequantize: bool = False, use_optimized_inference: bool = False, + weight_only: bool = False, **kwargs, ): if is_compressed_tensors_available(): @@ -1154,6 +1160,11 @@ def __init__( dequantize = dequantize or not run_compressed self.dequantize = dequantize self.use_optimized_inference = use_optimized_inference + self.weight_only = weight_only + # These legacy fields may be discarded by compressed-tensors' config parser. + self._additional_compression = [ + name for name in ("sparsity_config", "transform_config", "moe_sparsity_config") if kwargs.get(name) + ] # parse from dict to load nested QuantizationScheme objects if config_groups or kv_cache_scheme: @@ -1173,6 +1184,10 @@ def __init__( self.quant_method = QuantizationMethod.COMPRESSED_TENSORS def post_init(self): + if self.weight_only: + if self.dequantize or self.use_optimized_inference: + raise ValueError("`weight_only=True` cannot be combined with dequantize or use_optimized_inference.") + self._validate_weight_only() if self.use_optimized_inference: # Whether the optimized path is reachable at all is decided here; whether the hardware # can run its kernels is left to `HfQuantizer.validate_environment`. @@ -1189,6 +1204,56 @@ def post_init(self): ) self.use_optimized_inference = False + def _validate_weight_only(self): + config = self.quantization_config + if ( + config is None + or not config.config_groups + or config.format != "nvfp4-pack-quantized" + or not self.is_quantization_compressed + ): + raise ValueError("`weight_only=True` requires a compressed nvfp4-pack-quantized checkpoint.") + if config.kv_cache_scheme is not None or self._additional_compression: + raise ValueError( + "NVFP4 weight-only loading does not support KV-cache quantization, sparsity or transforms." + ) + for name, group in config.config_groups.items(): + weights = group.weights + if ( + (group.format or config.format) != "nvfp4-pack-quantized" + or weights is None + or weights.type != "float" + or weights.num_bits != 4 + or weights.strategy != "tensor_group" + or weights.group_size != 16 + or not weights.symmetric + or weights.dynamic + or weights.actorder is not None + or weights.block_structure is not None + ): + raise ValueError( + f"NVFP4 weight-only loading requires static symmetric float4 tensor_group weights with group_size=16 " + f"and no activation ordering in every config group; unsupported group: {name}." + ) + activations = group.input_activations + if group.output_activations is not None or ( + activations is not None + and ( + activations.type != "float" + or activations.num_bits != 4 + or activations.strategy != "tensor_group" + or activations.group_size != 16 + or not activations.symmetric + or activations.dynamic != "local" + or activations.actorder is not None + or activations.block_structure is not None + ) + ): + raise ValueError( + f"NVFP4 weight-only loading supports only absent or local-dynamic NVFP4 input quantization " + f"and no output quantization; unsupported group: {name}." + ) + @classmethod def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs): """ @@ -1251,7 +1316,11 @@ def to_diff_dict(self) -> dict[str, Any]: return serializable_config_dict def get_loading_attributes(self): - return {"dequantize": self.dequantize, "use_optimized_inference": self.use_optimized_inference} + return { + "dequantize": self.dequantize, + "use_optimized_inference": self.use_optimized_inference, + "weight_only": self.weight_only, + } @property def has_fp8_modules(self): diff --git a/tests/quantization/compressed_tensors_integration/test_nvfp4.py b/tests/quantization/compressed_tensors_integration/test_nvfp4.py new file mode 100644 index 000000000000..0a038c08e486 --- /dev/null +++ b/tests/quantization/compressed_tensors_integration/test_nvfp4.py @@ -0,0 +1,279 @@ +# Copyright 2026 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gc +import json +import os +import tempfile +import unittest +from unittest.mock import patch + +from transformers import AutoModel, AutoModelForCausalLM, CompressedTensorsConfig, Qwen3Config +from transformers.testing_utils import ( + require_compressed_tensors, + require_torch, + require_torch_accelerator, + require_torchao_version_greater_or_equal, + torch_device, +) +from transformers.utils import is_torch_available + + +if is_torch_available(): + import torch + + from transformers.quantizers.auto import AutoHfQuantizer + from transformers.quantizers.quantizer_compressed_tensors import CompressedTensorsHfQuantizer + + +def nvfp4_config(): + weights = { + "num_bits": 4, + "type": "float", + "strategy": "tensor_group", + "group_size": 16, + "symmetric": True, + "dynamic": False, + } + return { + "quant_method": "compressed-tensors", + "format": "nvfp4-pack-quantized", + "quantization_status": "compressed", + "config_groups": { + "nvfp4": { + "targets": ["Linear"], + "weights": weights, + "input_activations": {**weights, "dynamic": "local"}, + } + }, + "ignore": ["lm_head"], + } + + +@require_torch +@require_compressed_tensors +class NVFP4ConfigTest(unittest.TestCase): + def test_loading_options(self): + config = AutoHfQuantizer.merge_quantization_configs(nvfp4_config(), CompressedTensorsConfig(weight_only=True)) + config.post_init() + self.assertTrue(config.get_loading_attributes()["weight_only"]) + self.assertNotIn("weight_only", config.to_dict()) + self.assertNotIn("_additional_compression", config.to_dict()) + self.assertFalse(CompressedTensorsConfig.from_dict(config.to_dict()).weight_only) + for option in ("dequantize", "use_optimized_inference"): + with self.subTest(option=option), self.assertRaisesRegex(ValueError, "cannot be combined"): + CompressedTensorsConfig(**nvfp4_config(), weight_only=True, **{option: True}).post_init() + invalid = nvfp4_config() | {"format": "pack-quantized"} + with self.assertRaisesRegex(ValueError, "nvfp4-pack-quantized"): + CompressedTensorsConfig(**invalid, weight_only=True).post_init() + default_quantizer = CompressedTensorsHfQuantizer(CompressedTensorsConfig(**nvfp4_config())) + self.assertIs(default_quantizer.is_qat_trainable, False) + + def test_old_torchao_is_an_error(self): + from transformers.utils.import_utils import is_torchao_available + + quantizer = CompressedTensorsHfQuantizer(CompressedTensorsConfig(**nvfp4_config(), weight_only=True)) + is_torchao_available.cache_clear() + self.addCleanup(is_torchao_available.cache_clear) + with ( + patch("transformers.utils.import_utils.is_torch_available", return_value=True), + patch("transformers.utils.import_utils._is_package_available", return_value=(True, "0.15.0")), + self.assertRaisesRegex(ImportError, r"torchao>=0\.16\.0"), + ): + quantizer.validate_environment(device_map={"": "cpu"}) + + +@require_torch +@require_compressed_tensors +@require_torchao_version_greater_or_equal("0.16.0") +class NVFP4LoadingTest(unittest.TestCase): + @staticmethod + def make_checkpoint(directory, model_class=AutoModelForCausalLM, input_global_scale=True): + from safetensors.torch import save_file + + torch.manual_seed(17) + config = Qwen3Config( + vocab_size=64, + hidden_size=32, + intermediate_size=64, + num_hidden_layers=1, + num_attention_heads=2, + num_key_value_heads=1, + head_dim=16, + max_position_embeddings=64, + attention_bias=True, + tie_word_embeddings=False, + bos_token_id=1, + eos_token_id=2, + pad_token_id=0, + ) + reference = model_class.from_config(config, dtype=torch.bfloat16, attn_implementation="eager").eval() + tensors = {name: value.clone() for name, value in reference.state_dict().items()} + values = torch.tensor([0, 0.5, 1, 1.5, 2, 3, 4, 6, 0, -0.5, -1, -1.5, -2, -3, -4, -6]) + for name, module in reference.named_modules(): + if not isinstance(module, torch.nn.Linear) or name == "lm_head": + continue + n, k = module.weight.shape + packed = torch.arange(n * k // 2).to(torch.uint8).reshape(n, k // 2) + scales = (torch.randint(1, 9, (n, k // 16)).float() / 128).to(torch.float8_e4m3fn) + del tensors[f"{name}.weight"] + tensors.update( + { + f"{name}.weight_packed": packed, + f"{name}.weight_scale": scales, + f"{name}.weight_global_scale": torch.tensor([2.0]), + } + ) + if input_global_scale: + tensors[f"{name}.input_global_scale"] = torch.tensor([3.0]) + codes = torch.stack((packed & 15, packed >> 4), dim=-1).reshape(n, k).long() + module.weight = torch.nn.Parameter( + (values[codes] * scales.float().repeat_interleave(16, dim=1) / 2).to(torch.bfloat16), + requires_grad=False, + ) + reference.config.quantization_config = nvfp4_config() + reference.config.save_pretrained(directory) + weight_map = {} + # Separate packed weights from their scales to exercise cross-shard collection. + for index in range(2): + shard = {key: value for key, value in tensors.items() if key.endswith("weight_packed") == bool(index)} + filename = f"model-{index + 1:05d}-of-00002.safetensors" + save_file(shard, os.path.join(directory, filename), metadata={"format": "pt"}) + weight_map.update(dict.fromkeys(shard, filename)) + with open(os.path.join(directory, "model.safetensors.index.json"), "w", encoding="utf-8") as handle: + json.dump({"metadata": {}, "weight_map": weight_map}, handle) + return reference, tensors + + @staticmethod + def load_checkpoint(directory, model_class=AutoModelForCausalLM, device="cpu"): + return model_class.from_pretrained( + directory, + dtype=torch.bfloat16, + device_map=device, + quantization_config=CompressedTensorsConfig(weight_only=True), + attn_implementation="eager", + local_files_only=True, + output_loading_info=True, + ) + + def assert_backbone_parity(self, model, reference, tensors): + from torchao.prototype.mx_formats.nvfp4_tensor import NVFP4Tensor + + reference = reference.to(model.device) + actual_base, expected_base = model.base_model, reference.base_model + for name, module in expected_base.named_modules(): + actual = actual_base.get_submodule(name) + if isinstance(module, torch.nn.Linear): + source_name = f"model.{name}" if hasattr(reference, "lm_head") else name + self.assertIs(type(actual), torch.nn.Linear) + self.assertIsInstance(actual.weight, NVFP4Tensor) + self.assertIsNone(actual.weight.act_quant_kwargs) + self.assertEqual(actual.weight.per_tensor_scale.item(), 0.5) + torch.testing.assert_close( + actual.weight.qdata.cpu(), tensors[f"{source_name}.weight_packed"], rtol=0, atol=0 + ) + torch.testing.assert_close(actual.weight.dequantize(), module.weight, rtol=0, atol=0) + self.assertNotIsInstance(actual_base.embed_tokens.weight, NVFP4Tensor) + self.assertEqual(actual_base.rotary_emb.inv_freq.dtype, torch.float32) + if hasattr(model, "lm_head"): + self.assertNotIsInstance(model.lm_head.weight, NVFP4Tensor) + inputs = torch.tensor([[1, 5, 8, 11]], device=model.device) + with torch.no_grad(): + torch.testing.assert_close( + actual_base(inputs).last_hidden_state, expected_base(inputs).last_hidden_state, rtol=0, atol=0 + ) + if hasattr(model, "lm_head") and hasattr(reference, "lm_head"): + torch.testing.assert_close( + model.generate(inputs, max_new_tokens=3, do_sample=False), + reference.generate(inputs, max_new_tokens=3, do_sample=False), + rtol=0, + atol=0, + ) + + def test_prefix_loading_and_optional_activation_scale(self): + for source in (AutoModel, AutoModelForCausalLM): + with tempfile.TemporaryDirectory() as directory: + reference, tensors = self.make_checkpoint( + directory, source, input_global_scale=source is AutoModelForCausalLM + ) + for target in (AutoModel, AutoModelForCausalLM): + with self.subTest(source=source.__name__, target=target.__name__): + model, info = self.load_checkpoint(directory, target) + missing = ( + {"lm_head.weight"} if source is AutoModel and target is AutoModelForCausalLM else set() + ) + extra = {"lm_head.weight"} if source is AutoModelForCausalLM and target is AutoModel else set() + self.assertEqual(set(info["missing_keys"]), missing) + self.assertEqual(set(info["unexpected_keys"]), extra) + self.assertFalse(info["mismatched_keys"] or info["error_msgs"]) + self.assert_backbone_parity(model, reference, tensors) + + @require_torch_accelerator + def test_accelerator_loading(self): + if torch_device not in ("cuda", "xpu"): + self.skipTest("NVFP4 weight-only loading supports CUDA and XPU accelerators.") + with tempfile.TemporaryDirectory() as directory: + reference, tensors = self.make_checkpoint(directory, input_global_scale=False) + model, info = self.load_checkpoint(directory, device=torch_device) + self.assertFalse(any(info.values()), info) + self.assert_backbone_parity(model, reference, tensors) + + def test_invalid_checkpoint_tensors(self): + from safetensors.torch import save_file + + with tempfile.TemporaryDirectory() as directory: + reference, original = self.make_checkpoint(directory) + name = "model.layers.0.self_attn.q_proj" + for suffix, value in ( + ("weight_packed", None), + ("weight_scale", torch.ones(1)), + ("weight_global_scale", torch.tensor([1e-40])), + ("input_global_scale", torch.tensor([float("nan")])), + ("weight_zero_point", torch.tensor([0.0])), + ): + with self.subTest(suffix=suffix): + # Distinct files avoid rewriting mmap-backed tensors on Windows. + case = os.path.join(directory, suffix) + reference.config.save_pretrained(case) + tensors = dict(original) + if value is None: + del tensors[f"{name}.{suffix}"] + else: + tensors[f"{name}.{suffix}"] = value + save_file(tensors, os.path.join(case, "model.safetensors"), metadata={"format": "pt"}) + with self.assertRaisesRegex(RuntimeError, "conversion"): + self.load_checkpoint(case) + gc.collect() + + def test_memory_estimate_and_scope_guards(self): + from transformers.core_model_loading import WeightConverter, _IdentityOp + from transformers.integrations.accelerate import compute_module_sizes + + with tempfile.TemporaryDirectory() as directory: + model, _ = self.make_checkpoint(directory) + quantizer = CompressedTensorsHfQuantizer(CompressedTensorsConfig(**nvfp4_config(), weight_only=True)) + name = "model.layers.0.self_attn.q_proj" + weight = model.get_submodule(name).weight + self.assertEqual(quantizer.param_element_size(model, f"{name}.weight", weight), 2) + quantizer._process_model_before_weight_loading(model) + sizes, _ = compute_module_sizes(model, quantizer, only_modules=False) + self.assertEqual(sizes[f"{name}.weight"], weight.numel() // 2 + weight.numel() // 16 + 4) + for converter in quantizer.get_weight_conversions(): + key = "other.layers.0.self_attn.q_proj.weight_packed" + self.assertEqual(converter.rename_source_key(key), (key, None)) + with self.assertRaisesRegex(ValueError, "model-level WeightConverters"): + quantizer.update_weight_conversions([WeightConverter("weight", "weight", [_IdentityOp()])], model) + with self.assertRaisesRegex(ValueError, "bfloat16"): + quantizer.update_dtype(torch.float32) + self.assertFalse(quantizer.is_trainable or quantizer.is_qat_trainable or quantizer.is_serializable()) From 071de1a7a1605c30d2f6df12d0c015c7c4086636 Mon Sep 17 00:00:00 2001 From: Eryk Roch Rybak Date: Wed, 25 Nov 2026 15:38:16 +0200 Subject: [PATCH 2/4] Clarify NVFP4 weight-only scope and simplify tensor imports Document the NVFP4-only scope and reuse on devices without native FP4 GEMMs. Remove the validation-specific revision from the usage example. Import NVFP4Tensor directly for conversion and post-load validation, while retaining the early dependency check and existing loader hooks. --- docs/source/en/quantization/compressed_tensors.md | 8 ++++---- src/transformers/integrations/compressed_tensors.py | 4 +++- .../quantizers/quantizer_compressed_tensors.py | 9 ++++----- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/docs/source/en/quantization/compressed_tensors.md b/docs/source/en/quantization/compressed_tensors.md index a59d908a0c65..794a0ef8dfeb 100644 --- a/docs/source/en/quantization/compressed_tensors.md +++ b/docs/source/en/quantization/compressed_tensors.md @@ -71,7 +71,7 @@ A compressed-tensors checkpoint stores its weights compressed. [`CompressedTenso | 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 bytes and scales kept in torchao tensors | BF16 activations, with activation quantization explicitly disabled; 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. @@ -79,6 +79,8 @@ With the default, [`~PreTrainedModel.save_pretrained`] writes the compressed ten Pass `weight_only=True` to load a compressed-tensors `nvfp4-pack-quantized` checkpoint into torchao's `NVFP4Tensor`. This mode preserves the original packed weights and block scales without requantizing or converting the entire model to BF16. Install `compressed-tensors>=0.15.0` and a compatible `torchao>=0.16.0` build exposing `torchao.prototype.mx_formats.nvfp4_tensor.NVFP4Tensor`. +This mode enables reuse of existing NVFP4 checkpoints on supported devices without native NVFP4 GEMMs, retaining packed weight storage while executing Linear operations in BF16. Currently, `weight_only=True` supports only NVFP4; other quantized formats are rejected. + > [!WARNING] > This is an explicit change from W4A4 to W4A16: the checkpoint's input activation quantization is disabled, so outputs can differ from its original deployment. The current torchao weight-only path dequantizes each Linear weight for every forward call, then performs BF16 Linear. It is not a native or fused FP4 GEMM, and this loading mode does not imply a speedup. Temporary dequantization allocations also contribute to peak memory. @@ -87,15 +89,13 @@ import torch from transformers import AutoModelForCausalLM, AutoTokenizer, CompressedTensorsConfig model_id = "RedHatAI/Qwen3-14B-NVFP4" -revision = "cc120e7bc68557313002275d51db65096ca24303" model = AutoModelForCausalLM.from_pretrained( model_id, - revision=revision, 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, revision=revision) +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)) diff --git a/src/transformers/integrations/compressed_tensors.py b/src/transformers/integrations/compressed_tensors.py index 8c6cca3f70f7..1073f6b1ed7b 100644 --- a/src/transformers/integrations/compressed_tensors.py +++ b/src/transformers/integrations/compressed_tensors.py @@ -31,6 +31,8 @@ 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"])) @@ -86,7 +88,7 @@ def convert(self, input_dict, source_patterns, model=None, full_layer_name=None, 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 = self.hf_quantizer.nvfp4_tensor_class( + weight = NVFP4Tensor( packed.contiguous(), scales.contiguous(), block_size=16, diff --git a/src/transformers/quantizers/quantizer_compressed_tensors.py b/src/transformers/quantizers/quantizer_compressed_tensors.py index 61d743b506ea..8cbc6e2883a8 100644 --- a/src/transformers/quantizers/quantizer_compressed_tensors.py +++ b/src/transformers/quantizers/quantizer_compressed_tensors.py @@ -95,13 +95,12 @@ def validate_environment(self, *args, **kwargs): "Install a compatible build with `pip install 'torchao>=0.16.0'`." ) try: - from torchao.prototype.mx_formats.nvfp4_tensor import NVFP4Tensor + from torchao.prototype.mx_formats.nvfp4_tensor import NVFP4Tensor # noqa: F401 except ImportError as error: raise ImportError( "NVFP4 weight-only loading requires a torchao build providing " "`torchao.prototype.mx_formats.nvfp4_tensor.NVFP4Tensor`. Upgrade torchao." ) from error - self.nvfp4_tensor_class = NVFP4Tensor device_map = kwargs.get("device_map") if device_map is not None: if not isinstance(device_map, dict) or set(device_map) != {""}: @@ -230,10 +229,10 @@ def _process_model_before_weight_loading(self, model, **kwargs): def _process_model_after_weight_loading(self, model, **kwargs): if self.use_nvfp4_weight_only: + from torchao.prototype.mx_formats.nvfp4_tensor import NVFP4Tensor + missing = [ - name - for name in self.nvfp4_modules - if not isinstance(model.get_submodule(name).weight, self.nvfp4_tensor_class) + name for name in self.nvfp4_modules if not isinstance(model.get_submodule(name).weight, NVFP4Tensor) ] if missing: raise ValueError(f"Missing NVFP4 packed weights for selected modules: {missing}.") From c3d902e9a5562c67783d28b0b49ac18a8db925f7 Mon Sep 17 00:00:00 2001 From: Eryk Roch Rybak Date: Fri, 27 Nov 2026 13:40:39 +0200 Subject: [PATCH 3/4] Simplify NVFP4 validation and loading documentation Remove redundant deserializer checks covered by module preparation and the single-device loader. Share NVFP4 scheme validation while preserving distinct weight and activation requirements. Retain checkpoint integrity and scope guards, shorten the documentation, and add compact regression coverage for the shared validation. --- .../en/quantization/compressed_tensors.md | 14 ++++----- .../integrations/compressed_tensors.py | 13 ++------ src/transformers/utils/quantization_config.py | 31 ++++++++----------- .../test_nvfp4.py | 7 +++++ 4 files changed, 28 insertions(+), 37 deletions(-) diff --git a/docs/source/en/quantization/compressed_tensors.md b/docs/source/en/quantization/compressed_tensors.md index 794a0ef8dfeb..4f350caf8ef7 100644 --- a/docs/source/en/quantization/compressed_tensors.md +++ b/docs/source/en/quantization/compressed_tensors.md @@ -77,12 +77,10 @@ With the default, [`~PreTrainedModel.save_pretrained`] writes the compressed ten ## NVFP4 weight-only loading -Pass `weight_only=True` to load a compressed-tensors `nvfp4-pack-quantized` checkpoint into torchao's `NVFP4Tensor`. This mode preserves the original packed weights and block scales without requantizing or converting the entire model to BF16. Install `compressed-tensors>=0.15.0` and a compatible `torchao>=0.16.0` build exposing `torchao.prototype.mx_formats.nvfp4_tensor.NVFP4Tensor`. - -This mode enables reuse of existing NVFP4 checkpoints on supported devices without native NVFP4 GEMMs, retaining packed weight storage while executing Linear operations in BF16. Currently, `weight_only=True` supports only NVFP4; other quantized formats are rejected. +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 is an explicit change from W4A4 to W4A16: the checkpoint's input activation quantization is disabled, so outputs can differ from its original deployment. The current torchao weight-only path dequantizes each Linear weight for every forward call, then performs BF16 Linear. It is not a native or fused FP4 GEMM, and this loading mode does not imply a speedup. Temporary dequantization allocations also contribute to peak memory. +> 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 @@ -101,13 +99,13 @@ outputs = model.generate(**inputs, max_new_tokens=8, do_sample=False) print(tokenizer.decode(outputs[0], skip_special_tokens=True)) ``` -Supported checkpoints contain static, symmetric float4 `tensor_group` weights with group size 16, optionally with local-dynamic NVFP4 input activation quantization. All quantized groups must use this format. Targets and ignore patterns select ordinary `torch.nn.Linear` modules; unquantized modules, such as embeddings and the output head, retain the normal loading path. Block scales use `float8_e4m3fn`, and the compressed-tensors FP32 global scale is inverted to obtain torchao's multiplicative per-tensor scale. Input global scales are optional; when present, they are validated and consumed but not used for inference. +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. -Allocator planning accounts for the packed weights and their block/global scales rather than the logical BF16 weight size. Temporary dequantization tensors and the KV cache still require additional memory. +Memory planning accounts for packed weights and scales; temporary dequantization tensors and the KV cache require additional memory. -This mode requires `dtype=torch.bfloat16` and an explicit whole-model device (`device_map="xpu"`, `"cuda:0"`, or `"cpu"`). Omitting `device_map` loads on CPU, which is useful for small correctness tests. Automatic device placement, CPU/disk offload, mixed quantized formats, tied quantized weights, KV-cache quantization, sparsity, and transforms are not supported. Models requiring any model-level `WeightConverter` (including fused/grouped conversions for MoE experts) are rejected, even when the conversion only affects unquantized modules; weight renamings remain supported. Training, QAT, compilation, and saving the loaded quantized model are not supported either. +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`. Like the other compressed-tensors loading options, it is not written into checkpoint metadata. Set it explicitly each time you load the original checkpoint. Leave it unset to retain the existing compressed-tensors behavior, or use `dequantize=True` alone for a dense model that can be fine-tuned or saved. +`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 diff --git a/src/transformers/integrations/compressed_tensors.py b/src/transformers/integrations/compressed_tensors.py index 1073f6b1ed7b..fb6f5f9ee0a0 100644 --- a/src/transformers/integrations/compressed_tensors.py +++ b/src/transformers/integrations/compressed_tensors.py @@ -46,9 +46,6 @@ def convert(self, input_dict, source_patterns, model=None, full_layer_name=None, module_name, _, _ = full_layer_name.rpartition(".") module = model.get_submodule(module_name) - if module_name not in self.hf_quantizer.nvfp4_modules: - raise ValueError(f"NVFP4 conversion was requested for unselected module {module_name}.") - required = {"weight_packed", "weight_scale", "weight_global_scale"} allowed = required | {"input_global_scale"} if not required <= tensors.keys() or tensors.keys() - allowed: @@ -60,16 +57,10 @@ def convert(self, input_dict, source_patterns, model=None, full_layer_name=None, scales = tensors["weight_scale"] global_scale = tensors["weight_global_scale"] n, k = module.out_features, module.in_features - if k % 16 or 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)} and K divisible by 16." - ) + 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)}.") - if any(tensor.device != packed.device for tensor in tensors.values()) or packed.device.type == "meta": - raise ValueError(f"All NVFP4 tensors for {module_name} must be materialized on the same device.") - if module.weight.dtype != torch.bfloat16: - raise ValueError(f"NVFP4 weight-only module {module_name} requires BF16.") for name in ("weight_global_scale", "input_global_scale"): if name not in tensors: continue diff --git a/src/transformers/utils/quantization_config.py b/src/transformers/utils/quantization_config.py index 65e2dfb33c9f..0b819cdb285d 100644 --- a/src/transformers/utils/quantization_config.py +++ b/src/transformers/utils/quantization_config.py @@ -1205,6 +1205,17 @@ def post_init(self): self.use_optimized_inference = False def _validate_weight_only(self): + def is_nvfp4(args): + return ( + args.type == "float" + and args.num_bits == 4 + and args.strategy == "tensor_group" + and args.group_size == 16 + and args.symmetric + and args.actorder is None + and args.block_structure is None + ) + config = self.quantization_config if ( config is None @@ -1222,14 +1233,8 @@ def _validate_weight_only(self): if ( (group.format or config.format) != "nvfp4-pack-quantized" or weights is None - or weights.type != "float" - or weights.num_bits != 4 - or weights.strategy != "tensor_group" - or weights.group_size != 16 - or not weights.symmetric + or not is_nvfp4(weights) or weights.dynamic - or weights.actorder is not None - or weights.block_structure is not None ): raise ValueError( f"NVFP4 weight-only loading requires static symmetric float4 tensor_group weights with group_size=16 " @@ -1237,17 +1242,7 @@ def _validate_weight_only(self): ) activations = group.input_activations if group.output_activations is not None or ( - activations is not None - and ( - activations.type != "float" - or activations.num_bits != 4 - or activations.strategy != "tensor_group" - or activations.group_size != 16 - or not activations.symmetric - or activations.dynamic != "local" - or activations.actorder is not None - or activations.block_structure is not None - ) + activations is not None and (not is_nvfp4(activations) or activations.dynamic != "local") ): raise ValueError( f"NVFP4 weight-only loading supports only absent or local-dynamic NVFP4 input quantization " diff --git a/tests/quantization/compressed_tensors_integration/test_nvfp4.py b/tests/quantization/compressed_tensors_integration/test_nvfp4.py index 0a038c08e486..c7cc25d495a9 100644 --- a/tests/quantization/compressed_tensors_integration/test_nvfp4.py +++ b/tests/quantization/compressed_tensors_integration/test_nvfp4.py @@ -77,6 +77,13 @@ def test_loading_options(self): invalid = nvfp4_config() | {"format": "pack-quantized"} with self.assertRaisesRegex(ValueError, "nvfp4-pack-quantized"): CompressedTensorsConfig(**invalid, weight_only=True).post_init() + for target in ("weights", "input_activations"): + for field, value in (("group_size", 32), ("dynamic", "local" if target == "weights" else False)): + with self.subTest(target=target, field=field): + config = CompressedTensorsConfig(**nvfp4_config(), weight_only=True) + setattr(getattr(config.quantization_config.config_groups["nvfp4"], target), field, value) + with self.assertRaisesRegex(ValueError, "unsupported group"): + config.post_init() default_quantizer = CompressedTensorsHfQuantizer(CompressedTensorsConfig(**nvfp4_config())) self.assertIs(default_quantizer.is_qat_trainable, False) From 7e4e26a2da3c3111ae7db34870a1b8fd977a1996 Mon Sep 17 00:00:00 2001 From: Eryk Roch Rybak Date: Mon, 30 Nov 2026 19:32:51 +0200 Subject: [PATCH 4/4] Assert previously validated NVFP4 config invariant Replace duplicate input validation with an assertion documenting the config invariant established by post_init in the quantizer constructor. --- src/transformers/quantizers/quantizer_compressed_tensors.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/transformers/quantizers/quantizer_compressed_tensors.py b/src/transformers/quantizers/quantizer_compressed_tensors.py index 8cbc6e2883a8..6f528d0e1efa 100644 --- a/src/transformers/quantizers/quantizer_compressed_tensors.py +++ b/src/transformers/quantizers/quantizer_compressed_tensors.py @@ -152,8 +152,7 @@ def _process_model_before_weight_loading(self, model, **kwargs): if getattr(model.config, "distributed_config", None) is not None: raise ValueError("NVFP4 weight-only loading does not support tensor or expert parallelism.") config = self.quantization_config.quantization_config - if config is None: - raise ValueError("NVFP4 weight-only loading requires a checkpoint quantization config.") + assert config is not None # Validated by post_init in the quantizer constructor. self.nvfp4_modules = set() self.nvfp4_base_model_prefix = getattr(model, "base_model_prefix", "") fp32_pattern = None