Skip to content

Weight pruning: magnitude, Wanda and SparseGPT

At a glance

Wanda / SparseGPT / magnitude 2:4 pruning stored as semi-structured sparse tensors (see PruneConfig).

Registered name Family Saves Lossless Trainable Configuration
prune weight-compression weight memory or compute no no PruneConfig

Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: no · trtllm: no · vllm: no

prune sets a fraction of the weights of every linear map in the decoder layers to zero, either unstructured (a fixed fraction of every output row) or in an N:M pattern (at most N nonzeros in every M consecutive input weights). Three criteria choose the weights. magnitude keeps the largest |W_ij| and reads no data. Wanda (Sun et al., 2024) scores each weight by |W_ij| * ||X_j||_2, the weight's magnitude times the norm of its input channel over the calibration tokens. SparseGPT (Frantar & Alistarh, 2023) prunes the columns in blocks of 128 with the Optimal Brain Surgeon mask and updates the remaining weights of each row through the inverse Hessian (X^T X)^-1, so that they compensate the error of the removed ones. Calibration runs one decoder layer at a time on the outputs of the already pruned layers. Nothing is trained, and the result is lossy.

The default pattern is 2:4, the one pattern that sparse tensor cores multiply. Its maps are stored as PyTorch semi-structured sparse tensors, which hold half the values plus a small index and run on the sparse tensor cores of CUDA GPUs from compute capability 8.0 (A100, A6000, L40, H100) in fp16 or bf16. On other hardware the default raises a ConfigError before any weight changes. Unstructured sparsity and the other N:M patterns have no sparse kernel, so PruneConfig refuses them, together with semi_structured=False: either would keep the zeros inside dense tensors, which costs the full memory and time of the dense model. Pruning rewrites the base weights in place, so the technique cannot be detached.

Setup

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

import economize

device = "cuda" if torch.cuda.is_available() else "cpu"
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map=device)
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B")
ids = tokenizer("Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. "
                "How many clips did Natalia sell altogether?", return_tensors="pt").input_ids.to(device)

Training data is a flat file of uint32 token ids, the format of nanoGPT-style pretraining shards, and calibration data is a [N, S] tensor of token ids. Both are made here from GSM8K:

import numpy as np
from datasets import load_dataset

texts = [f"{row['question']}\n{row['answer']}" for row in load_dataset("openai/gsm8k", "main", split="train")]
tokens = np.concatenate([tokenizer(t + tokenizer.eos_token).input_ids for t in texts]).astype(np.uint32)
tokens[: len(tokens) * 9 // 10].tofile("train.bin")
tokens[len(tokens) * 9 // 10 :].tofile("val.bin")

calibration = torch.from_numpy(tokens[: 128 * 2048].astype(np.int64)).view(128, 2048)

Pruning changes the base model, so measure the dense perplexity first. This helper averages the next-token loss over 64 windows of the validation split:

from economize.train import fixed_windows

windows = fixed_windows("val.bin", 64, 1024).cuda()


@torch.no_grad()
def perplexity(model, windows):
    return torch.stack([model(w[None], labels=w[None]).loss for w in windows]).float().mean().exp().item()


dense_ppl = perplexity(base, windows)

Quick start

Wanda with the default 2:4 pattern reads the calibration tensor once:

from economize.techniques.prune import PruneConfig

model = economize.apply(base, PruneConfig(method="wanda"), calibration=calibration)

summary = model.techniques["prune"].summary
print(summary["pattern"], summary["zeros"] / summary["eligible"])   # fraction of zeros in the pruned maps
print(dense_ppl, perplexity(model, windows))
print(tokenizer.decode(model.generate(ids, max_new_tokens=32)[0]))

summary["eligible"] counts the weights of the selected maps and summary["zeros"] the zeros among them. The embeddings, the norms and the LM head are never pruned. (The page's tests run on a CPU, where no sparse kernel exists, so they swap in the masked dense reference of the test suite, which computes the same numbers.)

Unstructured sparsity reaches higher fractions of zeros at the same quality, but no kernel turns them into a saving, so the configuration is refused with that reason:

from economize.errors import ConfigError

try:
    PruneConfig(method="wanda", sparsity=0.5)
except ConfigError as error:
    print(error)   # only 2:4 pruning has a sparse kernel ...

Criteria and patterns

method picks the criterion. targets, exclude and layers restrict pruning to some maps and layers (layers is 1-indexed):

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, PruneConfig(method="sparsegpt", exclude=("self_attn.*",)), calibration=calibration)
print(model.techniques["prune"].summary["pattern"], perplexity(model, windows))

SparseGPT also reads blocksize (the column block, a multiple of M for N:M) and percdamp (the Hessian damping as a fraction of its mean diagonal). The other criteria reject non-default values of both. magnitude needs no calibration:

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, PruneConfig(method="magnitude"))

Every model must be loaded again before it is pruned again, as above, because pruning changes it in place.

Sparse kernels

Only the 2:4 pattern stored semi-structured makes the model faster, and it is the default. The sparse GEMM gains most at large token counts (prefill, verification of long drafts, batched serving) and little at batch-1 decoding. semi_structured_kernel picks the sparse kernel ("default", "cusparselt", "cutlass", or "auto", which times both sparse kernels on each weight shape and keeps the faster one; every map stays sparse):

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, PruneConfig(method="wanda", semi_structured_kernel="auto"), calibration=calibration)

vLLM, SGLang, ONNX Runtime, llama.cpp, MLX and TensorRT-LLM have no 2:4 kernel that economize can hand the weights to, so their exports refuse a pruned model, and economize.backend_support("prune") gives the reason per runtime.

Saving and loading

A checkpoint stores the configuration. Loading prunes an unmodified base model again with the same calibration data:

model.save_pretrained("qwen-wanda")

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.load(base, "qwen-wanda", calibration=calibration)

Combining with other techniques

Semi-structured sparse tensors cannot be quantized or factorized, and no installed kernel multiplies a weight that is both 2:4 sparse and quantized, so prune is refused together with quant or lowrank:

from economize.techniques.quant import QuantConfig

print(economize.compatible(PruneConfig(), QuantConfig()))   # False
print(economize.incompatibility("prune", "quant"))

Configuration

PruneConfig dataclass

PruneConfig(method: str = 'wanda', sparsity: float | str = '2:4', targets: tuple[str, ...] = ('*',), exclude: tuple[str, ...] = (), layers: tuple[int, ...] = (), blocksize: int = 128, percdamp: float = 0.01, semi_structured: bool | None = None, semi_structured_kernel: str = 'default', offload: bool = False)

2:4 weight pruning of the linear maps of the decoder layers, stored as semi-structured sparse tensors.

The pruned weights are held by torch.sparse semi-structured tensors (CUDA sm80+, fp16/bf16), which keep half the values and run on sparse tensor cores. 2:4 is the one pattern a sparse kernel runs, so other N:M patterns, unstructured fractions and semi_structured=False (masked dense weights, the same function at the dense model's memory and cost) are refused when the config is built.

Parameters:

Name Type Description Default
method str

Registered criterion: "wanda" (default), "sparsegpt" or "magnitude".

'wanda'
sparsity float | str

"2:4" (the default and the only accepted pattern: at most 2 nonzeros in every 4 consecutive input weights).

'2:4'
targets tuple[str, ...]

Globs over linear-module names inside a layer ("self_attn.*", "mlp.down_proj").

('*',)
exclude tuple[str, ...]

Globs removed from targets.

()
layers tuple[int, ...]

1-indexed layers to prune; empty means all.

()
blocksize int

SparseGPT column block (a multiple of 4).

128
percdamp float

SparseGPT relative Hessian damping.

0.01
semi_structured bool | None

None (the default) or True: the 2:4 weights are stored semi-structured. False is refused (it would keep masked dense weights); the field stays so that saved configs load.

None
semi_structured_kernel str

Registered storage kernel for the 2:4 weights (:data:~economize.techniques.prune.SEMI_STRUCTURED_KERNELS): "default" (PyTorch's choice), "cusparselt", "cutlass" or "auto" (the faster of the two per weight shape at decode sizes).

'default'
offload bool

Keep calibration activations on the CPU between layers.

False

blocksize and percdamp are method options (:attr:method_options): a method that does not read one (:attr:Pruner.options <economize.techniques.prune.Pruner.options>) rejects a non-default value.

sparse_storage property

sparse_storage: bool

Whether the pruned weights are stored as semi-structured sparse tensors.

Returns

bool semi_structured when it is set, else whether the pattern is 2:4 (the one pattern a sparse kernel runs).

References

  • Frantar, E., & Alistarh, D. (2023). SparseGPT: Massive language models can be accurately pruned in one-shot. In International Conference on Machine Learning. https://doi.org/10.48550/arXiv.2301.00774
  • Sun, M., Liu, Z., Bair, A., & Kolter, J. Z. (2024). A simple and effective pruning approach for large language models. In International Conference on Learning Representations. https://doi.org/10.48550/arXiv.2306.11695