float8 和 nvfp4 推理内核需额外安装 mslk,且稳定版与 nightly 版本需和 torchao 对应;MoE mxfp8 训练需另装 apache-tvm-ffi 与指定版本的 nvidia-cutlass-dsl;项目已缩减新功能开发,部分量化能力将迁移到 torch 或训练框架中
pip install torchaoREADME 未统一说明显存要求;示例基于 H100、B200 等 NVIDIA GPU,也提供 XPU 和纯 CPU 的安装源,并提到 ARM CPU 的 1-8 bit 内核
PyTorch 原生量化库,支持训练与推理,几乎不改模型代码就能提速省显存
PyTorch 官方的量化与稀疏化工具库,支持训练和推理阶段的低精度计算,覆盖 float8、MX 等数据类型,可加速 Transformer 和 Llama 等大模型。
核心能力
- 用 quantize_ 一行把模型权重量化到 int4
- 提供 float8 动态量化配置,可直接接入 transformers
- 支持 QAT 量化感知训练,恢复量化精度损失
- 兼容 torch.compile 与 FSDP2,可作为 vLLM 量化后端
- 提供 2:4 半结构化稀疏与 MoE MXFP8 训练原型
容易踩的坑
- v0.18.0最新正式版2026-08-03 · 2026-08-03 20:44 UTC
Highlights
NVFP4 training
NVFP4 for dense linears is now supported for training (prototype), implementing the recipe from Pretraining Large Language Models with NVFP4. This is a prototype feature and the API may change without notice. Hardening, MoE support, and torchtitan integration are planned.
Example usage:
import torch from torchao.quantization import quantize_ from torchao.prototype.moe_training.nvfp4_training.nvfp4_training import ( NVFP4TrainingConfig, ) # Blackwell (SM100+); bfloat16 model with Linear dims divisible by 128 model = model.cuda().bfloat16() # Replace nn.Linear with NVFP4Linear quantize_(model, NVFP4TrainingConfig()) # Train as usual out = model(x) out.sum().backward()- [nvfp4_training] Support NVFP4 linear training on Blackwell by @rdspring1 in https://github.com/pytorch/ao/pull/4369
- [nvfp4_training] Add Triton kernel for global amax of columnwise RHT (SM90+) by @rdspring1 in https://github.com/pytorch/ao/pull/4247
BC-Breaking / Deprecations
Minimum PyTorch version is now 2.11
Support for PyTorch older than 2.11 has been dropped from the code, and CI has moved to newer PyTorch versions.
- drop PyTorch 2.7 and older support from the code by @vkuzo in https://github.com/pytorch/ao/pull/4395
- drop PyTorch<2.8 support from the code by @vkuzo in https://github.com/pytorch/ao/pull/4398
- drop PyTorch<2.9 support by @vkuzo in https://github.com/pytorch/ao/pull/4399
- drop PyTorch <2.10 support by @vkuzo in https://github.com/pytorch/ao/pull/4400
- drop PyTorch <2.11 support by @vkuzo in https://github.com/pytorch/ao/pull/4401
- switch CI to PyTorch 2.12 by @vkuzo in https://github.com/pytorch/ao/pull/4402
- Pin CI to PyTorch 2.13 for release; drop unused torchaudio by @vkuzo in https://github.com/pytorch/ao/pull/4638
Removed: v1 tensor-subclass / layout system
The deprecated v1
AffineQuantizedTensorstack and layout system have been fully removed, completing the migration to v2 tensor subclasses.- Delete AffineQuantizedTensor, AQTTensorImpl, and Layout by @andrewor14 in https://github.com/pytorch/ao/pull/4245
- Delete deprecated TensorCoreTiledLayout and related code by @jerryzh168 in https://github.com/pytorch/ao/pull/4153
- Delete deprecated PlainLayout, PlainAQTTensorImpl and related v1 code paths by @jerryzh168 in https://github.com/pytorch/ao/pull/4151
- Remove LinearActivationQuantizedTensor and all related code by @jerryzh168 in https://github.com/pytorch/ao/pull/4258
- Remove LinearActivationWeightObservedTensor and insert_observers_ by @jerryzh168 in https://github.com/pytorch/ao/pull/4261
- Remove WeightTensorWithLinearActivationScaleMetadata and related code by @jerryzh168 in https://github.com/pytorch/ao/pull/4262
- Remove WeightTensorWithLinearActivationQuantizationMetadata by @jerryzh168 in https://github.com/pytorch/ao/pull/4263
- Remove unified.py (Quantizer and TwoStepQuantizer ABCs) by @jerryzh168 in https://github.com/pytorch/ao/pull/4264
- Remove MSLK FP8 tensorwise support by @cthi in https://github.com/pytorch/ao/pull/4461
- Remove
check_cpu_versionandcheck_xpu_versionhelpers by @Xia-Weiwen in https://github.com/pytorch/ao/pull/4211
Renamed / moved APIs
- [CPU] Rename Int4WeightOnlyOpaqueTensorConfig to PrototypeInt4WeightOnlyConfig by @Xia-Weiwen in https://github.com/pytorch/ao/pull/4205
- Rename Sparse2x4CUTLASSFloat8Tensor to Float8Sparse2x4_2DData2DMetadataTensor (#4343) by @bbeckca in https://github.com/pytorch/ao/pull/4343
- Move NF4Tensor to quantization.quantize_.workflows by @andrewor14 in https://github.com/pytorch/ao/pull/4256
Behavior changes
- Use fixed scale for Float8 softmax quantization instead of observer by @jerryzh168 in https://github.com/pytorch/ao/pull/4260
Training / QAT
mxfp8
- refactor autograd func by @danielvegamyhre in https://github.com/pytorch/ao/pull/4176
- remove unused block_si
- v0.17.02026-03-30 · 2026-03-30 22:38 UTC
查看更新说明
Highlights
We are excited to announce the 0.17 release of torchao! This release adds support for cuteDSL MXFP8 MoE kernels, per-head FP8 quantized low precision attention, ABI stability, and more!
CuteDSL MXFP8 MoE Kernels
We added a new CuteDSL MXFP8 quantization kernel for 3d expert weights that writes scale factors directly to blocked layout for tensorcores: https://github.com/pytorch/ao/pull/4090
- Used for scaling along dim1 in the backward pass of MoE training with grouped GEMMs.
- ~12% speedup over previous 2 kernel “quantize then scale layout transformation” approach!
Per-Head FP8 Quantized Low Precision Attention
We added a new API for per-head fp8 quantized attention with FA3 as the backend (https://github.com/pytorch/ao/pull/3959 and https://github.com/pytorch/ao/pull/3857)
- Users can either choose to use the elementary blocks as direct replacements for `F.scaled_dot_product_attention` or use the high-level wrapper, which replaces all F.SDPA calls within a module with the low precision attention variant.
- Running torch.compile on a wrapped module will enable RoPE fusion where appropriate
- Results show a 1.18x speedup on Wan2.1-T2V-1.3B, 1.23x speedup on LLaMA 3 prefill with high sequence lengths (131k), 1.07x speedup on flux.1-schnell with 2048x2048 image size
Example Usage of Direct Replacement:
from torchao.prototype.attention.fp8_fa3 import fp8_fa3_sdpa, fp8_fa3_rope_sdpa out = fp8_fa3_sdpa(q, k, v)Example Usage of Wrapper:
from torchao.prototype.attention import ( AttentionBackend, LowPrecisionAttentionConfig, apply_low_precision_attention, ) # Instantiate any nn.Module() model = MyModel() # Simple SDPA replacement config = LowPrecisionAttentionConfig(backend=AttentionBackend.FP8_FA3) model = apply_low_precision_attention(model, config) # Flash activation is handled internally by the wrapper output = model(inputs) # Torch.compile will enable rope fusion model = torch.compile(model)PyTorch ABI stability
As of https://github.com/pytorch/ao/issues/3516, torchao is now ABI stable for all cuda kernels! This means if the user is running torch 2.11+, they will be able to access torchao’s cuda kernels without having to upgrade torch version for each new torchao version. This applies to the current and all future torchao releases (0.17.0+). Note that python-only API compatibility is the same as before: we support the latest 3 torch minor versions.
Before:
# Compatible versions for cpp extensions: torchao 0.16.0 + torch 2.10.0 torchao 0.15.0 + torch 2.9.1 torchao 0.14.1 + torch 2.9.0 # Compatible versions for python-only API # 3 most recent torch versions: torchao 0.16.0 + torch 2.10.0, 2.9.1, 2.8.0 torchao 0.15.0 + torch 2.9.1, 2.8.0, 2.7.1 torchao 0.14.0 + torch 2.9.0, 2.8.0, 2.7.0After:
# Compatible versions for cpp extensions (all future releases): torchao 0.17.0 onwards + any torch 2.11+ # Compatible versions for python-only API # 3 most recent torch versions (same as before) torchao 0.17.0 + torch 2.11.0, 2.10.0, 2.9.1Deprecations
- Deprecate AQT and related classes (https://github.com/pytorch/ao/pull/4074)
We are planning to remove these classes in the future, so we are deprecating them in advance. Here are all the classes that now have new deprecation warnings:
Base classes (torchao/dtypes/utils.py): 1. Layout 2. PlainLayout 3. AQTTensorImpl torchao/dtypes/affine_quantized_tensor.py: 4. AffineQuantizedTensor torchao/dtypes/floatx/: 5. Float8Layout 6. Float8AQTTensorImpl 7. CutlassSemiSparseLayout 8. CutlassSemiSparseTensorImpl torchao/dtypes/ - v0.16.02026-02-10 · 2026-02-10 23:49 UTC
查看更新说明
Highlights
We are excited to announce the 0.16.0 release of torchao! This release adds support for MXFP8 MoE Building Blocks for Training with Expert Parallelism and deprecated older versions of some configs and less used quantization options to keep torchao leaner! We also revamped our doc page, README and made some progress in making torchao ABI stable.
MXFP8 MoE Building Blocks for Training with Expert Parallelism
This release includes the following differentiable building blocks for MXFP8 MoE Training with expert parallelism:
- a2a_dispatch_mxfp8_fwd_hp_bwd: All-to-all token dispatch (MXFP8 forward pass, BF16 backward pass)
- permute_mxfp8_fwd_hp_bwd: Permute and pad tokens for MXFP8 computation (MXFP8 forward pass, BF16 backward pass)
- _to_mxfp8_then_scaled_grouped_mm: MXFP8 grouped GEMM for routed expert computation (new: optionally accepts pre-quantized inputs). Produces bfloat16 output.
- unpermute_hp_fwd_mxfp8_bwd: Unpermute tokens back to original order (BF16 forward pass, MXFP8 backward pass)
- a2a_combine_hp_fwd_mxfp8_bwd: All-to-all token combine (BF16 forward pass, MXFP8 backward pass). Note the actual combine/aggregation op does not happen here, the naming is just to indicate it is intended to be used for the all2all immediatley preceding the aggregation.
These autograd functions can be chained together to implement efficient MoE training with expert parallel comms and grouped GEMMs in MXFP8.
This approach achieves 10% - 25% tokens/second speedup for DeepSeekV3 16b training:
- +10% tokens/second on single node 8xB200 with NVLink intra-node networking for inter-device communication.
- +25% tokens/second on multi-node B200 cluster with IB inter-node networking and NVLink intra-node networking.
Deprecations
- Deprecate v1 of
Float8WeightOnlyConfig,Float8DynamicActivationFloat8WeightConfig,Int8DynamicActivationIntxWeightConfig,IntxWeightOnlyConfig,Int4WeightOnlyConfig(https://github.com/pytorch/ao/pull/3510, https://github.com/pytorch/ao/pull/3511, https://github.com/pytorch/ao/pull/3512, https://github.com/pytorch/ao/pull/3513)
# v0.15.0 - version 1 was available. config = Float8WeightOnlyConfig(version=1, ...) config = Float8DynamicActivationFloat8WeightConfig(version=1, ...) config = Int8DynamicActivationIntxWeightConfig(version=1, ...) config = IntxWeightOnlyConfig(version=1, ...) config = Int4WeightOnlyConfig(version=1, ...) # v0.16.0 - use version 2 (default). Using version 1 is no longer supported. config = Float8WeightOnlyConfig(version=2, ...) config = Float8DynamicActivationFloat8WeightConfig(version=2, ...) config = Int8DynamicActivationIntxWeightConfig(version=2, ...) config = IntxWeightOnlyConfig(version=2, ...) config = Int4WeightOnlyConfig(version=2, ...)- Move
Int8DynamicActivationInt4WeightConfig,Int4DynamicActivationInt4WeightConfig,GemliteUIntXWeightOnlyConfig,Float8StaticActivationFloat8WeightConfig, `UI
- v0.15.02025-12-22 · 2025-12-22 19:09 UTC
查看更新说明
Highlights
We are excited to announce the 0.15.0 release of torchao! This release adds:
- MXFP8 MoE training demonstrates 1.2x e2e training speedup with identical convergence versus bf16, training Llama4 Scout on a 64 node GB200 Crusoe cluster!
- MXFP8 MoE kernels shipped with torchao builds for CUDA 12.8+ (just pip install instead of building from source to use!)
- Safetensors enablement
- Quantization with parameter level targeting
MXFP8 MoE training demonstrates 1.2x e2e training speedup with identical convergence versus bf16, training Llama4 Scout on a 64 node GB200 Crusoe cluster
Training runs on 64 node GB200 cluster with TorchTitan Llama4 Scout demonstrated a 1.2x e2e training speedup with equivalent convergence to bfloat16 training baseline. In fact, after 3,000 steps it finishes with slightly lower loss than bfloat16! This is consistent with our scaling experiments with MXFP8 training for dense models.
Number of GPUs BF16 tokens/sec MXFP8 tokens/sec MXFP8 speedup vs BF16 512 6169 7401 1.20x See the TorchAO MXFP8 MoE training documentation for more details. You can also check out the TorchTitan MXFP8 documentation to run pretraining jobs with TorchAO MXFP8 by adding a single config.
Safetensors Enablement
You can now save and load TorchAO model checkpoints using safetensors! This feature is integrated with Hugging Face transformers starting from v5.0.0 and vLLM 0.13.0 for model inference/serving.
We currently support the following stable configs:
Float8DynamicActivationFloat8WeightConfigInt4WeightOnlyConfigIntxWeightOnlyConfigInt8DynamicActivationIntxWeightConfigInt8WeightOnlyConfigInt8DynamicActivationInt8WeightConfigand will continue to add support for configs as they become stable in the future.
Example:
import torch from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig from torchao.quantization import Float8WeightOnlyConfig model_id = "facebook/opt-125m" quant_config = Float8WeightOnlyConfig() quantization_config = TorchAoConfig(quant_type=quant_config) quantized_model = AutoModelForCausalLM.from_pretrained( model_id, device_map="auto", torch_dtype=torch.bfloat16, quantization_config=quantization_config, ) tokenizer = AutoTokenizer.from_pretrained(model_id) #### Push to hub MODEL_NAME = model_id.split("/")[-1] save_to = f"torchao-testing/{MODEL_NAME}-Float8WeightOnlyConfig-v2-0.15.0.dev-safetensors" quantized_model.push_to_hub(save_to, safe_serialization=True) tokenizer.push_to_hub(save_to)To serve a safetensors model checkpoint on vLLM, use the CLI command
vllm serve torchao-testing/Qwen3-8B-INT4-0.15.0dev-safetensors.int4 weight only quantization with preshuffled packing format is supported in vllm (#3245, #26066)
Now we support running int4 weight only with preshuffled packing format in vllm. We can ship int4 weight only quantized checkpoint with plain packing format (e.g. https://huggingface.co/torchao-testing/opt-125m-Int4WeightOnlyConfig-v2-0.14.0.dev), and the Tensor with plain format will be converted to preshuffled format automatically in SM90+ and when fbgemm_gpu_genai is available.
Support for quantizing any parameter by its fully qualified name (FQN) via
FqnToConfig(#[3083](https://github.com/pytorch/ao/pul - v0.14.12025-10-13 · 2025-10-13 21:34 UTC
查看更新说明
Highlights
We are excited to announce the 0.14.1 release of torchao! This release adds support for MoE training on Backwell GPUs and NVFP4 QAT!
(Prototype) MoE training on Blackwell GPUs
We’ve added a quantized building block for speeding up MoE training on Blackwell GPUs: torchao’s `_scaled_grouped_mm`! It is a differentiable drop-in replacement for `torch._grouped_mm` that dynamically quantizes inputs using the given recipe, performs a scaled grouped GEMM, then returns the results in original precision. This results in significant speedups (see benchmarks below)!
import torch from torch.nn import functional as F from torchao.prototype.moe_training import ( _scaled_grouped_mm as torchao_scaled_grouped_mm ) from torchao.prototype.moe_training.conversion_utils import MoEScalingType from torchao.prototype.moe_training.utils import generate_jagged_offs num_groups, total_M, N, K = 8, 131072, 8192, 5120 # A = input actvations, B = expert weights A = torch.randn(total_M, K, dtype=torch.bfloat16, device="cuda", requires_grad=True) B = torch.randn(num_groups, N, K, dtype=torch.bfloat16, device="cuda", requires_grad=True) # Token group offsets computed by router in actual MoE layer offs = generate_jagged_offs(num_groups, total_M, device="cuda") # Forward and backward example out = torchao_scaled_grouped_mm( A, B.transpose(-2, -1), offs=offs, scaling_type=MoEScalingType.MXFP8, ) labels = torch.ones_like(out) loss = F.mse_loss(out, labels) loss.backward()Microbenchmarks (see README for commands to reproduce benchmarks):
- Forward + backward pass vs torch._grouped_mm:
- ~1.4-1.8x faster for Llama4 17bx16e shapes
- ~1.2-1.4x faster for DeepSeekV3 671b shapes
- Full MoE layer forward + backward pass:
- ~1.4x faster (Llama4 17bx16e shapes, batch_size=8, seq_len=16384)
- ~1.2x faster (DeepSeekV3 671b shapes, batch_size=8, seq_len=16384).
It’s also already integrated into TorchTitan for E2E training with DeepSeekV3 and Llama4! Just use the command line flag: `--model.converters=”quantize.grouped_mm.mx”, which will convert all `torch._grouped_mm` ops to torchao _scaled_grouped_mm ops under the hood:
Torchtitan e2e training benchmarks (see README for commands to reproduce benchmarks):
- ~1.4x e2e speedup of 2 layer Llama4 16e model with dp2ep (without TP) parallelism on 4 B200 GPUs connected via NVLink
(Prototype) NVFP4 QAT (https://github.com/pytorch/ao/pull/3050)
We added quantization-aware training (QAT) support for NVFP4 as a prototype feature! This feature is currently only available on blackwell GPUs:
from torchao.quantization import quantize_ from torchao.prototype.mx_formats import NVFP4InferenceConfig # NVFP4 activation and weight quantization base_config = NVFP4InferenceConfig() quantize_(model, QATConfig(base_config, step="prepare")) train(model) quantize_(model, QATConfig(base_config, step="convert"))Our NVFP4 QAT support is also integrated into axolotl:
axolotl train examples/llama-3/3b-qat-fsdp2-nvfp4.yamlInitial experimentation demonstrated that QAT recovered up to 41% mmlu_pro accuracy degradation and 33% bbh accuracy degradation from NVFP4 quantization, for Qwen3-8B and Gemma3-12B-it respectively:
# Qwen3-8B bbh: 0.779 (baseline) -> 0.7254 (quant) -> 0.7368 (qat), recovered 21.269% mmlu_pro: 0.4969 (baseline) -> 0.4521 (quant) -> 0.4707 (qat), recovered 41.518% # Gemma3-12B-it accuracy bbh: 0.7527 (baseline) -> 0.7068 (quant) -> 0.7222 (qat), recovered 33.551% mmlu_pro: 0.4074 (baseline) -> 0.3621 (quant) -> 0.3702 (qat), recovered 17.881%BC Breaking
Rename In
- Forward + backward pass vs torch._grouped_mm:
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
TorchAO
[!NOTE]
An update on next steps for torchao
We are minimizing new feature development in torchao, and consolidating quantization development in other repositories as follows:
- low level quantization primitives (dtypes, casts and gemms) will be added directly to
torch, as long as they are stable and foundational. Examples aretorch.nn.functional.scaled_mmand the upcomingtorch.nn.functional.quantize_tensor.- higher level quantization building blocks and e2e workflows will be inlined directly into the repositories that need them (for example,
torchtitan), for maximum flexibility and control.TorchAO's e2e quantization workflows will receive the necessary updates to keep working with future torch versions, and we will land bug fixes / improvements on a case-by-case basis.
For context, TorchAO was originally created in 2024 to provide unified no-model-changes-required quantization workflows for PyTorch models, and it was quickly adopted by key ecosystem libraries such as
transformers,diffusersandtorchtitan, leading to speedups of up to 1.5x-2x across a range of various quantized training (example) and inference (example) workloads. Since then, two industry trends have changed how developers prefer to consume quantization offerings:
- The rise of agentic software development decreased the cost of authoring use-case-specific quantization workflow code.
- The Mixture-of-Experts (MoE) architecture gained prominence. Implementing quantization for MoE (vs dense) is more complex because of additional decisions such as (i) whether to quantize before or after dispatch and (ii) choosing kernel fusion boundaries across dispatch, local expert computation and combine and aligning the chosen boundaries with quantization formats. This makes it simpler to inline MoE quantization into the training/inference framework versus encoding these choices in a config + op swap abstraction, especially with agent-assisted development.
We believe that offering a small set of highly optimized primitives in torch and authoring quantization workflows directly in training and inference frameworks is the right tradeoff to support quantization research and productization going forward.
PyTorch-Native Training-to-Serving Model Optimization
- Pre-train Llama-3.1-70B 1.5x faster with float8 training
- Recover 67% of quantized accuracy degradation on Gemma3-4B with QAT
- Quantize Llama-3-8B to int4 for 1.89x faster inference with 58% less memory
Latest News | Overview | Quick Start | Installation | Integrations | Inference | Training | Videos | Citation
📣 Latest News
- [Oct 25] QAT is now integrated into Unsloth for both full and LoRA fine-tuning! Try it out using this notebook.
- [Oct 25] MXFP8 MoE training prototype achieved ~1.45x speedup for MoE layer in Llama4 Scout, and ~1.25x speedup for MoE layer in DeepSeekV3 671b - with comparable numerics to bfloat16! Check out the docs to try it out.
- [Sept 25] MXFP8 training achieved 1.28x speedup on Crusoe B200 cluster with virtually identical loss curve to bfloat16!
- [Sept 19] TorchAO Quantized Model and Quantization Recipes Now Available on Huggingface Hub!
- [Jun 25] Our TorchAO paper was accepted to CodeML @ ICML 2025!
- [May 25] QAT is now integrated into Axolotl for fine-tuning (docs)!
- [Apr 25] Float8 rowwise training yielded 1.34-1.43x training speedup at 2k H100 GPU scale
- [Apr 25] TorchAO is added as a quantization backend to vLLM (docs)!
- [Mar 25] Our 2:4 Sparsity paper was accepted to SLLM @ ICLR 2025!
- [Jan 25] Our integration with GemLite and SGLang yielded 1.1-2x faster inference with int4 and float8 quantization across different batch sizes and tensor parallel sizes
- [Jan 25] We added 1-8 bit ARM CPU kernels for linear and embedding ops
- [Nov 24] We achieved 1.43-1.51x faster pre-training on Llama-3.1-70B and 405B using float8 training
- [Oct 24] TorchAO is added as a quantization backend to HF Transformers!
- [Sep 24] We officially launched TorchAO. Check out our blog here!
- [Jul 24] QAT recovered up to 96% accuracy degradation from quantization on Llama-3-8B
- [Jun 24] Semi-structured 2:4 sparsity achieved 1.1x inference speedup and 1.3x training speedup on the SAM and ViT models respectively
- [Jun 24] Block sparsity achieved 1.46x training speeedup on the ViT model with <2% drop in accuracy
🌅 Overview
TorchAO is an easy to use quantization library for native PyTorch. TorchAO works out-of-the-box with torch.compile() and FSDP2 across most HuggingFace PyTorch models.
For a detailed overview of stable and prototype workflows for different hardware and dtypes, see the Workflows documentation.
Check out our docs for more details!
🚀 Quick Start
First, install TorchAO. We recommend installing the latest stable version:
pip install torchao
# optional - install MSLK for float8 and nvfp4 inference kernels
pip install mslk --index-url https://download.pytorch.org/whl/cu130
# optional - install apache-tvm-ffi and cutedsl for mxfp8 MoE training kernels
pip install apache-tvm-ffi
pip install nvidia-cutlass-dsl==4.5.2 nvidia-cutlass-dsl-libs-base==4.5.2 nvidia-cutlass-dsl-libs-cu13==4.5.2
Quantize your model weights to int4!
import torch
from torchao.quantization import Int4WeightOnlyConfig, quantize_
quantize_(model, Int4WeightOnlyConfig(group_size=32, int4_packing_format="tile_packed_to_4d", int4_choose_qparams_algorithm="hqq"))
See our quick start guide for more details.
🛠 Installation
To install the latest stable version:
pip install torchao
# Nightly
pip install --pre torchao --index-url https://download.pytorch.org/whl/nightly/cu128
# Different CUDA versions
pip install torchao --index-url https://download.pytorch.org/whl/cu126 # CUDA 12.6
pip install torchao --index-url https://download.pytorch.org/whl/cu129 # CUDA 12.9
pip install torchao --index-url https://download.pytorch.org/whl/xpu # XPU
pip install torchao --index-url https://download.pytorch.org/whl/cpu # CPU only
# For developers
# Note: the `--no-build-isolation` flag is required.
USE_CUDA=1 pip install -e . --no-build-isolation
USE_XPU=1 pip install -e . --no-build-isolation
USE_CPP=0 pip install -e . --no-build-isolation
Please see the torchao compability table for version requirements for dependencies.
Optional Dependencies
MSLK is an optional runtime dependency that provides accelerated kernels for some of the workflows in torchao. Stable MSLK should be used with stable torchao, and nightly MSLK with nightly torchao.
# Stable
pip install mslk --index-url https://download.pytorch.org/whl/cu130
# Nightly
pip install --pre mslk --index-url https://download.pytorch.org/whl/nightly/cu130
apache-tvm-ffi and nvidia-cutlass-dsl are used for MoE mxfp8 training kernels.
pip install apache-tvm-ffi
pip install nvidia-cutlass-dsl==4.5.2 nvidia-cutlass-dsl-libs-base==4.5.2 nvidia-cutlass-dsl-libs-cu13==4.5.2
🔎 Inference
TorchAO delivers substantial performance gains with minimal code changes:
- Int4 weight-only: 1.73x speedup with 65% less memory for Gemma3-12b-it on H100 with slight impact on accuracy
- Float8 dynamic quantization: 1.5-1.6x speedup on gemma-3-27b-it and 1.54x and 1.27x speedup on Flux.1-Dev* and CogVideoX-5b respectively on H100 with preserved quality
- Int8 activation quantization and int4 weight quantization: Quantized Qwen3-4B running with 14.8 tokens/s with 3379 MB memory usage on iPhone 15 Pro through ExecuTorch
Following is our recommended flow for quantization and deployment:
from transformers import TorchAoConfig, AutoModelForCausalLM
from torchao.quantization import Float8DynamicActivationFloat8WeightConfig, PerRow
# Create quantization configuration
quantization_config = TorchAoConfig(quant_type=Float8DynamicActivationFloat8WeightConfig(granularity=PerRow()))
# Load and automatically quantize
quantized_model = AutoModelForCausalLM.from_pretrained(
"Qwen/Qwen3-32B",
dtype="auto",
device_map="auto",
quantization_config=quantization_config
)
Alternative quantization API to use when the above doesn't work is quantize_ API in quick start guide.
Serving with vllm on 1xH100 machine:
# Server
VLLM_DISABLE_COMPILE_CACHE=1 vllm serve pytorch/Qwen3-32B-FP8 --tokenizer Qwen/Qwen3-32B -O3
# Client
curl http://localhost:8000/v1/chat/completions -H "Content-Type: application/json" -d '{
"model": "pytorch/Qwen3-32B-FP8",
"messages": [
{"role": "user", "content": "Give me a short introduction to large language models."}
],
"temperature": 0.6,
"top_p": 0.95,
"top_k": 20,
"max_tokens": 32768
}'
For diffusion models, you can quantize using Hugging Face diffusers
import torch
from diffusers import DiffusionPipeline, PipelineQuantizationConfig, TorchAoConfig
from torchao.quantization import Int8WeightOnlyConfig
from torchao.quantization.granularity import PerGroup
pipeline_quant_config = PipelineQuantizationConfig(
quant_mapping={"transformer": TorchAoConfig(Int8WeightOnlyConfig(granularity=PerGroup(128)))}
)
pipeline = DiffusionPipeline.from_pretrained(
"black-forest-labs/FLUX.1-dev",
quantization_config=pipeline_quant_config,
torch_dtype=torch.bfloat16,
device_map="cuda"
)
We also support deployment to edge devices through ExecuTorch, for more detail, see quantization and serving guide. We also release pre-quantized models here.
🚅 Training
Quantization-Aware Training
Post-training quantization can result in a fast and compact model, but may also lead to accuracy degradation. We recommend exploring Quantization-Aware Training (QAT) to overcome this limitation, especially for lower bit-width dtypes such as int4. In collaboration with TorchTune, we've developed a QAT recipe that demonstrates significant accuracy improvements over traditional PTQ, recovering 96% of the accuracy degradation on hellaswag and 68% of the perplexity degradation on wikitext for Llama3 compared to post-training quantization (PTQ). For more details, please refer to the QAT README and the original blog:
import torch
from torchao.quantization import quantize_, Int8DynamicActivationIntxWeightConfig, PerGroup
from torchao.quantization.qat import QATConfig
# prepare
base_config = Int8DynamicActivationIntxWeightConfig(
weight_dtype=torch.int4,
weight_granularity=PerGroup(32),
)
quantize_(my_model, QATConfig(base_config, step="prepare"))
# train model (not shown)
# convert
quantize_(my_model, QATConfig(base_config, step="convert"))
Users can also combine LoRA + QAT to speed up training by 1.89x compared to vanilla QAT using this fine-tuning recipe.
Quantized training
torchao.float8 implements training recipes with the scaled float8 dtypes, as laid out in https://arxiv.org/abs/2209.05433. With torch.compile on, current results show throughput speedups of up to 1.5x on up to 512 GPU / 405B parameter count scale (details):
from torchao.float8 import convert_to_float8_training
convert_to_float8_training(m)
Our float8 training is integrated into TorchTitan's pre-training flows so users can easily try it out. For more details, check out these blog posts about our float8 training support:
- Accelerating Large Scale Training and Convergence with PyTorch Float8 Rowwise on Crusoe 2K H200s
- Supercharging Training using float8 and FSDP2
- Efficient Pre-training of Llama 3-like model architectures using torchtitan on Amazon SageMaker
- Float8 in PyTorch
Memory-efficient optimizers
Optimizers like ADAM can consume substantial GPU memory - 2x as much as the model parameters themselves. TorchAO provides two approaches to reduce this overhead:
1. Quantized optimizers: Reduce optimizer state memory by 2-4x by quantizing to lower precision
from torchao.optim import AdamW8bit, AdamW4bit, AdamWFp8
optim = AdamW8bit(model.parameters()) # replace with Adam4bit and AdamFp8 for the 4 / fp8 versions
Our quantized optimizers are implemented in just a few hundred lines of PyTorch code and compiled for efficiency. While slightly slower than specialized kernels, they offer an excellent balance of memory savings and performance. See detailed benchmarks here.
2. CPU offloading: Move optimizer state and gradients to CPU memory
For maximum memory savings, we support single GPU CPU offloading that efficiently moves both gradients and optimizer state to CPU memory. This approach can reduce your VRAM requirements by 60% with minimal impact on training speed:
optim = CPUOffloadOptimizer(model.parameters(), torch.optim.AdamW, fused=True)
optim.load_state_dict(ckpt["optim"])
🔗 Integrations
TorchAO is integrated into some of the leading open-source libraries including:
- Unsloth now supports QAT: Read blog and guide.
- HuggingFace transformers with a builtin inference backend and low bit optimizers
- HuggingFace diffusers best practices with
torch.compileand TorchAO in a standalone repo diffusers-torchao - vLLM for LLM serving: usage, detailed docs
- Integration with MSLK for SOTA kernels on server GPUs
- Integration with ExecuTorch for edge device deployment
- Axolotl for QAT and PTQ
- TorchTitan for float8 pre-training
- HuggingFace PEFT for LoRA using TorchAO as their quantization backend
- TorchTune for our NF4 QLoRA, QAT, and float8 quantized fine-tuning recipes
- SGLang for LLM serving: usage
🎥 Videos
- Keynote talk at GPU MODE IRL
- Low precision dtypes at PyTorch conference
- Slaying OOMs at the Mastering LLM's course
- Advanced Quantization at CUDA MODE
- Chip Huyen's GPU Optimization Workshop
- Cohere for AI community talk
💬 Citation
If you find the torchao library useful, please cite it in your work as below.
@misc{or2025torchao,
title={TorchAO: PyTorch-Native Training-to-Serving Model Optimization},
author={Andrew Or and Apurva Jain and Daniel Vega-Myhre and Jesse Cai and Charles David Hernandez and Zhenrui Zheng and Driss Guessous and Vasiliy Kuznetsov and Christian Puhrsch and Mark Saroufim and Supriya Rao and Thien Tran and Aleksandar Samardžić},
year={2025},
eprint={2507.16099},
archivePrefix={arXiv},
primaryClass={cs.LG},
url={https://arxiv.org/abs/2507.16099},
}