KnapSpec¶
At a glance
KnapSpec (Cha et al., ICML 2026): self-speculative drafting with an adaptive set of skipped sublayers.
| Registered name | Family | Saves | Lossless | Trainable | Configuration |
|---|---|---|---|---|---|
knapspec |
drafting | latency | yes | no | KnapSpecConfig |
Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: no · trtllm: no · vllm: real
KnapSpec (Cha et al., 2026) is a training-free self-drafter that skips sublayers of the model. A draft step runs the
model with the attention of some layers and the MLP of others left out, and reads the next token from the model's
own norm and LM head. Every interval decoded tokens the drafter chooses a new skip set and draft length from the
hidden states of its recent exact passes. A dynamic program over the 2 L sublayers, each weighted by its measured
latency, keeps for every latency budget the skip set whose output is closest (in cosine similarity) to the full
model's, and the pair of skip set and draft length with the highest modelled tokens per unit time wins. Attention
latency is fitted as a linear function of the context length, so the choice shifts toward skipping attention as the
context grows. The model verifies every draft, so greedy decoding is lossless, and nothing is trained.
economize follows the paper's defaults. Two details the paper leaves open are fixed as follows: the first search
reads the last prompt_tokens tokens of the prompt, and every candidate skip set attends over the full model's
keys and values of earlier positions. KnapSpec runs on attention-only models and refuses models with recurrent
layers.
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)
Quick start¶
The paper's confidence exit at 0.7 is the decoder's min_confidence, and cycle_length=11 leaves room for its
largest draft length of 10. The paper searches every 64 tokens for models below 10B parameters:
from economize.techniques.knapspec import KnapSpecConfig
model = economize.apply(base, KnapSpecConfig(interval=64),
decoding=economize.DecodeConfig(cycle_length=11, min_confidence=0.7))
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, draft steps and layer-tokens of both
The current choice is the technique's plan: the layers whose attention and MLP a draft step skips, the draft
length, and the acceptance rate and similarity the search estimated:
plan = model.techniques["knapspec"].plan
print(sorted(plan.attention), sorted(plan.mlp), plan.draft_length, plan.acceptance, plan.similarity)
Latency measurement¶
By default the drafter times one attention and one MLP sublayer on the model's device the first time it drafts,
at the context lengths of calibration_lengths (capped by the cache size). Measured latencies can be passed
instead as (t_mlp, attention_slope, attention_base) in seconds, with t_attn(n) = attention_slope * n +
attention_base, which makes the search independent of the timing noise of a shared device:
model.detach()
model = economize.apply(base, KnapSpecConfig(interval=64, latency=(2e-4, 1e-8, 1e-4)),
decoding=economize.DecodeConfig(cycle_length=11, min_confidence=0.7))
result = model.decode(ids[0], 64)
min_similarity prunes candidates below a cosine similarity (0.5), max_skip_fraction caps the skipped share of
the latency (0.5), history sets how many recent exact passes the search reads, and keep_first and keep_last
protect the outermost layers, which the paper does not.
Saving and loading¶
The checkpoint holds the configuration only. The skip set depends on the context and is searched again while decoding:
model.save_pretrained("knapspec")
model.detach()
model = economize.load(base, "knapspec", decoding=economize.DecodeConfig(cycle_length=11, min_confidence=0.7))
Decoding options¶
Sampling stays lossless with the rejection verifier:
sampling = economize.DecodeConfig(cycle_length=11, min_confidence=0.7, verifier="rejection")
sampled = model.generate(ids, max_new_tokens=64, do_sample=True, temperature=0.7, top_p=0.9, decoding=sampling)
DecodeConfig(cuda_graphs=True) records the draft steps as CUDA graphs on a GPU. The drafter keeps up to
max_graphs of them, one per skip set, each in a memory pool of its own, and drops the least recently used.
KnapSpec searches again at the start of every generation. A server that decodes many short requests can pass
KnapSpecConfig(reuse_plan=True), which keeps the skip set across generations and searches once every interval
decoded tokens in total.
Combining with other techniques¶
KnapSpec composes with techniques that are not drafters, for example a 4-bit KV cache:
from economize.techniques.kv_quant.kivi import KIVIConfig
print(economize.compatible("knapspec", "kivi")) # True
model.detach()
model = economize.apply(base, KIVIConfig(bits=4), KnapSpecConfig(interval=64),
decoding=economize.DecodeConfig(cycle_length=11, min_confidence=0.7))
Serving¶
economize's vLLM plugin serves the skip set that is current at export, without searching again during decoding. SGLang's draft model has a fixed layer list and no export for KnapSpec:
from economize.backends.vllm import serving
plan = serving.to_vllm(model, "out/qwen-knapspec", num_speculative_tokens=10)
llm = plan.llm()
Configuration¶
KnapSpecConfig
dataclass
¶
KnapSpecConfig(min_similarity: float = 0.5, history: int = 5, max_draft: int = 10, interval: int = 128, prompt_tokens: int = 16, max_skip_fraction: float = 0.5, keep_first: int = 0, keep_last: int = 0, latency: tuple[float, float, float] | None = None, calibration_lengths: tuple[int, ...] = (64, 512, 2048, 8192), calibration_repeats: int = 20, max_graphs: int = 8, reuse_plan: bool = False)
Hyperparameters of a KnapSpec self-drafter.
A draft step runs the model with the attention of some layers and the MLP of others skipped. Every
interval decoded tokens the drafter searches a new skip set and draft length on the hidden states of its
recent exact passes: a dynamic program over the 2 L sublayers and their skipped latency keeps, per budget,
the candidate closest (cosine) to the full model, and the pair of skip set and draft length with the highest
modelled tokens per unit time wins. The defaults are the paper's.
Attributes:
| Name | Type | Description |
|---|---|---|
min_similarity |
float
|
Candidates whose mean cosine similarity to the full model's state falls below it are
pruned (the paper's |
history |
int
|
Number of recent exact passes whose committed tokens the search runs on (the paper's |
max_draft |
int
|
Largest draft length the search may choose (the paper's |
interval |
int
|
Decoded tokens between two searches (the paper's |
prompt_tokens |
int
|
Most committed tokens of one exact pass the search reads: the prompt's tail for the first search (the paper does not say what the first search runs on), all of a later pass at the usual cycle lengths. |
max_skip_fraction |
float
|
Largest share of the model's latency weight a skip set may remove (the paper's
|
keep_first |
int
|
The first |
keep_last |
int
|
The last |
latency |
tuple[float, float, float] | None
|
Measured sublayer latencies |
calibration_lengths |
tuple[int, ...]
|
Context lengths of the latency measurement. |
calibration_repeats |
int
|
Timed calls per context length. |
max_graphs |
int
|
Skip sets whose draft steps the drafter keeps as CUDA graphs (the most recently used ones; each records into a memory pool of its own). |
reuse_plan |
bool
|
Keep the skip set across generations and search again only after |
candidates
¶
candidates(num_layers: int) -> tuple[int, ...]
Layers whose sublayers the search may skip.
References¶
- Cha, S., Kim, G., Han, D., Yang, T., & Han, I. (2026). KnapSpec: Self-speculative decoding via adaptive layer selection as a knapsack problem. In International Conference on Machine Learning. https://doi.org/10.48550/arXiv.2602.20217