TriForce¶
At a glance
TriForce: the base model drafts on the prompt chunks its query attends to.
| Registered name | Family | Saves | Lossless | Trainable | Configuration |
|---|---|---|---|---|---|
triforce |
drafting | latency | yes | no | TriForceConfig |
Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: no · trtllm: no · vllm: no
TriForce (Sun et al., 2024) is self-speculative decoding for long prompts with a retrieval view of the KV cache. The
prompt part of the cache is cut into chunks of chunk_size slots, and the drafter, the base model itself, reads only
the first chunk and the chunks whose mean key best matches the current query, budget slots in all, plus the slots
after the last whole chunk and every generated position. With a long prompt the KV reads dominate a decoding step,
so the drafter is cheap, and since it keeps every weight it agrees with the model on most tokens. Every cycle's exact
pass reads the whole cache, so greedy decoding is lossless. Nothing is trained.
In economize the chunks are chosen per KV head of every full-attention layer. With grouped-query attention the scores of the query heads of a group are summed, so the heads that share a KV head also share its chunks. The selection is made once per generation, in the first draft step, which runs on the whole cache. Its chunks go into persistent buffers that the later draft steps and their CUDA graphs read. Each later draft layer gathers its chosen chunks and the generation's tail (the slots from the end of the last whole prompt chunk to the end of the cache) from the shared cache and attends over them alone, so its attention FLOPs and KV reads do not grow with the prompt. Layers with a sliding window, chunked or recurrent attention run unchanged. Long-context drafting compares the view with MagicDec's.
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¶
The drafter pays off once the prompt is much longer than budget. Twenty GSM8K solutions before the question make a
prompt of a few thousand tokens, and the plain model's greedy output on it is the reference:
from economize.techniques.sparse_kv_draft import TriForceConfig
text = "\n\n".join(texts[:20]) + "\n\n" + tokenizer.decode(ids[0]) + "\n"
prompt = tokenizer(text, return_tensors="pt").input_ids.cuda()
plain = economize.apply(base)
reference = plain.decode(prompt[0], 64).tokens
plain.detach()
model = economize.apply(base, TriForceConfig(budget=1024, chunk_size=64),
decoding=economize.DecodeConfig(cycle_length=5))
triforce = model.techniques["triforce"]
print(triforce.config.select_sets) # chunks kept per KV head
result = model.decode(prompt[0], 64)
print((result.tokens == reference).float().mean().item()) # agreement with the plain model
print(result.mean_accepted) # accepted drafts per verification
The default budget=4096 suits prompts of tens of thousands of tokens. A budget at or above the prompt length keeps
every chunk, and the draft then equals the exact model.
Attention implementations¶
TriForce records its selection from the arguments of scaled_dot_product_attention, so it runs on sdpa and on
economize attention and refuses eager:
model.detach()
base.set_attn_implementation("eager")
try:
economize.apply(base, TriForceConfig(budget=1024, chunk_size=64))
except economize.ConfigError as error:
print(error)
base.set_attn_implementation("sdpa")
The gathered view¶
A draft layer after the selection attends over budget chunk entries plus the tail per KV head, gathered from the
cache together with the matching columns of the attention mask, and simulation() returns None. The tail holds the
rest of the prompt after its last whole chunk, the generated positions and the slack of the cache: the cache ends at
the generation's capacity (the longest prompt plus the new tokens and one cycle, rounded up by a graphed decoder), so
the tail's width is about the number of new tokens plus the spread of the batch's prompt lengths. It is rounded up to
a multiple of 64 slots, adding fewer than 64 or a quarter of its width, so that similar generations share CUDA
graphs. The selection step pays one host synchronization to fix that width.
When the chunks and the tail would be no fewer entries than the whole cache (a short prompt), or when a row of the batch is not valid at the selection, the draft layers read the whole cache with the entries outside the chunks and the tail hidden in the mask. They draft the same tokens, read no more than the gathered view would and claim no saving. DeepSeek's multi-head latent attention caches one latent per position for all heads, so each KV head cannot read its own chunks, and TriForce refuses such a model when it is applied (MagicDec, whose view is the same for every head, serves it).
Decoding options¶
cuda_graphs=True replays the draft steps after the selection from CUDA graphs. The drafts come with the model's own
distributions, so sampling with the rejection verifier follows the base model's distribution, and the tree policies
of tree search work as with any other self-drafter:
sampling = economize.DecodeConfig(cycle_length=5, verifier="rejection")
sampled = model.generate(prompt, max_new_tokens=64, do_sample=True, temperature=0.7, top_p=0.9, decoding=sampling)
tree = model.decode(prompt[0], 64, decoding=economize.DecodeConfig(cycle_length=5, draft_policy="dynamic_tree"))
TriForce composes with the same techniques as MagicDec, such as kivi or quant, and refuses other drafters.
Differences from the official code¶
- TriForce is a hierarchy: a small draft model drafts for the retrieval-cache drafter, which drafts for the base model. economize builds the retrieval-cache level only.
- The official code scores the chunks with the query of the first decoding step after the prompt and rescores at every later exact step. economize scores once per generation, with the query of the first generated token.
- The official code keeps a separate compacted cache and appends generated tokens to it. economize gathers the chosen chunks and the tail from the shared cache in every draft layer, which reads as many entries without a second cache, so the drafter saves no memory.
Serving¶
vLLM and SGLang do not serve the drafter, since no proposer hook of theirs runs the base model over a sparse view of
its paged cache. economize.backend_support("triforce") gives the reason per backend.
Configuration¶
TriForceConfig
dataclass
¶
TriForceConfig(budget: int = 4096, chunk_size: int = 64, view: str = 'gathered')
Hyperparameters of the TriForce retrieval self-drafter (Sun et al., 2024, arXiv 2404.11912).
The prompt part of each full-attention layer's cache is cut into chunks of chunk_size slots. Once per
generation, the first draft step runs densely and scores every chunk by the dot product of the step's query with
the chunk's mean key. The first chunk and the budget // chunk_size - 1 best others are kept, per KV head;
the slots after the last whole chunk of the prompt and every generated position are always kept. Later draft
steps attend to the kept slots only. The exact pass reads the whole cache, so decoding stays lossless.
Attributes:
| Name | Type | Description |
|---|---|---|
budget |
int
|
Prompt slots one draft query reads per KV head in a full-attention layer, besides the always-kept
tail ( |
chunk_size |
int
|
Slots per retrieval chunk. |
view |
str
|
How a full-attention layer reads the selection (:data: |
References¶
- Sun, H., Chen, Z., Yang, X., Tian, Y., & Chen, B. (2024). TriForce: Lossless acceleration of long sequence generation with hierarchical speculative decoding. In Conference on Language Modeling. https://doi.org/10.48550/arXiv.2404.11912