Quantization, Sparsity & Pruning with torchao

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Quantization stores weights (and sometimes activations) in fewer bits; sparsity and pruning set weights to zero. Both shrink a model and can speed it up, at some cost in accuracy. The theory (uniform and affine quantization, calibration, post-training versus quantization-aware training, structured versus unstructured pruning, distillation) is in Model Compression; quantization of language models for local inference with GGUF or GPTQ is in Quantization for Inference. This page covers the PyTorch tooling.

Examples were run on Python 3.13 with PyTorch 2.15 (CPU) and torchao 0.18.0 on 2026-10-31. The int8 and pruning examples ran on CPU; the QAT example’s Int4 convert step (which needs the CUDA kernels of the separate mslk package), the float8 training example and the 2:4 sparsity example need a CUDA GPU and were not executed. Many configurations need specific GPUs (the documentation lists recommended hardware per configuration), and torchao evolves quickly: configuration class names, their arguments and their stability labels change between releases, so check the API reference of the version you install.

Where quantization lives now

PyTorch core used to ship torch.ao.quantization with an eager mode, an FX graph mode and later a PT2E mode. The core quantization page now says development is being centralised in torchao:

  • eager-mode APIs (torch.ao.quantization.quantize, quantize_dynamic) should migrate to torchao quantize_;

  • FX graph mode (prepare_fx, convert_fx) should migrate to the torchao PT2E functions (prepare_pt2e, convert_pt2e);

  • the page announced a plan to delete torch.ao.quantization in 2.10 "if there are no blockers" (or in the first release after any blockers are cleared); only a small API reference of still-public helpers is retained.

Tutorials and books that call torch.quantization.quantize_dynamic, torch.quantization.prepare or get_default_qconfig describe the old stack; see Legacy APIs & Migration.

Installing torchao

pip install torchao
# nightly build for CUDA 12.8
pip install --pre torchao --index-url https://download.pytorch.org/whl/nightly/cu128

Other wheel indexes exist for CUDA 12.6 and 12.9, XPU and CPU. torchao is built against particular PyTorch versions; the documentation points to a compatibility table, so install the torchao release that matches your PyTorch.

Post-training quantization with quantize_

The main inference API is quantize_(model, config, filter_fn=None). It replaces the weights of matching modules (by default linear layers) in place with quantized tensor subclasses. The model structure and forward code stay the same; only the weight tensors change type. Behaviour is selected by a config object.

import copy

import torch
from torch import nn
from torchao.quantization import Int8DynamicActivationInt8WeightConfig, quantize_

device = "cuda" if torch.cuda.is_available() else "cpu"
model = nn.Sequential(nn.Linear(1024, 1024, bias=False), nn.Linear(1024, 1024, bias=False))
model = model.to(device=device, dtype=torch.bfloat16).eval()
model_q = copy.deepcopy(model)

quantize_(model_q, Int8DynamicActivationInt8WeightConfig())
print(type(model_q[0].weight).__name__)      # Int8Tensor: a quantized tensor subclass

with torch.inference_mode():
    x = torch.randn(128, 1024, device=device, dtype=torch.bfloat16)
    print((model(x) - model_q(x)).abs().max())     # quantization error, about 0.02 on CPU

torch.save(model_q.state_dict(), "model_w8a8.pth")  # state dict with quantized tensors

In the official example the weights shrink from 4 MB to 2 MB (2x), and the measured speedup on the toy model is only 1.03x with torch.compile(..., mode="max-autotune", fullgraph=True). The page itself notes that this model is too small to show a real speedup and recommends CUDA GPUs and models larger than about 8B parameters for meaningful gains. The page shows saving the state dictionary but no loading code, so test your own save-and-load round trip. The weights_only and trust implications of loading pickled checkpoints are explained in Saving & Loading Models.

Choosing a config

The quantization API reference documents these configs (names as of torchao 0.18; prototype ones are labelled in the page):

Config What it does

Int8WeightOnlyConfig

Symmetric per-channel int8 weights; activations stay in the original dtype. A safe first step for memory.

Int8DynamicActivationInt8WeightConfig

Per-token int8 dynamic activations with per-channel int8 weights.

Int4WeightOnlyConfig

Weight-only int4 with group-wise quantization only (for example group_size=32). Larger packing and algorithm options exist, such as int4_packing_format and int4_choose_qparams_algorithm="hqq" in the landing-page example, and differ by device (CUDA or XPU).

Float8WeightOnlyConfig, Float8DynamicActivationFloat8WeightConfig

Symmetric float8 weights, optionally with dynamic float8 activations. The dynamic form measured the best end-to-end speedup of the tested options on H100 in the inference workflow page (per-row granularity), and needs a GPU with float8 support (CUDA compute capability 8.9 or newer, AMD MI350 or newer, or Intel XPU).

Float8DynamicActivationInt4WeightConfig

Float8 per-row dynamic activations with group-wise int4 weights; only group size 128.

IntxWeightOnlyConfig, Int8DynamicActivationIntxWeightConfig

Weights of 1 to 8 bits; aimed at edge and CPU targets.

NVFP4*, MXDynamicActivationMXWeightConfig, UIntx* (prototype)

Blackwell-oriented micro-scaling formats and gemlite-based bit-packed formats; prototype, so expect changes.

FqnToConfig

Apply different configs to different modules chosen by fully qualified name.

Selecting a config is mostly a hardware question. The documentation’s "recommended hardware" table pairs float8 rowwise with H100 and B200, int4 or int8 weights with A100, NVFP4 and MX formats with B200, and low-bit integer weights with edge devices. Measure accuracy on your own evaluation set, not only perplexity: on one image model the documentation reports visible differences between float8 rowwise and NVFP4. Quantize only the layers that benefit by passing filter_fn, a function (module, fully_qualified_name) returning True for modules to convert, and keep the first and last layers (embeddings, output head) in higher precision when accuracy suffers. Speedups usually grow with matrix size and need torch.compile (see torch.compile) to fuse the quantize and dequantize steps; they are often well below the theoretical limit, and small layers can be slower than bfloat16.

Quantized models can be exported and compiled: see torch.export, AOTInductor and, for devices, ExecuTorch for Mobile & Edge, which uses the torchao PT2E functions with backend quantizers.

Quantization-aware training

Post-training quantization can lose too much accuracy at low bit-widths. Quantization-aware training (QAT) trains with simulated quantization ("fake quantization") so that the weights adapt. In torchao the API is QATConfig used with the same quantize_ function in two steps:

from torchao.quantization import Int4WeightOnlyConfig, quantize_
from torchao.quantization.qat import QATConfig

base_config = Int4WeightOnlyConfig(group_size=32)

# 1. prepare: swap nn.Linear for FakeQuantizedLinear
quantize_(model, QATConfig(base_config, step="prepare"))

# 2. train as usual (your training loop, see the training-loop page)
train(model)

# 3. convert: swap back to nn.Linear and quantize with the base config
quantize_(model, QATConfig(base_config, step="convert"))

The QAT article lists Int4WeightOnlyConfig as the supported base config in that example (check the page for newer additions). Custom fake-quantization settings (activation and weight dtype, granularity, symmetry, group size) are expressed with IntxFakeQuantizeConfig passed as activation_config and weight_config to QATConfig; embeddings are handled weight-only by passing a filter_fn that selects nn.Embedding. The older per-scheme quantizer classes (Int4WeightOnlyQATQuantizer and similar) hard-code their settings and are marked legacy, so prefer QATConfig. Training itself is the ordinary loop of The Training Loop & Evaluation; QAT is typically a short fine-tuning phase on a pre-trained model, with a reduced learning rate (see Learning-Rate Schedulers & SWA/EMA).

Float8 training

The training side of torchao converts linear layers to float8 matrix multiplications to speed up pre-training on recent GPUs:

import torch
import torch.nn as nn
from torchao.float8 import Float8LinearConfig, convert_to_float8_training

m = nn.Sequential(
    nn.Linear(8192, 4096, bias=False),
    nn.Linear(4096, 128, bias=False),
).bfloat16().cuda()
optimizer = torch.optim.SGD(m.parameters(), lr=0.1)


def module_filter_fn(mod: nn.Module, fqn: str) -> bool:
    if fqn == "1":                      # keep the last layer in bfloat16
        return False
    if isinstance(mod, nn.Linear):
        return mod.in_features % 16 == 0 and mod.out_features % 16 == 0
    return True


config = Float8LinearConfig.from_recipe_name("tensorwise")   # or "rowwise", "rowwise_with_gw_hp"
convert_to_float8_training(m, config=config, module_filter_fn=module_filter_fn)
m = torch.compile(m)                    # needed for competitive performance

x = torch.randn(4096, 8192, device="cuda", dtype=torch.bfloat16)
for _ in range(10):
    optimizer.zero_grad()
    m(x).sum().backward()
    optimizer.step()

Notes from the documentation: the recipes trade speed against robustness to outliers (tensorwise is fastest and least robust, rowwise handles outliers better, rowwise_with_gw_hp is the most accurate of the three); speedups depend on matrix sizes (small GEMMs can be slower than bfloat16) and the quoted gains of about 25 percent come from a specific Llama-3-8B setup with torch.compile, FSDP2 and activation checkpointing; and the path composes with DTensor-based parallelism (see FSDP2 and DTensor, Tensor & Pipeline Parallelism). Training with fewer bits interacts with the mixed-precision machinery of Mixed Precision with torch.amp.

Sparsity

Semi-structured (2:4) sparsity requires that two of every four consecutive weights are zero. NVIDIA GPUs from Ampere onwards (compute capability 8.0 or higher) have sparse tensor cores that skip the zeros. The PyTorch tutorial (labelled beta, last updated September 2025) describes the workflow:

  1. Start from a dense, fine-tuned model.

  2. Prune with a sparsifier from torch.ao.pruning (the tutorial uses WeightNormSparsifier with sparse_block_shape=(1, 4) and zeros_per_block=2), calling prepare and step to compute the mask.

  3. Fine-tune to recover accuracy, then call squash_mask() to fold the mask into the weights.

  4. Convert to fp16 and replace the dense weights with to_sparse_semi_structured(weight), which returns a SparseSemiStructuredTensor.

import torch
from torch.sparse import to_sparse_semi_structured

linear = torch.nn.Linear(10240, 3072).half().cuda().eval()

# Build a 2:4 mask: keep the two largest-magnitude weights in every group of four.
w = linear.weight.detach()
groups = w.reshape(-1, 4)
keep = groups.abs().topk(2, dim=1).indices
mask = torch.zeros_like(groups, dtype=torch.bool).scatter_(1, keep, True).reshape_as(w)
linear.weight = torch.nn.Parameter(w * mask)

linear.weight = torch.nn.Parameter(to_sparse_semi_structured(linear.weight))

x = torch.rand(3072, 10240).half().cuda()
with torch.inference_mode():
    y = linear(x)

The mask construction above is written for this page; the tutorial produces the mask with WeightNormSparsifier. Requirements and results reported by the tutorial: PyTorch 2.1 or later, an NVIDIA GPU with compute capability 8.0 or higher, fp16 weights (other dtypes are described in the torch.sparse reference and were not verified here), and shape constraints on the weight matrix. On an A100 a single large linear layer ran about 1.38x faster; BERT on SQuAD showed roughly 1.1x to 1.2x without compilation and about 1.3x with it, at a small accuracy loss (F1 86.93 dense versus 86.49 sparse). Small batch sizes were slower than dense. The tutorial warns that speedups may differ on newer GPU architectures.

torchao packages this as sparsify_(model, config, filter_fn=None), "essentially the same as quantize but for sparsity subclasses", with semi_sparse_weight() for 2:4 sparsity; the reference also lists apply_fake_sparsity (simulate 2:4 sparsity on all linear layers) and WandaSparsifier (Wanda pruning). The documentation’s import paths for these are inconsistent between the reference pages, so read the page of the installed version. It can also be combined with quantization.

Pruning with torch.nn.utils.prune

torch.nn.utils.prune is the classic, framework-level pruning API. It zeroes weights through a mask but, by itself, does not make the model smaller or faster: the tensors stay dense. It is useful for research, for producing masks that a sparse runtime or the 2:4 flow above can exploit, and for understanding sparsity.

import torch
import torch.nn.utils.prune as prune
from torch import nn

model = nn.Sequential(nn.Linear(100, 50), nn.ReLU(), nn.Linear(50, 10))
first = model[0]

prune.l1_unstructured(first, name="weight", amount=0.3)   # zero the 30% smallest-magnitude weights
print([n for n, _ in first.named_parameters()])           # ['bias', 'weight_orig']
print([n for n, _ in first.named_buffers()])              # ['weight_mask']

# global pruning across several layers
params = ((model[0], "weight"), (model[2], "weight"))
prune.global_unstructured(params, pruning_method=prune.L1Unstructured, amount=0.2)

# structured: remove whole output rows by L2 norm
prune.ln_structured(model[2], name="weight", amount=0.5, n=2, dim=0)

# make it permanent: drop the mask and keep the zeroed weight
prune.remove(first, "weight")

How it works, according to the tutorial:

  • Pruning removes weight from the parameters and registers weight_orig (the unpruned values) as a parameter and weight_mask as a buffer. weight becomes a plain attribute recomputed by a forward pre-hook before every forward pass.

  • Pruning the same parameter again is stored in a PruningContainer that combines masks in series.

  • Both weight_orig and weight_mask appear in the state_dict, so a pruned model can be saved and restored; call prune.remove before exporting or deploying if you want a plain weight again.

  • random_unstructured, l1_unstructured, ln_structured and global_unstructured take amount as a float (fraction) or an integer (count). Custom criteria subclass prune.BasePruningMethod and implement compute_mask.

Because the model stays dense, real savings need either 2:4 conversion on supported GPUs, a sparse storage format (see Sparse, Nested & Complex Tensors), or physically removing the pruned channels and rebuilding smaller layers.

  1. Try bfloat16 or float16 first (see Mixed Precision with torch.amp and Hardware & Mixed Precision); it often provides most of the memory saving with no accuracy cost.

  2. Add weight-only int8 or int4 quantization; evaluate on your task.

  3. If accuracy drops at low bit-widths, use QAT.

  4. For throughput on recent GPUs, evaluate float8 dynamic quantization, with torch.compile.

  5. Consider 2:4 sparsity only when you can fine-tune and have supported hardware.

  6. Validate each step against the original on a held-out set before deploying; quantization errors are task dependent.