Skip to content

Two-model speculative decoding

At a glance

Speculative decoding with a separate, smaller draft LM.

Registered name Family Saves Lossless Trainable Configuration
draft_model drafting latency yes no DraftModelConfig

Backends (default configuration): transformers: real · gguf: real · mlx: untested · onnx: no · sglang: real · trtllm: untested · vllm: real

Two-model speculative decoding (Leviathan et al., 2023; Chen et al., 2023) drafts with a separate, smaller causal LM of the same tokenizer. The draft LM proposes several tokens one after another, and the base model scores all of them in one forward pass and keeps the longest prefix it agrees with, plus one token of its own. Greedy decoding is lossless, and with the rejection verifier sampled outputs follow the base model's distribution. What is saved is the number of sequential forward passes of the base model, at the cost of the draft LM's steps.

In economize the draft LM keeps its own KV cache. At the start of every cycle it catches up, in one call, on the committed tokens it has not seen yet (the whole prompt in the first cycle), and this call also yields the first draft. Every further draft is one call. The draft LM is loaded from model whenever the technique attaches and is frozen, so its weights are not part of the economize checkpoint and the technique trains nothing. A draft LM can be distilled on the base model's distributions beforehand, as shown below.

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

A draft LM only pays off next to a much larger base model, so this page drafts for Qwen2.5-7B-Instruct with Qwen2.5-0.5B-Instruct. The Qwen2.5 models share one tokenizer, so the setup's tokenizer and ids serve both:

from economize.techniques.draft_model import DraftModelConfig

big = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-7B-Instruct", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(big, DraftModelConfig(model="Qwen/Qwen2.5-0.5B-Instruct", dtype="bfloat16"),
                        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())           # exact passes of the base model and calls of the draft LM

cycle_length=5 drafts four tokens per verification. The call log records the catch-up as draft_catchup and every draft step with the layer span of the draft LM, which is a span of the smaller model. dtype="auto" (the default) runs the draft LM in the base model's dtype.

When both tokenizers are available locally, attaching compares them and refuses a draft LM in which a shared token id stands for a different token. A draft vocabulary that is a strict prefix of the base model's gives a warning: the draft LM reads the ids beyond it as its last token, which stays lossless but drafts poorly after them.

Training

Agreement between the two models, and with it the number of accepted drafts, grows when the draft LM is distilled on the base model's next-token distributions (DistillSpec, Zhou et al., 2023). The logit_distill objective does this for a draft LM wrapped without techniques, with the base model as teacher_model:

from economize.train import fit
from economize.train.objectives import LogitDistill

draft = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct", dtype=torch.bfloat16, device_map="cuda")
fit(economize.apply(draft), "train.bin", LogitDistill(divergence="tvd"), teacher_model=big, steps=2000,
    batch_size=8, seq_len=1024, output_dir="runs/draft_distill")

model.detach()
model = economize.apply(big, DraftModelConfig(model="runs/draft_distill/final/base", dtype="bfloat16"),
                        decoding=economize.DecodeConfig(cycle_length=5))

The run writes the trained weights as a plain transformers model to runs/draft_distill/final/base/, which DraftModelConfig.model reads like a Hub id. The directory holds no tokenizer, so the tokenizer is saved next to the weights for the vocabulary check. divergence is one of kl, rkl, js, tvd and ce_top1. The paper also trains on text that the draft LM generates itself, while fit reads a fixed token file.

Saving and loading

The checkpoint holds the configuration only, and loading reads the draft LM again from model:

model.save_pretrained("two_model")
model.detach()

model = economize.load(big, "two_model", decoding=economize.DecodeConfig(cycle_length=5))

Decoding options

min_confidence ends a cycle early when the draft LM's top probability falls below the threshold. Sampling stays lossless with the rejection verifier:

model.decode(ids[0], 64, decoding=economize.DecodeConfig(cycle_length=8, min_confidence=0.5))

sampling = economize.DecodeConfig(cycle_length=5, verifier="rejection")
sampled = model.generate(ids, max_new_tokens=64, do_sample=True, temperature=0.7, top_p=0.9, decoding=sampling)

On a GPU, cuda_graphs=True records the draft steps and exact passes as CUDA graphs, which matters for timing since a draft step of a small LM is short.

Combining with other techniques

Weight and KV-cache techniques of the recipe apply to the base model only, for example int8 weights:

from economize.techniques.quant import QuantConfig

print(economize.compatible("draft_model", "quant"), economize.compatible("draft_model", "lookup"))  # True False

model.detach()
model = economize.apply(big, QuantConfig(format="int8"),
                        DraftModelConfig(model="Qwen/Qwen2.5-0.5B-Instruct", dtype="bfloat16"),
                        decoding=economize.DecodeConfig(cycle_length=5))

A draft LM that does not fit next to the base model runs on a second GPU with placed_draft_model.

Serving

The vLLM export serves the draft LM with vLLM's draft_model method and the SGLang export with its STANDALONE algorithm, each with the draft LM saved to the plan folder:

from economize.backends.vllm import serving

plan = serving.to_vllm(model, "out/qwen-draft-model", num_speculative_tokens=4)
llm = plan.llm()

llama.cpp (--model-draft), MLX (--draft-model) and TensorRT-LLM (draft-target speculation) run the pair natively from their exports, as described in Exports.

Configuration

DraftModelConfig dataclass

DraftModelConfig(model: str = '', revision: str | None = None, dtype: str = 'auto', attn_implementation: str = 'sdpa')

A smaller causal LM of the same tokenizer drafts for the model (Leviathan et al., 2023; Chen et al., 2023).

The draft LM keeps its own KV cache. Every cycle it first catches up on the committed tokens it has not seen (the token of the last exact pass, plus the last accepted draft after a fully accepted cycle; the prompt in the first cycle) in one call that also yields the first draft, then drafts one token per call.

Attributes:

Name Type Description
model str

Hugging Face model id or local directory of the draft LM. Its weights are not part of the economize checkpoint; they are loaded from here whenever the technique attaches.

revision str | None

Revision of model on the Hub.

dtype str

Compute dtype of the draft LM; "auto" uses the dtype of the base model.

attn_implementation str

Attention implementation the draft LM is loaded with.

References

  • Chen, C., Borgeaud, S., Irving, G., Lespiau, J.-B., Sifre, L., & Jumper, J. (2023). Accelerating large language model decoding with speculative sampling (arXiv:2302.01318). arXiv. https://doi.org/10.48550/arXiv.2302.01318
  • Leviathan, Y., Kalman, M., & Matias, Y. (2023). Fast inference from transformers via speculative decoding. In International Conference on Machine Learning. https://doi.org/10.48550/arXiv.2211.17192
  • Zhou, Y., Lyu, K., Rawat, A. S., Menon, A. K., Rostamizadeh, A., Kumar, S., Kagy, J.-F., & Agarwal, R. (2023). DistillSpec: Improving speculative decoding via knowledge distillation (arXiv:2310.08461). arXiv. https://doi.org/10.48550/arXiv.2310.08461