ao

pytorch活跃维护

PyTorch 官方的量化与稀疏化工具库,支持训练和推理阶段的低精度计算,覆盖 float8、MX 等数据类型,可加速 Transformer 和 Llama 等大模型。

PyTorch native quantization for training and inference

v0.18.0发布于 2026-08-03 20:44 UTC3,025star +2 / 7 天682fork同步于 2026-11-10 11:42 UTC

怎么上手

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

README 未统一说明显存要求;示例基于 H100、B200 等 NVIDIA GPU,也提供 XPU 和纯 CPU 的安装源,并提到 ARM CPU 的 1-8 bit 内核

纯 CPU 可运行需要 CUDA多卡 / 张量并行
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

PyTorch 原生量化库,支持训练与推理,几乎不改模型代码就能提速省显存

PyTorch 官方的量化与稀疏化工具库,支持训练和推理阶段的低精度计算,覆盖 float8、MX 等数据类型,可加速 Transformer 和 Llama 等大模型。

核心能力

  • 用 quantize_ 一行把模型权重量化到 int4
  • 提供 float8 动态量化配置,可直接接入 transformers
  • 支持 QAT 量化感知训练,恢复量化精度损失
  • 兼容 torch.compile 与 FSDP2,可作为 vLLM 量化后端
  • 提供 2:4 半结构化稀疏与 MoE MXFP8 训练原型

容易踩的坑

float8 和 nvfp4 推理内核需额外安装 mslk,且稳定版与 nightly 版本需和 torchao 对应;MoE mxfp8 训练需另装 apache-tvm-ffi 与指定版本的 nvidia-cutlass-dsl;项目已缩减新功能开发,部分量化能力将迁移到 torch 或训练框架中

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

最近发版

5 个版本v0.18.0
  1. 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()
    

    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.

    Removed: v1 tensor-subclass / layout system

    The deprecated v1 AffineQuantizedTensor stack and layout system have been fully removed, completing the migration to v2 tensor subclasses.

    Renamed / moved APIs

    Behavior changes

    Training / QAT

    mxfp8

  2. 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.0
    

    After:

    # 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.1
    

    Deprecations

    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/
    
  3. 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

    # 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
  4. 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 GPUsBF16 tokens/secMXFP8 tokens/secMXFP8 speedup vs BF16
    512616974011.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: Float8DynamicActivationFloat8WeightConfig Int4WeightOnlyConfig IntxWeightOnlyConfig Int8DynamicActivationIntxWeightConfig Int8WeightOnlyConfig Int8DynamicActivationInt8WeightConfig

    and 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

  5. 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.yaml
    

    Initial 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

用户点评

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

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

    README 原文

    未翻译

    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 are torch.nn.functional.scaled_mm and the upcoming torch.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, diffusers and torchtitan, 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

    license

    Latest News | Overview | Quick Start | Installation | Integrations | Inference | Training | Videos | Citation

    📣 Latest News

    🌅 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:

    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:

    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:

    🎥 Videos

    💬 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},
    }