Skip to content

REST

At a glance

REST: drafts retrieved from a datastore of text by the context's longest matching suffix.

Registered name Family Saves Lossless Trainable Configuration
rest drafting latency yes no RestConfig

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

REST (He et al., 2024) drafts by retrieval from a datastore of text. At every cycle it searches the datastore for the last n committed tokens of a row, for n = max_span, ..., min_span, and uses the longest suffix that occurs. The max_depth tokens that follow each of up to max_occurrences occurrences are merged into a trie in which every node counts the continuations through it. The tree_size most frequent nodes form a draft tree, which the model verifies in one forward pass with tree attention, keeping the longest path it agrees with. Greedy decoding is lossless. No model layer runs while drafting, so the cost of a draft is the extra positions of the verification pass plus a lookup in the datastore. The technique has no parameters and needs no training. Its acceptance depends on how close the datastore is to the text being generated: the paper builds it from code for code generation and from chat transcripts for chat.

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)

Building a datastore

The datastore is a SuffixIndex, a suffix array over token records, saved as a folder. Here every GSM8K training example except the first (the prompt's own question) becomes one record:

from economize.techniques.retrieval import SuffixIndex

records = [tokenizer(t + tokenizer.eos_token).input_ids for t in texts[1:]]
SuffixIndex.build(records, depth=64).save("gsm8k_store")
print(SuffixIndex.load("gsm8k_store").num_records)

depth is the number of leading tokens on which the suffix order is exact. A search pattern plus its continuation must fit in it, so max_span + max_depth must not exceed it. The command-line builder indexes a token file such as train.bin directly. --spans names an [R, 2] array of record boundaries, and without it the whole file is one record:

python -m economize.techniques.retrieval build gsm8k_store --tokens train.bin --dtype uint32 --depth 64
python -m economize.techniques.retrieval info gsm8k_store

Quick start

The defaults are the paper's: suffixes of 16 down to 2 tokens, at most 5000 occurrences, continuations of 10 tokens and trees of 64 nodes. cycle_length=11 lets a path of 10 drafted tokens be accepted whole:

from economize.techniques.rest import RestConfig

model = economize.apply(base, RestConfig(datastore="gsm8k_store"), decoding=economize.DecodeConfig(cycle_length=11))

result = model.decode(ids[0], 64)
print(tokenizer.decode(result.tokens))
print(result.mean_accepted)            # accepted drafts per verification
print(result.cost_summary())           # model calls and the positions they ran

The output is the model's greedy output token for token.

Decoding options

tree=False drafts only the trie's most frequent path as a chain, which needs no tree attention and suits small batches. tree_size sets the width of a tree draft, and max_depth its depth. When a common suffix occurs more than max_occurrences times, occurrences="first" reads the first ones in suffix-array order, as the reference draftretriever library does, while "spread" reads evenly spaced ones:

model.detach()
model = economize.apply(base, RestConfig(datastore="gsm8k_store", tree=False, max_depth=8, occurrences="spread"),
                        decoding=economize.DecodeConfig(cycle_length=9))
result = model.decode(ids[0], 64)

The drafts are deterministic, so the rejection verifier treats them as point masses and stays lossless at a temperature above zero:

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

Combining with other techniques

REST is a drafter, so it does not combine with a second drafter. It composes with techniques that change the cache or the model, such as KV-cache quantization:

from economize.techniques.kv_quant.kivi import KIVIConfig

print(economize.compatible(RestConfig(datastore="gsm8k_store"), KIVIConfig(bits=4)))  # True

model.detach()
model = economize.apply(base, KIVIConfig(bits=4), RestConfig(datastore="gsm8k_store"),
                        decoding=economize.DecodeConfig(cycle_length=11))
result = model.decode(ids[0], 64)

Serving

vLLM serves REST through economize's custom proposer. vLLM has no tree verification, so it verifies the best path of the trie as one chain:

from economize.backends.vllm import serving

model.detach()
model = economize.apply(base, RestConfig(datastore="gsm8k_store"))
plan = serving.to_vllm(model, "out/qwen-rest", num_speculative_tokens=10)
llm = plan.llm()

Configuration

RestConfig dataclass

RestConfig(datastore: str, max_span: int = 16, min_span: int = 2, max_occurrences: int = 5000, max_depth: int = 10, tree: bool = True, tree_size: int = 64, occurrences: OccurrenceRule = 'first')

Hyperparameters of REST (He et al., 2024, "REST: Retrieval-Based Speculative Decoding").

Every cycle, the last n committed tokens of a row are searched in the datastore for n = max_span, ..., min_span, longest first, and the first n with an occurrence is used. The max_depth tokens that follow each of up to max_occurrences occurrences (within one datastore record) form a trie in which every node counts the continuations through it. The tree_size most frequent nodes (a prefix-closed subtree; ties go to the shallower node, then to the lower token) are the tree draft, which the verifier checks in one exact pass. In chain mode the draft is the trie's most frequent path (at every node the child with the largest count). A row without any occurrence drafts nothing in that cycle.

The defaults are the paper's (and its draftretriever library's): spans 16 down to 2, k = 5000 occurrences, continuations of 10 tokens and draft trees of 64 nodes. A tree path never exceeds the cycle's budget, so cycle_length = max_depth + 1 lets every path be accepted whole.

Attributes:

Name Type Description
datastore str

Folder of the :class:~economize.techniques.retrieval.SuffixIndex of the datastore (build it with python -m economize.techniques.retrieval build).

max_span int

Longest suffix of the context that is searched.

min_span int

Shortest suffix of the context that is searched.

max_occurrences int

Most occurrences whose continuations enter the trie (the paper's k).

max_depth int

Most tokens of every continuation (the trie's depth, draftretriever's long).

tree bool

Draft the trie's top nodes as a tree (with a verifier that verifies trees); otherwise the most frequent path as a chain.

tree_size int

Most nodes of a tree draft (the paper's 64 "choices").

occurrences OccurrenceRule

Which occurrences are read when there are more than max_occurrences: "first" (the first ones in suffix-array order, as draftretriever) or "spread" (evenly spaced over all of them).

References

  • He, Z., Zhong, Z., Cai, T., Lee, J. D., & He, D. (2024). REST: Retrieval-based speculative decoding. In Conference of the North American Chapter of the Association for Computational Linguistics. https://doi.org/10.48550/arXiv.2311.08252