Skip to content

Quest

At a glance

Quest: every decoding query reads only the KV-cache pages whose keys can score high.

Registered name Family Saves Lossless Trainable Configuration
quest sparse-decode latency no no QuestConfig

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

Quest (Tang et al., 2024) speeds up the attention of decoding steps over long contexts without discarding any KV-cache entry. The cache is split into pages of page_size consecutive slots, and every page stores the channel-wise minimum and maximum of its keys. A decoding query bounds the largest score any key of a page can reach, by taking per channel the larger of the products with the minimum and the maximum, and attends only to the pages with the highest bounds. Which entries matter depends on the query, so the selection is made anew at every step and in every layer, and an entry that one step skips stays available to the next.

economize reads token_budget // page_size - 1 committed pages per query plus the page of the token being decoded. Prompts, queries longer than max_queries tokens and the first dense_layers layers attend densely, as in the reference. The cache keeps every entry and adds the page bounds, so Quest saves the bytes attention reads and not the memory the cache holds. It is lossy and trains nothing.

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 selected pages are read by economize's attention kernel. economize.attention.install() registers it with transformers, and the model selects it by name, at load time with attn_implementation="economize" or afterwards:

import economize.attention

economize.attention.install()
base.set_attn_implementation("economize")

A long prompt and the plain model's greedy output on it as the reference:

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()

Three token budgets, in pages of 16 slots:

from economize.techniques.quest import QuestConfig

for budget in (256, 512, 1024):
    model = economize.apply(base, QuestConfig(page_size=16, token_budget=budget))
    result = model.decode(prompt[0], 64)
    stats = model.techniques["quest"].cost_summary(result)
    agreement = (result.tokens == reference).float().mean().item()
    print(budget, stats["kv_bytes_read"], stats["kv_bytes_read_full"], stats["kv_compression"], agreement)
    model.detach()

kv_bytes_read sums the K/V bytes and page bounds that the exact passes read, and kv_bytes_read_full the bytes a dense cache would read. kv_compression compares the bytes held, which the bounds make slightly larger than a dense cache, so it is a little below 1. The agreement is the fraction of the 64 tokens that equal the plain model's. The paper evaluates budgets from 256 to 4096 tokens on contexts of 32k tokens.

On a GPU the kernel loads only the selected pages. On a CPU, and on any other fallback, the attention runs under sdpa with the pages that were not selected hidden in the mask, so the tokens equal the kernel's up to rounding.

Attention implementation

The pages reach the kernel attached to the key tensor, which sdpa and eager cannot read. Quest checks the implementation when it is applied:

base.set_attn_implementation("sdpa")
try:
    economize.apply(base, QuestConfig())
except economize.IncompatibleTechniquesError as error:
    print(error)
base.set_attn_implementation("economize")

Decoding options

max_queries=1 restricts only single decoding queries, so the verification passes of speculative decoding, which hold several queries per row, attend densely and the drafts are verified against the dense cache. layers limits Quest to some layers (1-indexed). Sliding-window layers are left dense unless include_sliding=True, since their window is usually shorter than the budget.

Combining with other techniques

Quest reads the stored entries of kv_fp8 and kv_fp8_fused, so it composes with them, and with MInference, which changes only the prefill. Its page summaries index the logical slots of the dense cache, so it refuses the caches that store the entries elsewhere: the packed codes of kivi and kivi_fused and the compacted entries of kv_evict, kv_evict_fused and DuoAttention.

from economize.core.compatibility import incompatibility
from economize.techniques.kv_evict import KVEvictConfig
from economize.techniques.kv_kivi_fused import FusedKIVIConfig

print(economize.compatible(QuestConfig(), KVEvictConfig(method="streaming")))   # False
print(incompatibility(QuestConfig(), FusedKIVIConfig()))

Serving

The serving engines read every page of a request and keep no per-page key bounds, so Quest runs in transformers only:

print(economize.backend_support("quest")["vllm"].detail)

Configuration

QuestConfig dataclass

QuestConfig(page_size: int = 16, token_budget: int = 2048, dense_layers: int = 2, max_queries: int = 1, layers: tuple[int, ...] = (), include_sliding: bool = False)

Quest: query-aware selection of cache pages at decode time.

Attributes:

Name Type Description
page_size int

Slots per page (a power of two, at least 16; 16 as in the reference).

token_budget int

Cache entries every decoding query reads, the running page included: it reads token_budget // page_size - 1 committed pages and the page of its own token. The paper evaluates budgets from 256 to 4096 on 32k-token contexts.

dense_layers int

The first cache layers that attend densely (2 as in the reference, whose first two layers have no page structure).

max_queries int

Longest query (tokens per row) that is restricted to the pages; longer ones, prompts among them, attend densely. 1 as in the reference, which selects for single decoding queries.

layers tuple[int, ...]

1-indexed layers Quest acts on (empty: every layer); dense_layers, sliding-window and KV-sharing layers are left out in any case.

include_sliding bool

Also restrict sliding-window and chunked layers (the reference has none; their window is usually shorter than the budget).

pages property

pages: int

Committed pages a decoding query reads (the reference's page budget minus the running page).

References

  • Tang, J., Zhao, Y., Zhu, K., Xiao, G., Kasikci, B., & Han, S. (2024). Quest: Query-aware sparsity for efficient long-context LLM inference. In International Conference on Machine Learning. https://doi.org/10.48550/arXiv.2406.10774