Attention complexity and FlashAttention
Derive stable online softmax and tiled exact attention, analyze backward recomputation and memory traffic, and compare GPU attention backends.
After this lesson you can
- Derive online softmax state updates and merge them across blocks.
- Implement tiled forward and backward attention with causal masking.
- Distinguish quadratic arithmetic, memory capacity, and data movement.
- Explain the assumptions behind FlashAttention I/O complexity.
- Compare available GPU backends with correctness and timing checks.
Before you start
The matrix that need not be stored
For one head, and dense attention calculates row-wise and . Dominant computation costs and matrix occupies elements. With and float32, one score matrix occupies bytes, 4 GiB. This excludes other heads and intermediates.
Quadratic attention complexity does not require writing the whole matrix to external memory. Operation cost and traffic between fast and slow memory are different questions. FlashAttention reorganizes exact dense attention into blocks and recomputes intermediates, trading extra backward work; its result is the same in exact arithmetic and can differ through floating-point rounding. The original formulation and assumptions are in Dao et al..
For the count, consider one head without a mask and count two FLOPs per multiplication and addition. has outputs and a length- reduction, approximately FLOPs; adds another . Softmax adds order- work excluded from this approximation. For batch and equal heads, multiply both products by . Q, K, V, and output projections are additional order- terms; at small they can dominate even though attention grows quadratically with length.
In an implementation materializing scores and probabilities, each has elements. Saving them for backward can cost more than Q, K, and V vectors themselves, whose size grows as . A causal mask reduces mathematically visible positions to per head, but an implementation first constructing the entire square can still pay for some of that work. A kernel skipping future blocks avoids some operations; blocks crossing the diagonal must still mask invalid positions.
One row without seeing every element
For scores and values , maintain maximum , sum , and numerator . Output is . In online softmax, when adding a block with maximum , sum , and numerator calculated relative to , combine with :
Rescaling is essential: if a larger maximum arrives, old terms were measured against another reference. Initialize , , and , explicitly handling the empty state to avoid . Stable streaming summation is studied in Milakov and Gimelshein.
At the end the maximum is 4 and the normalizer relative to it is approximately 1.531; weighted output is approximately 2.555. Do not confuse that sum with unstabilized exponential sum: its scale changed when the maximum was subtracted. Adding a constant to all visible scores leaves weighted output unchanged, although the maximum changes.
The figure’s first block contains 2 and -1: its maximum is 2 and normalizer . When the block containing 4 and 0 arrives, the new maximum is 4. Before adding its contributions, multiply the previous state by , because everything expressed relative to 2 must be expressed relative to 4. The numerator needs exactly the denominator’s factor. Rescaling only the sum changes output; rescaling both preserves previous elements’ contribution.
Each block contributes a summary whose size is proportional to value dimension, not the number of scores already processed. At the end, is the whole row’s logsumexp. Retaining it permits an individual probability to be recovered as when its score is recomputed. This does not imply a particular kernel stores only that scalar: it must also retain inputs, output, and other metadata needed for backward and integration with the rest of the model.
A mask introduces an edge case needing an explicit decision. If a block contains no visible key, it contributes neither numerator nor denominator: previous state must stay unchanged. The code below represents excluded scores with and handles an empty maximum before subtraction; otherwise would produce an undefined value. The final assertion requires at least one valid key per query. A fully masked row does not define an ordinary softmax distribution; different libraries may return zeros or propagate non-finite values. Check that contract before replacing one backend with another.
Stability also does not mean every contribution is representable. If a score is sufficiently far below the maximum, its exponential can round to zero. Subtracting the maximum prevents positive-exponential overflow and retains at least one contribution of one when a finite score exists; it does not recover terms too small for the chosen type. For the same reason, accumulator types for maximum, sum, and numerator matter in addition to Q, K, and V types. A real implementation can mix internal precisions without changing output type.
Proof
For two disjoint blocks, by definition , and likewise for the second. Their sum is exactly the union’s normalizer under . The component-wise argument gives the numerator. State uniquely represents the union’s sums and maximum, so merging three blocks in any grouping gives the same result in exact arithmetic. Floating-point orders may round differently.
∎Tiling and recomputation
Tiled attention keeps a query block and traverses key and value blocks. It computes temporary scores, updates maximum, normalizer, and numerator, and releases scores before the next block. It needs only the result and per row to reconstruct probabilities. A causal mask excludes before exponentiation; blocks wholly above the diagonal can be skipped.
In backward recomputation, each score block is recalculated and obtained. If and , the softmax derivative gives
Then accumulate , , and blockwise. The calculation adds products that could have been avoided by saving , but saves that storage and traffic. This should not be confused with reducing dense attention’s quadratic FLOP order.
To see where comes from, the output derivative with respect to is . The softmax vector product subtracts its weighted mean: . That row reduction and reconstructed probabilities therefore suffice. In a parallel implementation several tiles can contribute to the same K or V gradient; accumulation method and floating-point order affect performance and rounding.
Implementation and checking
The cell implements an educational NumPy version without claiming to reproduce the GPU kernel. It tests blocks that do not divide the sequence and a causal mask. Differences arise from operation order and are checked with tolerance.
import numpy as np
scores = np.array([2.,-1.,4.,0.,-2.,3.])
weights = np.exp(scores-scores.max())
print('Figura: máximo, suma, salida:', scores.max(), weights.sum(), (weights @ np.arange(6))/weights.sum())
def flash_forward(Q, K, V, block_q, block_k, causal=False):
n, d = Q.shape
O = np.empty((n, V.shape[1]))
lse = np.empty(n)
for i in range(0,n,block_q):
ii = np.arange(i,min(i+block_q,n))
q = Q[ii]
m = np.full(len(ii), -np.inf)
l = np.zeros(len(ii))
u = np.zeros((len(ii),V.shape[1]))
for j in range(0,len(K),block_k):
jj = np.arange(j,min(j+block_k,len(K)))
s = q @ K[jj].T / np.sqrt(d)
if causal:
s = np.where(jj[None,:] <= ii[:,None], s, -np.inf)
new_m = np.maximum(m, np.max(s,axis=1))
safe = np.where(np.isfinite(new_m),new_m,0)
alpha = np.where(np.isfinite(m), np.exp(m-safe),0)
p = np.exp(s-safe[:,None])
u = alpha[:,None]*u + p @ V[jj]
l = alpha*l + p.sum(axis=1)
m = new_m
assert np.all(l > 0), 'cada consulta necesita al menos una clave válida'
O[ii] = u/l[:,None]
lse[ii] = m + np.log(l)
return O, lse
def flash_backward(Q,K,V,O,lse,G,block_q,block_k,causal=False):
n,d = Q.shape
dQ,dK,dV = np.zeros_like(Q),np.zeros_like(K),np.zeros_like(V)
for i in range(0,n,block_q):
ii=np.arange(i,min(i+block_q,n))
D=np.sum(G[ii]*O[ii],axis=1)
for j in range(0,len(K),block_k):
jj=np.arange(j,min(j+block_k,len(K)))
s=Q[ii] @ K[jj].T/np.sqrt(d)
if causal:
s=np.where(jj[None,:] <= ii[:,None],s,-np.inf)
p=np.exp(s-lse[ii,None])
ds=p*(G[ii] @ V[jj].T-D[:,None])
dQ[ii] += ds @ K[jj]/np.sqrt(d)
dK[jj] += ds.T @ Q[ii]/np.sqrt(d)
dV[jj] += p.T @ G[ii]
return dQ,dK,dV
rng=np.random.default_rng(9)
Q,K,V,G=[rng.normal(size=(7,4)) for _ in range(4)]
for causal in (False,True):
S=Q @ K.T/np.sqrt(Q.shape[1])
if causal:
S=np.where(np.arange(7)[None,:] <= np.arange(7)[:,None],S,-np.inf)
P=np.exp(S-np.max(S,axis=1,keepdims=True)); P/=P.sum(axis=1,keepdims=True)
O=P @ V
ds=P*(G @ V.T-np.sum(G*O,axis=1)[:,None])
dense=(ds @ K/2,ds.T @ Q/2,P.T @ G)
out,lse=flash_forward(Q,K,V,3,2,causal)
back=flash_backward(Q,K,V,out,lse,G,3,2,causal)
print('causal:',causal,'error salida:',np.max(np.abs(out-O)),
'error backward:',max(np.max(np.abs(a-b)) for a,b in zip(back,dense)))
assert np.allclose(out,O,atol=1e-12)
assert all(np.allclose(a,b,atol=1e-12) for a,b in zip(back,dense))
def objective(q,k,v):
result,_=flash_forward(q,k,v,3,2,causal)
return np.sum(result*G)
h=1e-6
for index, ix in [(0,(2,1)),(1,(1,0)),(2,(0,2))]:
plus=[z.copy() for z in (Q,K,V)]
minus=[z.copy() for z in (Q,K,V)]
plus[index][ix]+=h; minus[index][ix]-=h
numerical=(objective(*plus)-objective(*minus))/(2*h)
assert np.isclose(back[index][ix],numerical,rtol=1e-6,atol=1e-7)
print('Diferencias centrales: correctas para Q, K y V')
# Puntuaciones grandes y negativas: la referencia también debe estabilizar softmax.
q = np.array([[1000.], [1001.]])
k = np.array([[-1000.], [-1001.]])
v = np.array([[1.], [2.]])
out, lse = flash_forward(q, k, v, 1, 1)
assert np.isfinite(out).all() and np.isfinite(lse).all()
assert np.allclose(out, 1.)
print('Puntuaciones muy negativas: salida y LSE finitos')Traffic and model limits
In the two-level memory model of FlashAttention theorem 2, with and measured in elements, standard materialized attention has HBM accesses and the analyzed algorithm . Input-output complexity counts transfers, not bytes or seconds, and constants and traversal orders matter. Proposition 3 states no exact algorithm asymptotically improves that expression for all sizes in the interval. It does not prove a tight lower bound for each separate . Exact bytes cannot be obtained solely from notation.
One intuition is that if tile size is proportional to , more fast memory permits each load to be reused in more products. Position pairs still grow as ; savings come from how many pairs are processed per data movement. This intuition does not replace the paper’s assumptions or proof: real SRAM also has register, occupancy, alignment, and per-block shared-memory limits. A theoretical tile that fits by bytes may be a poor practical choice, and multiple cache levels complicate correspondence with the two-level model.
Three quantities differ when interpreting a measurement. Peak allocated indicates memory managed by the library allocator at an instant; traffic sums data moved over the operation; capacity indicates what can remain available simultaneously. A tensor may be read repeatedly without a proportional peak increase, and an allocator reservation can persist when tensors are no longer active. The counter below describes predicted transfers of a simplified algorithm; the CUDA lab measures allocator peak. Neither is a physical HBM traffic counter.
Loop order also determines reuse. With a fixed query block its accumulators live while K and V blocks are visited, but K and V are reloaded for another query block. Changing partition can reuse K and V at the cost of retaining or combining more query states. Backward also has a shared reduction: each query block contributes to gradients of the same keys and values. A parallel design must resolve that sum without losing contributions, and synchronization cost can change the best partition.
The next figure uses its own traffic model to make those constants explicit. The materialized path counts reading Q, K, and V, writing O, and four matrix transfers (write and read scores, write and read probabilities). The tiled path retains each Q block and accumulator in fast memory, traverses K and V, writes O and one LSE, and rereads K and V for every Q block. K and V accounting counts the last block in full, as if padded; Q and O count only valid positions. A causal mask skips wholly future block pairs. It uses two bytes per element for accumulators too, a simplification that does not describe real kernel precision. Estimated capacity sums Q, K, V, scores, accumulator, and two scalars per row. The result represents only that plan, not an HBM measurement.
The next counter implements the figure’s plan, not physical GPU reads. A visit counts complete K and V for that block, even if the last is padded; a causal row skips only wholly future blocks and still processes the masked diagonal. If another implementation shares K and V across several Q blocks, uses four-byte accumulators, or changes visit order, the count changes. This illustrates why an asymptotic bound does not determine actual bytes.
import math
def traffic(T,d,B,causal=False,bytes_per_element=2):
n=math.ceil(T/B)
pairs=0
read_elements=T*d # Q una vez
write_elements=T*d+T # O y LSE una vez
for i in range(n):
for j in range(n):
if causal and j>i:
continue
pairs+=1
read_elements+=2*B*d # K y V, último bloque rellenado
dense_read=3*T*d+2*T*T # Q, K, V; puntuaciones y probabilidades
dense_write=T*d+2*T*T # O; puntuaciones y probabilidades
return dict(pairs=pairs, read=read_elements*bytes_per_element,
write=write_elements*bytes_per_element,
dense_read=dense_read*bytes_per_element,
dense_write=dense_write*bytes_per_element,
workspace=(4*B*d+B*B+2*B)*bytes_per_element)
sample=traffic(4096,64,128)
print('lecturas por bloques y materializadas, MiB:',sample['read']/2**20,sample['dense_read']/2**20)
print('espacio estimado por bloque, bytes:',sample['workspace'])
assert sample['read']/2**20 == 32.5 and sample['dense_read']/2**20 == 65.5
assert sample['workspace'] == 98816
assert traffic(512,64,128,True)['pairs'] == 10FlashAttention-2 delays accumulator division until the end, distributes query blocks across thread groups, and reorganizes work between warps to reduce shared-memory communication. This increases available parallelism even with few heads or sequences per batch. It does not eliminate dependence on per-row maximum and normalizer. Its paper reports approximately twice the first version’s speed in the described A100 experiments, not on every GPU.
FlashAttention-3 exploits asynchronous transfers and matrix products on Hopper, specializes warps as data producers and consumers, and overlaps work. Its FP8 variant adds block quantization and outlier handling: it targets the same attention, but quantization adds errors relative to higher precision. These techniques depend on hardware capabilities and should not automatically be attributed to every backend called “flash”.
The backend available in scaled_dot_product_attention depends on device, shape, type, mask, and version. Forcing a backend and examining the profiler reveals what ran; timing an API name alone is insufficient.
Before comparing times, keep batch, query and key lengths, dimensions, type, and mask equal. Also compare forward and all three derivatives with a reference, using type-appropriate tolerances; a close output alone does not validate backward. Warmup avoids including some initialization in the average, and CUDA events measure device-scheduled work after synchronization. Full application time includes projections, optimizer, communication, and data preparation. An isolated attention improvement does not automatically become the same training improvement.
If Flash is not compiled or a specific combination is unsupported, the program should record the exception and leave that combination without a result. Silently using math and labeling it Flash would invalidate the comparison. Even when both work, a short case can favor the kernel with lower launch overhead, while a long one amortizes it and avoids more materialization. Repeat measurements and observe concurrent load before drawing conclusions from a small difference.
Figure 2 of the original paper provides a bounded example: for GPT-2 medium attention with sequence 1024, 16 heads of dimension 64, and batch 64 on A100, it reports 66.6 versus 75.2 GFLOPs, 40.3 versus 4.4 GB HBM traffic, and 41.7 versus 7.3 ms for standard and FlashAttention implementations respectively. These are published data for that configuration, not a measurement of your GPU or universal guarantee: they show how more compute can accompany less traffic and time.
This local lab compares forward and backward with FP16 inputs on the available GPU. The selector forces each backend: if unsupported it reports failure rather than attributing another backend’s result to it. It warms up, measures with CUDA events, clears gradients between iterations, and records peak memory additional to input state. Useful FLOP rate divides by time an ideal count for six forward and backward matmuls: two FLOPs per multiplication and addition for each visible pair, head, and component. It omits softmax, mask, and recomputation; it is not a kernel instruction counter. Other processes and clock frequencies affect time. One seed is used and this is not a full-training benchmark.
The next figure records one actual run on RTX 3060, PyTorch 2.11.0+cu128 under WSL, with batch 1, two heads, and dimension 64. The profiler explicitly identified Flash forward and backward kernels and output and gradients were compared with math. Each time is the mean of five steps in one shared-GPU run: fluctuations show why repetition and load control matter. Memory is peak allocated additional to inputs in that run, not HBM traffic. Your environment’s results may differ or Flash may be unavailable.
import torch
import torch.nn.functional as F
from torch.nn.attention import SDPBackend, sdpa_kernel
from torch.profiler import profile, ProfilerActivity
assert torch.cuda.is_available(), 'el laboratorio requiere CUDA'
print('GPU:', torch.cuda.get_device_name(), 'PyTorch:', torch.__version__, 'CUDA:', torch.version.cuda)
print('Flash incluido en esta compilación:', torch.backends.cuda.is_flash_attention_available())
torch.manual_seed(9)
flash_ok_128 = False
for causal in (False, True):
for T in (128, 512, 1024, 2048):
q,k,v = [torch.randn(1,2,T,64,device='cuda',dtype=torch.float16,requires_grad=True) for _ in range(3)]
reference = None
for name, backend in [('math',SDPBackend.MATH),('flash',SDPBackend.FLASH_ATTENTION)]:
try:
def step():
for x in (q,k,v): x.grad = None
with sdpa_kernel(backend):
out = F.scaled_dot_product_attention(q,k,v,dropout_p=0.0,is_causal=causal)
out.backward(torch.ones_like(out))
return out
for _ in range(2): step()
torch.cuda.synchronize()
for x in (q,k,v): x.grad = None
torch.cuda.reset_peak_memory_stats()
base = torch.cuda.memory_allocated()
start,end = torch.cuda.Event(enable_timing=True),torch.cuda.Event(enable_timing=True)
start.record()
for _ in range(5): step()
end.record(); end.synchronize()
if name == 'flash' and T == 128 and not causal: flash_ok_128 = True
milliseconds = start.elapsed_time(end)/5
visible_pairs = T*(T+1)//2 if causal else T*T
useful_flops = 12*1*2*visible_pairs*64
print('causal',causal,'T',T,'backend',name,'ms/paso',round(milliseconds,3),
'TFLOP/s útiles aproximados',round(useful_flops/(milliseconds*1e9),4),
'pico adicional MiB',round((torch.cuda.max_memory_allocated()-base)/2**20,2))
out = step()
sample = [out.detach().float().clone()] + [x.grad.detach().float().clone() for x in (q,k,v)]
if name == 'math':
reference = sample
elif reference is not None:
errors = [float((a-b).abs().max()) for a,b in zip(sample,reference)]
print('errores máximos salida, dQ, dK, dV:', errors)
assert all(torch.allclose(a,b,rtol=0.03,atol=0.03) for a,b in zip(sample,reference))
except RuntimeError as exc:
print('causal',causal,'T',T,'backend',name,'no disponible:',str(exc).splitlines()[0])
del q,k,v
q,k,v = [torch.randn(1,2,128,64,device='cuda',dtype=torch.float16,requires_grad=True) for _ in range(3)]
selected = SDPBackend.FLASH_ATTENTION if flash_ok_128 else SDPBackend.MATH
with profile(activities=[ProfilerActivity.CPU,ProfilerActivity.CUDA]) as prof:
with sdpa_kernel(selected):
F.scaled_dot_product_attention(q,k,v,dropout_p=0.0).sum().backward()
torch.cuda.synchronize()
print('Profiler, backend solicitado:', selected)
print('Operaciones SDPA observadas:', [e.key for e in prof.key_averages() if 'attention' in e.key.lower()])npm run lab and open the connection link.An additional noncausal math sweep with the same batch and head shape completed , 8192, 12288, and 16384 in another WSL run on RTX 3060; additional peak allocation was 536.2, 2064, 4632, and 8224 MiB respectively. Before , 11155 MiB free were reported. A separate attempt also finished: it reported 2243.3 MiB free initially, 12856.2 MiB additional peak allocated, and 234.313 seconds. That peak exceeds the GPU’s reported 12287.5 MiB total; the backing mechanism has not been identified and it must not be interpreted as dedicated VRAM. Concurrent conditions changed, and this grid observed no failure or determined card maximum length.
To explore a larger shape in your environment, the next cell is disabled by default. If ORYON_LONG_ATTENTION=1 is set, it forces math at , reports free memory before the attempt, and distinguishes completion from OutOfMemoryError. Results depend on available memory, system, and other tasks; this is not a universal limit. One pass under that memory pressure is also unsuitable for stable timing comparison.
import os, gc, time, torch
import torch.nn.functional as F
from torch.nn.attention import SDPBackend, sdpa_kernel
if os.environ.get('ORYON_LONG_ATTENTION') != '1':
print('Prueba larga omitida; configura ORYON_LONG_ATTENTION=1 para ejecutarla.')
else:
assert torch.cuda.is_available()
T=20480
gc.collect(); torch.cuda.empty_cache(); torch.cuda.synchronize()
free,total=torch.cuda.mem_get_info()
print('GPU:',torch.cuda.get_device_name(),'libres/total MiB:',round(free/2**20,1),round(total/2**20,1))
q=k=v=out=None
try:
q,k,v=[torch.randn(1,2,T,64,device='cuda',dtype=torch.float16,requires_grad=True) for _ in range(3)]
torch.cuda.reset_peak_memory_stats(); base=torch.cuda.memory_allocated(); start=time.perf_counter()
with sdpa_kernel(SDPBackend.MATH):
out=F.scaled_dot_product_attention(q,k,v,dropout_p=0.,is_causal=False)
out.backward(torch.ones_like(out))
torch.cuda.synchronize()
print('completo; pico adicional MiB:',round((torch.cuda.max_memory_allocated()-base)/2**20,1),
'segundos:',round(time.perf_counter()-start,3))
except torch.cuda.OutOfMemoryError as exc:
print('memoria insuficiente en esta ejecución:',str(exc).splitlines()[0])
finally:
del q,k,v,out
gc.collect(); torch.cuda.empty_cache()npm run lab and open the connection link.Exercises
Step 1 of 3. What maximum is used for the union?
import numpy as np
def flash_forward(Q, K, V, block_q, block_k, causal):
pass