Skip to content

Structured width pruning: FLAP, LLM-Pruner and Minitron

At a glance

Structured width pruning: delete attention head groups, FFN channels and residual channels.

Registered name Family Saves Lossless Trainable Configuration
width_prune weight-compression weight memory, compute or latency no lora WidthPruneConfig

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

width_prune deletes whole units and leaves a dense model with smaller matrices. A head is removed together with the key and value head it reads (one key/value group with the query heads that share it), so a GQA model keeps its layout. An FFN channel is one row of the gate and up maps and one column of the down map. A residual channel, pruned by Minitron only, is one column of the embedding, one entry of every norm and one row or column of every map on the residual stream. Three criteria score the units on calibration data. FLAP (An et al., 2024) multiplies the fluctuation of a channel's inputs by the squared norm of its weight column, Var[x_j] ||W_:,j||^2, and folds the removed channels' mean contribution into a bias of the output map. LLM-Pruner (Ma et al., 2023) sums the first-order Taylor importance |W * dL/dW| over each coupled group, from one backward pass of the calibration cross-entropy. Minitron (Muralidharan et al., 2024) uses activation magnitudes and is the only criterion that prunes the residual stream.

The saving is real: every pruned map is a smaller nn.Linear. Pruning is lossy, and two recovery stages exist. A LoRA on the seven maps of every layer (lora_rank > 0, LLM-Pruner's recovery) is the technique's only trainable part, and Minitron distills the whole pruned model from the original. Pruning rewrites the base model 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)

Width pruning changes the base model, so measure the perplexity and the parameter count of the full model first:

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, dense_params = perplexity(base, windows), base.num_parameters()

Quick start

FLAP with its default adaptive structure removes 20% of the attention and FFN parameters of the whole model, with widths that differ from layer to layer:

from economize.techniques.width_prune import WidthPruneConfig

model = economize.apply(base, WidthPruneConfig(method="flap", sparsity=0.2), calibration=calibration)

summary = model.techniques["width_prune"].summary
print(summary["heads"][:4], summary["intermediate"][:4])     # query heads and FFN channels of the first layers
print(dense_params, summary["parameters"], summary["removed_parameters"])
print(dense_ppl, perplexity(model, windows))

summary["plain_checkpoint"] tells whether every layer kept the same widths. Only then is the configuration rewritten, and the model saves as an ordinary smaller checkpoint. structure="uniform" removes the same count in every layer.

Recovery training

LLM-Pruner keeps the first four and the last two layers whole by default. With lora_rank=8 it adds the recovery LoRA, which economize.train.fit trains. The logit_distill objective matches the next-token distributions of the unpruned model, passed as teacher_model:

from economize.train import fit

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
teacher = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, WidthPruneConfig(method="llm_pruner", sparsity=0.2, lora_rank=8),
                        calibration=calibration)
print(perplexity(model, windows))
fit(model, "train.bin", "logit_distill", teacher_model=teacher, steps=2000, batch_size=8, seq_len=1024,
    output_dir="runs/llm-pruner")
print(perplexity(model, windows))

Until it is merged, the LoRA runs as an extra product on every map. For inference, reattach the trained checkpoint with merge_lora=True, which multiplies the update into the pruned weights:

import dataclasses

model.save_pretrained("qwen-llm-pruner")
checkpoint = economize.read_checkpoint("qwen-llm-pruner")
merged = dataclasses.replace(checkpoint.configs[0], merge_lora=True)

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.attach(base, economize.Checkpoint([merged], checkpoint.states))
print(perplexity(model, windows))

Pruning the residual stream

Minitron prunes heads, FFN channels and residual channels, uniformly in every layer. Its retraining distills the whole pruned model, which LogitDistill(parameters="all") does:

from economize.train.objectives import LogitDistill

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, WidthPruneConfig(method="minitron", mlp_sparsity=0.36, attn_sparsity=0.0,
                                               hidden_sparsity=0.25), calibration=calibration)
print(model.techniques["width_prune"].summary["width"], perplexity(model, windows))
fit(model, "train.bin", LogitDistill(parameters="all"), teacher_model=teacher, steps=2000, batch_size=8,
    seq_len=1024, output_dir="runs/minitron")

Saving and loading

The kept indices are buffers of the technique, so a checkpoint replays the pruning, and the LoRA, on an unmodified base model without calibration data:

model.save_pretrained("qwen-minitron")

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
pruned = economize.load(base, "qwen-minitron")
print(pruned.techniques["width_prune"].summary["width"])

Combining with other techniques

Width pruning runs at order 7, after depth pruning and SliceGPT and before pruning and quantization, which see the pruned (and, with merge_lora=True, merged) weights:

from economize.techniques.quant import QuantConfig

print(economize.compatible("width_prune", "quant"))
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, WidthPruneConfig(method="flap", sparsity=0.2, structure="uniform"),
                        QuantConfig(format="int8", group_size=None, symmetric=True), calibration=calibration)
print(perplexity(model, windows))

A layer-dependent head count conflicts with the KV-cache techniques, which assume one head geometry. vLLM and SGLang build every layer from one configuration, so they serve uniform pruning only. vLLM also refuses Qwen2 models with pruned heads, since it derives the head size from hidden_size // num_attention_heads.

Configuration

WidthPruneConfig dataclass

WidthPruneConfig(method: str = 'flap', sparsity: float = 0.2, attn_sparsity: float | None = None, mlp_sparsity: float | None = None, hidden_sparsity: float = 0.0, structure: str | None = None, keep_first: int | None = None, keep_last: int | None = None, round_to: int = 1, compensate: bool | None = None, lora_rank: int = 0, lora_alpha: float = 16.0, merge_lora: bool = False, offload: bool = False, gradient_chunk: int = 0)

Remove attention heads, FFN channels and (Minitron) residual channels, which leaves a smaller dense model.

Heads are removed in key/value groups: a group is one key and value head and the query heads that share them (one query head without GQA), so the attention keeps its layout. The pruned model has the same modules and state-dict keys as the original with smaller weights; when every layer keeps the same widths, the config is rewritten (num_attention_heads, num_key_value_heads, intermediate_size, hidden_size and an explicit head_dim) and the model saves and serves as a plain checkpoint.

Parameters:

Name Type Description Default
method str

Registered importance criterion (:data:~economize.techniques.width_prune.WIDTH_CRITERIA): "flap" (An et al., AAAI 2024: fluctuation of the inputs times the squared column norms, with a bias that compensates for the removed channels), "llm_pruner" (Ma et al., NeurIPS 2023: first-order Taylor importance |W * dL/dW| summed over each coupled group) or "minitron" (Muralidharan et al., NeurIPS 2024: activation magnitudes, mean over the sequence and L2 over the batch).

'flap'
sparsity float

Fraction of the prunable units removed. With structure="uniform" it is the fraction of key/value groups and FFN channels removed in each pruned layer (attn_sparsity and mlp_sparsity override it per block type); with "adaptive" it is the fraction of the attention and FFN parameters of the whole model removed (FLAP's pruning_ratio), spread over layers by the global threshold.

0.2
attn_sparsity float | None

Fraction of key/value groups removed per layer ("uniform" only; None: sparsity).

None
mlp_sparsity float | None

Fraction of FFN channels removed per layer ("uniform" only; None: sparsity).

None
hidden_sparsity float

Fraction of residual-stream channels removed in every layer, the embedding and the head (criteria that score the residual stream, "minitron").

0.0
structure str | None

"uniform" or "adaptive" (None: the criterion's default, "adaptive" for FLAP and "uniform" for the others).

None
keep_first int | None

Leading layers whose heads and channels are kept (None: the criterion's default, 4 for LLM-Pruner as its Llama scripts, else 0). Residual channels are removed everywhere.

None
keep_last int | None

Trailing layers whose heads and channels are kept (None: 2 for LLM-Pruner, else 0).

None
round_to int

Kept FFN channels per layer are a multiple of this ("uniform" only).

1
compensate bool | None

Add FLAP's bias E[x_removed] W_removed^T to the attention output and down maps (None: the criterion's default, True for FLAP; only criteria that compensate accept it).

None
lora_rank int

Rank of a LoRA update of the seven maps of every layer, trained after pruning (LLM-Pruner's recovery stage; 0: none). It is the technique's only trainable part.

0
lora_alpha float

LoRA scaling numerator (the update is multiplied by lora_alpha / lora_rank).

16.0
merge_lora bool

Multiply the recovery LoRA into the pruned weights when the technique attaches, so that the model runs at the cost of the pruned model alone and later weight transforms (quantization, sparsity) apply to the merged weights. The LoRA is then no longer trainable; its parameters stay in the technique's state, so a saved technique reloads (and merges) exactly. Set it for inference after the recovery training.

False
offload bool

Keep calibration activations on the CPU between layers.

False
gradient_chunk int

Pruned layers whose weight gradients a gradient-based criterion ("llm_pruner") holds at once. The calibration batches run forward and backward once per chunk of this many layers, and each chunk's gradients are reduced to unit scores and freed before the next, which bounds the extra memory to the gradients of one chunk (0: all pruned layers in one pass). The scores do not depend on it.

0

resolved_structure property

resolved_structure: str

The resolved structure.

first property

first: int

The resolved keep_first.

last property

last: int

The resolved keep_last.

compensates property

compensates: bool

The resolved compensate.

attn_ratio property

attn_ratio: float

Fraction of key/value groups removed per pruned layer ("uniform").

mlp_ratio property

mlp_ratio: float

Fraction of FFN channels removed per pruned layer ("uniform").

uniform_widths property

uniform_widths: bool

Whether every layer of the pruned model has the same widths, so that its config describes it and it serves as a plain checkpoint ("uniform" with no protected layers, or nothing pruned per layer).

prunes_heads property

prunes_heads: bool

Whether attention heads may be removed.

pruned_layers

pruned_layers(num_layers: int) -> list[int]

The 1-indexed layers whose heads and channels are pruned.

References

  • An, Y., Zhao, X., Yu, T., Tang, M., & Wang, J. (2024). Fluctuation-based adaptive structured pruning for large language models. In AAAI Conference on Artificial Intelligence. https://doi.org/10.48550/arXiv.2312.11983
  • Ma, X., Fang, G., & Wang, X. (2023). LLM-Pruner: On the structural pruning of large language models. In Advances in Neural Information Processing Systems. https://doi.org/10.48550/arXiv.2305.11627
  • Muralidharan, S., Sreenivas, S. T., Joshi, R., Chochowski, M., Patwary, M., Shoeybi, M., Catanzaro, B., Kautz, J., & Molchanov, P. (2024). Compact language models via pruning and knowledge distillation. In Advances in Neural Information Processing Systems. https://doi.org/10.48550/arXiv.2407.14679