Keep less intermediate data in attention
Compare full score storage with a tiled calculation that carries an online softmax state.
Before you run
The starter supplies query 1.0, eight scalar keys and eight matching values. Multiplying the query by each key gives eight scores. Softmax turns the scores into weights; multiply each weight by its matching value and add those products for the output. The optional model expands the same steps to vectors, which contain several components.
Definitions
- Softmax
- Convert scores to positive weights: exponentiate each score minus the largest score, then divide by the sum. The weights sum to one.
- Online softmax
- A running calculation that updates the maximum, denominator and weighted sum as each tile of scores arrives.
Read the starter excerpts
Read-only CUDA C++ · onlineAttention · kernel body excerpt
float keep = expf(maximum - next);
denominator *= keep;
weighted *= keep;
for (int i = begin; i < begin + keysPerTile; ++i) {
float weight = expf(query * key[i] - next);
denominator += weight;
weighted += weight * value[i];
}Inside onlineAttention, next is the new maximum score found for the tile. expf(x) computes the exponential of an FP32 value; it supplies the rescaling factor and weights. denominator and weighted carry the running totals. This correctness example uses one GPU thread over eight keys; it is not a parallel FlashAttention implementation.
CUDA C++ · launch inside main()
onlineAttention<<<1, 1>>>(deviceKey, deviceValue, output);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 Tiles and weighted value in Console. Eight keys are processed two at a time.
Change the source
In the CUDA source editor, above onlineAttention, change keysPerTile from 2 to 4. Predict Tiles, then run again. In Console, compare Tiles and weighted value: does processing fewer tiles change the final weighted value?
Read the starter’s execution diagram
- Score tileCompare this tile’s scores with the running maximum.
- Rescale old totalsMultiply the earlier denominator and weighted sum by exp(old maximum − new maximum).
- Update totalsAdd this tile’s contributions and pass the new state forward.
After the final tile, divide the weighted sum by the denominator.
Hardware context
Running totals can remain as thread working state while successive key and value tiles are read. Avoiding a full score array changes intermediate storage. Real parallel attention kernels also use shared memory and matrix units according to their implementation.
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: online softmax steps
Predict and run
For each query, take a scaled dot product with every key to obtain scores. Softmax converts those scores to weights, and the output is the weighted sum of the value vectors. The model supplies eight query vectors, eight key vectors and eight value vectors. Each vector contains four components. Divide each query–key dot product by sqrt(4) = 2 to scale the scores in this model.
Try it
Select Store full scores and probabilities under Score handling. Predict the number of elements written to full intermediate arrays and click Run model. Switch to Online · two keys per tile and rerun. Use Next step to find a rise in the running maximum and inspect how earlier contributions are rescaled.
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 algorithm outline
// CUDA algorithm outline, separate launches:
// 1. Store every dot(Q[q], K[k]) / sqrt(d) in scores.
// 2. Softmax each scores row into probabilities.
// 3. For each q, store sum_k(probabilities[q,k] * V[k]).When a tile raises the maximum, rescale the earlier contributions before adding new ones. The trace follows query 0. Intermediate array writes count all eight queries and exclude the final output.
Apply what you saw
If the running maximum increases, what happens to the earlier denominator and weighted sum before the new terms are added?
Compare your explanation
Multiply both by exp(old maximum − new maximum). This puts the old terms on the same scale as the new terms.
See what attention keeps between input tiles 1 min 41 sec · Video walkthrough, captions and transcript
Use fullscreen to inspect the code and diagram labels.
Read the transcript
The inputs stay in GPU memory
This teaching kernel follows one scalar query over eight keys and eight values. The keys and values are input arrays in GPU memory. The question is which intermediate values the thread must keep while it visits those arrays.
A tile feeds the thread’s working state
With two keys per tile, the thread visits four tiles. It updates a running maximum, a sum of weights and a weighted sum of values. These are per-thread working values during SM execution, not full arrays of scores stored between separate kernels.
Rescale before combining the next tile
When a later tile increases the maximum, the old sums are rescaled to that new maximum before new contributions are added. The first tile’s working state is shown here. The state survives so that earlier keys still contribute.
The final division uses the retained state
After all eight keys, the weighted sum divided by the weight sum gives about 7.421. This scalar starter demonstrates the dependency and retained state; it is not a full high-performance attention implementation.
Use four keys in each tile
Now consider four keys per tile, with the same query, keys and values. Pause and predict the tile count. Should visiting fewer tiles change which eight keys contribute to the result?
Tile grouping changes; the required result does not
There are now two tiles. The same eight keys and values still contribute, and the illustrated result agrees. The memory benefit comes from retaining a small running state instead of materialising intermediate arrays. Tile count alone does not measure runtime.
References single-precision functions · explicit memory management
The browser exercises need no installed CUDA documentation version. For local execution, use the documentation matching your toolkit. External references need internet access.
- CUDA Math API · single-precision functions (new tab)
expf computes a single-precision exponential. Rescaling by exp(old_max - new_max) preserves the running softmax total.
Why does the online attention example rescale old totals when its running maximum increases?
Compare your answer
The old totals were expressed relative to the old maximum. Multiplying by exp(old maximum − new maximum) expresses them relative to the new maximum before adding new contributions.
- 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.
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.