Drafter-only pruning¶
At a glance
N:M pruning of the drafter's own modules (see DraftPruneConfig).
| Registered name | Family | Saves | Lossless | Trainable | Configuration |
|---|---|---|---|---|---|
draft_prune |
draft-compression | latency | yes | no | DraftPruneConfig |
Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: no · trtllm: no · vllm: no
Drafter-only pruning sets n of every m consecutive input weights of each output row of a drafter to zero, by
default two of every four, and leaves the base model dense. It is the pruning counterpart of
draft-only quantization. The drafter is a separate technique, such as an EAGLE-3 head, and
draft_prune prunes the linear maps that this drafter adds: the drafter's draft_modules() when it defines them,
otherwise every nn.Linear in its module tree. Maps whose weight is a base-model parameter and LoRA factors are left
alone, and so is a map whose input width is not a multiple of m. The weights with the smallest magnitude in each
group are removed, which reads no data, so the score is magnitude. Since the dense base model verifies every drafted
token, the output does not change and the technique is lossless. What changes is the cost of a draft step and
possibly the acceptance rate. Nothing is trained.
Setup¶
Every tutorial starts from the same model and prompt:
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)
Quick start¶
draft_prune needs exactly one drafter with modules of its own in the same recipe, and it attaches after it. The
pruned maps are stored as 2:4 semi-structured sparse tensors, which need a CUDA GPU of compute capability 8.0 or newer
(the page's tests run on a CPU with the masked dense reference of the test suite, which computes the same numbers):
from economize.techniques.draft_prune import DraftPruneConfig
from economize.techniques.eagle3 import Eagle3Config
model = economize.apply(base, Eagle3Config(), DraftPruneConfig(),
decoding=economize.DecodeConfig(cycle_length=6))
print(model.techniques["draft_prune"].summary) # pruned modules, pattern, sparsity and storage
result = model.decode(ids[0], 64)
print(tokenizer.decode(result.tokens))
print(result.mean_accepted) # accepted drafts per verification
model.detach()
The output is the model's greedy output token for token. detach() restores the drafter's original weights bit for
bit. A drafter without modules of its own, such as prompt lookup, REST or a separate draft model, is refused:
from economize.techniques.lookup import LookupConfig
print(economize.compatible(DraftPruneConfig(), Eagle3Config())) # True
print(economize.compatible(DraftPruneConfig(), LookupConfig())) # False
A drafter is trained dense and pruned afterwards, in the same way as draft-only quantization:
append DraftPruneConfig to the configurations of a saved checkpoint and attach it again. Comparing mean_accepted
of the dense and the pruned head on prompts of the target workload shows what the pruning costs.
Sparse kernels¶
Each 2:4-pruned map is stored as a PyTorch semi-structured sparse tensor, which needs a CUDA GPU of compute capability
8.0 or newer and half-precision weights; on other devices draft_prune raises a ConfigError before any weight
changes. semi_structured_kernel picks the kernel ("default", "cusparselt", "cutlass", or "auto", which
times both sparse kernels on each weight shape and keeps the faster one). A draft step at batch 1 reads every weight once and is bound by memory
traffic, so the sparse kernels gain little on the narrow maps of a small drafter. The wide up and gate projections of
an MLP gain the most.
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, Eagle3Config(), DraftPruneConfig(semi_structured_kernel="auto"),
decoding=economize.DecodeConfig(cycle_length=6))
Other patterns, such as n=1, m=4, and semi_structured=False are refused: no kernel multiplies them, so the zeros
would stay inside dense weights that save no time.
Serving¶
vLLM and SGLang load hidden-state drafters only with dense float weights, so their exports refuse a pruned drafter,
and economize.backend_support("draft_prune") gives the reason.
Configuration¶
DraftPruneConfig
dataclass
¶
DraftPruneConfig(n: int = 2, m: int = 4, score: str = 'magnitude', semi_structured: bool = True, semi_structured_kernel: str = 'auto', targets: tuple[str, ...] = ('*',), exclude: tuple[str, ...] = ('*lora*',))
N:M pruning of the drafter's own linear maps only (the verified base model is untouched).
Lossless: every drafted token is still verified by the unpruned model, so only the acceptance rate and the cost of a draft step change. The drafter's predictor, readout and full layer copies are pruned; LoRA factors and modules whose weights are shared with the base model are skipped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Nonzeros kept in every group of |
2
|
m
|
int
|
Group size along the input dimension. Maps whose input size |
4
|
score
|
str
|
Registered calibration-free pruning criterion (:data: |
'magnitude'
|
semi_structured
|
bool
|
The 2:4 weights are always stored as |
True
|
semi_structured_kernel
|
str
|
Registered storage kernel for the 2:4 weights
(:data: |
'auto'
|
targets
|
tuple[str, ...]
|
Globs over module names inside the drafter ( |
('*',)
|
exclude
|
tuple[str, ...]
|
Globs removed from |
('*lora*',)
|
as_prune_config
¶
as_prune_config() -> PruneConfig
The equivalent :class:~economize.techniques.prune.PruneConfig, which the pruning criterion and the
storage checks of prune read.