LLM Systems

Inference Kernels, KV Cache Layout, and Paged Attention

How paged KV-cache allocation maps logical token history onto fixed-size physical blocks, where slack appears, and what prefix sharing can save.

status: reviewimportance: criticaldifficulty 4/5math: graduateread: 20mlive demo

Concept Structure

Inference Kernels, KV Cache Layout, and Paged Attention

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

3prerequisites
1next concepts
3related links

Learner Contract

What this page should let you do.

You are here becauseHow paged KV-cache allocation maps logical token history onto fixed-size physical blocks, where slack appears, and what prefix sharing can save.

This LLM Systems concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.

By the end4/4 sections ready | runnable code expected | live demo

Explain the mechanism, trace the main notation, and test one prediction in the live demo.

Do this firstIntuition

Read the intuition before the notation; the math should name a mechanism you already felt.

Then go nextCost and Latency Observability

Follow this edge after making one prediction here; the next page should reuse the result, not restart the route.

Test the linkManipulate one control and predict the visible change.Then continue to Cost and Latency Observability

Claim/source review status

Substantive review recorded

1/1 claims have bounded review metadata; still check caveats and source scope.Metadata-derived; review may be AI-assisted. Not a human certification.
Claims1/1 reviewed
Sources4 cited
Codeattached
Demolive
Reviewed2026-07-02
Updatedpage 2026-07-02

Learning item flow

4/4 sections readyAsk about thisResearch room
ConceptInference Kernels, KV Cache Layout, and Paged AttentionLLM Systems
5 sources attachedLocal snapshot ready
concept:llm-systems/inference-kernels-kv-cache-paged-attention
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

An autoregressive model remembers the past by keeping key and value vectors for earlier tokens. That remembered state is the logical KV cache: the token history each new query token is allowed to attend to.

Serving systems have to store that logical cache somewhere physical. A simple contiguous allocation asks every request to reserve a growing slab of memory. That is easy to picture, but it has two painful behaviors:

  • requests have different lengths, so reserved slabs leave holes and tails;
  • several continuations can share the same prompt, but separate slabs duplicate the prompt cache.

PagedAttention, from Kwon et al., borrows the virtual-memory idea: split each request's KV cache into fixed-size blocks and use a block table to map logical blocks to physical blocks. The model still attends over the same logical tokens. The storage system just stops requiring each request's cache to sit in one contiguous physical region.

Source spine: Kwon et al., PagedAttention, vLLM paged-attention docs, current vLLM KV cache manager source, Hugging Face KV cache docs, and Stanford CS336.

The learner trap is to collapse three different questions into one:

  • How many logical tokens does the model need?
  • How many physical blocks did the allocator reserve?
  • Does this prove the serving stack is fast?

This page keeps them separate. The demo below is a deterministic allocation witness, not a benchmark.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

For a decoder-only model, a rough per-token KV byte cost is

Ctok=LHkvdhead2b.C_{\mathrm{tok}} = L H_{kv} d_{\mathrm{head}} \cdot 2 b.

Here LL is the number of layers, HkvH_{kv} is the number of key/value heads, dheadd_{\mathrm{head}} is the head width, bb is bytes per scalar, and the factor 22 stores both keys and values.

If request ii has TiT_i logical cache tokens, then the logical KV byte count is

Blogical=iTiCtok.B_{\mathrm{logical}} = \sum_i T_i C_{\mathrm{tok}}.

A paged allocator chooses a block size SS measured in tokens. Request ii needs

Ni=TiSN_i = \left\lceil \frac{T_i}{S} \right\rceil

logical blocks if no blocks are shared. The reserved token-slots are then

Rslots=SiNi.R_{\mathrm{slots}} = S \sum_i N_i.

The tail slack is

Wslack=RslotsiTi.W_{\mathrm{slack}} = R_{\mathrm{slots}} - \sum_i T_i.

Prefix sharing changes the counting. If kk continuations share the same prompt prefix of length PP, the logical references still count that prefix kk times, but the physical storage can store the prefix blocks once and map several logical block tables to those physical blocks. A useful teaching ledger is:

Tlogical=iTi,Tunique=TlogicalTshared saved,Wslack=RslotsTunique.\begin{aligned} T_{\mathrm{logical}} &= \sum_i T_i, \\ T_{\mathrm{unique}} &= T_{\mathrm{logical}} - T_{\mathrm{shared\ saved}}, \\ W_{\mathrm{slack}} &= R_{\mathrm{slots}} - T_{\mathrm{unique}}. \end{aligned}

The invariant is simple: paging changes allocation and sharing. It does not change the attention equation or magically make the logical context smaller.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt

This witness computes a small paged-cache ledger. It compares logical token references, unique stored tokens after prefix sharing, reserved block slots, and tail slack.

from math import ceil

def allocate(requests, block=8):
    shared, next_block, rows = {}, 0, []
    unique_tokens = logical_tokens = 0
    for req in requests:
        logical_tokens += req["prefix"] + req["tail"]
        blocks = []
        if req["group"]:
            key = (req["group"], req["prefix"])
            if key not in shared:
                n = ceil(req["prefix"] / block)
                shared[key] = list(range(next_block, next_block + n))
                next_block += n
                unique_tokens += req["prefix"]
            blocks += shared[key]
        else:
            n = ceil(req["prefix"] / block)
            blocks += list(range(next_block, next_block + n))
            next_block += n
            unique_tokens += req["prefix"]
        n = ceil(req["tail"] / block)
        blocks += list(range(next_block, next_block + n))
        next_block += n
        unique_tokens += req["tail"]
        rows.append((req["id"], blocks))
    reserved = next_block * block
    return logical_tokens, unique_tokens, reserved, reserved - unique_tokens, rows

batch = [
    {"id": "A1", "group": "prompt-A", "prefix": 12, "tail": 3},
    {"id": "A2", "group": "prompt-A", "prefix": 12, "tail": 5},
    {"id": "A3", "group": "prompt-A", "prefix": 12, "tail": 2},
]

print(allocate(batch, block=4)[:4])

The result is not a speed measurement. It is the allocation accounting that a speed measurement would need to name before it could be trusted.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

Before reveal, choose which allocation effect you think matters most in the selected request trace. The lab hides physical block ids, slot counts, and the explanation until you commit.

Live Concept Demo

Explore Inference Kernels, KV Cache Layout, and Paged Attention

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 4/5graduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Inference Kernels, KV Cache Layout, and Paged Attention should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

How paged KV-cache allocation maps logical token history onto fixed-size physical blocks, where slack appears, and what prefix sharing can save.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Inference Kernels, KV Cache Layout, and Paged Attention should make visible.

Visual Inquiry

Make the image answer a mathematical question

How paged KV-cache allocation maps logical token history onto fixed-size physical blocks, where slack appears, and what prefix sharing can save.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Inference Kernels, KV Cache Layout, and Paged Attention easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

paper · 2023Efficient Memory Management for Large Language Model Serving with PagedAttentionKwon et al.

Primary mechanism source for splitting KV cache into fixed-size blocks, mapping logical blocks to physical blocks, reducing fragmentation, and sharing prompt blocks.

Open source
documentation · 2026vLLM Paged Attention developer documentationvLLM

Implementation-learning source. The page itself warns that it is historical relative to current vLLM code, so it is used for terminology and high-level kernel layout, not current-runtime claims.

Open source
reference · 2026vLLM SingleTypeKVCacheManager sourcevLLM

Implementation-surface source for block allocation bookkeeping, request-to-block mapping, prefix-cache hits, and freeing request blocks. Not used as a benchmark or API stability guarantee.

Open source
documentation · 2026Transformers KV cache strategiesHugging Face

Documentation source for dynamic, static, offloaded, quantized, and prefix-cache strategy tradeoffs.

Open source
course-notes · 2026Stanford CS336: Language Modeling from ScratchStanford

Graduate course context for resource accounting, systems optimization, profiling, benchmarking, and memory-efficient language-model systems.

Open source

Claim Review

How paged KV-cache allocation maps logical token history onto fixed-size physical blocks, where slack appears, and what prefix sharing can save.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources5 references

kwon-2023-pagedattention, vllm-paged-attention-docs-2026, vllm-kv-cache-manager-main-2026-07-02, hf-transformers-kv-cache-2026, cs336-2026

Local checks4 local checks

Use equations, runnable code, and demos to check whether the source support is operational.

Substantively reviewedPaged KV-cache allocation separates logical token history from physical storage: requests map logical KV blocks to fixed-size physical blocks, which can reduce external fragmentation and enable block-level sharing, while still leaving tail slack inside partially filled blocks.Claim metadata: source checked

PagedAttention supports fixed-size KV blocks, non-contiguous physical placement, block tables, reduced fragmentation, and prompt sharing. vLLM docs/source support the implementation vocabulary around paged KV caches, block size, request-to-block tracking, prefix hits, and freeing request blocks. Hugging Face cache docs support the broader cache-strategy distinction and prefix-cache reuse.

Sources: Efficient Memory Management for Large Language Model Serving with PagedAttention, vLLM Paged Attention developer documentation, vLLM SingleTypeKVCacheManager source, Transformers KV cache strategiesThe page and demo are deterministic teaching witnesses. They do not claim current vLLM throughput, kernel efficiency, allocator optimality, hardware capacity, latency, quality, or production behavior.A bounded review summary is present; still check caveats and exact reference scope.

Downloaded and searched the PagedAttention paper, current vLLM paged-attention docs, current vLLM KV cache manager source, Hugging Face KV-cache docs, and Stanford CS336 course page. The claim is supported as a mechanism-level teaching artifact, with current implementation and performance claims explicitly excluded. GPT Pro publication critique remains pending because 127.0.0.1:51672 refused connection.

Reviewer: codex-local-primary-source-audit; reviewed 2026-07-02

Practice Loop

Try the idea before it explains itself

How paged KV-cache allocation maps logical token history onto fixed-size physical blocks, where slack appears, and what prefix sharing can save.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Inference Kernels, KV Cache Layout, and Paged Attention.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Grounded research drawerClose
ConceptInference Kernels, KV Cache Layout, and Paged AttentionLLM Systems

Research Room

Attach the question to a claim, equation, code, or demo

Pick the concept, equation, source, runnable code, claim, misconception, or demo state before asking for help. The handoff keeps that page item in context.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptLLM Systems

Inference Kernels, KV Cache Layout, and Paged Attention

Attached question

What is the smallest example that makes Inference Kernels, KV Cache Layout, and Paged Attention click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays in this browser, attached to the selected learning item.

No local draft saved.
Evidence to inspect
  • References to inspect: attached references on this page.
  • Definition, prerequisite, and contrast concept links
  • The equation or runnable code that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - Inference Kernels, KV Cache Layout, and Paged Attention Selected item key: recorded for copy. Context: LLM Systems Page anchor: recorded for copy. Open question: What is the smallest example that makes Inference Kernels, KV Cache Layout, and Paged Attention click without losing the math? Evidence to inspect: - References to inspect: attached references on this page. - Definition, prerequisite, and contrast concept links - The equation or runnable code that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

View it in context
concept/concept-notebook/llm-systems/inference-kernels-kv-cache-paged-attention concept:llm-systems/inference-kernels-kv-cache-paged-attention