MagicDec¶
At a glance
MagicDec: the base model drafts on a StreamingLLM view of its own KV cache.
| Registered name | Family | Saves | Lossless | Trainable | Configuration |
|---|---|---|---|---|---|
magicdec |
drafting | latency | yes | no | MagicDecConfig |
Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: no · trtllm: no · vllm: no
MagicDec (Sadhukhan et al., 2025) is self-speculative decoding for long prompts. With a long prompt the cost of a
decoding step is dominated by reading the KV cache, so a drafter that keeps every weight of the model and reads only
a small part of the cache is cheap and still accurate. MagicDec drafts with the base model itself on a StreamingLLM
view of its cache: the first sinks positions (the attention sinks) and a recent window, budget slots in all.
Every cycle's exact pass reads the whole cache and keeps the longest prefix of drafts it agrees with, so greedy
decoding is lossless. Nothing is trained.
In economize each draft step runs every layer with the base weights. The full-attention layers read the view, and
sliding-window, chunked and recurrent layers run unchanged since their reads are already bounded. A draft layer
gathers the budget entries of the view from the shared cache and attends over them alone, so its attention FLOPs
and KV reads stay fixed as the prompt grows, on every attention implementation. The cache itself is shared with the
exact pass, so the drafter saves no memory. Long-context drafting describes the views of MagicDec and
TriForce side by side.
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¶
The drafter pays off once the prompt is much longer than budget. Twenty GSM8K solutions before the question make a
prompt of a few thousand tokens, and the plain model's greedy output on it is the reference:
from economize.techniques.sparse_kv_draft import MagicDecConfig
text = "\n\n".join(texts[:20]) + "\n\n" + tokenizer.decode(ids[0]) + "\n"
prompt = tokenizer(text, return_tensors="pt").input_ids.cuda()
plain = economize.apply(base)
reference = plain.decode(prompt[0], 64).tokens
plain.detach()
model = economize.apply(base, MagicDecConfig(budget=512, sinks=4), decoding=economize.DecodeConfig(cycle_length=5))
result = model.decode(prompt[0], 64)
print((result.tokens == reference).float().mean().item()) # agreement with the plain model
print(result.mean_accepted) # accepted drafts per verification
print(result.cost_summary())
Every draft step runs all layers, so relative_layer_tokens in the cost summary is above one. The saving lies in
the KV reads, which the call log does not count, and timings on a GPU measure it.
The gathered view¶
A draft layer writes its new keys and values to the cache as usual and then attends over a copy of the
sinks + window entries of the view, gathered with the matching columns of the attention mask, and simulation()
returns None. A chain step reads the same slots in every layer, so the slots and the gathered mask are computed
once per step. A tree step gathers the sinks and the window - 1 + T slots that hold every window its T nodes can
see. When the view would hold no fewer entries than the cache (a short context), the draft layers read the whole
cache with the entries outside the view hidden in the mask, which drafts the same tokens, reads no more than
gathering would and claims no saving. See
long-context drafting for the cost of the view.
Decoding options¶
The view depends only on the positions, so the drafter keeps no state and its steps replay from CUDA graphs with
cuda_graphs=True. The drafts come with the model's own distributions, so sampling with the rejection verifier
follows the base model's distribution. The drafter also implements tree steps, which the tree policies of
tree search use:
sampling = economize.DecodeConfig(cycle_length=5, verifier="rejection")
sampled = model.generate(prompt, max_new_tokens=64, do_sample=True, temperature=0.7, top_p=0.9, decoding=sampling)
tree = model.decode(prompt[0], 64, decoding=economize.DecodeConfig(cycle_length=5, draft_policy="dynamic_tree"))
Combining with other techniques¶
MagicDec composes with weight, activation and KV-cache techniques, which then apply to the draft steps and the exact pass alike, for example a 4-bit KV cache. It refuses every other drafter:
from economize.techniques.kv_quant.kivi import KIVIConfig
print(economize.compatible("magicdec", "kivi"), economize.compatible("magicdec", "eagle3")) # True False
model.detach()
base.set_attn_implementation("sdpa")
model = economize.apply(base, KIVIConfig(bits=4), MagicDecConfig(budget=512, sinks=4), calibration=calibration,
decoding=economize.DecodeConfig(cycle_length=5))
result = model.decode(prompt[0], 64)
Differences from the official code¶
MagicDec's own engine keeps a separate, compacted StreamingLLM cache for the drafter and batches long-context requests. economize gathers the view's entries from the shared cache in every draft layer, which reads the same number of entries without a second cache, through the ordinary cycle loop, which also decodes batches.
Serving¶
vLLM and SGLang do not serve the drafter, since their proposers draft with a model that owns its KV cache and no
proposer hook runs the base model over a sparse view of its paged cache. economize.backend_support("magicdec")
gives the reason per backend.
Configuration¶
MagicDecConfig
dataclass
¶
MagicDecConfig(budget: int = 512, sinks: int = 4, view: str = 'gathered')
Hyperparameters of the MagicDec self-drafter (Sadhukhan et al., 2025, arXiv 2408.11049).
A draft step runs the whole model, and each of its full-attention layers reads a StreamingLLM view of the cache:
the first sinks positions and the last budget - sinks positions up to the query. Sliding-window,
chunked and recurrent layers run unchanged. The exact pass reads the whole cache, so decoding stays lossless.
Attributes:
| Name | Type | Description |
|---|---|---|
budget |
int
|
KV entries one draft query reads in a full-attention layer (sinks plus window). |
sinks |
int
|
Leading positions every draft query reads (StreamingLLM's attention sinks). |
view |
str
|
How a full-attention layer reads the budget (:data: |
References¶
- Sadhukhan, R., Chen, J., Chen, Z., Tiwari, V., Lai, R., Shi, J., Yen, I. E.-H., May, A., Chen, T., & Chen, B. (2025). MagicDec: Breaking the latency-throughput tradeoff for long context generation with speculative decoding. In International Conference on Learning Representations. https://doi.org/10.48550/arXiv.2408.11049