How an LLM KV cache actually works

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.

First, keep three different things separate

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.


1. Hardware layout

A typical inference machine contains:

  • a CPU, which runs the operating system and coordinates work;
  • ordinary RAM, where programs and data can live;
  • one or more GPUs, which are exceptionally fast at the large grids of multiplication used by neural networks;
  • fast links between GPUs, and sometimes between separate machines.

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.

User request
Inference server on CPU
GPU worker 1
GPU worker 2
GPU worker 3
GPU worker 4
GPU worker 5
Streamed answer

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.

GPU versus machine

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.


2. What a deployed model contains

A deployed LLM has two main ingredients:

  1. Architecture — the ordered tensor operations and connectivity: embeddings, attention blocks, feed-forward blocks, normalisation, and the output projection.
  2. Weights — the trained numerical tensors used by those operations, particularly the matrices used in multiplications.

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 learned parameters, not stored text

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.

Loading the model

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:

  • Tensor parallelism: each layer's large weight grids are sliced across GPUs. Every GPU computes part of the same layer, then the partial results are combined.
  • Pipeline parallelism: groups of whole layers live on different GPUs or machines. A request moves through one group and then the next.

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.

Model files on storage
Load and divide weights
Worker 1: weight shard
Worker 2: weight shard
Worker 3: weight shard
Worker 4: weight shard
Worker 5: weight shard
One logical model

At this point the weights are loaded, but no particular user's KV cache exists yet.


3. A request arrives

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.


4. The attention operations relevant to caching

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 role of Q, K, and V

  • The current position's query is used to calculate a relevance score against every permitted source position.
  • Each source position's key is the vector used in that relevance calculation.
  • Each source position's value is the vector weighted and summed after the relevance scores are normalised.

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:

  1. compare the current query with earlier keys;
  2. turn the comparison scores into proportions;
  3. calculate a weighted sum of the source-position value vectors.

Why a past token's K and V can be reused

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.

Why not cache old queries too?

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.


5. One cold request, with an empty cache

The first processing of the prompt is called prefill.

For our five-token prompt, the simplified pathway is:

KV cacheModel workersInference serverTokenizerUserKV cacheModel workersInference serverTokenizerUserloop[Every transformer layer]The moon looks bright because5 token IDsPrefill all 5 prompt tokensCompute token representations, Q, K and VStore K and V for all 5 positionsProbabilities for the first answer tokenSample and stream token 1

Several important things happen during prefill:

  1. The prompt tokens pass through the model's layers.
  2. Each attention layer computes K and V vectors for each prompt token.
  3. Those K and V vectors are placed in the request's cache.
  4. The final layer produces logits—one score for every possible next token.
  5. A sampling rule selects the first output token.

Logits are not yet probabilities; a softmax operation turns them into probabilities. Temperature and other sampling settings can then affect which token is chosen.

After the first output token

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:

  1. compute the new token's Q, K, and V;
  2. append its K and V to that layer's cache;
  3. compare its query with the cached keys for all earlier positions;
  4. calculate the weighted sum of the corresponding cached values;
  5. continue through the rest of the layer and model.

Then the model selects the next token and repeats.


6. Inspect the request and cache state

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>

What the demo deliberately leaves out

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.


7. What the cache saves—and what it does not

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:

  • The new query must still compare itself with past keys.
  • The corresponding value tensors still have to be read and combined in a weighted sum.
  • The cache consumes GPU memory and grows with sequence length.
  • Moving cache data can itself become a bottleneck.

So caching removes repeated transformer work for old positions, while attention over the growing history still costs time and memory.

Prefill and decode have different shapes

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.


8. How large is a KV cache?

For a conventional transformer, a useful approximation for one sequence is:

cache bytes ≈ 2 × layers × tokens × KV heads × head size × bytes per number

where:

  • the first 2 means both K and V;
  • layers is the number of cache-using transformer layers;
  • tokens is the number of positions retained;
  • KV heads is the number of key/value attention heads;
  • head size is how many numbers sit in each head's vector;
  • bytes per number is the storage precision, such as two bytes for bfloat16.

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.

Where does that cache live across five workers?

It depends on how the model is divided.

  • With tensor parallelism, attention heads—and often their cache—can be sharded across workers.
  • With pipeline parallelism, each worker typically keeps the K/V tensors for the layers it owns.
  • Some designs replicate parts of the cache; others introduce additional cache parallelism.

The logical cache belongs to the sequence, even if its physical tensors are distributed among several devices.


9. “A request with a cache” can mean two different things

Meaning A: continuing the same answer

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)

Meaning B: a later request reusing an earlier prefix

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.

No
Yes
New request token IDs
Split or inspect prefix blocks
Exact cached prefix?
Prefill from the first unmatched block
Attach reusable K/V blocks
Prefill only the new suffix
Generate answer tokens

Important limitations:

  • Reuse is based on the same token prefix, not merely similar meaning.
  • Many systems cache fixed-size blocks, so a partial final block may not count as a hit.
  • Relevant model, adapter, positional and other configuration must be compatible.
  • Prefix caching speeds prompt processing—time to first token—but does not eliminate the normal decode work for the answer.
  • Cached blocks can be evicted when memory is needed.

Why changing one early token spoils later reuse

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.


10. How a serving engine finds cached prefixes

A practical engine cannot compare every new prompt with every old prompt token by token. A common design is:

  1. divide token sequences into blocks;
  2. hash a block together with the hash of its preceding prefix and relevant configuration;
  3. use the hash as a lookup key for a physical KV-cache block;
  4. count a hit only when the chain of blocks matches from the beginning;
  5. retain recently useful blocks and evict older ones when memory is required.

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 hash key identifies a token-prefix block and relevant configuration;
  • the block ID locates physical cache storage;
  • the cache block contains K/V tensors produced by the model.

The lookup metadata identifies cached computation; it is not itself the cached computation.


11. Return to the side-channel paper

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:

  • isolate cache entries by user or security context;
  • run mutually suspicious models on different engine instances;
  • use batch-invariant computations where practical;
  • test whether supposedly equivalent configurations produce bit-identical internal results.

12. Common misconceptions, corrected

“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.


13. The shortest accurate mental model

  1. Weights are the stable learned model.
  2. A prompt becomes tokens.
  3. Prefill processes the prompt and creates per-layer K/V tensors.
  4. The KV cache retains those tensors.
  5. Each decode step computes one new position, reads old K/V, and appends new K/V.
  6. A serving engine may also reuse an exact cached prefix for a later request.
  7. This saves computation but consumes memory, and shared caches create isolation questions.

If those seven sentences make sense, you understand the core mechanism.

43 page views

SmallDocs are a tool for people who perform complex work with AI agents. They expand the range of communication your agent can have with you and help you to increase your rate of understanding. Learn more about SmallDocs.

Format document
General
px
Colors
▶ Headings
▶ Blocks

Default for code blocks, blockquotes, and charts. Override individually below.

▶ Code
▶ Blockquote
▶ Charts
▶ Tables
Headers
▶ General h1–h4
em
▶ H1 h1
em
▶ H2 h2
em
▶ H3 h3
em
▶ H4 h4
em
Paragraph
em
Lists
em
em
Links
Code
Blockquote
px
em
Save as default styles
  • Requires sdocs-dev CLI
    • Install: npm link from project root
  • Saves to ~/.sdocs/styles.yaml
  • Paste the command below in your terminal

        
      
Export document

Download as PDF document

Download as Word document

Plain markdown, no styles

Markdown with YAML front matter styles

100% private Open source: verify server CLI for you & your agents: Copy install promptcurl -fsSL https://smalldocs.org/install | sh Discord GitHub For business You agree to our Terms