huggingface/transformers · #50238
[compressed-tensors] better path through conversion mapping
docs/source/en/quantization/compressed_tensors.md6 + / 4 −
@@ -68,10 +68,12 @@ A compressed-tensors checkpoint stores its weights compressed (fp8, or packed in | Configuration | Weights after loading | Execution | |---------------|-----------------------|-----------|-| default | left compressed | compressed-tensors owns the layers and decompresses the model on the first forward pass |-| `dequantize=True` | dequantized to the model dtype (e.g. BF16) | regular dense matmuls, and the model can be fine-tuned or saved in that dtype |+| 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 | +With the default, [`~PreTrainedModel.save_pretrained`] writes the compressed tensors back unchanged, so a loaded model saves in the same compressed-tensors format.+ ## 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.@@ -110,7 +112,7 @@ print(tokenizer.decode(outputs[0], skip_special_tokens=True)) ### Dequantizing at load time -Without `use_optimized_inference=True`, the model takes the regular compressed-tensors route: the weights are left compressed and compressed-tensors decompresses them on the first forward pass. Pass `dequantize=True` to dequantize them during loading instead, which is what you want to fine-tune the model or save it in its original precision (e.g. BF16).+Without `use_optimized_inference=True`, the model takes the regular compressed-tensors route: the weights are left compressed and compressed-tensors decompresses them on the first forward pass. Pass `dequantize=True` to decompress them during loading instead, which is what you want to fine-tune the model or save it in its original precision (e.g. BF16). The result is a plain dense model: no compressed-tensors scheme is attached, so activation quantization (e.g. w8a8) is dropped too. ```python from transformers import AutoModelForCausalLM, CompressedTensorsConfig@@ -184,7 +186,7 @@ For a more detailed look at the model weights, use the [safetensors viewer](http When loading a compressed-tensors model with the [`~quantizers.HFQuantizer`] integration, the targeted modules are handed over to compressed-tensors: it attaches the resolved `quantization_scheme`, sets `quantization_status`, registers the parameters the checkpoint stores (`weight` in fp8, plus `weight_scale` and, for a static strategy, `input_scale`) and installs its own forward pass over them. They stay [nn.Linear](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) instances, so that is what `print` shows — recent compressed-tensors versions no longer wrap them in a `CompressedLinear` subclass. Modules listed under `ignore`, such as `lm_head`, are left untouched. -With `dequantize=False` (the default), the weights are still compressed once loading is over, and compressed-tensors decompresses the whole model on the first forward pass. `dequantize=True` does it during loading instead, so no forward pass is needed to get dense weights.+With `dequantize=False` (the default), the weights are still compressed once loading is over, and compressed-tensors decompresses the whole model on the first forward pass. `dequantize=True` decompresses each weight while loading it instead, so no forward pass is needed to get dense weights, and the modules are plain dense layers with no `quantization_scheme`. ```python import torchsrc/transformers/integrations/compressed_tensors.py22 + / 3 −
@@ -42,9 +42,20 @@ def get_experts_scheme(quantization_config): return groups[0] +def get_dense_scheme(quantization_config):+ """The config group quantizing the dense layers: in mixed configs, the one whose targets do not single out the+ experts (see `get_experts_scheme`)."""+ groups = list(quantization_config.config_groups.values())+ for group in groups:+ if not any(target.startswith("re:") and "experts" in target for target in group.targets):+ return group+ return groups[0]++ class CompressedTensorsDequantize(ConversionOps): """- Dequantize MoE layers when they are in new layout, because they aren't `nn.Module` anymore!+ Decompresses the checkpoint weights while loading: each dense module's serialized tensors (general converter),+ and the MoE experts, which are in the new fused layout and aren't `nn.Module`s anymore. Takes packed weights and scales from the loaded state dict, creates a dummy Module to take advantage of higher-lvl API `decompress_module` and dequantizes all weights.@@ -68,11 +79,19 @@ def convert( **kwargs, ) -> dict[str, torch.Tensor]: from compressed_tensors.compressors import BaseCompressor- from compressed_tensors.compressors.format import infer_module_format ct_quantization_config = self.hf_quantizer.compressor.quantization_config dtype = kwargs["model"].get_parameter(full_layer_name).dtype + if "weight" in input_dict or "weight_scale" in input_dict:+ # The quantizer's general converter: the keys are the serialized names of one dense module+ state_dict = {name: value[0] if isinstance(value, list) else value for name, value in input_dict.items()}+ if "weight_scale" in state_dict:+ scheme = self.scheme or get_dense_scheme(ct_quantization_config)+ compressor = BaseCompressor.get_value_from_registry(scheme.format or ct_quantization_config.format)+ state_dict = compressor.decompress(state_dict, scheme)+ return {full_layer_name: state_dict["weight"].to(dtype)}+ quantization_scheme = self.scheme or get_experts_scheme(ct_quantization_config) weights_args = quantization_scheme.weights@@ -103,7 +122,7 @@ def convert( processed_out[key] = output return processed_out - format = quantization_scheme.format or infer_module_format(nn.Linear, quantization_scheme)+ format = quantization_scheme.format or ct_quantization_config.format compressor = BaseCompressor.get_value_from_registry(format) class DummyModule(nn.Module):src/transformers/quantizers/quantizer_compressed_tensors.py26 + / 39 −
@@ -13,7 +13,6 @@ # limitations under the License. from copy import deepcopy-from functools import partial from ..utils import is_compressed_tensors_available, is_torch_available, is_torch_greater_or_equal, logging from ..utils.quantization_config import CompressedTensorsConfig@@ -24,7 +23,7 @@ import torch from ..core_model_loading import WeightConverter- from ..integrations.compressed_tensors import CompressedTensorsDequantize, get_experts_scheme+ from ..integrations.compressed_tensors import CompressedTensorsDequantize logger = logging.get_logger(__name__)@@ -90,47 +89,35 @@ def validate_environment(self, *args, **kwargs): self.use_fp8_kernel = False def _process_model_before_weight_loading(self, model, **kwargs):- ct_config = self.compressor.quantization_config- remaining_groups = dict(ct_config.config_groups)+ if self.quantization_config.dequantize:+ # The model stays dense: the `dequantize` load operation runs on every checkpoint weight+ return+ from compressed_tensors.quantization import apply_quantization_config + ct_config = deepcopy(self.compressor.quantization_config) if self.use_fp8_kernel: from ..integrations.compressed_tensors import replace_with_compressed_tensors_fp8_linear # Quantization may only target a subset of the layers: each config group scopes # its scheme with `targets` (class names or `re:` regexes) minus `ignore`.- fp8_groups = {name: group for name, group in remaining_groups.items() if _is_fp8_scheme(group)}- remaining_groups = {name: group for name, group in remaining_groups.items() if name not in fp8_groups}-+ fp8_groups = {name: group for name, group in ct_config.config_groups.items() if _is_fp8_scheme(group)}+ ct_config.config_groups = {+ name: group for name, group in ct_config.config_groups.items() if name not in fp8_groups+ } self.modules_to_not_convert = self.get_modules_to_not_convert(model, None, model._keep_in_fp32_modules)- targets = [target for group in fp8_groups.values() for target in group.targets] replace_with_compressed_tensors_fp8_linear( model,- targets=targets,+ targets=[target for group in fp8_groups.values() for target in group.targets], ignore=ct_config.ignore, modules_to_not_convert=self.modules_to_not_convert, ) - from compressed_tensors.quantization import apply_quantization_config-- remaining_config = deepcopy(ct_config)- remaining_config.config_groups = remaining_groups-- apply_quantization_config(model, remaining_config, run_compressed=False)+ apply_quantization_config(model, ct_config, run_compressed=False) # Packed formats (e.g. int4 `weight_packed`) need the compressed module layout to # receive the checkpoint tensors. if self.quantization_config.is_quantization_compressed: self.compressor.compress_model(model=model) - def _process_model_after_weight_loading(self, model, **kwargs):- """Dequantize the layers loaded through the compressed-tensors wrappers, but only when asked- for: with `dequantize=False` the weights are left compressed, and the hook `compress_model`- registered decompresses them on the first forward pass instead.-- FP8-kernel modules were never wrapped (their weights loaded directly in FP8) and hold no- compressed-tensors scheme, so neither the call below nor that hook touches them."""- if self.quantization_config.dequantize and self.quantization_config.is_quantization_compressed:- self.compressor.decompress_model(model=model)- @property def is_trainable(self): # The FP8 kernel path is inference-only; load with `dequantize=True` to fine-tune.@@ -156,7 +143,7 @@ def get_weight_conversions(self): tensors into the row-wise kernel layout once at load time — see :class:`ConvertFP8LinearScale`.""" if not self.use_fp8_kernel:- return []+ return super().get_weight_conversions() from ..integrations.compressed_tensors import ConvertFP8LinearScale @@ -168,18 +155,18 @@ def get_weight_conversions(self): ) ] - @property- def serialized_names(self):- ct_config = self.quantization_config.quantization_config- if ct_config is None or not ct_config.config_groups: # e.g. sparsity only, kv cache only- return {}- if _is_fp8_scheme(get_experts_scheme(ct_config)):- return {"weight": ["weight", "weight_scale"]}- return {"weight": ["weight_packed", "weight_scale", "weight_shape"]}+ # Every name a compressed-tensors format stores for a weight; a checkpoint only has its own format's+ serialized_names = {+ "weight": [+ "weight",+ "weight_scale",+ "weight_zero_point",+ "weight_global_scale",+ "weight_packed",+ "weight_shape",+ ]+ } def get_load_operations(self):- ct_config = self.quantization_config.quantization_config- if ct_config is None or not ct_config.config_groups: # e.g. sparsity only, kv cache only- return {}- scheme = get_experts_scheme(ct_config)- return {"dequantize": partial(CompressedTensorsDequantize, scheme=scheme)}+ # No `deserialize`: the serialized tensors load as is into the params compressed-tensors creates+ return {"dequantize": CompressedTensorsDequantize}src/transformers/quantizers/quantizer_fouroversix.py0 + / 3 −
@@ -82,9 +82,6 @@ def _process_model_before_weight_loading( for parameter_name in module.parameters_to_quantize: delattr(module, parameter_name) - def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):- return model- def is_serializable(self): return True src/transformers/utils/quantization_config.py0 + / 8 −
@@ -1173,14 +1173,6 @@ def __init__( self.quant_method = QuantizationMethod.COMPRESSED_TENSORS def post_init(self):- if not self.dequantize and not self.is_quantization_compressed:- # Nothing is stored compressed, so there is neither anything to execute compressed nor- # anything to accelerate: the weights are already dense.- logger.warning(- "Compressed execution is only supported for compressed checkpoints. Setting `dequantize=True`."- )- self.dequantize = True- 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`.tests/quantization/compressed_tensors_integration/test_compressed_models.py84 + / 10 −
@@ -156,20 +156,94 @@ def test_deprecated_run_compressed_maps_to_dequantize(self): self.assertEqual(compressed_count, 0) def test_dequantize_outputs_match_default(self):- """An explicit `dequantize=True` must produce the same outputs as the default load+ """For weight-only schemes, an explicit `dequantize=True` produces the same outputs as the default load (both are dequantized).""" from transformers import AutoTokenizer + tokenizer = AutoTokenizer.from_pretrained(self.tinyllama_w4a16)+ input_ids = tokenizer(self.prompt, return_tensors="pt").input_ids++ model_default = AutoModelForCausalLM.from_pretrained(self.tinyllama_w4a16)+ output_default = model_default.generate(input_ids, max_new_tokens=100)++ model_dequantized = AutoModelForCausalLM.from_pretrained(+ self.tinyllama_w4a16, quantization_config=CompressedTensorsConfig(dequantize=True)+ )+ output_dequantized = model_dequantized.generate(input_ids, max_new_tokens=100)++ self.assertEqual(tokenizer.decode(output_default[0]), tokenizer.decode(output_dequantized[0]))++ def test_dequantize_drops_activation_quantization(self):+ """`dequantize=True` loads a plain dense model: no compressed-tensors scheme is left, so w8a8 also stops+ quantizing its activations."""+ model = AutoModelForCausalLM.from_pretrained(+ self.tinyllama_w8a8, quantization_config=CompressedTensorsConfig(dequantize=True)+ )+ self.assertFalse(any(hasattr(module, "quantization_scheme") for module in model.modules()))+ self.assertTrue(model.model.layers[0].self_attn.q_proj.weight.is_floating_point())+++@require_compressed_tensors+@require_torch+class CompressedLoadTest(unittest.TestCase):+ """By default the checkpoint loads in compressed-tensors' own format: every serialized tensor lands as is in the+ params compressed-tensors creates, nothing is decompressed up front, and saving writes the same tensors back."""++ stubs = [+ "nm-testing/tinyllama-w4a16-compressed", # pack-quantized+ "nm-testing/tinyllama-w8a8-compressed", # int-quantized+ "nm-testing/TinyLlama-1.1B-Chat-v1.0-FP8-Dynamic-compressed", # float-quantized+ ]++ def tearDown(self):+ gc.collect()+ backend_empty_cache(torch_device)+ gc.collect()++ @staticmethod+ def _read_safetensors(path):+ import glob+ import os++ from safetensors.torch import load_file++ tensors = {}+ for file in glob.glob(os.path.join(path, "*.safetensors")):+ tensors.update(load_file(file))+ return tensors++ def _assert_same_tensors(self, actual, expected):+ self.assertEqual(sorted(actual), sorted(expected))+ for name, value in expected.items():+ self.assertEqual(actual[name].dtype, value.dtype, name)+ torch.testing.assert_close(actual[name].cpu(), value, rtol=0, atol=0, msg=name)++ def test_load_keeps_checkpoint_tensors_compressed(self):+ from huggingface_hub import snapshot_download+ for stub in self.stubs:- tokenizer = AutoTokenizer.from_pretrained(stub)- input_ids = tokenizer(self.prompt, return_tensors="pt").input_ids+ with self.subTest(stub=stub):+ checkpoint = self._read_safetensors(snapshot_download(stub, allow_patterns=["*.safetensors"]))+ self.assertTrue(any(name.endswith("weight_scale") for name in checkpoint)) - model_default = AutoModelForCausalLM.from_pretrained(stub)- output_default = model_default.generate(input_ids, max_new_tokens=100)+ model, loading_info = AutoModelForCausalLM.from_pretrained(stub, output_loading_info=True) - model_dequantized = AutoModelForCausalLM.from_pretrained(- stub, quantization_config=CompressedTensorsConfig(dequantize=True)- )- output_dequantized = model_dequantized.generate(input_ids, max_new_tokens=100)+ self.assertEqual(loading_info["missing_keys"], set())+ self.assertEqual(loading_info["unexpected_keys"], set())+ state_dict = model.state_dict()+ self._assert_same_tensors({name: state_dict[name] for name in checkpoint}, checkpoint) - self.assertEqual(tokenizer.decode(output_default[0]), tokenizer.decode(output_dequantized[0]))+ def test_save_writes_the_compressed_tensors_back(self):+ import tempfile++ from huggingface_hub import snapshot_download++ for stub in self.stubs:+ with self.subTest(stub=stub):+ checkpoint = self._read_safetensors(snapshot_download(stub, allow_patterns=["*.safetensors"]))+ model = AutoModelForCausalLM.from_pretrained(stub)+ with tempfile.TemporaryDirectory() as tmpdirname:+ model.save_pretrained(tmpdirname)+ saved = self._read_safetensors(tmpdirname)++ self._assert_same_tensors(saved, checkpoint)