示例需从 Hugging Face 下载 meta-llama/Meta-Llama-3-8B,需提前准备模型访问权限;压缩后的模型需配合 vLLM 等支持该格式的推理引擎加载;开发流程需额外安装 .[dev] 依赖并执行 pre-commit install。
compressed-tensors
vllm-projectApache-2.0活跃维护safetensors 的扩展,能把稀疏量化后的张量高效存到磁盘,省空间又不牺牲加载速度,适合大模型量化权重的持久化。
A safetensors extension to efficiently store sparse quantized tensors on disk
pip install compressed-tensorsREADME 未说明具体显存要求;示例代码在有 CUDA 时用 cuda:0,否则回退 CPU,说明可 CPU 运行。
统一存储 GPTQ、AWQ 等压缩模型的 safetensors 扩展格式,省去多套格式适配
safetensors 的扩展,能把稀疏量化后的张量高效存到磁盘,省空间又不牺牲加载速度,适合大模型量化权重的持久化。
核心能力
- 用单一 checkpoint 格式统一表示 GPTQ、AWQ、SmoothQuant、SparseGPT 等压缩方案
- 支持 INT8、FP8、NVFP4、MXFP4、MXFP8 等多种量化格式
- 支持激活量化、混合精度、低比特与 KV cache 量化
- 支持非均匀量化,不同层可用不同量化方式
- 支持非结构化与 2:4 半结构化稀疏及旋转类变换量化
容易踩的坑
- 0.20.1Compressed-Tensors v0.20.1最新正式版2026-10-28 · 2026-10-28 16:50 UTC
What's Changed
- [Bugfix] Keep block-quantized compressed weights contiguous by @kylesayrs in https://github.com/vllm-project/compressed-tensors/pull/990
- [Bugfix] Skip meta-device check for non-persistent buffers in from_accelerate by @kylesayrs in https://github.com/vllm-project/compressed-tensors/pull/989
Full Changelog: https://github.com/vllm-project/compressed-tensors/compare/0.20.0...0.20.1
- 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-quantizedandMXFP6A16/MXFP6A8presets. Quark/OCP-compatible packing is consumed directly by existing vLLM kernels. #941 - MXFP4xFP8: Adds a new
MXFP4xFP8preset, enabling MXFP4 weights with DeepSeek-style FP8 block-quantized activations. #940 - MoE expert sparsity: Introduces
ExpertSparsityConfigfor prune (REAP) and novice (MoNe) checkpoints.MagnitudeExpertPrunernow also prunes per-expert router bias vectors. #938, #978 - Layerwise compression:
apply_quantization_confignow acceptsallowed_modules. Settingleave_decompressed=Falsefully removes quantization metadata, enabling per-layer decompress/recompress pipelines. #867 - Faster disk onloading:
disk_load_contextsupports 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_pretraineddiscovers 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_contextreuses 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,DeviceCachestaging, and support fordevice_map="disk". #903, #906, #904 - Offloading correctness and efficiency:
set_onload_deviceno longer onloads children to discover the offload device. Disk dtype casts preserveParametermetadata, 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
- MXFP6 (E2M3): Introduces a new 6-bit floating-point format with
- 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
MagnitudeExpertPrunerconverter 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_compressornow 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_versionnow requirestransformers>=5.16.
Multi-GPU Checkpoint Conversion
The
entrypoints/convertpipeline 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
x3multiplier heuristic was replaced by aTensorProfiler(TorchDispatchMode) that measures true peak memory during the converter validate pass, falling back to a2.5xinput 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
MagnitudeExpertPrunerconverter (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 undercompressed_tensors/utils/moe.py. - The converter interface gained multi-converter chaining support (#805): pipelines accept a list of converters and chain va
- Multi-GPU Checkpoint Conversion #849, #869, #889: A dynamic, capacity-first multi-GPU scheduler is now built into
- 0.18.0Compressed-Tensors v0.18.02026-08-08 · 2026-08-08 01:53 UTC
查看更新说明
What's Changed
- Add Buildkite pipeline for test-check workflow on H100 duo and L4 solo by @deepak-kumar-neu in https://github.com/vllm-project/compressed-tensors/pull/722
- Rename upload step label in pipeline.yml by @dsikka in https://github.com/vllm-project/compressed-tensors/pull/725
- [Converters] Support loading safetensors on meta device by @kylesayrs in https://github.com/vllm-project/compressed-tensors/pull/726
- [Offload] Use explicit class patching for
load_offloaded_modelby @kylesayrs in https://github.com/vllm-project/compressed-tensors/pull/728 - Ignore non-linear MoE gate layers by @kylesayrs in https://github.com/vllm-project/compressed-tensors/pull/733
- [Offload] Skip device-map entries with no local module in dispatch_with_map by @waynehacking8 in https://github.com/vllm-project/compressed-tensors/pull/737
- fix model chkpt name mismatch for ignore by @HDCharles in https://github.com/vllm-project/compressed-tensors/pull/739
- Add runner selection dropdown for manual Buildkite triggers by @deepak-kumar-neu in https://github.com/vllm-project/compressed-tensors/pull/744
- CT support for humming by @HDCharles in https://github.com/vllm-project/compressed-tensors/pull/732
- [Offload] Force offloading of buffers by @kylesayrs in https://github.com/vllm-project/compressed-tensors/pull/731
- [Offload] Better error for disk offloaded transformers models by @kylesayrs in https://github.com/vllm-project/compressed-tensors/pull/729
- Add tqdm to
apply_quantization_configby @kylesayrs in https://github.com/vllm-project/compressed-tensors/pull/730 - Revert default GPU runner to H100duo by @deepak-kumar-neu in https://github.com/vllm-project/compressed-tensors/pull/745
- Add XPU support to Buildkite pipeline and scripts by @chensuyue in https://github.com/vllm-project/compressed-tensors/pull/736
- [Bugfix] Fix cast_to_fp4 per-rank torch.compile recompilation (#734) by @Yatimai in https://github.com/vllm-project/compressed-tensors/pull/741
- [Offloading] Speedup
to_accelerateby only instantiatingOffloadedWeightsLoaderonce by @kylesayrs in https://github.com/vllm-project/compressed-tensors/pull/752 - [Bugfix] Enforce block_structure length validation for string format by @amogh-nagri-11 in https://github.com/vllm-project/compressed-tensors/pull/755
- [Bugfix] [Distributed] Fix disk distributed module compression by @kylesayrs in https://github.com/vllm-project/compressed-tensors/pull/750
- Fix tied transform weight detection for offloaded models by @ZewenShen-Cohere in https://github.com/vllm-project/compressed-tensors/pull/751
- Add psutil as required dependency by @timkpaine in https://github.com/vllm-project/compressed-tensors/pull/740
- [Bugfix] Fix ignore list for linearized MoE layers by @kylesayrs in https://github.com/vllm-project/compressed-tensors/pull/759
- [Bugfix] Validate positive block structure dimensions by @harivilasp in https://github.com/vllm-project/compressed-tensors/pull/763
- Fix MTP tensor copy from indexed checkpoints by @SorenDreano in https://github.com/vllm-project/compressed-tensors/pull/756
- [Offload] [1/2] Disambiguate synchronous
__setitem__/offloadfromupdate_offloadby @kylesayrs in https://github.com/vllm-project/compressed-tensors/pull/709 - Revert "[Offload] [1/2] Disambiguate synchronous `setitem/offload… by @kylesayrs in https://github.com/vllm-project/compressed-tensors/pull/767
- CT humming schemes by @HDCharles in https://github.com/vllm-project/compressed-tensors/pull/760
- fix pack_fp4_to_uint8 faster/less mem by @HDCharles in https://github.com/vllm-project/compressed-tensors/pull/775
- [Bugfix] Remove unreachable GROUP+dynamic activation validation branch by @ishrith-gowda in https://github.com/vllm-project/compressed-tensors/pull/772
- Treat imatrix weight observer as calibration data dependent by @dshane1903 in https://github.com/vllm-project/compressed-tensors/pull/710
- Fix NVFP4 packing for float32 inputs by @yiliu30 i
- 0.17.1Compressed-Tensors v0.17.12026-06-11 · 2026-06-11 18:43 UTC
查看更新说明
What's Changed
- Add Buildkite pipeline for test-check workflow on H100 duo and L4 solo by @deepak-kumar-neu in https://github.com/vllm-project/compressed-tensors/pull/722
- Rename upload step label in pipeline.yml by @dsikka in https://github.com/vllm-project/compressed-tensors/pull/725
- [Converters] Support loading safetensors on meta device by @kylesayrs in https://github.com/vllm-project/compressed-tensors/pull/726
- [Offload] Use explicit class patching for
load_offloaded_modelby @kylesayrs in https://github.com/vllm-project/compressed-tensors/pull/728 - Ignore non-linear MoE gate layers by @kylesayrs in https://github.com/vllm-project/compressed-tensors/pull/733
New Contributors
- @deepak-kumar-neu made their first contribution in https://github.com/vllm-project/compressed-tensors/pull/722
Full Changelog: https://github.com/vllm-project/compressed-tensors/compare/0.17.0...0.17.1
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
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},
}