ReDrafter¶
At a glance
ReDrafter: a recurrent draft head on the model's last hidden state.
| Registered name | Family | Saves | Lossless | Trainable | Configuration |
|---|---|---|---|---|---|
redrafter |
drafting | latency | yes | rnn_w, rnn_u, input_proj, blocks, proj, down | RedrafterConfig |
Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: no · trtllm: no · vllm: real
ReDrafter (Cheng et al., 2024) drafts with a small recurrent network on top of the base model's last hidden state.
After the base model has processed token t, a recurrent state starts at s_0 = 0 and takes the embedding of every
later token, s_k = SiLU(W E[x_{t+k}] + U s_{k-1} + b). A head of residual blocks reads [h_t; s_k] and drafts token
t + k + 1. Token t + 1 is the base model's own, and the later inputs are the drafter's previous outputs, so a
draft step costs one recurrent update and the head. With a beam width above one, every cycle runs beam search over
the head and the base model verifies all beams at once as a tree of their distinct prefixes. Greedy verification is
lossless. The recurrence and the head are trained on a frozen base model by distillation.
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.redrafter import RedrafterConfig
model = economize.apply(base, RedrafterConfig(beam_length=5), 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())
beam_length counts the base model's token, so beam_length=5 drafts at most four tokens per cycle and
cycle_length=5 uses all of them. With the default beam_width=1 the drafter proposes a single chain. The output
equals the base model's greedy output before and after training.
Training¶
fit trains the drafter on the frozen base model. The default objective step_distill is the paper's knowledge
distillation: step k reads the true tokens t + 1..t + k and is trained on the KL divergence from the base
model's distribution of token t + k + 1, over beam_length - 1 steps.
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/redrafter")
print(result.eval) # teacher-forced KL and agreement per draft step
The divergence, the step weights and an extra cross-entropy on the true token are options of StepDistill:
from economize.train.objectives import StepDistill
fit(model, "train.bin", StepDistill(technique="redrafter", steps=4, ce_weight=0.1), steps=2000, batch_size=8,
seq_len=1024)
Saving and loading¶
model.save_pretrained("redrafter_head")
model.detach()
model = economize.load(base, "redrafter_head", decoding=economize.DecodeConfig(cycle_length=5))
Decoding options¶
Beam search drafts beam_width candidate continuations per cycle. The base model checks them together and accepts
the longest prefix that matches its own greedy tokens. top_k limits the candidates of each beam step and must be at
least beam_width:
model.detach()
beams = RedrafterConfig(beam_width=8, beam_length=5, top_k=50)
model = economize.apply(base, beams, decoding=economize.DecodeConfig(cycle_length=5))
model.decode(ids[0], 64)
Sampling stays lossless with the rejection verifier. Verifying a tree needs a sampler that gives its full
distributions, so the beam model samples through decode with a TopPSampler. A single chain (beam_width=1)
also samples through model.generate(..., do_sample=True).
sampling = economize.DecodeConfig(cycle_length=5, verifier="rejection")
sampled = model.decode(ids[0], 64, decoding=sampling, selector=economize.TopPSampler(temperature=0.7, top_p=0.9))
The head itself has two variants. head="own", the default, reads the hidden state after the final norm and ends
in its own vocabulary projection, initialized from the LM head. head="shared" reads the state before the final norm,
maps back to the model width and reuses the base model's frozen final norm and LM head, which saves one vocabulary
projection. exit_dim widens the residual blocks, and input_init="select" starts a widened head equal to the
narrow one.
Combining with other techniques¶
The drafter composes 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"),
RedrafterConfig(beam_length=5),
calibration=calibration,
decoding=economize.DecodeConfig(cycle_length=5),
)
Serving¶
economize's vLLM plugin runs the recurrence and the head as one draft round, and vLLM verifies a chain. SGLang has no recurrent beam-search proposer.
from economize.backends.vllm import serving
plan = serving.to_vllm(model, "out/qwen-redrafter", num_speculative_tokens=4)
llm = plan.llm()
Configuration¶
RedrafterConfig
dataclass
¶
RedrafterConfig(num_layers: int = 2, head: str = 'own', beam_width: int = 1, beam_length: int = 5, top_k: int = 50, exit_dim: int | None = None, input_init: str = 'default', param_dtype: str = 'float32')
Hyperparameters of the recurrent drafter (Cheng et al., 2024), by default the reference's.
After the exact pass the drafter reads the model's last hidden state h_t at the last processed token t.
A recurrent state starts at s_0 = 0 and takes the embedding of every token after t,
s_k = SiLU(W E[x_{t+k}] + U s_{k-1} + b) (token t + 1 is the exact pass's own, the later ones are drafts),
and the head drafts token t + k + 1 from [h_t; s_k]: an optional input projection to exit_dim,
num_layers residual blocks x + SiLU(A x + c) and a bias-free projection to the vocabulary.
With beam_width > 1 and a verifier that takes trees, a cycle runs beam search over the head (the reference's
drafting) and the verifier checks every beam at once as a tree of their distinct prefixes (the reference's
dynamic tree attention). Otherwise the head drafts a chain through the selector (the greedy beam at width 1).
With head="own" the head reads the post-norm hidden state and has its own vocabulary projection, as the
reference does (initialized to the model's LM head on h_t). With head="shared" it reads the pre-norm
state and ends in a linear map back to d (initialized to select h_t), and the model's frozen final norm
and LM head read its output, which saves 2 d V parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
num_layers |
int
|
Residual blocks of the head (reference: 2). |
head |
str
|
|
beam_width |
int
|
Beams of the beam search (reference evaluation: 45); |
beam_length |
int
|
Tokens per beam including the exact token |
top_k |
int
|
The reference's top-k warp of the head's logits before the softmax at inference ( |
exit_dim |
int | None
|
Width of the residual blocks (default |
input_init |
str
|
|
param_dtype |
str
|
Storage and compute dtype: |
References¶
- Cheng, Y., Zhang, A., Zhang, X., Wang, C., & Wang, Y. (2024). Recurrent drafter for fast speculative decoding in large language models (arXiv:2403.09919). arXiv. https://doi.org/10.48550/arXiv.2403.09919