Medusa¶
At a glance
Medusa: extra heads on the last hidden state draft several future tokens at once.
| Registered name | Family | Saves | Lossless | Trainable | Configuration |
|---|---|---|---|---|---|
medusa |
drafting | latency | yes | heads | MedusaConfig |
Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: no · trtllm: untested · vllm: real
Medusa (Cai et al., 2024) adds K decoding heads on top of the base model's last hidden state. At the last
processed token t, the LM head predicts token t + 1 as usual and head j predicts token t + 1 + j, so one
step drafts up to K tokens without running any extra layer of the base model. Each head is a stack of residual
blocks x + SiLU(W x + b) followed by its own vocabulary projection, initialized from the LM head. The drafts form a
chain or a static sparse tree, and the base model verifies them in one forward pass. Greedy verification and
rejection sampling are lossless. Medusa's typical acceptance is available as a lossy verifier. Medusa-1 trains only
the heads on a frozen base model, which is what economize implements.
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¶
from economize.techniques.medusa import MedusaConfig
model = economize.apply(base, MedusaConfig(num_heads=5), decoding=economize.DecodeConfig(cycle_length=6))
result = model.decode(ids[0], 64)
print(tokenizer.decode(result.tokens))
print(result.mean_accepted) # accepted drafts per verification
print(result.cost_summary())
Five heads draft five tokens, so cycle_length=6 uses all of them. New heads accept little before training, and the
output is still exactly the base model's greedy output.
head="shared" is a variant of economize's own: the residual blocks read the hidden state before the final norm,
and the base model's frozen final norm and LM head read their output. It saves the K vocabulary projections. Heads
trained in one variant do not transfer to the other.
Training¶
fit trains the heads on the frozen base model. The default objective medusa_ce is Medusa-1's: the cross-entropy
of head j on the true token, weighted by 0.8 ** j and summed over the heads, with AdamW at 1e-3 and no weight
decay:
from economize.train import fit, fixed_windows
result = fit(model, "train.bin", steps=2000, batch_size=8, seq_len=1024, seed=0,
eval_data=fixed_windows("val.bin", 64, 1024), output_dir="runs/medusa")
print(result.eval)
MedusaCE adds a divergence from the base model's distribution through kl_weight, as in the self-distillation of
Medusa-2. The base model itself stays frozen.
from economize.techniques.medusa.objective import MedusaCE
fit(model, "train.bin", MedusaCE(ce_weight=1.0, kl_weight=1.0, step_decay=0.8), steps=2000, batch_size=8,
seq_len=1024)
Saving and loading¶
model.save_pretrained("medusa_heads")
model.detach()
model = economize.load(base, "medusa_heads", decoding=economize.DecodeConfig(cycle_length=6))
FasterDecoding's heads (a folder with config.json and medusa_lm_head.pt) load onto their base model in the same
way:
from huggingface_hub import snapshot_download
vicuna = AutoModelForCausalLM.from_pretrained("lmsys/vicuna-7b-v1.3", dtype=torch.bfloat16, device_map="cuda")
model = economize.load(vicuna, snapshot_download("FasterDecoding/medusa-vicuna-7b-v1.3"),
decoding=economize.DecodeConfig(cycle_length=6))
Decoding options¶
A static tree verifies several candidates per head at once. tree names a tree registered in MEDUSA_TREES
("mc_sim_7b_63" is the paper's tree for Vicuna-7B, "small" a seven-node tree) or gives its paths, each a tuple of
per-head ranks:
model.detach()
model = economize.apply(base, MedusaConfig(num_heads=5, tree="small"), decoding=economize.DecodeConfig(cycle_length=6))
model.decode(ids[0], 64)
Typical acceptance accepts a draft when the base model gives it a probability above a threshold that falls with the
entropy of the base model's distribution. It does not reproduce the base model's distribution, so it is lossy. On a
tree the verifier needs a sampler that gives its full distributions, so the tree model samples through decode
with a TopPSampler:
typical = economize.DecodeConfig(cycle_length=6, verifier="typical", verifier_options={"threshold": 0.09, "alpha": 0.3})
sampler = economize.TopPSampler(temperature=0.7, seed=0)
sampled = model.decode(ids[0], 64, decoding=typical, selector=sampler)
verifier="rejection" keeps sampling lossless instead. A chain of heads (no tree) also samples through
model.generate(..., do_sample=True).
Combining with other techniques¶
The heads compose with techniques that are not drafters, for example int8 weights:
from economize.techniques.quant import QuantConfig
model.detach()
model = economize.apply(
AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda"),
QuantConfig(format="int8"),
MedusaConfig(num_heads=5),
calibration=calibration,
decoding=economize.DecodeConfig(cycle_length=6),
)
Serving¶
vLLM serves head="own" heads with its method="medusa" and drafts their top-1 chain. TensorRT-LLM's
MedusaForCausalLM also runs them. SGLang has no Medusa proposer.
from economize.backends.vllm import serving
plan = serving.to_vllm(model, "out/qwen-medusa", num_speculative_tokens=5)
llm = plan.llm()
Configuration¶
MedusaConfig
dataclass
¶
MedusaConfig(num_heads: int = 5, num_layers: int = 1, head: str = 'own', tree: str | Paths | None = None, param_dtype: str = 'float32')
Hyperparameters of Medusa heads (Cai et al., 2024).
Head j (1..K) maps the model's last hidden state at the last processed token t through
num_layers residual blocks x + SiLU(W x + b) and drafts token t + 1 + j (the LM head itself gives
t + 1). With head="own" (Medusa-1) every head reads the post-norm hidden state and has its own
vocabulary projection, initialized from the LM head. With head="shared" the blocks read the pre-norm hidden
state and the model's frozen final norm and LM head read the result, which saves K * V * d parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
num_heads |
int
|
|
num_layers |
int
|
Residual blocks per head. |
head |
str
|
|
tree |
str | Paths | None
|
Optional static draft tree: the name of a tree in :data: |
param_dtype |
str
|
Storage and compute dtype of the heads: |
References¶
- Cai, T., Li, Y., Geng, Z., Peng, H., Lee, J. D., Chen, D., & Dao, T. (2024). Medusa: Simple LLM inference acceleration framework with multiple decoding heads. In International Conference on Machine Learning. https://doi.org/10.48550/arXiv.2401.10774