Hydra¶
At a glance
Hydra: Medusa-style draft heads that also read the tokens drafted before them.
| Registered name | Family | Saves | Lossless | Trainable | Configuration |
|---|---|---|---|---|---|
hydra |
drafting | latency | yes | prefix, heads | HydraConfig |
Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: no · trtllm: no · vllm: real
Hydra (Ankner et al., 2024) makes Medusa's draft heads sequentially dependent. After the last processed token t,
head j drafts token t + 1 + j from the base state P_t and the embeddings of the tokens before it,
[P_t; E[x_{t+1}]; ...; E[x_{t+j}]], where x_{t+1} is the base model's own token and the later ones were drafted by
heads 1..j - 1. Each head is a stack of residual blocks with its own vocabulary projection. Hydra++, the default,
uses four blocks per head and computes P_t with one extra decoder layer that attends over the base model's last
hidden states with its own KV cache. Drafting costs the heads and that layer only. The base model verifies the chain
or a static tree in one forward pass, so greedy decoding is lossless. The heads and the prefix layer are trained on
a frozen base model by distillation from its distributions.
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.hydra import HydraConfig
model = economize.apply(base, HydraConfig(num_heads=4), decoding=economize.DecodeConfig(cycle_length=5))
result = model.decode(ids[0], 64)
print(tokenizer.decode(result.tokens))
print(result.mean_accepted) # accepted drafts per verification
print(result.cost_summary())
cycle_length=5 lets the four heads draft four tokens per verification. The output is exactly the base model's
greedy output at any training state. prefix=False drops the prefix layer and gives the original Hydra, whose
heads read the last hidden state directly.
Training¶
fit trains the heads and the prefix layer on the frozen base model. The default objective step_distill is the
teacher distillation of Hydra++: head j is trained on the KL divergence from the base model's distribution of
token t + 1 + j, with the earlier draft tokens taken from the training sequence.
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/hydra")
print(result.eval) # teacher-forced KL and agreement per head
StepDistill exposes the divergence, an extra cross-entropy on the true token and the weights of the heads:
from economize.train.objectives import StepDistill
fit(model, "train.bin", StepDistill(technique="hydra", steps=4, ce_weight=0.1, step_decay=0.8), steps=2000,
batch_size=8, seq_len=1024)
Saving and loading¶
model.save_pretrained("hydra_heads")
model.detach()
model = economize.load(base, "hydra_heads", decoding=economize.DecodeConfig(cycle_length=5))
Decoding options¶
A static tree from Medusa's registry verifies several candidates per head. Head j then runs once for every node at
depth j - 1, on that node's path:
model.detach()
model = economize.apply(base, HydraConfig(num_heads=4, tree="mc_sim_7b_63"),
decoding=economize.DecodeConfig(cycle_length=5))
model.decode(ids[0], 64)
min_confidence ends a draft early once the heads become unsure, which saves the verification of tokens that would
probably be rejected:
model.decode(ids[0], 64, decoding=economize.DecodeConfig(cycle_length=5, min_confidence=0.6))
Sampling stays lossless with verifier="rejection", and Medusa's typical acceptance is the lossy
verifier="typical" (see Medusa).
Combining with other techniques¶
The heads compose with techniques that are not drafters, such as a 4-bit KV cache:
from economize.techniques.kv_quant.kivi import KIVIConfig
model.detach()
model = economize.apply(base, KIVIConfig(bits=4), HydraConfig(num_heads=4),
decoding=economize.DecodeConfig(cycle_length=5))
Serving¶
economize's vLLM plugin serves Hydra and Hydra++ heads, including the prefix layer's KV cache, and vLLM verifies the top-1 chain. SGLang has no Medusa-style proposer.
from economize.backends.vllm import serving
plan = serving.to_vllm(model, "out/qwen-hydra", num_speculative_tokens=4)
llm = plan.llm()
Configuration¶
HydraConfig
dataclass
¶
HydraConfig(num_heads: int = 4, num_layers: int = 4, prefix: bool = True, head: str = 'own', tree: str | Paths | None = None, prefix_intermediate_size: int | None = None, param_dtype: str = 'float32')
Hyperparameters of Hydra heads (Ankner et al., 2024), by default the Hydra++ recipe.
Head j (1..K) drafts token t + 1 + j after the last processed token t from the base state P_t
and the embeddings of the tokens before it, [P_t; E[x_{t+1}]; ...; E[x_{t+j}]]: token t + 1 is the exact
pass's own, the later ones were drafted by heads 1..j - 1. This sequential dependence is what separates Hydra
from Medusa. A head is num_layers residual blocks; the first one maps the (j + 1) d wide input to d
(res(x) + SiLU(W x), res a linear map), the others are x + SiLU(W x + b).
With prefix=True (Hydra++) P_t is the output at t of one extra decoder layer with its own attention
and KV cache over the model's last hidden states; with prefix=False (Hydra) it is the last hidden state
itself. With head="own" the heads read the post-norm hidden state and have their own vocabulary projections
(with bias, initialized from the LM head), as the reference does. With head="shared" they read the pre-norm
state and the model's frozen final norm and LM head read their output, which saves K * V * d parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
num_heads |
int
|
|
num_layers |
int
|
Residual blocks per head (Hydra++: 4). |
prefix |
bool
|
Run the prefix attention layer of Hydra++. |
head |
str
|
|
tree |
str | Paths | None
|
Optional static draft tree (a name of :data: |
prefix_intermediate_size |
int | None
|
Width of the prefix layer's gated MLP (default: the model's). |
param_dtype |
str
|
Storage and compute dtype: |
References¶
- Ankner, Z., Parthasarathy, R., Nrusimha, A., Rinard, C., Ragan-Kelley, J., & Brandon, W. (2024). Hydra: Sequentially-dependent draft heads for Medusa decoding. In Conference on Language Modeling. https://doi.org/10.48550/arXiv.2402.05109