FlashAttention (flash attention) divides attention calculations into tiles to reduce the overhead of repeatedly writing intermediate results to a GPU's large-capacity memory. Distinguish it from techniques that quantize weights or reduce the number of tokens attended to.
To understand why it can help with long inputs, you need to answer two questions: which matrices no longer need to be stored, and what should be measured under matching conditions? This article refers to the original paper and official implementation, and presents CPU numerical checks and memory-capacity calculations. We have not measured GPU speed or memory usage.
Written and edited by the Flatkey Editorial Team. Sources checked: November 20, 2026. Compute, linked at the end of this article, is a service offered by Flatkey, the publisher of this article.
What does standard attention calculate?
In a simple self-attention calculation, queries Q, keys K, and values V produce the following:
S = Q Kᵀ / √d
P = softmax(S) # 各問い合わせの行ごとに正規化
O = P V
With sequence length N and head dimension d, S and P each have shape N×N for one head. A naive implementation constructs S, constructs the normalized matrix P, and then multiplies by V. For long sequences, storing and reading and writing these large intermediate results becomes costly.
The original FlashAttention paper addresses transfers between GPU HBM and on-chip SRAM, using tiling and recomputation to reduce this overhead. HBM is not a name for all GPU memory. Some GPUs, including GeForce models, use GDDR, so keep the hardware specifications separate from the algorithm's explanation.
How FlashAttention works: small tiles and online softmax
FlashAttention processes Q, K, and V in small tiles and updates the output instead of retaining the entire large matrix P in large-capacity memory. However, independently applying softmax to each tile and simply adding their outputs would not produce the same normalization as the full calculation.
For one query row, keep the maximum score seen so far, m; the sum of exponentials, l; and the unnormalized accumulated values after multiplication by V, a. When the next score block s and its corresponding V arrive, update them as follows:
m_new = max(m, max(s))
alpha = exp(m - m_new)
w = exp(s - m_new)
l_new = alpha × l + sum(w)
a_new = alpha × a + sum(w × V)
最後の出力 O = a / l
Set alpha to 0 for the first block only. The key is that when the maximum changes, both the previous l and the previous a must be rescaled to the same new reference.
This evaluates the dense attention formula in a different order. It is not an approximation that drops some of the attended positions. Floating-point addition can nevertheless round differently depending on its order, so evaluating the same formula does not mean every bit will match. The official PyTorch documentation also explains numerical differences between the selected backends.
The dense attention score calculation itself does not automatically become linear in sequence length, either. Avoid confusing the elimination of a fully stored quadratic-size intermediate matrix with a reduction in the number of pairs being calculated.
Which memory allocation are we calculating?
First, consider just one dense score tensor. If B is the batch size and H is the number of query heads, self-attention has shape [B, H, N, N]. Assuming every element is stored in FP16 at 2 bytes per element, the required byte count is B × H × N × N × 2.
| B | H | N | Calculated capacity of one score tensor |
|---|---|---|---|
| 1 | 32 | 2,048 | 256 MiB |
| 1 | 32 | 4,096 | 1 GiB |
| 1 | 32 | 8,192 | 4 GiB |
| 2 | 32 | 8,192 | 8 GiB |
A MiB is 2 to the power of 20 bytes; a GiB is 2 to the power of 30 bytes. These figures are recalculated from the tensor shape and element size, not observed GPU allocations or memory savings. Intermediate precision, fusion, reuse, and mask representation differ between implementations. For example, PyTorch's math backend may retain intermediate calculations in float even when the inputs are half precision.
The table excludes model weights, Q/K/V/O, the KV cache, gradients, the optimizer, workspace, and allocator headroom. P may also exist separately. You therefore cannot assume that the entire amount in the table will disappear or that the whole model's memory footprint will shrink by the same proportion. For an overall breakdown, see LLM GPU memory requirements.
What we checked on a CPU—and what we did not
On November 20, 2026, we used only the standard library on CPython 3.14.6, macOS 26.7.2, arm64 to compare a conventional row-by-row attention calculation with the online updates above.
The conditions were random seed 0, B=2, H=2, N=37, Q/K dimension 16, and V dimension 12. We used two sets of uniformly distributed Q/K inputs, [-1,1] and [-20,20], with V in [-1,1], and combined causal masking on and off with block lengths 1, 3, 7, 16, and 64. Across the 20 conditions, the maximum absolute output error was 4.440892098500626e-16, below the chosen tolerance of 1e-10.
This is a numerical check of the online updates through to the output on small inputs. It uses Python float, so it does not validate FP16 arithmetic. The conventional path is also reference code evaluated one row at a time; it does not actually allocate a large [B,H,N,N] tensor. CUDA kernels, backpropagation, speed, GPU memory, and the quality of a model's answers were outside the scope of this check.
The following minimal example also shows how the denominator and the accumulated V values are updated as the maximum changes. No additional packages are needed.
import math
# 1つのqueryについて、すでに QK^T/sqrt(d) を計算したスコア
scores = [1.0, 2.0, 3.0, 4.0]
values = [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [2.0, -1.0]]
m_ref = max(scores)
w_ref = [math.exp(s - m_ref) for s in scores]
l_ref = math.fsum(w_ref)
reference = [math.fsum(w_ref[i] * values[i][d]
for i in range(4)) / l_ref for d in range(2)]
m, l, a = -math.inf, 0.0, [0.0, 0.0]
for start in range(0, len(scores), 2):
block = scores[start:start + 2]
m_new = max(m, max(block))
alpha = 0.0 if m == -math.inf else math.exp(m - m_new)
w = [math.exp(s - m_new) for s in block]
l = alpha * l + math.fsum(w)
a = [alpha * a[d] + math.fsum(w[j] * values[start + j][d]
for j in range(len(block)))
for d in range(2)]
m = m_new
online = [x / l for x in a]
error = max(abs(x - y) for x, y in zip(reference, online))
print("reference:", [round(x, 10) for x in reference])
print("online: ", [round(x, 10) for x in online])
print("max_abs_error:", error)
Output in this environment:
reference: [1.5567699411, -0.3198871231]
online: [1.5567699411, -0.3198871231]
max_abs_error: 0.0
A difference of 0 in this small example does not guarantee a bit-for-bit match for other inputs, precisions, or kernels.
A real GPU implementation also requires parallelization, data layout, and kernel fusion. Do not treat this Python loop as an implementation for speeding up attention.
What to record for a fair comparison
Before evaluating a claim that enabling it made a workload faster, check that both runs perform the same work on the same inputs.
| Conditions to fix and record | What to check |
|---|---|
| Model and software | Model name and revision; PyTorch, CUDA, driver, and library versions |
| Hardware | GPU model and count, power settings, other loads, and execution environment |
| Tensors | B/H/N/d, Q/K/V precision and layout, GQA, masks, and dropout |
| Baseline | Whether it is a naive matrix implementation, the math backend, or a fused kernel |
| Measurement interval | Warm-up, synchronization, repetition count, and whether the run is inference or forward plus backward |
| Memory | Distinguish peak allocated from peak reserved over the same scope, and align the starting point |
| Results | Keep the error tolerance, timing distribution, failures, and unsupported conditions |
PyTorch's scaled_dot_product_attention selects an implementation according to the input conditions. A baseline labeled only “PyTorch” may already be using a fused implementation. If necessary, use the official sdpa_kernel to restrict the candidates, and record warnings and the actual execution path. Merely installing a package does not prove that the target model's calls use it.
Measure the time of a single kernel separately from the response time of the entire LLM server. Prefill, which processes the input together, and decode, which continues generation, have different computational shapes. End-to-end performance also involves tokenization, communication, scheduling, and reading weights. For a procedure to measure TTFT, inter-token intervals, and throughput, continue to the vLLM benchmark guide. This article's CPU results cannot establish a GPU speedup factor.
Do not judge compatibility by the version name alone
The official repository describes FlashAttention-2, FlashAttention-3 for Hopper, and FlashAttention-4 using CuTeDSL separately. As of our November 20, 2026 check, their installation procedures and compatibility conditions still needed to be read separately.
Check GPU architecture, head dimension, precision, forward and backward support, OS, and framework integration in the documentation for the version you have fixed. The existence of a newer generation number does not, by itself, show that the optimal implementation is running with your model.
Frequently asked questions
Does the KV cache shrink by the same proportion?
This explanation of the mechanism alone cannot establish that. Retaining large score and probability matrices is a different memory category from caching the K/V of past tokens. If you are considering KV-cache capacity or tiering, see the KV-cache offloading guide.
Is it the same as quantization or PagedAttention?
They have different purposes and operate on different things. Quantization concerns numerical representation; page-based KV management concerns storage and its operation. Even when they are used alongside a FlashAttention computation path, compare their respective contributions separately.
Will it always resolve an OOM error?
Some causes will remain unresolved—for example, when weights or the KV cache alone exceed capacity. First estimate memory by category, then identify the processing stage at which usage peaks.
Set the comparison conditions before choosing an execution environment
Start by estimating intermediate matrices separately from total memory, then check the actual backend and measurements under matching conditions. Avoiding assumptions about performance and required capacity based only on the FlashAttention name makes comparisons more reproducible.
If you need a GPU environment, you can check configurations through Flatkey GPU Compute. Match the GPU required by your software to the configuration actually offered, and confirm the region, availability, and terms of use. You can also return to the English blog index for related deployment and operations articles.



