This guide develops the mechanism in dependency order. It begins with the hardware and the deployed model, follows a request through tokenisation and transformer inference, then shows where a KV cache changes the execution path.
No prior knowledge of AI-serving infrastructure is assumed. Technical terms are introduced with their concrete role in the computation.
Working definition: a KV cache stores the key and value tensors previously computed by a transformer's attention layers. Later inference steps reuse those tensors instead of recomputing them for earlier token positions.
| Thing | What it contains | How long it usually lasts | Does a user request change it? |
|---|---|---|---|
| Model weights | Billions of learned numbers defining the model's behaviour | Months or years | No |
| KV cache | Temporary internal numbers for the tokens being processed | Seconds or minutes | Yes |
| Chat database | Messages saved by an application | Days or longer | Yes |
All three are sometimes described as “memory,” but they belong to different layers of the system and have different lifecycles.
A typical inference machine contains:
A physical machine can hold several GPUs. A model can also span GPUs in several networked machines. The five workers below are an example deployment topology, not a model requirement.
The five workers participate in one model instance. Depending on the parallelism strategy, each worker holds a shard of each layer or a subset of complete layers.
A GPU is a component. A machine is the larger computer holding CPUs, RAM, network interfaces, and perhaps several GPUs. Engineers sometimes say “five machines” when they mean a distributed cluster, and sometimes “five GPUs” inside one machine. KV-cache placement depends on the exact arrangement, but the logical idea is the same.
A deployed LLM has two main ingredients:
Training uses optimisation to update the weights so that the model assigns higher probability to appropriate next tokens. During ordinary inference, the server reads those weights but does not update them.
Weights are multidimensional arrays of numbers. Statistical regularities learned from training data are distributed across those arrays; there is no ordinary one-fact-to-one-file or one-fact-to-one-parameter mapping.
For scale, an 8-billion-parameter model has roughly eight billion learned values. If each value is stored in two bytes, the raw weights alone need about 16 GB, before temporary working memory and caches.
Before serving requests, the system reads model files from storage and places the weights into GPU memory. If the model does not fit on one GPU, it can be split.
Two common arrangements are:
There is also data parallelism, where several complete copies of a model serve different requests. That increases capacity, but does not help one oversized copy fit.
At this point the weights are loaded, but no particular user's KV cache exists yet.
Suppose the user sends:
The moon looks bright because
The server first uses a tokenizer to convert text into tokens—text fragments represented by integer IDs.
Illustrative tokenisation:
[The] [moon] [looks] [bright] [because]
41 902 811 77 216
Depending on the tokenizer, a token may be a word, part of a word, punctuation, or a leading-space-plus-word fragment. The model receives token IDs rather than characters or words.
Each token ID indexes a row in the model's embedding matrix. The selected row is a vector with the model's internal width; positional information is then incorporated so that identical tokens at different positions can be treated differently.
Then the representations pass through many transformer layers. A 32-layer model performs a version of the following process 32 times.
At one attention layer, each token representation is transformed into three vectors—three lists of numbers:
query = current representation × query weights
key = current representation × key weights
value = current representation × value weights
For layer input h at a particular token position, three learned matrix multiplications produce a query, key, and value. In multi-head attention, these vectors are then divided into attention heads.
The model compares a query with all available keys. Stronger matches give the corresponding values more influence.
attention output = weighted sum of source-position value vectors
attention weight = normalised query–key similarity score
Operationally, one attention head performs three steps:
In a causal language model, a position can attend only to itself and earlier positions. Adding token 5 therefore does not invalidate the keys and values already computed for positions 1–4. A KV cache retains those still-valid tensors for reuse.
The cache stores keys and values for every retained token position at every cache-using layer. It is not one key and one value for the whole sequence.
When producing the next token, the model needs the new position's query so it can look back at earlier keys and values. Old queries performed their job when their own positions were processed; they are not needed for this new lookup. That is why the familiar structure is a KV cache, not a QKV cache.
The first processing of the prompt is called prefill.
For our five-token prompt, the simplified pathway is:
Several important things happen during prefill:
Logits are not yet probabilities; a softmax operation turns them into probabilities. Temperature and other sampling settings can then affect which token is chosen.
Suppose the selected token is [it].
Now the model enters decode mode. Instead of processing the entire prompt again, it processes only the new token through the layers. At each attention layer:
Then the model selects the next token and repeats.
The interactive model below shows control flow and cache occupancy. It does not execute a neural network, and its token values are illustrative. The first mode follows generation within one request; the second shows prefix reuse across requests.
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>KV cache pathway explorer</title>
<style>
body { padding: 1rem; }
h1 { margin: 0 0 .35rem; font-size: 1.35rem; }
.lede { margin: 0 0 1rem; color: var(--sdoc-app-muted-color); }
.modebar, .nav { display: flex; gap: .5rem; flex-wrap: wrap; align-items: center; }
button { cursor: pointer; }
button.active { background: var(--sdoc-app-accent-color); color: white; border-color: var(--sdoc-app-accent-color); }
.step { margin: 1rem 0; padding: .85rem 1rem; border-left: 4px solid var(--sdoc-app-accent-color); background: var(--sdoc-app-surface); }
.step strong { display: block; margin-bottom: .25rem; }
.pipeline { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: .65rem; margin: 1rem 0; }
.lane { border: 1px solid var(--sdoc-app-border-color); border-radius: var(--sdoc-app-radius); padding: .75rem; min-height: 6.5rem; }
.lane.on { border-color: var(--sdoc-app-accent-color); box-shadow: inset 0 0 0 1px var(--sdoc-app-accent-color); }
.lane h2 { font-size: 1rem; margin: 0 0 .6rem; }
.tokens { display: flex; flex-wrap: wrap; gap: .3rem; }
.token { display: inline-block; border: 1px solid var(--sdoc-app-border-color); border-radius: .35rem; padding: .22rem .38rem; font-family: var(--sdoc-app-code-font-family); font-size: .82rem; background: var(--sdoc-app-background); }
.token.new { background: #dbeafe; border-color: #2563eb; color: #0f172a; }
.token.hit { background: #dcfce7; border-color: #16a34a; color: #052e16; }
.token.miss { background: #ffedd5; border-color: #ea580c; color: #431407; }
.cache { overflow-x: auto; margin: .75rem 0; }
table { width: 100%; border-collapse: collapse; font-size: .82rem; }
th, td { border: 1px solid var(--sdoc-app-border-color); padding: .35rem; text-align: center; white-space: nowrap; }
td.filled { background: #dbeafe; color: #0f172a; }
td.reused { background: #dcfce7; color: #052e16; }
.metrics { display: grid; grid-template-columns: repeat(4, minmax(0,1fr)); gap: .5rem; margin: .75rem 0 1rem; }
.metric { border-top: 2px solid var(--sdoc-app-border-color); padding-top: .45rem; }
.metric b { display: block; font-size: 1.15rem; }
.metric span { color: var(--sdoc-app-muted-color); font-size: .78rem; }
.note { color: var(--sdoc-app-muted-color); font-size: .84rem; }
@media (max-width: 700px) {
.pipeline { grid-template-columns: 1fr 1fr; }
.metrics { grid-template-columns: 1fr 1fr; }
}
@media (max-width: 430px) {
.pipeline, .metrics { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<h1>KV cache pathway explorer</h1>
<p class="lede">Blue = newly calculated. Green = reused from cache. Orange = recomputed after a mismatch.</p>
<div class="modebar" aria-label="Choose pathway">
<button id="within" class="active">Within one answer</button>
<button id="across">Across two requests</button>
</div>
<div class="step" aria-live="polite">
<strong id="stepTitle"></strong>
<span id="stepText"></span>
</div>
<div class="pipeline">
<section class="lane" id="requestLane"><h2>1 · Request</h2><div id="request"></div></section>
<section class="lane" id="serverLane"><h2>2 · Server</h2><div id="server"></div></section>
<section class="lane" id="modelLane"><h2>3 · Model workers</h2><div id="model"></div></section>
<section class="lane" id="outputLane"><h2>4 · Result</h2><div id="output"></div></section>
</div>
<h2>Representative per-layer KV cache</h2>
<p class="note">A real model has more layers, attention heads and vector dimensions. Each visible cell stands for a much larger pair of K and V tensors.</p>
<div class="cache" id="cache"></div>
<div class="metrics">
<div class="metric"><b id="newWork">0</b><span>token positions newly processed</span></div>
<div class="metric"><b id="reused">0</b><span>token positions reused</span></div>
<div class="metric"><b id="attention">0</b><span>past positions available to attention</span></div>
<div class="metric"><b id="weights">No</b><span>model weights changed</span></div>
</div>
<div class="nav">
<button id="prev">← Previous</button>
<button id="next">Next →</button>
<button id="reset">Reset</button>
<span class="note" id="counter"></span>
</div>
<script>
const withinSteps = [
{
title: 'The model is loaded; the request cache is empty',
text: 'The frozen weights are already divided across five workers. No K or V tensors exist for this request yet.',
request: ['The','moon','looks','bright','because'], server: 'Waiting to tokenize', model: 'Weights ready on 5 workers', output: 'Nothing yet',
filled: 0, reused: 0, fresh: 0, attention: 0, active: 'requestLane'
},
{
title: 'The server tokenizes the prompt',
text: 'Printed text becomes five token IDs. Tokenization is deterministic for a particular tokenizer.',
request: ['The','moon','looks','bright','because'], server: '5 token IDs queued for prefill', model: 'No forward pass yet', output: 'Nothing yet',
filled: 0, reused: 0, fresh: 0, attention: 0, active: 'serverLane'
},
{
title: 'Prefill processes all prompt positions',
text: 'At every layer, the model computes representations plus Q, K and V. K and V for all five positions are written to the request cache.',
request: ['The','moon','looks','bright','because'], server: 'Prefill batch: 5 positions', model: 'All 5 positions cross every layer', output: 'Next-token scores',
filled: 5, reused: 0, fresh: 5, attention: 5, active: 'modelLane'
},
{
title: 'The first output token is selected',
text: 'The final prompt position produces logits. A sampling rule selects “it”. The weights still have not changed.',
request: ['The','moon','looks','bright','because'], server: 'Sample from next-token probabilities', model: 'Prompt K/V retained', output: '[it]',
filled: 5, reused: 5, fresh: 0, attention: 5, active: 'outputLane'
},
{
title: 'Decode processes only the new token',
text: 'The token “it” crosses the model. Its query reads the earlier cached keys and values; its own K and V are appended.',
request: ['The','moon','looks','bright','because','it'], server: 'Decode step: 1 new position', model: '1 new K/V pair per layer; 5 old pairs reused', output: '[it] [reflects]',
filled: 6, reused: 5, fresh: 1, attention: 6, active: 'modelLane'
},
{
title: 'The loop repeats one token at a time',
text: '“reflects” is now the new input position. Its K/V join the cache. Attention still reads the growing past, but old transformer-layer work is not rebuilt.',
request: ['The','moon','looks','bright','because','it','reflects'], server: 'Decode step: 1 new position', model: '1 new K/V pair per layer; 6 old pairs reused', output: '[it] [reflects] [sunlight]',
filled: 7, reused: 6, fresh: 1, attention: 7, active: 'outputLane'
}
];
const acrossSteps = [
{
title: 'Request A has already populated a prefix cache',
text: 'The server has retained full cache blocks after Request A. Eight shared-prefix token positions are available for reuse.',
request: ['System:','be','brief','.','Document:','Moon','facts','.','Q:A'], server: 'Prefix blocks indexed by token IDs', model: 'Weights unchanged', output: 'Answer A complete',
filled: 8, reused: 0, fresh: 8, attention: 9, active: 'serverLane', cross: true
},
{
title: 'Request B arrives with the same first eight tokens',
text: 'The question differs, but the system prompt and document are an exact token-for-token prefix match.',
request: ['System:','be','brief','.','Document:','Moon','facts','.','Q:B'], server: 'Hash prompt blocks from left to right', model: 'Not started', output: 'Nothing yet',
filled: 8, reused: 0, fresh: 0, attention: 9, active: 'requestLane', cross: true
},
{
title: 'The server reuses the matching prefix',
text: 'The eight cached positions skip prefill. Only the new suffix “Q:B” must be processed. This reduces time to the first answer token.',
request: ['System:','be','brief','.','Document:','Moon','facts','.','Q:B'], server: 'Cache hit: 8 · New suffix: 1', model: 'Process only Q:B during prefill', output: 'Next-token scores',
filled: 9, reused: 8, fresh: 1, attention: 9, active: 'modelLane', cross: true
},
{
title: 'Generation still proceeds normally',
text: 'Prefix caching saved prompt processing. It does not perform the answer-generation work: each new output token still requires a decode step.',
request: ['System:','be','brief','.','Document:','Moon','facts','.','Q:B'], server: 'Begin ordinary decode loop', model: 'Read cached prefix; append new output K/V', output: '[The] …',
filled: 10, reused: 9, fresh: 1, attention: 10, active: 'outputLane', cross: true
},
{
title: 'Change an early token and later cache entries no longer match',
text: 'If “brief” becomes “detailed”, the representation of later tokens can change. Reuse stops at the first nonmatching cache block; the suffix is recomputed.',
request: ['System:','be','detailed','.','Document:','Moon','facts','.','Q:B'], server: 'Early mismatch after 2 tokens', model: 'Recompute from the unmatched block onward', output: 'New answer pathway',
filled: 9, reused: 2, fresh: 7, attention: 9, active: 'serverLane', cross: true, mismatch: 2
}
];
let mode = 'within';
let index = 0;
const $ = id => document.getElementById(id);
function tokensHTML(tokens, step) {
return '<div class="tokens">' + tokens.map((t, i) => {
let cls = 'token';
if (step.cross && index >= 2 && i < step.reused) cls += ' hit';
else if (step.mismatch !== undefined && i >= step.mismatch) cls += ' miss';
else if (!step.cross && i >= step.reused && i < step.reused + step.fresh) cls += ' new';
return `<span class="${cls}">${t}</span>`;
}).join('') + '</div>';
}
function cacheHTML(step) {
const count = Math.max(step.filled, 1);
const labels = step.request.slice(0, count);
let html = '<table><thead><tr><th>Layer</th>';
for (let i=0; i<count; i++) html += `<th>${labels[i] || '—'}</th>`;
html += '</tr></thead><tbody>';
['1','2','…','32'].forEach(layer => {
html += `<tr><th>${layer}</th>`;
for (let i=0; i<count; i++) {
const reused = i < step.reused;
const cls = reused ? 'reused' : (i < step.filled ? 'filled' : '');
html += `<td class="${cls}">${i < step.filled ? (reused ? 'reuse K,V' : 'new K,V') : 'empty'}</td>`;
}
html += '</tr>';
});
return html + '</tbody></table>';
}
function render() {
const steps = mode === 'within' ? withinSteps : acrossSteps;
const step = steps[index];
$('stepTitle').textContent = step.title;
$('stepText').textContent = step.text;
$('request').innerHTML = tokensHTML(step.request, step);
$('server').textContent = step.server;
$('model').textContent = step.model;
$('output').textContent = step.output;
$('cache').innerHTML = cacheHTML(step);
$('newWork').textContent = step.fresh;
$('reused').textContent = step.reused;
$('attention').textContent = step.attention;
$('weights').textContent = 'No';
['requestLane','serverLane','modelLane','outputLane'].forEach(id => $(id).classList.toggle('on', id === step.active));
$('prev').disabled = index === 0;
$('next').disabled = index === steps.length - 1;
$('counter').textContent = `Step ${index + 1} of ${steps.length}`;
$('within').classList.toggle('active', mode === 'within');
$('across').classList.toggle('active', mode === 'across');
}
$('within').onclick = () => { mode='within'; index=0; render(); };
$('across').onclick = () => { mode='across'; index=0; render(); };
$('prev').onclick = () => { if (index > 0) index--; render(); };
$('next').onclick = () => {
const steps = mode === 'within' ? withinSteps : acrossSteps;
if (index < steps.length - 1) index++;
render();
};
$('reset').onclick = () => { index=0; render(); };
render();
</script>
</body>
</html>
Each visible “K,V” cell represents tensors across attention heads and vector dimensions, not two individual numbers. It also shows only four representative layers. Real serving systems batch many requests, divide work across devices, manage memory in blocks, and use highly optimised GPU kernels.
The logical dependency is nonetheless real: later decoding needs earlier K/V tensors, and cached tensors can replace recomputation.
Without a KV cache, generating token 101 would require rebuilding the relevant layer states for tokens 1–100. Generating token 102 would rebuild much of that work again for tokens 1–101.
With a KV cache, the old keys and values are reused. The model computes the new position through the layers and appends its K/V tensors.
But the cache does not make a long history free:
So caching removes repeated transformer work for old positions, while attention over the growing history still costs time and memory.
| Phase | Input handled at once | Main job | Cache action |
|---|---|---|---|
| Prefill | Many prompt tokens | Understand the supplied context and create the first next-token scores | Create K/V for prompt positions |
| Decode | Usually one new token per sequence | Produce the next token repeatedly | Read old K/V; append one new position |
Prefill can use broad parallelism over prompt tokens. Decode is sequential because token 2 of the answer depends on token 1, which does not exist until it has been selected.
For a conventional transformer, a useful approximation for one sequence is:
cache bytes ≈ 2 × layers × tokens × KV heads × head size × bytes per number
where:
Example configuration:
2 × 32 layers × 8,192 tokens × 8 KV heads × 128 values × 2 bytes
= 1,073,741,824 bytes
= 1 GiB for one sequence
That is an illustrative architecture, not a claim that every 8K request uses exactly 1 GiB. Cache size changes with the model architecture, numerical precision, token count, batching, and cache compression. Models using grouped-query or multi-query attention can have fewer KV heads and therefore smaller caches.
It depends on how the model is divided.
The logical cache belongs to the sequence, even if its physical tensors are distributed among several devices.
This is the basic generation cache. The server holds a handle to the request's existing K/V tensors and supplies the next token position. Libraries often pass an object named something like past_key_values or Cache back into the model's next forward call.
In simplified pseudocode:
new K, new V = compute_for(new_token)
all K = cached K + new K
all V = cached V + new V
attention_output = attend(new query, all K, all V)
updated_cache = append(cache, new K, new V)
Serving engines can retain and index cache blocks after or across requests. If a new prompt begins with exactly the same token sequence, the server can reuse the earlier prefix's K/V tensors and skip that portion of prefill.
This is commonly called prefix caching or automatic prefix caching.
Important limitations:
At layer 1, the token after the change can attend to the changed token. Its representation may therefore differ. At layer 2, that altered representation can affect later computations again. The safe reusable unit is consequently an exact prefix, not a bag of individually matching words scattered through the prompt.
A practical engine cannot compare every new prompt with every old prompt token by token. A common design is:
The actual cache contents are K/V tensors. The hash is an index used to find them.
The hash and the cached tensors are different data structures:
The lookup metadata identifies cached computation; it is not itself the cached computation.
The earlier paper relies on a consequence of shared inference infrastructure.
Different GPU kernels can perform mathematically equivalent operations in different orders. Finite-precision arithmetic means those orders can leave tiny, repeatable rounding differences. Usually those differences do not alter visible text.
If Alice causes an agreed prefix to be calculated in a large engine step that selects one GPU kernel, the resulting cached K/V tensors can retain that kernel's rounding signature. When Bob later reuses the same prefix, a detector trained or prompted for that numerical difference can infer whether Alice's cached version was present.
The cache is therefore not a written message board. It is reused computation whose minute numerical history can, under contrived conditions, carry a signal.
That is also why the proposed defences make sense:
“The KV cache remembers facts for the model.”
It retains internal attention tensors for particular processed token positions. It is not long-term learned knowledge.
“The cache contains the answer.”
It contains reusable intermediate state. New answer tokens still have to be scored and selected.
“Caching changes the model.”
The weights remain frozen. Cache entries are temporary runtime state.
“A cache hit means the prompt is semantically similar.”
Ordinary prefix caching requires an exact compatible token prefix, generally at the engine's block granularity.
“The cache eliminates work for long contexts.”
It eliminates repeated calculation of old K/V tensors. The new query still attends over retained history unless the model uses another approximation or sparse-attention method.
“A five-machine model has five independent caches.”
Physically, cache shards may live on different workers. Logically, they form the cache state for the same sequence and model execution.
If those seven sentences make sense, you understand the core mechanism.
Default for code blocks, blockquotes, and charts. Override individually below.
npm link from project root~/.sdocs/styles.yamlDownload as PDF document
One slide per landscape page with selectable text
Editable shapes and text in PowerPoint / Keynote / Slides
Download as Word document
Plain markdown, no styles
Markdown with YAML front matter styles
Copy install promptcurl -fsSL https://smalldocs.org/install | sh
Discord
GitHub
For business
You agree to our Terms