Follow the key-value cache during inference
Change sequence length and account for the key-value data read and appended during decoding.
Before you run
During token-by-token generation, or decoding, the model uses the earlier sequence to produce the next token. A token is one indexed sequence item, such as a piece of text. This starter reads the earlier tokens’ keys and values, then appends one new token’s key and value. This starter represents one layer with four FP32 values per key and per value. cached selects the old token count; the optional model accounts for a larger multi-layer cache.
Definition
- Key-value cache
- Stored attention keys and values from earlier tokens, reused when decoding the next token.
Read the starter excerpts
Read-only CUDA C++ · append · starter kernel
__global__ void append(float* keys, float* values, float* readback) {
int lane = threadIdx.x;
float previous = 0.0f;
for (int token = 0; token < cached; ++token) {
int index = token * width + lane;
previous += keys[index] + values[index];
}
int index = cached * width + lane;
keys[index] = 1.0f;
values[index] = 2.0f;
readback[lane] = previous;
}append reads cached keys and values for each lane, then writes the next token slot. cached is the number of old tokens, width the values per token, and capacity the allocated token slots. The printed byte count counts the key and value bytes requested by this step; it does not measure memory traffic.
CUDA C++ · launch inside main()
append<<<1, width>>>(keys, values, readback);The settings inside <<< >>> give the block count and threads per block. Parentheses pass the arguments to the kernel. These read-only excerpts show the starter. The CUDA source editor contains the storage and launch settings.
Edit and run CUDA
The CUDA source editor opens with the complete starter or your saved draft. To run the starter again, use Editor tools → Restore starter. Choose Undo restore there to recover the previous draft.
Click Compile and run with the starter. Find Old cache read and append in Console. Both are byte counts for one step of this example.
Change the source
In the CUDA source editor, above append, change cached from 4 to 8. Predict Old cache read in bytes, then run again. Compare Old cache read and append in Console: which grows with the old token count, and which stays fixed?
Read the starter’s execution diagram
| Earlier token slots | Next token slot | |
|---|---|---|
| Keys | Read old keys | Write new key |
| Values | Read old values | Write new value |
A longer context extends the read region. One step still appends one new key and value per layer.
Hardware context
The key-value cache here is an application data structure in device memory. It is distinct from the GPU’s L1 and L2 hardware caches. Longer histories request more old key and value data.
Read the hardware key
- Resident warp
- A warp has 32 lane positions; a small block can leave some unused. A resident warp has its state and required resources allocated on an SM. Its next instruction may still be waiting for data.
- Instruction
- One operation run by GPU hardware, such as a load, multiply or store.
- Warp scheduler
- Selects ready warp instructions for available execution hardware.
- Registers
- Hold working values associated with individual threads.
- Execution units
- Perform arithmetic and other instructions for threads; they are shared hardware.
- Load/store units
- Execute memory instructions, forming requests from active lanes’ addresses.
- L1 / L2 cache
- Keep recently used data on the GPU chip. L1 is local to an SM; L2 is shared across SMs in this simplified view.
- Shared memory
- SM-local storage allocated to blocks for explicit data exchange. It may share physical storage with L1, depending on the GPU.
- Bank
- A subdivision of shared memory that serves a group of word addresses.
- Tensor cores
- Matrix execution units used by supported warp-wide matrix instructions.
CPU side · CUDA host
Host ↔ device · copies move data; launches request execution
GPU device
GPU compute chip
SM · streaming multiprocessor
Logical groups using this SM’s resources
Issue to the appropriate units
Registers ↔ execution units · operands and results
Have their own execution hardware and registers.
Blocks may be assigned to different SMs.
Global-memory requests ↔ on-chip interconnect
Chip ↔ device memory · data transfers
Simplified NVIDIA-style architecture. Boundaries show containment; arrows name relationships. Unit counts, block placement and timing vary by GPU. A thread or warp is not a dedicated physical processor.
Explore the model: cache-data accounting
Predict and run
During decoding, a model appends one key and one value per layer for the new token. It also reads previously cached keys and values for attention. Assume one sequence and 32 layers. Each layer stores a 1,024-component key vector and a separate 1,024-component value vector for each token, using two bytes per component.
Try it
Select 128 tokens under Tokens already cached and click Run model. Change to 512 tokens, predict the MiB of existing key-value data read, then run again. Compare the old-data read with the one-token append: which depends on the history length? One MiB is 1,048,576 bytes.
These controls change only this model and its displayed excerpt; they do not edit the CUDA program above. Enter a prediction to compare with the model result.
CUDA C++ excerpt
// CUDA data-layout excerpt. One sequence, 32 layers.
constexpr size_t width = 1024;
constexpr size_t capacity = 2049;
const size_t token = 128; // first free slot
const size_t base = (layer * capacity + token) * width;
// A CUDA thread copies one coordinate j of this layer.
Kcache[base + j] = newK[j];
Vcache[base + j] = newV[j];Kcache and Vcache are separate arrays. The allocation can hold 2,049 tokens. The model counts the occupied data prefix and its logical reads, excluding model weights, unused capacity and cache effects.
Apply what you saw
Which term changes when you increase the context from 512 to 2,048, and which stays fixed?
Compare your explanation
The old data read is four times as large. The append still writes 131,072 bytes because it adds one token to the same 32 layers.
Locate the key-value cache in device memory 1 min 43 sec · Video walkthrough, captions and transcript
Use fullscreen to inspect the code and diagram labels.
Read the transcript
This cache is an application data structure
The key-value cache stores earlier tokens’ keys and values in device memory. It is not the GPU’s L1 or L2 hardware cache. The starter has room for seventeen token slots, with four FP32 values per key and four per value.
Allocated capacity and used history differ
Four token slots are logically part of the old history. Reserving seventeen slots does not mean all seventeen belong to that history. The kernel’s four threads each inspect one component across the four old tokens.
The SM consumes old cache values
A key and value together contain eight FP32 components per token, or thirty-two payload bytes. Four old tokens therefore supply one hundred and twenty-eight requested payload bytes to this step. Hardware caches may affect the physical traffic.
Append one token at the next position
The new key and value are written at token slot four. That is thirty-two append payload bytes. Reading old history and appending a new entry are different jobs, with different amounts of data.
Double the old history to eight tokens
Consider eight old tokens with the same component width and one new token. Pause and predict which payload doubles: the old-history read, the append, or both? The reserved capacity still has room for this case.
History reads grow; one append stays the same
The old-history read becomes two hundred and fifty-six payload bytes. The single-token append remains thirty-two bytes. Longer history changes how much old data is consumed, even when the number of new tokens is unchanged. These are payload counts, not measured bandwidth.
References explicit memory management · coalesced global-memory access
The browser exercises need no installed CUDA documentation version. For local execution, use the documentation matching your toolkit. External references need internet access.
- CUDA · explicit memory management (new tab)
An FP32 value occupies four bytes. Allocation reserves storage; a separate copy supplies its contents.
Seven FP32 values need how many bytes? Does allocating those bytes also copy the CPU inputs?
Compare your answer
Seven four-byte values need 28 bytes. Allocation reserves storage; a separate copy or other initialisation supplies its contents.
- CUDA · coalesced global-memory access (new tab)
Active lanes’ addresses determine the aligned regions requested. Sector counts do not measure device-memory traffic or time.
If adjacent active lanes read adjacent FP32 values, can a sector count alone establish how many device-memory reads occur?
Compare your answer
No. It counts aligned address regions in the stated model. Cache hits and the actual memory-system behaviour determine traffic beyond those requests.
Further GPU investigation Run this CUDA example on an NVIDIA GPU
In the CUDA source editor, open Editor tools and choose Export .cu to save the complete program. Use an NVIDIA GPU and a matching CUDA toolkit to run it outside the browser.
Browser simulation checks program behaviour; physical GPU timing requires a hardware measurement.
Enable JavaScript to save completion.