diff --git a/docs/source/en/quantization/compressed_tensors.md b/docs/source/en/quantization/compressed_tensors.md index c45df3a480a6..4f350caf8ef7 100644 --- a/docs/source/en/quantization/compressed_tensors.md +++ b/docs/source/en/quantization/compressed_tensors.md @@ -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. diff --git a/src/transformers/integrations/compressed_tensors.py b/src/transformers/integrations/compressed_tensors.py index 543214f35dd0..fb6f5f9ee0a0 100644 --- a/src/transformers/integrations/compressed_tensors.py +++ b/src/transformers/integrations/compressed_tensors.py @@ -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 diff --git a/src/transformers/quantizers/quantizer_compressed_tensors.py b/src/transformers/quantizers/quantizer_compressed_tensors.py index 6f6644c23fa8..6f528d0e1efa 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,35 @@ 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 # 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 + 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 +133,70 @@ 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 + 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 + 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 +226,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: + 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, NVFP4Tensor) + ] + 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 +312,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..0b819cdb285d 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,51 @@ 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 + 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 not is_nvfp4(weights) + or weights.dynamic + ): + 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 (not is_nvfp4(activations) or activations.dynamic != "local") + ): + 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 +1311,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..c7cc25d495a9 --- /dev/null +++ b/tests/quantization/compressed_tensors_integration/test_nvfp4.py @@ -0,0 +1,286 @@ +# 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() + 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) + + 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())