Prefix Caching and Prompt Reuse : How to Reduce the Cost of AI Queries

Prefix Caching and Prompt Reuse : How to Reduce the Cost of AI Queries
3 min read

Prefix caching involves storing the KV cache (the key and value tensors computed for each token, i.e., each unit of text processed by the model) for a given prefix, then reusing it when a subsequent query begins with the same prefix under a compatible model configuration. This technique reduces the repeated prefill work, but it does not reduce the cost of generating new output tokens.

Reusing prefill work

During prefill, each model layer calculates the keys and values for each token in the prompt. If a subsequent query shares the first P tokens, these tensors can be reused, because causal attention prevents these first P positions from depending on subsequent tokens.

Matching is based on token IDs, not on similar-looking text. Spaces, capitalization, conversation templates, tool order, or tokenizer version can change the token sequence. Therefore, two prompts with the same meaning do not share cache state if their encoded prefixes do not match.

Take two prompts composed of the same system instructions, the same tool definitions, and the same document A, followed by two different questions. The first three parts can be reused if they are tokenized identically, and only the differing question requires new prefill. However, the reused cache occupies memory: the system thus trades cache capacity for a reduced time to first token and a higher prefill throughput.

Prefix caching is distinct from response caching, which returns a previously produced answer. Prefix caching reuses the model’s internal state, and the model continues to process the uncovered part of the prompt as well as the generated output.

Finding the longest cached prefix

The article presents a pedagogical cache, deliberately simple, which associates full token prefixes with cache handles. For a new query, the longest_match method searches for the longest prefix already stored. In the example, tokens 10,20,30 and 40 are found, and only tokens 50 and 60 need to be prefilled.

Production systems, however, use block hashes, tries, radix trees, or other indexes, and store the actual KV blocks layer by layer, along with reference counters and compatibility metadata. A block cache can only reuse complete blocks: with 16-token blocks, a match of 47 tokens provides only 32 reusable tokens, unless the engine manages a finer matching unit.

Compatibility and safety of reuse

Token matching is not enough. The cache identity must incorporate the model architecture, checkpoint revision, LoRA adapter, tokenizer and conversation model version, position and attention configuration, data type or KV cache quantization, as well as multimodal embeddings associated with the prefix. Random sampling parameters do not affect the prompt’s KV values, but model-side randomness must be disabled for common inference.

Position-sensitive models require the prefix to occupy the same positions: reusing a sequence from position 1,000 at position zero is generally not valid. Shared services must also plan for isolation, because a prefix preceded by another query could reveal its existence. Cache namespaces or per-query salts can limit reuse to an authorized trusted group.

Designing prompts for reuse

It is recommended to place stable content before content specific to each query: system prompt, tool definitions, examples, or shared document, then the user’s question. A timestamp, request ID, or username placed at the beginning breaks the match for everything that follows.

The article illustrates this principle with vLLM, by enabling enable_prefix_caching=True on the facebook/opt-125m model. Two questions share the same returns policy text. The first request should report zero tokens from cache, while the second should display a non-zero number, which may be less than the full prefix since only complete blocks are reused. The author notes that processing time can vary, and a performance measurement should distinguish between cold and hot caches.

Finally, the token-level hit rate is considered more informative than the request-level hit rate. A request that finds 4,000 out of 4,100 tokens and another that finds only 16 out of 4,100 both count as hits, but they do not save the same amount of work. Prefix caching does not significantly improve workloads dominated by long generated responses, nor prompts that share no exact prefix.

S’abonner
Notification pour
guest

0 Commentaires
Le plus ancien
Le plus récent Le plus populaire
0
Nous aimerions avoir votre avis, veuillez laisser un commentaire.x