FR-Spec¶
At a glance
FR-Spec: the drafts of another drafter restricted to a frequent-token vocabulary.
| Registered name | Family | Saves | Lossless | Trainable | Configuration |
|---|---|---|---|---|---|
frspec |
drafting | latency | yes | inner | FRSpecConfig |
Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: real · trtllm: no · vllm: real
FR-Spec (Zhao et al., 2025) restricts the drafts of another drafter to a vocabulary of frequent tokens. Models with
large vocabularies spend a large share of a small drafter's cost in its LM head, while most accepted drafts come from
a small set of common tokens. FR-Spec ranks the token ids by their frequency in a corpus, and the drafter proposes
only among the K most frequent ones. The base model verifies with its full vocabulary, so greedy decoding stays
lossless, and a token outside the draft vocabulary is still emitted by verification when the drafter misses it.
In economize, frspec wraps any chain drafter. When the inner drafter can restrict its LM head (early exit and the
vendor MTP modules can), its draft steps compute the logits of the K draft ids only. Otherwise its full logits are
masked to -inf outside the draft ids, which gives the same drafts without the saving in the head.
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¶
drafter names the wrapped drafter and vocab_size the number of draft ids. With no ids given, economize counts
the tokens of the calibration data passed to economize.apply and keeps the most frequent ones:
from economize.techniques.eagle import EagleConfig
from economize.techniques.frspec import FRSpecConfig
config = FRSpecConfig(drafter=EagleConfig(), vocab_size=32768)
model = economize.apply(base, config, calibration=calibration, 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
The new EAGLE head drafts poorly until it is trained, and the output is the base model's greedy output either way.
frequency_order gives the same ranking (ties keep the smaller id first), so the ids can also be passed as
token_ids, most frequent first:
from economize.techniques.frspec import frequency_order
draft_ids = frequency_order(calibration, base.config.vocab_size)[:32768].tolist()
model.detach()
model = economize.apply(base, FRSpecConfig(drafter=EagleConfig(), vocab_size=32768, token_ids=draft_ids),
decoding=economize.DecodeConfig(cycle_length=6))
The paper counts the frequencies on SlimPajama-627B, and the acceptance depends on how close the counting corpus
is to the prompts. The authors publish their vocabularies (freq_<K>.pt) with their drafters, and read_token_ids
reads them. The Qwen2 lists fit Qwen2.5, which uses the same tokenizer. These lists are sorted by id, so they fix
the vocabulary but give no ranking, and a truncated list is not the most frequent ids:
from huggingface_hub import hf_hub_download
from economize.techniques.frspec import read_token_ids
published = read_token_ids(hf_hub_download("thunlp/Qwen2-7B-Instruct-FR-Spec", "freq_32768.pt"))
model.detach()
model = economize.apply(base, FRSpecConfig(drafter=EagleConfig(), vocab_size=len(published), token_ids=published),
decoding=economize.DecodeConfig(cycle_length=6))
An early-exit drafter reads the base model's own LM head, which FR-Spec slices to the draft rows:
from economize.techniques.early_exit import EarlyExitConfig
model.detach()
model = economize.apply(base, FRSpecConfig(drafter=EarlyExitConfig(exit_layer=12), vocab_size=32768),
calibration=calibration, decoding=economize.DecodeConfig(cycle_length=4))
model.decode(ids[0], 64)
Training¶
FR-Spec trains nothing, and fit on the wrapper raises a ConfigError. The inner drafter is trained on its own,
with its own objective, and its weights are loaded into the wrapper's inner afterwards:
from economize.train import fit
model.detach()
model = economize.apply(base, EagleConfig())
fit(model, "train.bin", steps=2000, batch_size=8, seq_len=1024, output_dir="runs/eagle")
weights = model.techniques["eagle"].state_dict()
model.detach()
model = economize.apply(base, FRSpecConfig(drafter=EagleConfig(), vocab_size=32768), calibration=calibration,
decoding=economize.DecodeConfig(cycle_length=6))
model.techniques["frspec"].inner.load_state_dict(weights)
Saving and loading¶
The checkpoint holds the draft ids and the inner drafter's parameters, so loading needs no calibration data:
model.save_pretrained("frspec_eagle")
model.detach()
model = economize.load(base, "frspec_eagle", decoding=economize.DecodeConfig(cycle_length=6))
Decoding options¶
Sampling stays lossless with the rejection verifier. The draft distribution is the inner drafter's distribution
renormalized over the draft ids:
sampling = economize.DecodeConfig(cycle_length=6, verifier="rejection")
sampled = model.generate(ids, max_new_tokens=64, do_sample=True, temperature=0.7, top_p=0.9, decoding=sampling)
FR-Spec restricts chain drafts only, and an inner drafter that drafts trees raises ConfigError.
Combining with other techniques¶
FR-Spec composes with techniques on the base model that are not drafters, such as KIVIConfig(bits=4). Prompt
lookup drafts without logits and is refused as the inner drafter. To combine the two, FR-Spec goes inside the
hybrid's fallback, so that the copied tokens keep the full vocabulary:
from economize.techniques.hybrid import HybridConfig
model.detach()
model = economize.apply(base, HybridConfig(fallback=FRSpecConfig(drafter=EagleConfig(), vocab_size=32768)),
calibration=calibration, decoding=economize.DecodeConfig(cycle_length=6))
model.decode(ids[0], 64)
Serving¶
vLLM and SGLang serve FR-Spec around an EAGLE-3 head (economize.backend_support("frspec") lists every backend):
from economize.backends.vllm import serving
from economize.techniques.eagle3 import Eagle3Config
model.detach()
model = economize.apply(base, FRSpecConfig(drafter=Eagle3Config(), vocab_size=32768), calibration=calibration)
plan = serving.to_vllm(model, "out/qwen-frspec", num_speculative_tokens=5)
llm = plan.llm()
Configuration¶
FRSpecConfig
dataclass
¶
FRSpecConfig(drafter: TechniqueConfig, vocab_size: int, token_ids: tuple[int, ...] | None = None)
Frequency-ranked draft vocabulary (FR-Spec, Zhao et al., 2025) around another drafter.
The inner drafter proposes the argmax (or a sample) of its logits restricted to vocab_size token ids;
verification keeps the model's full head, so decoding stays lossless. The ids are, in this order of precedence,
token_ids, a saved state, or the vocab_size most frequent tokens of the calibration data passed to
:func:economize.apply (calibration=), counted with :func:~economize.techniques.frspec.frequency_order.
Attributes:
| Name | Type | Description |
|---|---|---|
drafter |
TechniqueConfig
|
Configuration of the wrapped drafting technique (e.g. an |
vocab_size |
int
|
Number of draft token ids |
token_ids |
tuple[int, ...] | None
|
The draft ids, most frequent first ( |
References¶
- Zhao, W., Pan, T., Han, X., Zhang, Y., Sun, A., Huang, Y., Zhang, K., Zhao, W., Li, Y., Wang, J., Liu, Z., & Sun, M. (2025). FR-Spec: Accelerating large-vocabulary language models via frequency-ranked speculative sampling (arXiv:2502.14856). arXiv. https://doi.org/10.48550/arXiv.2502.14856