Module contents
Lesson 15 of 22Advanced 115 min

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, Q,K,V∈RT×d\mat{Q},\mat{K},\mat{V}\in\R^{T\times d} and dense attention calculates P=softmax⁡(QK⊤/d)\mat{P}=\softmax(\mat{Q}\mat{K}\T/\sqrt d) row-wise and O=PV\mat{O}=\mat{P}\mat{V}. Dominant computation costs O(T2d)\bigO(T^2d) and matrix P\mat{P} occupies O(T2)\bigO(T^2) elements. With T=32768T=32768 and float32, one score matrix occupies 327682⋅4=23232768^2\cdot4=2^{32} 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. QK⊤QK\T has T2T^2 outputs and a length-dd reduction, approximately 2T2d2T^2d FLOPs; PVPV adds another 2T2d2T^2d. Softmax adds order-T2T^2 work excluded from this approximation. For batch BB and HH equal heads, multiply both products by BHBH. Q, K, V, and output projections are additional order-Tdmodelo2Td_{\text{modelo}}^2 terms; at small TT they can dominate even though attention grows quadratically with length.

In an implementation materializing scores and probabilities, each has BHT2BHT^2 elements. Saving them for backward can cost more than Q, K, and V vectors themselves, whose size grows as BHTdBHTd. A causal mask reduces mathematically visible positions to T(T+1)/2T(T+1)/2 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 sjs_j and values vj\vb{v}_j, maintain maximum mm, sum ℓ=∑jesj−m\ell=\sum_j e^{s_j-m}, and numerator u=∑jesj−mvj\vb{u}=\sum_j e^{s_j-m}\vb{v}_j. Output is u/ℓ\vb{u}/\ell. In online softmax, when adding a block with maximum mBm_B, sum ℓB\ell_B, and numerator uB\vb{u}_B calculated relative to mBm_B, combine with m′=max⁡(m,mB)m'=\max(m,m_B):

ℓ′=em−m′ℓ+emB−m′ℓB,u′=em−m′u+emB−m′uB.\ell'=e^{m-m'}\ell+e^{m_B-m'}\ell_B,\qquad \vb{u}'=e^{m-m'}\vb{u}+e^{m_B-m'}\vb{u}_B.

Rescaling is essential: if a larger maximum arrives, old terms were measured against another reference. Initialize m=−∞m=-\infty, ℓ=0\ell=0, and u=0\vb{u}=\vb{0}, explicitly handling the empty state to avoid −∞−(−∞)-\infty-(-\infty). Stable streaming summation is studied in Milakov and Gimelshein.

InteractiveRescaling when a new maximum arrives
−1−0.500.511.522.5122−1Score
1
Running maximum2.00
Normalizing sum1.050
Weighted output0.047
Advance through blocks of two scores. Scores are [2, -1, 4, 0, -2, 3] and values are [0, 1, 2, 3, 4, 5]. The second pair changes the maximum: the previous sum is rescaled before addition.

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 1+e−31+e^{-3}. When the block containing 4 and 0 arrives, the new maximum is 4. Before adding its contributions, multiply the previous state by e−2e^{-2}, 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, m+log⁡ℓm+\log\ell is the whole row’s logsumexp. Retaining it permits an individual probability to be recovered as esj−LSE⁡e^{s_j-\operatorname{LSE}} 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 −∞-\infty and handles an empty maximum before subtraction; otherwise −∞−(−∞)-\infty-(-\infty) 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 em1−mℓ1=∑j∈B1esj−me^{m_1-m}\ell_1=\sum_{j\in B_1}e^{s_j-m}, and likewise for the second. Their sum is exactly the union’s normalizer under m=max⁡(m1,m2)m=\max(m_1,m_2). 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 LSE⁡i=mi+log⁡ℓi\operatorname{LSE}_i=m_i+\log\ell_i per row to reconstruct probabilities. A causal mask excludes j>ij>i before exponentiation; blocks wholly above the diagonal can be skipped.

In backward recomputation, each score block SijS_{ij} is recalculated and Pij=eSij−LSE⁡iP_{ij}=e^{S_{ij}-\operatorname{LSE}_i} obtained. If G=∂L/∂O\mat{G}=\partial L/\partial\mat{O} and Di=Gi⊤OiD_i=\vb{G}_i\T\vb{O}_i, the softmax derivative gives

∂L∂Sij=Pij(Gi⊤Vj−Di).\frac{\partial L}{\partial S_{ij}}=P_{ij}\big(\vb{G}_i\T\vb{V}_j-D_i\big).

Then accumulate ∇Q=∇SK/d\nabla_Q=\nabla_S K/\sqrt d, ∇K=∇S⊤Q/d\nabla_K=\nabla_S\T Q/\sqrt d, and ∇V=P⊤G\nabla_V=P\T G blockwise. The calculation adds products that could have been avoided by saving PP, but saves that storage and traffic. This should not be confused with reducing dense attention’s quadratic FLOP order.

To see where DiD_i comes from, the output derivative with respect to PijP_{ij} is Gi⊤Vj\vb{G}_i\T\vb{V}_j. The softmax vector product subtracts its weighted mean: ∑jPij(Gi⊤Vj)=Gi⊤∑jPijVj=Gi⊤Oi\sum_j P_{ij}(\vb{G}_i\T\vb{V}_j)=\vb{G}_i\T\sum_j P_{ij}\vb{V}_j=\vb{G}_i\T\vb{O}_i. 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.

[ ]Tiled forward and backwardBrowser
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 d≤M≤Tdd\le M\le Td and MM measured in elements, standard materialized attention has Θ(Td+T2)\Theta(Td+T^2) HBM accesses and the analyzed algorithm Θ(T2d2/M)\Theta(T^2d^2/M). 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 MM sizes in the interval. It does not prove a tight lower bound for each separate MM. Exact bytes cannot be obtained solely from Θ\Theta notation.

One intuition is that if tile size is proportional to M/dM/d, more fast memory permits each load to be reused in more products. Position pairs still grow as T2T^2; 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 T×TT\times T 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.

InteractiveA tiled traffic plan
Columns: K blocks
00.511.522.5Materialized2.25Tiled2.126MiB transferred
512
32
1
64
Block pairs visited256
Estimated SRAM usage18.1 KiB
Does the block fit?Yes
Adjust T, block, and SRAM. If the block does not fit, the plan cannot run at that capacity. The materialized path computes the complete square even in causal mode; the tiled path skips future blocks.

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.

[ ]Count transfers in an explicit planBrowser
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'] == 10

FlashAttention-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.

InteractiveA published A100 comparison
010203040Standard40.3Flash4.4GB HBM
Metric
Flash / standard0.11
Switch between computation, traffic, and time. Six values come from figure 2 of the cited paper for the configuration described above; they do not replace a local benchmark against sequence length.

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.

InteractiveA local run: math and Flash
  • Math
  • Flash
Mask
Metric
Flash / math at T=20480.22
Switch between time and additional peak, and between causal and noncausal. These are four lengths measured in one run, not a speed guarantee. Peak is measured with the PyTorch allocator.
[ ]Measure SDPA on the available GPULocal GPU
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()])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

An additional noncausal math sweep with the same batch and head shape completed T=4096T=4096, 8192, 12288, and 16384 in another WSL run on RTX 3060; additional peak allocation was 536.2, 2064, 4632, and 8224 MiB respectively. Before T=16384T=16384, 11155 MiB free were reported. A separate T=20480T=20480 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 T=20480T=20480, 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.

[ ]An optional long shapeLocal GPU
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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Quiz
What does FlashAttention change compared with materialized dense attention?
Numeric
How many GiB does a 32768 × 32768 float32 matrix occupy?
Numeric
In the figure's idealized plan, take T = 4096, d = 64, square blocks of 128, and two-byte elements, without a causal mask. If the only reads are Q once and full K and V for every Q block, how many MiB are read? Available SRAM is 100 KiB and the plan requires 98816 bytes for its blocks.
Proof
Prove: Merging states of two blocks reproduces their union's sums.
0
Each block has maximum m, normalizer l, and numerator u, all relative to its own maximum.

Step 1 of 3. What maximum is used for the union?

Code
Implement flash_forward(Q, K, V, block_q, block_k, causal), returning output and per-row logsumexp. Traverse blocks without building the complete attention matrix; tests use equal-length matrices and at least one valid key per query.
import numpy as np
def flash_forward(Q, K, V, block_q, block_k, causal):
  pass
Shift+Enter to run
Key idea
FlashAttention avoids materializing the attention matrix through a stable online reduction and blocks in fast memory. It preserves dense attention, with rounding differences and a traffic-recomputation trade-off.