Skip to content

KV-Cache Prefix Sharing

Principle

In LLM applications, a common system prompt or prefix is often used for multiple requests. The KV-cache for this prefix is recalculated each time, wasting computational resources. Prefix sharing allows it to be calculated once and reused.

Implementation

  1. Prefix Calculation: The KV-cache for the common prefix is computed and saved.
  2. Identification: Requests are matched to the common prefix.
  3. Reuse: When processing a new request, the saved cache is used.
Approach Description
Static The prefix is fixed, the cache is precomputed
Dynamic The prefix is determined as it goes, the cache is saved in a tree
Hybrid A combination of static and dynamic

Benefits

  • Reduced time to first token (TTFT).
  • Decreased computational load.
  • Resource savings for mass requests with a common prefix.
# Pseudocode for cache reuse
if prefix in cache:
    kv = cache[prefix]
else:
    kv = compute_kv(prefix)
    cache[prefix] = kv
output = decode_with_kv(input_tokens, kv)

See also