compressed-tensors

vllm-projectApache-2.0活跃维护

safetensors 的扩展,能把稀疏量化后的张量高效存到磁盘,省空间又不牺牲加载速度,适合大模型量化权重的持久化。

A safetensors extension to efficiently store sparse quantized tensors on disk

0.20.1发布于 2026-10-28 16:50 UTC335star148fork同步于 2026-11-10 23:59 UTC

怎么上手

由 README 提炼,执行前请确认
pip install compressed-tensors
硬件要求按 README 说明

README 未说明具体显存要求;示例代码在有 CUDA 时用 cuda:0,否则回退 CPU,说明可 CPU 运行。

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

统一存储 GPTQ、AWQ 等压缩模型的 safetensors 扩展格式,省去多套格式适配

safetensors 的扩展,能把稀疏量化后的张量高效存到磁盘,省空间又不牺牲加载速度,适合大模型量化权重的持久化。

核心能力

  • 用单一 checkpoint 格式统一表示 GPTQ、AWQ、SmoothQuant、SparseGPT 等压缩方案
  • 支持 INT8、FP8、NVFP4、MXFP4、MXFP8 等多种量化格式
  • 支持激活量化、混合精度、低比特与 KV cache 量化
  • 支持非均匀量化,不同层可用不同量化方式
  • 支持非结构化与 2:4 半结构化稀疏及旋转类变换量化

容易踩的坑

示例需从 Hugging Face 下载 meta-llama/Meta-Llama-3-8B,需提前准备模型访问权限;压缩后的模型需配合 vLLM 等支持该格式的推理引擎加载;开发流程需额外安装 .[dev] 依赖并执行 pre-commit install。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本0.20.1
  1. 0.20.1Compressed-Tensors v0.20.1最新正式版2026-10-28 · 2026-10-28 16:50 UTC

    What's Changed

    Full Changelog: https://github.com/vllm-project/compressed-tensors/compare/0.20.0...0.20.1

  2. 0.20.0Compressed-Tensors v0.20.02026-10-27 · 2026-10-27 14:37 UTC
    查看更新说明

    Compressed-Tensors 0.20.0 adds MXFP6 and MXFP4xFP8 quantization support, MoE non-uniform expert sparsity (REAP, MoNe) and much faster distributed loading and disk onloading.

    Key Features and Improvements

    • MXFP6 (E2M3): Introduces a new 6-bit floating-point format with mxfp6-pack-quantized and MXFP6A16 / MXFP6A8 presets. Quark/OCP-compatible packing is consumed directly by existing vLLM kernels. #941
    • MXFP4xFP8: Adds a new MXFP4xFP8 preset, enabling MXFP4 weights with DeepSeek-style FP8 block-quantized activations. #940
    • MoE expert sparsity: Introduces ExpertSparsityConfig for prune (REAP) and novice (MoNe) checkpoints. MagnitudeExpertPruner now also prunes per-expert router bias vectors. #938, #978
    • Layerwise compression: apply_quantization_config now accepts allowed_modules. Setting leave_decompressed=False fully removes quantization metadata, enabling per-layer decompress/recompress pipelines. #867
    • Faster disk onloading: disk_load_context supports grouped subgraph reads. Weights can also be staged in CPU or pinned memory before being onloaded to GPUs. #883, #910, #944, #976
    • Batched distributed offload: Uses one metadata broadcast and barrier per dispatch instead of per tensor. Tied weights now share a single storage allocation on every rank. #925
    • Conversion improvements: max_workers="auto" is now the default for checkpoint conversion jobs. FP8BlockDequantizer.from_pretrained discovers FP8 block targets, and MTP export accepts an explicit weight map. #911, #897, #933
    • Python compatibility: Python 3.11 or newer is now required. #946

    Offloading and Performance

    • Faster disk reads: disk_load_context reuses safetensors handles across reads, delivering 2.8×–6.3× faster shard reads. Staging a single Qwen3-MoE layer drops from 11.0 ms to 4.4 ms. #883, #910
    • Improved staging and caching: Adds OffloadCache.stage, memory pinning, DeviceCache staging, and support for device_map="disk". #903, #906, #904
    • Offloading correctness and efficiency: set_onload_device no longer onloads children to discover the offload device. Disk dtype casts preserve Parameter metadata, and qparams can be initialized on disk. #886, #907, #936, #967
    • Faster NVFP4 quantization: A fused NVFP4 quantize-and-pack Triton kernel is 1.07×–1.77× faster per weight. #815
    • Faster 4-bit unpacking: Splits bytes instead of gathering words, reducing Llam
  3. 0.19.0Compressed-Tensors v0.19.02026-09-21 · 2026-09-21 16:48 UTC
    查看更新说明

    Key Highlights

    • Multi-GPU Checkpoint Conversion #849, #869, #889: A dynamic, capacity-first multi-GPU scheduler is now built into entrypoints/convert. Conversion jobs are scheduled across accelerators based on measured free memory, with a profiler-based (TorchDispatchMode) memory estimator replacing heuristic multipliers.
    • Magnitude Expert Pruner Converter #834: New MagnitudeExpertPruner converter that structurally prunes MoE experts by magnitude, with a Qwen3-VL example. Built on the new multi-converter chaining interface (#805), which lets conversion pipelines chain multiple converters (e.g. prune → quantize) with validate/config propagation through the chain.
    • Distributed Decompression #878: model_compressor now supports decompression under distributed execution, with fixes for dtype mismatch (#851) and tensor-shape reconciliation in the distributed CPU/disk offload caches (#857).
    • Meta-Device (Model-Free) Pipeline Improvements #810, #870, #837: Fast NVFP4 compression on meta tensors, qparam calculation on meta device, and fixed pack-quantized decompression on meta, enabling resumable model-free PTQ runs where already-processed shards are accounted as meta tensors without recomputing.
    • Removed GPTQ Group/Dynamic Activation Ordering #840: The GPTQ-specific activation ordering code paths have been removed from the quantization lifecycle.
    • Transformers >= 5.16 #848: requires_version now requires transformers>=5.16.

    Multi-GPU Checkpoint Conversion

    The entrypoints/convert pipeline can now schedule conversion work across multiple accelerators:

    • A dynamic multi-GPU scheduler (exec_jobs_dynamic, _pick_device, _free_bytes) was ported from llm-compressor as a reusable, protocol-agnostic building block for PTQ pipelines (#849).
    • Checkpoint conversion is now scheduled across devices by default, with a meta-tensor job memory estimator that profiles each job and schedules it to a device with sufficient free memory (#869).
    • The x3 multiplier heuristic was replaced by a TensorProfiler (TorchDispatchMode) that measures true peak memory during the converter validate pass, falling back to a 2.5x input footprint estimate with a warning if profiling fails (#889).
    • A warning is now emitted when an existing quantization config is found before being passed into the converter chain.

    Magnitude Expert Pruner & Multi-Converter Chaining

    • The new MagnitudeExpertPruner converter (compressed_tensors.entrypoints.convert.converters.MagnitudeExpertPruner) removes low-magnitude MoE experts structurally (#834), with a Qwen3-VL expert-pruning example. New MoE pruning utilities were added under compressed_tensors/utils/moe.py.
    • The converter interface gained multi-converter chaining support (#805): pipelines accept a list of converters and chain va
  4. 0.18.0Compressed-Tensors v0.18.02026-08-08 · 2026-08-08 01:53 UTC
    查看更新说明

    What's Changed

  5. 0.17.1Compressed-Tensors v0.17.12026-06-11 · 2026-06-11 18:43 UTC
    查看更新说明

    What's Changed

    New Contributors

    Full Changelog: https://github.com/vllm-project/compressed-tensors/compare/0.17.0...0.17.1

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    compressed-tensors

    The compressed-tensors library extends the safetensors format, providing a versatile and efficient way to store and manage compressed tensor data. This library supports various compression schemes, making it a unified format for handling models compressed with algorithms like GPTQ, AWQ, SmoothQuant, and SparseGPT, across formats like INT8, FP8, NVFP4, MXFP4, MXFP8, and more.

    Why compressed-tensors?

    As model compression becomes increasingly important for efficient deployment of LLMs, the landscape of quantization and compression techniques has become increasingly fragmented. Each method often comes with its own storage format and loading procedures, making it challenging to work with multiple techniques or switch between them. compressed-tensors addresses this by providing a single, extensible format that can represent a wide variety of compression schemes.

    • Unified Checkpoint Format: Supports various compression schemes in a single, consistent format.
    • Wide Compatibility: Works with popular quantization methods like GPTQ, SmoothQuant, AWQ, AutoRound, etc. See llm-compressor
    • Flexible Quantization Support:
      • Activation quantization
      • Mixed precision
      • Low/arbitrary-bit
      • KV cache quantization
      • Non-uniform schemes (different layers can be quantized in different ways!)
    • Sparsity Support: Handles both unstructured and semi-structured (e.g., 2:4) sparsity patterns.
    • Transform Support: Rotation-based quantization techniques (Hadamard, random Hadamard, random matrix transforms).
    • Checkpoint Conversion: Convert between formats like AutoAWQ, ModelOpt NVFP4, FP8 block, and compressed-tensors.
    • Model Offloading: Transparent CPU/disk/distributed offloading for models larger than available VRAM.
    • Open-Source Integration: Designed to work seamlessly with Hugging Face models, PyTorch, vLLM, and SGLang.

    This allows developers and researchers to easily experiment with composing different quantization methods, simplify model deployment pipelines, and reduce the overhead of supporting multiple compression formats in inference engines.

    Installation

    From PyPI

    Stable release:

    pip install compressed-tensors
    

    Nightly release:

    pip install --pre compressed-tensors
    

    From Source

    git clone https://github.com/vllm-project/compressed-tensors
    cd compressed-tensors
    pip install -e .
    

    Development

    Install the development dependencies and run the linting, formatting, and type checks:

    pip install -e .[dev]
    make quality   # check
    make style     # auto-fix
    

    Pre-commit Hooks

    We provide pre-commit hooks that run the same checks as make quality (plus a DCO sign-off hook) before each commit, so problems are caught locally instead of in CI. After installing the [dev] dependencies, enable them once per clone:

    pre-commit install
    

    The hooks then run automatically on git commit. To run them against all files on demand:

    pre-commit run --all-files
    

    To bypass the hooks for a single commit, use git commit --no-verify; to skip one hook, prefix the command with SKIP=<hook-id> (e.g. SKIP=flake8).

    Getting Started

    Compressing a Model to MXFP4

    The following example loads Llama 3 8B, applies round-to-nearest (RTN) MXFP4 weight quantization, compresses the weights, and saves the result. No calibration data is needed — scales are computed directly from the weights.

    import math
    
    import torch
    from transformers import AutoModelForCausalLM
    
    from compressed_tensors.compressors import ModelCompressor
    from compressed_tensors.offload import update_offload_parameter
    from compressed_tensors.quantization import (
        QuantizationConfig,
        apply_quantization_config,
    )
    from compressed_tensors.quantization.utils import calculate_qparams
    
    model_name = "meta-llama/Meta-Llama-3-8B"
    device = "cuda:0" if torch.cuda.is_available() else "cpu"
    
    # Load the model
    model = AutoModelForCausalLM.from_pretrained(
        model_name, device_map=device, torch_dtype="auto"
    )
    
    # Set-up the quantization config. This defines:
    # 1. What quantization scheme we're applying and to which layers
    # 2. Any layers that should be ignored
    # In this case, all the Linear layers are targeted, apart from the lm_head
    config = QuantizationConfig(
        config_groups={"MXFP4": ["Linear"]},
        ignore=["lm_head"],
    )
    # Apply the config to the model. This step uses the config to define
    # the quantization parameters (such as the scales) for the targeted layers
    # and attaches a QuantizationScheme which defines how the weights and activations
    # should be quantized (e.g number of bits, group or block sizes, etc)
    apply_quantization_config(model, config)
    
    # Compute weight scales using round-to-nearest quantization
    for name, module in model.named_modules():
        # Only target layers with a QuantizationScheme attached
        scheme = getattr(module, "quantization_scheme", None)
        if scheme is None or scheme.weights is None:
            continue
    
        weight = module.weight.data
        args = scheme.weights
        # MXFP4 uses group-wise quantization for its weights, with group_size 32
        group_size = args.group_size
    
        if group_size is not None and group_size > 0:
            reshaped = weight.unflatten(-1, (math.ceil(weight.shape[-1] / group_size), group_size))
            min_val = reshaped.amin(dim=-1)
            max_val = reshaped.amax(dim=-1)
        else:
            min_val, max_val = torch.aminmax(weight)
    
        # Calculate the quantization parameters, such as the weight scale, using the min and max values
        scale, _ = calculate_qparams(min_val, max_val, args)
        # Update the parameters attached to the module based on the calculated value
        # In this case, we update the `weight_scale` attached to the targeted linear layers
        update_offload_parameter(module, "weight_scale", scale)
    
    
    output_dir = "./Meta-Llama-3-8B-MXFP4"
    # set-up a compressor 
    compressor = ModelCompressor.from_pretrained_model(model)
    # Compress the model using the calibrated scales and save it using the mxfp4-pack-quantized format.
    # This format defines the weight packing, which can be seamlessly loaded through vLLM.
    compressor.compress_model(model)
    model.save_pretrained(output_dir)
    # Update the model's config with the relevant compressed-tensors details, illustrated below. 
    compressor.update_config(output_dir)
    

    Once done, the config.json will have the following quantization_config:

    "quantization_config": {
        "config_groups": {
          "group_0": {
            "format": "mxfp4-pack-quantized",
            "input_activations": {
              "actorder": null,
              "block_structure": null,
              "dynamic": true,
              "group_size": 32,
              "num_bits": 4,
              "observer": null,
              "observer_kwargs": {},
              "scale_dtype": "torch.uint8",
              "strategy": "group",
              "symmetric": true,
              "type": "float",
              "zp_dtype": null
            },
            "output_activations": null,
            "targets": [
              "Linear"
            ],
            "weights": {
              "actorder": null,
              "block_structure": null,
              "dynamic": false,
              "group_size": 32,
              "num_bits": 4,
              "observer": "memoryless_minmax",
              "observer_kwargs": {},
              "scale_dtype": "torch.uint8",
              "strategy": "group",
              "symmetric": true,
              "type": "float",
              "zp_dtype": null
            }
          }
        },
        "format": "mxfp4-pack-quantized",
        "global_compression_ratio": null,
        "ignore": [
          "lm_head"
        ],
        "kv_cache_scheme": null,
        "quant_method": "compressed-tensors",
        "quantization_status": "compressed",
        "sparsity_config": {},
        "transform_config": {},
        "version": "0.18.1.dev0+gac8e2ba.d20260813"
      },
    

    See examples/ for more examples including quantization with calibration and checkpoint conversion (examples/convert_checkpoint/).

    Citation

    If you find compressed-tensors useful in your research or projects, please consider citing it:

    @software{compressedtensors2024,
        title={{compressed-tensors}},
        author={Red Hat AI and vLLM Project},
        year={2024},
        month={4},
        url={https://github.com/vllm-project/compressed-tensors},
    }