FlashAttention and Optimized Kernels
Block-wise exact attention is an algorithm; making it fast is a kernel. Both measured, plus an honest account of what could not be run here.
I implemented causal block-wise attention in eager PyTorch using online softmax, the mathematical technique behind FlashAttention. Against an fp64 direct-attention reference, it agreed to the reported fp16 rounding tolerance. At 8,192 tokens, PyTorch recorded 15.8 MiB of additional peak tensor allocation for the tiled version, compared with 3,148 MiB for direct attention. Yet the tiled version took 1.12–1.21 seconds, versus 67–71 milliseconds for direct attention: about 16–18 times slower in these runs.
On the same fp16 inputs, PyTorch’s forced memory-efficient SDPA backend needed 12.0 MiB of additional peak allocated tensor memory and ran 5.5–8.6 times faster than direct attention at 8,192 tokens. Across the measured lengths of 1,024–8,192, its speed-up ranged from 5.5 to 13.5 times. The backend was explicitly selected; it was not PyTorch’s FlashAttention backend.
These implementations compute the same causal attention function up to floating-point rounding, but they do not execute the same operations. The direct reference forms dense score and probability matrices and masks future positions; the tiled implementation skips some wholly masked key blocks. Eager tiling greatly reduces the peak size of intermediate tensors without removing the cost of many framework operations. A fused backend also reduces intermediate transfers and dispatch overhead. The distinction matters: an algorithm, a framework implementation of it, and a particular compiled GPU kernel are three different things to benchmark.
The qualification comes first: FlashAttention itself was not run. With PyTorch 2.6.0+cu124 on the RTX 2060 (compute capability 7.5), the FlashAttention backend was unavailable because the tested PyTorch build reported that it was not compiled with FlashAttention. The measurements in this chapter concern eager PyTorch tiling and the separate memory-efficient SDPA backend. Published FlashAttention and FlashAttention-2 performance results will be attributed to their authors, not to this machine.
Where this sits
Attention and Its Computational Cost showed that direct attention materialises large score and probability tensors, while the measured memory-efficient SDPA backend avoids their quadratic peak allocation. Memory Bandwidth and Compute Bottlenecks developed a three-term performance estimator, with launch/dispatch, estimated bytes and arithmetic as competing costs; it also demonstrated that fusion can eliminate materialised intermediates. This chapter asks two separate questions: can online softmax compute the same attention function without keeping the full score matrix, and can an implementation make that arithmetic run faster? The first is a mathematical and storage question. The second is an execution question.
The Inference Lab increment is a readable, deliberately unfused implementation, tiled_attention, the partial-result combiner merge_partials, a simplified traffic model and an SDPA-backend availability probe. The fp64 direct calculation is the independent numerical reference for the reported comparisons; tiled_attention is an inspectable algorithmic implementation, not an independent high-precision oracle. The lab also adds splitkv_decode to demonstrate a key-splitting formulation without claiming that its framework-level implementation reproduces the performance of a fused Flash-Decoding kernel.
For the Pi series, this chapter explains why long retrieved contexts, tool transcripts and conversational history create a kernel-level cost that cannot be solved merely by declaring an algorithm more memory-efficient. Block-wise attention can reduce temporary storage, but overall inference latency still depends on the available kernel, sequence shape, batching and the rest of the model. The practical consequence is to record both the selected attention implementation and the workload it actually served.
The online softmax
The difficulty with computing attention in blocks is normalisation. Ordinary softmax subtracts a maximum and divides by a sum over every visible key. A query tile cannot know the final normaliser after seeing only the first key tile. Saving all its scores would defeat the purpose of tiling; online softmax instead carries enough statistics forward to correct earlier contributions as later keys arrive.
For a nonempty set of visible keys \(J\), define the following partial result for one query row. Assume finite scores and values; masked-out keys are excluded from \(J\). The partial numerator \(o_J\) is a vector, not yet a normalised attention output:
This extends Tokens, Embeddings and Probability’s stable softmax: the running maximum is updated whenever a new block contains a larger score, and \(e^{m_{\text{old}}-m_{\text{new}}}\) rescales the accumulated denominator and numerator. It avoids exponentiating arbitrarily large positive scores in the tested finite-input cases. The GPU experiment scaled queries by 30 and measured a maximum absolute difference of \(4.7\times10^{-5}\) from the float64 reference; a separate CPU unit test scales them by 40. These are stability checks, not a proof that every nonfinite input or masking pattern is supported.
For each tile of \(B_q\) queries, the following pseudocode accumulates fp32-style running statistics over blocks of \(B_k\) keys. Causal masking must be applied to scores within partially visible diagonal blocks, not merely by skipping wholly future blocks:
m, l, acc = -inf, 0, 0
for each tile of B_k keys (skip tiles wholly in the future if causal):
s = q_tile @ k_tile^T / sqrt(d) # [B_q, B_k], never written to main memory in a fused kernel
m' = max(m, rowmax(s))
p = exp(s - m')
l = l * exp(m - m') + rowsum(p)
acc = acc * exp(m - m') + p @ v_tile
m = m'
output_tile = acc / l
Only a \(B_q\times B_k\) score tile is needed at a time. In an appropriately fused implementation its intermediates can remain on chip; in this book’s eager-PyTorch version, the score tile and running-statistic updates are ordinary framework tensors and kernel launches. The same pseudocode therefore explains both the memory saving and why the readable implementation is slow.
It is exact
The GPU correctness sweep uses one sequence, 12 heads of dimension 64, causal attention, four \((B_q,B_k)\) choices—\((32,512)\), \((64,64)\), \((128,128)\) and \((256,64)\)—and lengths of 512 and 2,048 tokens. Each output is compared with the direct attention formula evaluated in float64 on the same already-rounded input tensors. The table reports the range of maximum absolute elementwise differences over those cases; it does not cover decoding, other masks, dropout or other head dimensions.
| Precision | Maximum absolute output difference against float64 reference, across tested shapes and lengths |
|---|---|
| fp32 | \(8.2\times10^{-7}\) to \(1.25\times10^{-6}\) |
| fp16 | \(9.3\times10^{-4}\) to \(9.7\times10^{-4}\) |
The measured errors remain in the same narrow range across the four tested tile shapes, which supports numerical equivalence for those configurations. It does not establish identical intermediate precision across kernels, and the data do not isolate output rounding as the only fp16 error source. With queries scaled by 30, the fp32 maximum absolute difference was \(4.7\times10^{-5}\). For publication-quality regression tests, add relative error, finite-output checks, multiple seeds and comparison of generated-token decisions near argmax ties; none of those extra results is claimed here.
Causal attention permits a second saving: key tiles wholly in the future of a query tile need not be visited. At 2,048 positions, the implementation visited 136 of 256 possible tile pairs for 128×128 blocks (53.125%), and 528 of 1,024 for 64×64 blocks (51.5625%). These are counts of visited tile pairs, not measurements of executed FLOPs or HBM traffic; diagonal tiles still contain masked positions. This is why the causal arithmetic opportunity approaches one half for long sequences but the time saving is implementation-dependent, as Attention and Its Computational Cost demonstrated.
What it saves: traffic
The IO argument is to avoid repeatedly writing and reading the \(T\times T\) score and probability matrices from high-bandwidth memory (HBM). To make that idea testable, the Lab uses a simplified element-transfer model, per head and sequence. It counts selected compulsory-style reads and writes, not GPU memory-controller transactions or a measured traffic trace. For the chapter’s explicit direct-attention implementation, which forms a dense matrix even under a causal mask, the model counts:
| Tokens | Naive | Tiled, \(B_q = 64\) | \(B_q = 128\) | \(B_q = 256\) |
|---|---|---|---|---|
| 1,024 | 12.5 MiB | 2.4 MiB (5.3×) | 1.4 MiB (9.1×) | 0.9 MiB (14.3×) |
| 4,096 | 194 MiB | 33.5 MiB (5.8×) | 17.5 MiB (11.1×) | 9.5 MiB (20.4×) |
| 8,192 | 772 MiB | 131 MiB (5.9×) | 67 MiB (11.5×) | 35 MiB (22.1×) |
| 16,384 | 3,080 MiB | 518 MiB (5.9×) | 262 MiB (11.8×) | 134 MiB (23.0×) |
Increasing the query tile \(B_q\) reduces the modeled number of K and V rereads. But the relationship is constrained by shared-memory/register capacity, occupancy, tensor-core tile shapes, masking and scheduling: doubling \(B_q\) is not universally feasible or twice as effective in a real kernel. The table does not account for spilling, additional passes or L2 reuse. This is the IO-awareness of FlashAttention in simplified form, not the paper’s full IO-complexity proof. The PyTorch memory-efficient backend used below does not expose its actual tiling parameters in these results, so \(B_q=128\) is an illustrative assumption, not an inferred implementation detail.
What it saves: the numbers
For \(T=1{,}024\) to 8,192, the GPU comparison fixes fp16, batch 1, 12 heads, dimension 64 and causal masking. The direct formula, eager tiled_attention with 128×128 blocks and forced SDPBackend.EFFICIENT_ATTENTION run on the same generated inputs. Each command run uses warm-ups and CUDA-event timing samples (ten for direct/fused, four for tiled), and the command was repeated twice. Peak memory means additional peak PyTorch allocated tensor bytes above the already-live input tensors, not measured HBM reads/writes or total device memory consumption.
| Tokens | Naive | Block-wise in plain PyTorch (128 × 128) | Fused memory-efficient kernel |
|---|---|---|---|
| 1,024 | 1.07 ms, 50.5 MiB | 23 – 24 ms, 5.3 MiB | 0.14 ms, 1.5 MiB |
| 2,048 | 5.7 ms, 200 MiB | 74 – 79 ms, 6.8 MiB | 0.42 ms, 3.0 MiB |
| 4,096 | 18.6 ms, 790 MiB | 282 – 318 ms, 9.8 MiB | 1.97 – 1.98 ms, 6.0 MiB |
| 8,192 | 67 – 72 ms, 3,148 MiB | 1,124 – 1,205 ms, 15.8 MiB | 7.8 – 13.0 ms, 12.0 MiB |
Avoiding a full score tensor helps both tiled implementations’ peak allocations. The eager version took 13.1–22.7 times as long as direct attention over the measured sizes; the forced memory-efficient backend ran about 7.8–13.5 times faster for 1,024–4,096 tokens and 5.5–8.6 times faster at 8,192. These ranges are specific to this software build and GPU. The fastest implementation here was neither the reference formula nor the readable tiling loop; it was the separately compiled backend that PyTorch selected only because the experiment explicitly requested it.
Why is eager tiling so slow? At \(T=8{,}192\) with 128×128 blocks, the code visits 2,080 causal tile pairs. Each pair executes multiple PyTorch operations—matrix products, masking, reductions, exponentials and updates of the running statistics. Those operations can issue distinct GPU kernels and materialise temporary tile-sized tensors. Multiplying 2,080 by an informal estimate of roughly fourteen operations suggests tens of thousands of framework-level operations, but this is not a measured CUDA kernel count: some operations may fuse or take different paths, and the earlier session’s 35–40 µs host-dispatch timings cannot be applied as a constant launch cost here. A CPU/GPU timeline or kernel trace is needed to attribute the measured 1.12–1.21 seconds.
Eager tiling reduces peak intermediate size without guaranteeing reduced total HBM traffic or latency. Unlike a fused implementation, it repeatedly reads and writes its small tile tensors and running statistics. Fusion can retain more of that state on chip and reduce dispatch overhead, but even fusion is not a universal speed-up: the relevant shape, occupancy, memory hierarchy and available kernel determine the result. The chapter’s comparison therefore demonstrates a memory-allocation saving directly and a fusion-related timing difference empirically; it does not measure either implementation’s HBM traffic directly.
The traffic model against the measurement
For an assumed query tile of 128, the simplified counting model gives naive-to-tiled element ratios of 9.1, 10.3, 11.1 and 11.5 at \(T=1{,}024, 2{,}048, 4{,}096, 8{,}192\). The measured direct-to-fused time ratios were approximately 7.8–7.9, 13.5, 9.4–9.5 and 5.5–8.6. Their magnitude and direction are compatible with eliminating score-tensor materialisation; they do not validate the assumed tile size or prove that runtime is proportional to the modeled transfers. The direct implementation also pays for dense arithmetic, masking and launches; the fused kernel may exploit triangular work and a different instruction mix. The 8,192-token fused timings alone varied from 7.77 to 12.95 ms between runs. A causal performance explanation should therefore retain this as an illustrative consistency check until hardware counters and kernel identification are available.
Which kernel ran
scaled_dot_product_attention is a semantic API, not a guarantee of which CUDA kernel executed. The availability command forces each available SDPBackend choice in turn using a fixed fp16 test shape (batch 1, 12 heads, 256 tokens, dimension 64), and records both success and PyTorch’s emitted warnings. These results establish eligibility for the probed shape in the recorded environment; other masks, dtypes and shapes can change dispatch.
| Forced SDPA backend | Probe result | Relevant message from PyTorch 2.6.0+cu124 |
|---|---|---|
| Math | ran | No refusal |
| Memory-efficient | ran | No refusal |
| FlashAttention | unavailable | “Torch was not compiled with flash attention.” |
| cuDNN attention | unavailable | “cuDNN MHA only supports gpu architectures in the range [sm80, sm90]. Attempting to run on a sm 7.5 gpu.” |
The probe also logged messages about other backends being disabled by the forced-selection context. Those are not separate explanations of why the requested backend failed.
For this exact environment, the reported FlashAttention refusal concerns how PyTorch was built; the reported cuDNN attention refusal concerns the RTX 2060’s sm 7.5 capability. Neither statement establishes the compatibility of every separately distributed FlashAttention kernel with this GPU, and neither should be extrapolated to later PyTorch releases. The Attention and Its Computational Cost measurements were already distinguished from FlashAttention: no rerun or retrospective reclassification is necessary. A reproducible backend report should include the tested tensor shape, dtype, causal/mask settings, software build and backend-selection mechanism alongside the warning text.
The performance claims for FlashAttention proper therefore come from papers, not this Lab’s measurements. Dao and collaborators’ FlashAttention paper (NeurIPS 2022) established IO-aware exact attention and reported gains on its evaluated hardware. FlashAttention-2 (ICLR 2024) improved work partitioning and reduced non-matrix-multiplication overhead; the authors report roughly 2× speed-up over the first version and 50–73% of theoretical arithmetic peak on an NVIDIA A100. These are published author results on their tested configurations, not achieved throughput or measured upper bounds for this RTX 2060.
What the local experiment establishes is narrower but useful: a forced, fused memory-efficient SDPA backend computed the tested causal attention efficiently while avoiding a quadratic output-sized peak allocation. Its Attention and Its Computational Cost throughput estimate of roughly 17.3 TFLOP/s used a causal-pair arithmetic convention and was about 55% of Matrix Multiplication and GPU Execution’s best measured fp16 matrix-product rate. That quotient is a comparison between two modeled/observed rates, not direct hardware utilisation or a measurement of FlashAttention. The identity of the backend and the accounting convention must accompany the number.
The decode shape: splitting the keys
Attention and Its Computational Cost observed that at batch 1, a one-query attention workload of 12 heads had an effective byte rate near 50 GB/s, calculated as nominal KV-cache bytes divided by elapsed time. That is not a memory-controller bandwidth counter. Limited GPU parallelism is one possible explanation: only a small number of independent heads may be available to the backend. A published approach, described in the PyTorch team’s Flash-Decoding article, divides the keys and values into segments, computes partial online-softmax results in parallel and reduces those results. This chapter tests the numerical formulation with ordinary PyTorch operations; it does not implement or benchmark the article’s fused kernels.
Mathematically, each split produces a partial maximum, denominator and value-weighted numerator that can be combined by the same softmax identity. The local splitkv_decode implementation agreed with a direct float64 attention reference to maximum absolute differences on the order of \(2.5\times10^{-5}\) to \(2.2\times10^{-4}\) in the recorded sweeps. It is numerically equivalent within these observed tolerances, not bit-exact: the implementation casts partial probabilities to the value dtype before its matrix product. CPU unit tests also cover split counts 1, 2, 3, 4, 8, 12 and 96, but do not constitute a fused-kernel performance test.
The implementation reshapes the key dimension into a split axis, performs batched matrix products and a final merge using separate PyTorch operations. This does not guarantee that different splits are scheduled as independent, well-occupied GPU work units in the manner intended by Flash-Decoding. Across two runs, timings varied markedly and no reproducible monotonic improvement with more splits emerged. The following ranges select the measured batch/length cases rather than a controlled count of GPU blocks:
| Key length | Batch | Forced memory-efficient SDPA | Eager split-KV, across 1–64 splits |
|---|---|---|---|
| 1,024 | 1 | 88–99 µs | 412–724 µs |
| 4,096 | 1 | 252–253 µs | 583–856 µs |
| 16,384 | 1 | 992–998 µs | 571–767 µs |
| 16,384 | 4 | 1,158–1,162 µs | 993–1,066 µs |
For 1,024 and 4,096 keys at batch 1, eager split-KV was slower than the forced efficient backend. At 16,384 keys it was faster in the recorded runs even with one split. That last observation means the result cannot be credited specifically to extra split-level parallelism. Changing the number of splits did not produce a robust trend, and the fastest measured split count changed between runs. It would be incorrect to say either that split-KV parallelism has been validated or that the published approach has been refuted.
The proposed small-batch occupancy mechanism therefore remains untested by a suitable fused split-KV experiment. Eager-PyTorch overhead, changed matrix-product shapes, temporary storage and the merge all affect this benchmark. Dividing a nominal 48 MiB of batch-1 cache traffic by Memory Bandwidth and Compute Bottlenecks’s approximately 300 GB/s gives about 0.17 ms as an illustrative bandwidth term; it does not bound the complete operation without knowing actual traffic, cache effects and effective bandwidth. A decisive test would hold the kernel family and inputs constant, record hardware-kernel launches, occupancy, HBM/L2 bytes, and end-to-end latency as the split count changes.
One useful counterexample remains. At 16,384 keys and batch 1, the eager implementation with a single split ran in roughly 571–751 µs, while forced memory-efficient SDPA took approximately 992–998 µs in the two runs. Using nominal KV bytes divided by elapsed time gives an effective-rate comparison of approximately 67–88 GB/s against 50 GB/s; those are derived ratios, not measured cache-read throughput. The difference may reflect workload-specific matrix-product scheduling, allocation, cache behaviour or other implementation effects. Without instrumentation it establishes a measured timing reversal, not the reason for that reversal.
Other kernels
The same kernel-design principle applies beyond attention. The following are possible fusion opportunities, not speed-ups measured in this chapter. Each is valid only if the fused operation preserves the intended numerical semantics and has a suitable compiled implementation:
- residual addition with the following layer normalisation;
- bias application and GELU after a matrix product;
- query/key/value projection, layout changes and related pointwise operations, where their shapes allow it;
- rotary positional transforms for architectures that use them (GPT-2 in this Lab does not);
- packed-weight dequantisation combined with the matrix product, the missing path identified in Quantization and Numerical Precision;
- token-filtering and sampling operations, where an implementation can avoid extra sorting or intermediate tensors without changing the specified sampling rule.
Memory Bandwidth and Compute Bottlenecks measured a concrete fused multiply-add example: approximately 1.54–1.59× faster than two separate PyTorch operations on its tested large vectors, near the ratio predicted by modeled memory passes. That result motivates this design space; it does not establish the speed-up of any fusion listed above. For each proposed kernel the Lab should first specify mathematical equivalence, then record numerical error, backend availability, intermediate allocation, measured time and hardware/shape constraints.
What the numbers do not show
- No FlashAttention backend run. Only eager tiling and forced PyTorch memory-efficient SDPA were timed; published FlashAttention results remain external evidence.
- One machine and one software build. RTX 2060 (sm 7.5) with PyTorch 2.6.0+cu124 under Windows WDDM; a different build or mask can change dispatch.
- Fixed attention shape. Main timings use fp16, batch 1, 12 heads of dimension 64 and causal masking; the split-KV sweep additionally uses batches 1 and 4.
- Estimated HBM traffic. The traffic model omits temporary buffers, mask bytes, caches, spilling and exact on-chip tile resources; no memory-controller counters were collected.
- PyTorch allocator peaks. Additional peak allocated tensor bytes are not the same as physical GPU-memory occupancy or memory traffic.
- Unknown fused tile parameters. A query tile of 128 is illustrative and cannot be inferred reliably from timing ratios.
- Timing variation. At 8,192 tokens, the two fused-kernel runs gave 7.77 and 12.95 ms; a source of the variation was not isolated.
- Unfused operation counts are estimates. CUDA kernels and host scheduling were not traced.
- Numerical scope. The fp64 comparison holds the input tensors fixed and covers limited shapes; associativity across three partials, empty sets, NaNs/Infs and end-to-end token decisions are not comprehensively tested.
- Split-KV hypothesis not qualified. No fused split-KV kernel, occupancy counters or controlled scaling study was run.
- Forward inference only. No backward pass, dropout, ragged batches, grouped-query attention, production scheduler or multi-GPU experiment.
Inference Lab increment
The Lab now has:
tiled_attention(q, k, v, causal, block_q, block_k): an eager block-wise reference implementation, reporting visited and possible tile pairs. It currently assumes matching query/key lengths and ordinary multi-head dimensions.merge_partials(m1, l1, o1, m2, l2, o2): the online-softmax partial-result merge. The unit tests cover two-way equivalence and commutative order, while a dedicated three-way associativity test is still needed.splitkv_decode(q, k, v, splits): an eager one-query formulation tested against direct attention, not a fused Flash-Decoding kernel.naive_hbm_elements,tiled_hbm_elementsandtraffic_ratio: simplified element-transfer counts, not instrumented HBM activity.availability,exactness,traffic,python_tiledandsplitkv: reproducible commands for the recorded probes and tables, subject to backend/hardware availability.
The standing rule is to report (1) the mathematical operation and error tolerance, (2) the concrete implementation and forced or verified backend, (3) the input shape and environment, and (4) time and memory metrics with their measurement definitions. A proof that the scores need not be materialised is not a wall-clock speed-up. Equally, one fast implementation does not establish that all kernels in the same algorithmic family have the same performance. An unavailable backend is a result about that build and probe, not a universal hardware verdict.
What you should now be able to do
- Derive the online-softmax partial result and two-part merge, then prove associativity over nonempty key sets in exact arithmetic.
- Distinguish that mathematical associativity from bitwise order independence in floating point.
- Compute the modeled direct-versus-fused traffic ratio and identify what the counting model leaves out.
- Explain how eager tiling can reduce peak tensor allocation yet increase runtime through separate operations.
- Report both a forced SDPA backend and the shape/dtype/mask used to test its availability.
- Compare a fused output with a direct fp64 attention reference using a stated numerical tolerance.
- Explain why split-KV is an exact mathematical decomposition but does not guarantee a speed-up without suitable GPU parallelism.
- Keep local measurements, analytic estimates, unsupported hypotheses and published FlashAttention results separate.
Key terms
- Online softmax: maintaining a running maximum and normaliser while processing scores in blocks.
- Partial result: the triple \((m,\ell,o)\) for a nonempty key subset: maximum, unnormalised exponential sum and unnormalised value-weighted sum.
- Merge rule: reweighting partial numerators and denominators to a common maximum before adding them.
- Tile: a block of query or key/value positions selected to exploit a memory hierarchy and available parallelism.
- IO-aware: an algorithm or kernel design that explicitly accounts for transfer costs between device-memory levels.
- Peak allocated tensor memory: the largest PyTorch-managed live allocation over a measurement interval, not measured HBM bytes transferred.
- Fused kernel: a compiled GPU execution path that combines operations while reducing intermediate materialisation or separate dispatches.
- Split-KV decoding: distributing key/value attention over partial key ranges and combining their normalised contributions.
- SDPA backend: a particular implementation eligible behind PyTorch’s attention API for the tested inputs.
- Effective byte rate: a modeled byte count divided by measured time; not a hardware counter.
Reader exercises
- Prove algebraically that
merge_partialsis associative for three nonempty key sets with finite scores. Then add an explicit \((A\oplus B)\oplus C\) versus \(A\oplus(B\oplus C)\) test. Report bitwise agreement separately from numerical tolerance. - Run
availabilityon your hardware with exactly the chapter’s fp16 shape. Repeat with fp32, causal masking and another head dimension; record the software build and each refusal reason. - Use \(6B_q/d\) to predict the asymptotic modeled traffic ratio for several tile sizes. Explain why a measured timing speed-up cannot uniquely identify the actual tile size.
- Instrument eager
tiled_attentionusing a trace that records CUDA kernels and host-to-device scheduling. Compare actual kernel counts with the rough 2,080-pair operation estimate. - Repeat the eager attention test with 64, 256 and 512 query tiles, controlling for masking and memory use. Where do reduced iteration counts stop helping?
- Add tests for all-masked or empty partials, extreme finite scores and changes in merge order; decide whether the API should reject or explicitly handle each case.
- Repeat
splitkvwith repeated process runs and a controlled split-count sweep. Add a genuinely fused variant if your environment supports one; measure hardware occupancy and the memory hierarchy before attributing gains to splitting. - Check the published FlashAttention and FlashAttention-2 claims against the hardware and kernel versions they actually report; distinguish their measured speed-ups from this chapter’s forced memory-efficient SDPA results.
References
The three primary research papers for this chapter are:
- Milakov and Gimelshein (2018), Online normalizer calculation for softmax — establishes the stable online normaliser and associative partial reduction in exact arithmetic; this Lab extends the partial state with a value-weighted numerator.
- Dao et al. (2022), FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness — IO-aware attention tiling, its HBM/SRAM reasoning and an exact fused implementation. Its kernel was not run here.
- Dao (2023; ICLR 2024), FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning — reduces non-matmul overhead and improves work partitioning; the reported A100 gains belong to that paper, not this GPU.
Additional implementation context: Rabe and Staats (2021), Self-attention Does Not Need O(n²) Memory distinguishes memory complexity from runtime; PyTorch SDPA API documents backend eligibility and numerical differences; PyTorch Flash-Decoding describes split-key parallelism, which this Lab did not reproduce as a fused kernel.
Evidence in this chapter
| Claim | Status and evidence boundary |
|---|---|
| Online softmax merges nonempty partial results without changing the attention function in exact arithmetic | Established by the online-normaliser and FlashAttention research; two-way merge tested locally; three-way associativity test still needed |
| Eager tiled attention matches the float64 direct formula to the reported fp16/fp32 tolerances | Local GPU results, two lengths and four tile shapes |
| Causal blocking skips wholly future tile pairs | Local block-count result; pair counts are not executed FLOP counters |
| \(4Td+6T^2\) versus \(2Td+\sum 2ed\) and limiting ratio \(6B_q/d\) | Simplified analytical element-transfer model; not measured physical HBM traffic |
| At 8,192 tokens, eager tiling uses 15.8 MiB versus 3,148 MiB for direct attention and is approximately 16–18× slower | Local result; peak PyTorch allocated tensor memory and CUDA-event time |
| Forced memory-efficient SDPA is 5.5–13.5× faster than direct attention across tested lengths | Local result; not a FlashAttention measurement; 8,192 timings varied between runs |
| FlashAttention backend refused because of the PyTorch build; cuDNN attention refused due to sm 7.5 | PyTorch warnings for the specific probe shape and software environment |
| FlashAttention-2 provides approximately 2× the first version and 50–73% peak on an A100 | External paper’s published result; not reproduced locally |
| Split-KV results agree numerically with a float64 reference | Local results with the stated tolerances; not bitwise identity |
| More key splits improve batch-1 occupancy and performance | Hypothesis not established by the eager-PyTorch implementation |
| At 16,384 keys, single-split eager PyTorch was faster than forced efficient SDPA | Local timing comparison; explanation and actual memory-traffic difference unmeasured |
| Fused split-KV, hardware counter attribution, training/backward, GQA, general hardware | Not measured |