InferenceAI

Enter at least two characters to search.

Start free

Append to a KV Cache

mediumInference20 min25 XP

A decoder receives one new key vector and one new value vector per token. Implement append_kv_cache(keys, values, new_key, new_value, max_tokens). Return [updated_keys, updated_values]. Append the new pair, then retain only the newest max_tokens pairs. If max_tokens <= 0, return [[], []]. The two input caches have equal length. Do not mutate either input list. This models a sliding-window cache, where old positions are evicted together.

Explore the underlying concept with illustrative inputs. This experiment is separate from the problem’s test cases.

INTERACTIVE ENGINEERING · TEACHING MODEL

KV caching

Decode tokens while keeping keys and values aligned in a bounded window.

Retained token positions

Token 1K1V1
EmptyKV
EmptyKV
EmptyKV
Retained pairs1
Evicted pairs0

Dense example: 1 request × 1 tokens × 32 layers × 8 KV heads × 128 dimensions × 2 bytes × 2 (K and V) = 0.125 MiB.

Change the experiment

Core calculation
keys = (keys + [new_key])[-capacity:]
values = (values + [new_value])[-capacity:]
Try it yourself

Set a capacity of two and decode five tokens. Which pairs remain, and how many were evicted?

1 tokens decoded. 1 cached pairs; 0 evicted.

Cached keys and values avoid recomputing their projections for earlier tokens. Attention still reads the retained cache.

Playback pauses in hidden tabs and offscreen. With reduced motion enabled, use the timeline or Next step.

Open the full explainer and practice links

Examples

EXAMPLE WALKTHROUGHevict oldest pair

A guided view of the published example, not a trace of your code.

INPUT[[[1],[2]],[[10],[20]],[3],[30],2]
TASKappend_kv_cache()
EXPECTED OUTPUT[[[2],[3]],[[20],[30]]]

Start with the input values shown in this example.

Example 1 of 2

Input: keys = [[1],[2]], values = [[10],[20]], new_key = [3], new_value = [30], max_tokens = 2

Output: [[[2],[3]],[[20],[30]]]

Explanation: evict oldest pair

Input: keys = [], values = [], new_key = [1,2], new_value = [3,4], max_tokens = 3

Output: [[[1,2]],[[3,4]]]

Explanation: first token

Hint 1

Append to copies so callers retain their original caches.

Hint 2

Slice both lists using the same token limit.

Topics

PythonKV CacheAttentionInference