Module contents
Lesson 7 of 28Advanced 115 min

Attention kernels in Triton and the CUDA ecosystem

Module m18 derived FlashAttention in NumPy; here we write the GPU kernel. We implement Triton forward with online softmax and causal-block skipping and backward with recomputation, including GQA and sliding-window variants. We then move up a level to FlexAttention, which generates kernels from a score function and block mask, and down to CUDA C++ and data-center GPU features behind FlashAttention-3.

After this lesson you can

  • Implement causal and noncausal FlashAttention forward in Triton with per-row logsumexp.
  • Implement backward with D = rowsum(dO ∘ O) preprocessing and dK, dV and dQ kernels, verified against SDPA.
  • Express masks and biases (sliding window, documents, prefix) with FlexAttention and measure the benefit of skipping blocks.
  • Compile and call a custom CUDA C++ kernel from PyTorch and decide when it is worthwhile compared with Triton.
  • Explain what TMA, wgmma and warp specialization contribute to FlashAttention-3 performance.

Before you start

From algorithm to GPU program

In FlashAttention you learned that exact attention can be processed in blocks without storing the quadratic probability matrix. The kernel must also assign work to programs, handle masks and edges, accumulate with sufficient precision, and decide what information to save for backward. The first FlashAttention paper optimizes traffic between memory and SRAM; FlashAttention-2 improves work partitioning and parallelism. A newer version does not guarantee greater speed for every shape and GPU.

The Triton blockwise forward pass assigns a program to a query block of one head and one batch element. The program reads its QQ tile and traverses K,VK,V tiles. For each block it computes scores S=QK⊤/dS=QK\T/\sqrt d, applies the mask, and updates maximum mm, sum ℓ\ell, and output accumulator. With m′m' as the new maximum, it rescales old accumulators by em−m′e^{m-m'} before adding the block. Finally it writes OO and LSE⁡=m+log⁡ℓ\operatorname{LSE}=m+\log\ell per row. This is online softmax applied to Triton’s program model.

InteractiveAttention programs and blocks

Rows are Q blocks and columns are K blocks. A diagonal causal block is partial and requires an elementwise mask. The count covers whole skipped blocks. Actual work also includes edges and softmax.

8
Mask
Block pair 1
Executed blocks36 / 64
Skipped blocks28
Work in current program1 blocks
Each row is a query program and each column a key tile. Blocks above the causal diagonal can be skipped entirely.

With equal-sized square blocks, a key block strictly after the query block is entirely invalid and needs no matrix product. The diagonal block contains valid and invalid positions and needs an elementwise mask. For T=4096T=4096 and blocks of 128, there are 32 blocks per axis: 32⋅31/2=49632\cdot31/2=496 of 1024 are skipped, or 48.4375%. The count includes entire diagonal blocks in executed work and does not claim their arithmetic cost is exactly that of a full block.

Rows with no valid keys need an explicit policy. Starting at m=−∞m=-\infty and updating with another −∞-\infty makes the subtraction produce NaN. In an ordinary square causal mask each valid query can see itself; when mixing lengths, documents, or padding that assumption can fail. The kernel must choose and verify the expected output and gradient for empty rows.

The online update merits a concrete check. Suppose processed blocks have maximum mm and sum ℓ=∑jeSj−m\ell=\sum_j e^{S_j-m}, and the new block has maximum mbm_b. Choosing m′=max⁡(m,mb)m'=\max(m,m_b) changes the old contribution to em−m′ℓe^{m-m'}\ell. New terms are eSj−m′e^{S_j-m'}. The same factor rescales accumulator A=∑jeSj−mVjA=\sum_j e^{S_j-m}V_j. After incorporating all blocks, O=A/ℓO=A/\ell. LSE retains the scale lost to shifts and allows PP to be reconstructed in backward.

A real implementation uses suitable accumulator precision and matrix units compatible with the input type. In BF16, for example, converting probabilities to feed a matrix product introduces rounding even if sum and maximum stay in FP32. It is normal to compare against a higher-precision reference and set appropriate tolerances, but a large tolerance must not hide an incorrect causal index. Test sequences not divisible by block size and extreme values, as well as a small case allowing inspection of the dense matrix.

A concrete calculation shows the memory difference. For batch one, 16 heads, and T=4096T=4096, a full FP32 score matrix needs 16⋅40962⋅4=107374182416\cdot4096^2\cdot4=1073741824 bytes, exactly 1 GiB. Saving one FP32 LSE per row needs 262144 bytes; a BF16 output with d=64d=64 needs 8388608 bytes. These figures exclude Q,K,VQ,K,V, gradients, and other temporaries, and the system may materialize additional matrices. The algorithm avoids a persistent quadratic matrix but does not stop dense attention work growing quadratically.

Tile size also affects parallelism. If each program owns a query block, program count is batch times heads times ⌈T/BM⌉\lceil T/B_M\rceil. With few heads or short sequences there may be too few programs to occupy the GPU; for long sequences and a causal mask, early programs traverse fewer keys than later ones. Increasing BMB_M reduces program count and amortizes some loads, but increases the accumulator and can reduce occupancy. The fastest shape depends on architecture and must be measured, not inferred solely from a FLOP formula.

Recompute probabilities in backward

Let P=softmax⁡(S)P=\operatorname{softmax}(S) and O=PVO=PV. With gradient dOdO, the formulas are dV=P⊤dOdV=P\T dO, dP=dOV⊤dP=dO V\T, and dS=P⊙(dP−D)dS=P\odot(dP-D), where Di=∑jPijdPijD_i=\sum_j P_{ij}dP_{ij}. Since Oi=∑jPijVjO_i=\sum_jP_{ij}V_j,

Di=∑kdOikOik=∑jPij∑kdOikVjk=∑jPijdPij.D_i=\sum_k dO_{ik}O_{ik}=\sum_jP_{ij}\sum_k dO_{ik}V_{jk} =\sum_jP_{ij}dP_{ij}.

The equality lets us compute DD from O,dOO,dO without storing PP. Each block is then reconstructed as Pij=exp⁡(Sij−LSE⁡i)P_{ij}=\exp(S_{ij}-\operatorname{LSE}_i), giving dQ=dSK/ddQ=dS K/\sqrt d and dK=dS⊤Q/ddK=dS\T Q/\sqrt d. The kernel backward pass can use one program per key block for dK,dVdK,dV and another per query block for dQdQ. Both passes recompute probabilities, but each output has one owner and avoids conflicts. An alternative uses atomics or a partial buffer to sum dQdQ contributions, changing memory, traffic, cost, and summation order.

The factor 1/d1/\sqrt d appears in dQdQ and dKdK because it differentiates the scale applied to QK⊤QK\T; it does not apply to dVdV. Masked positions have zero probability and derivative. A kernel per key block traverses every query block that can attend to those keys; one per query block traverses in the opposite direction. In both cases the sum must include every valid block, including the final partial one. If a program skips a causal future region, it must maintain the same boundary condition in forward and backward.

With floating-point atomics, contributions can arrive in different orders, and nonassociative addition can change the last bits. Without atomics, a temporary buffer permits writing one partial per block pair and reducing later; that strategy can consume a significant fraction of the memory one aimed to save. Recomputing in a separate kernel reduces conflicts and buffer use but rereads inputs and repeats products. The best partition depends on length, head count, dimension, and architecture.

InteractiveWho writes each gradient
Q, K, V and LSE
Recompute P and dS
One kernel per Q block accumulates dQ
Write dK and dV

In this dense model, Q blocks have 128 rows and every block pair contributes to dQ. It omits edges and masking. An alternative buffer for partial results uses q × k × 128 × d elements before reduction. Physical traffic depends on the types, cache, and compilation.

8
8
64
Strategy
Stage 1 of 4
Logical dQ writes65,536
Contributions per element8
Summation orderLocal to the program
Compare a logical count of dQ writes for atomics and a separate kernel. This is not a measurement of physical transactions.

In GQA multiple query heads share one key and value head. If HqH_q is divisible by HkvH_{kv}, head hh uses ⌊h/(Hq/Hkv)⌋\lfloor h/(H_q/H_{kv})\rfloor. The K,VK,V gradients must sum contributions from every query head sharing that head. A causal window further restricts j≤ij\le i and i−j<wi-j<w; with variable lengths, conditions are combined per position. Verify the chosen semantics before comparing against another backend.

For example, with eight query heads and two key and value heads, queries 0 through 3 use KV head 0 and queries 4 through 7 use KV 1. In forward each program can select that head without physically duplicating its tensors. In backward an owner of KV head 0 must sum the corresponding four partial gradients. A reference repeating K,VK,V for every query head is useful for checking semantics although it consumes more memory; autograd then accumulates contributions into the original shared tensors.

Query and key lengths can differ. The index of a padded position must prevent both invalid data reads and writes of gradient contributions. A row with a valid query but zero keys needs a defined convention: for example, zero output and gradients, with an auxiliary LSE value not used without the validity mask. Compare that convention with the reference backend before assuming implementations are equivalent. The simplest causal code with an always-valid diagonal does not itself cover that case.

Check recomputation on a small example

This CPU control calculates causal attention in blocks and reconstructs PP in backward using only stored LSE. It does not execute a GPU kernel or demonstrate its speed. The dense reference retains PP so you can compare both gradients.

[ ]Online softmax and blockwise backwardBrowser
import numpy as np
rng=np.random.default_rng(7);t,d=11,8
q=rng.normal(size=(t,d));k=rng.normal(size=(t,d));v=rng.normal(size=(t,d));do=rng.normal(size=(t,d))
scores=q@k.T/np.sqrt(d);valid=np.arange(t)[:,None]>=np.arange(t)[None,:]
masked=np.where(valid,scores,-np.inf);mx=masked.max(axis=1)
p=np.exp(masked-mx[:,None]);p/=p.sum(axis=1,keepdims=True)
ref=p@v;delta=(do*ref).sum(axis=1)
dp=do@v.T;ds=p*(dp-delta[:,None]);refdq=ds@k/np.sqrt(d);refdk=ds.T@q/np.sqrt(d);refdv=p.T@do
m=np.full(t,-np.inf);den=np.zeros(t);acc=np.zeros((t,d))
for start in range(0,t,4):
    end=min(t,start+4);z=masked[:,start:end];new=np.maximum(m,z.max(axis=1))
    safe=np.where(np.isfinite(new),new,0.)
    old=np.exp(m-safe);prob=np.exp(z-safe[:,None])
    acc=acc*old[:,None]+prob@v[start:end];den=den*old+prob.sum(axis=1);m=new
out=acc/den[:,None];lse=m+np.log(den);delta=(do*out).sum(axis=1)
dq=np.zeros_like(q);dk=np.zeros_like(k);dv=np.zeros_like(v)
for start in range(0,t,4):
    end=min(t,start+4);prob=np.exp(masked[:,start:end]-lse[:,None])
    dp=do@v[start:end].T;ds=prob*(dp-delta[:,None])
    dq+=ds@k[start:end]/np.sqrt(d);dk[start:end]=ds.T@q/np.sqrt(d);dv[start:end]=prob.T@do
for name,a,b in [('O',out,ref),('dQ',dq,refdq),('dK',dk,refdk),('dV',dv,refdv)]:
    print(name,'error máximo',np.max(np.abs(a-b)))
    np.testing.assert_allclose(a,b,atol=1e-12,rtol=1e-12)

Local lab: Triton forward and backward

The educational kernel runs one program per query block for forward and dQ and another per key block for dK/dV. It stores output and LSE, recomputes probabilities, and sums query heads sharing KV. It supports causal masks, windows, fixed-length documents, linear bias, and per-batch lengths. Rows without valid keys produce zero output and gradients. The path assumes contiguous Q, K and V, equal physical length, and head dimension up to 128; it does not implement dropout.

The cell compares BF16 output and gradients with a dense FP32 reference, including GQA and an empty row, and checks the standard case against available SDPA MATH and FLASH backends. A rejected backend is explicitly recorded. It measures forward and forward plus backward after compilation and warm-up. As in the previous lesson, Triton line information is disabled to avoid non-ASCII virtual names rejected by this ptxas version.

[ ]Causal FlashAttention, GQA and tiled backwardLocal GPU
"""Prototipo de atención exacta por bloques; pendiente de ejecutar en CUDA."""
import os
os.environ['TRITON_DISABLE_LINE_INFO']='1'
import math
import torch
import triton
import triton.language as tl
import triton.testing
import torch.nn.functional as F
from torch.nn.attention import SDPBackend, sdpa_kernel

@triton.jit
def fwd(Q,K,V,O,LSE,QL,KL,HQ:tl.constexpr,HK:tl.constexpr,T:tl.constexpr,
        D:tl.constexpr,CAUSAL:tl.constexpr,WINDOW:tl.constexpr,DOC:tl.constexpr,ALIBI:tl.constexpr,
        BM:tl.constexpr,BN:tl.constexpr,BD:tl.constexpr):
    bi=tl.program_id(0); h=tl.program_id(1); b=tl.program_id(2)
    hk=h//(HQ//HK); mi=bi*BM+tl.arange(0,BM); nj=tl.arange(0,BN); dd=tl.arange(0,BD)
    ql=tl.load(QL+b);kl=tl.load(KL+b)
    q=tl.load(Q+((b*HQ+h)*T+mi[:,None])*D+dd[None,:],(mi[:,None]<ql)&(dd[None,:]<D),0)
    m=tl.full((BM,),-float('inf'),tl.float32);s=tl.full((BM,),0,tl.float32)
    acc=tl.full((BM,BD),0,tl.float32)
    for start in range(0,T,BN):
        j=start+nj
        # Salto de bloques estrictamente futuros; el diagonal se enmascara por posición.
        if not CAUSAL or start < (bi+1)*BM:
            k=tl.load(K+((b*HK+hk)*T+j[:,None])*D+dd[None,:],(j[:,None]<kl)&(dd[None,:]<D),0)
            v=tl.load(V+((b*HK+hk)*T+j[:,None])*D+dd[None,:],(j[:,None]<kl)&(dd[None,:]<D),0)
            scores=tl.dot(q,tl.trans(k))*tl.rsqrt(float(D))
            if ALIBI: scores=scores-(h+1)*0.01*(mi[:,None]-j[None,:])
            mask=(mi[:,None]<ql)&(j[None,:]<kl)
            if CAUSAL: mask=mask&(j[None,:]<=mi[:,None])
            if WINDOW>0: mask=mask&(j[None,:]>mi[:,None]-WINDOW)
            if DOC>0: mask=mask&(mi[:,None]//DOC==j[None,:]//DOC)
            scores=tl.where(mask,scores,-float('inf'))
            nm=tl.maximum(m,tl.max(scores,1));safe=tl.where(nm==-float('inf'),0.,nm)
            old=tl.exp(m-safe);p=tl.exp(scores-safe[:,None])
            acc=acc*old[:,None]+tl.dot(p.to(v.dtype),v)
            s=s*old+tl.sum(p,1);m=nm
    valid=s>0;denom=tl.where(valid,s,1.)
    out=acc/denom[:,None];lse=tl.where(valid,m+tl.log(denom),0.)
    tl.store(O+((b*HQ+h)*T+mi[:,None])*D+dd[None,:],out,(mi[:,None]<T)&(dd[None,:]<D))
    tl.store(LSE+(b*HQ+h)*T+mi,lse,mi<T)

@triton.jit
def dq_kernel(Q,K,V,O,DO,LSE,DQ,QL,KL,HQ:tl.constexpr,HK:tl.constexpr,T:tl.constexpr,
              D:tl.constexpr,CAUSAL:tl.constexpr,WINDOW:tl.constexpr,DOC:tl.constexpr,ALIBI:tl.constexpr,
              BM:tl.constexpr,BN:tl.constexpr,BD:tl.constexpr):
    bi=tl.program_id(0);h=tl.program_id(1);b=tl.program_id(2);hk=h//(HQ//HK)
    i=bi*BM+tl.arange(0,BM);jj=tl.arange(0,BN);d=tl.arange(0,BD)
    ql=tl.load(QL+b);kl=tl.load(KL+b);qmask=(i[:,None]<ql)&(d[None,:]<D)
    q=tl.load(Q+((b*HQ+h)*T+i[:,None])*D+d[None,:],qmask,0)
    o=tl.load(O+((b*HQ+h)*T+i[:,None])*D+d[None,:],qmask,0).to(tl.float32)
    do=tl.load(DO+((b*HQ+h)*T+i[:,None])*D+d[None,:],qmask,0)
    lse=tl.load(LSE+(b*HQ+h)*T+i,i<T,0);delta=tl.sum(o*do.to(tl.float32),1)
    dq=tl.full((BM,BD),0,tl.float32)
    for start in range(0,T,BN):
        j=start+jj
        if not CAUSAL or start<(bi+1)*BM:
            kmask=(j[:,None]<kl)&(d[None,:]<D)
            k=tl.load(K+((b*HK+hk)*T+j[:,None])*D+d[None,:],kmask,0)
            v=tl.load(V+((b*HK+hk)*T+j[:,None])*D+d[None,:],kmask,0)
            z=tl.dot(q,tl.trans(k))*tl.rsqrt(float(D));mask=(i[:,None]<ql)&(j[None,:]<kl)
            if ALIBI: z=z-(h+1)*0.01*(i[:,None]-j[None,:])
            if CAUSAL: mask=mask&(j[None,:]<=i[:,None])
            if WINDOW>0: mask=mask&(j[None,:]>i[:,None]-WINDOW)
            if DOC>0: mask=mask&(i[:,None]//DOC==j[None,:]//DOC)
            p=tl.where(mask,tl.exp(z-lse[:,None]),0.)
            dp=tl.dot(do,tl.trans(v));ds=p*(dp-delta[:,None])*tl.rsqrt(float(D))
            dq+=tl.dot(ds.to(k.dtype),k)
    tl.store(DQ+((b*HQ+h)*T+i[:,None])*D+d[None,:],dq,(i[:,None]<T)&(d[None,:]<D))

@triton.jit
def dkv_kernel(Q,K,V,O,DO,LSE,DK,DV,QL,KL,HQ:tl.constexpr,HK:tl.constexpr,T:tl.constexpr,
               D:tl.constexpr,CAUSAL:tl.constexpr,WINDOW:tl.constexpr,DOC:tl.constexpr,ALIBI:tl.constexpr,
               BM:tl.constexpr,BN:tl.constexpr,BD:tl.constexpr):
    bj=tl.program_id(0);hk=tl.program_id(1);b=tl.program_id(2)
    j=bj*BN+tl.arange(0,BN);ii=tl.arange(0,BM);d=tl.arange(0,BD)
    ql=tl.load(QL+b);kl=tl.load(KL+b);kmask=(j[:,None]<kl)&(d[None,:]<D)
    k=tl.load(K+((b*HK+hk)*T+j[:,None])*D+d[None,:],kmask,0)
    v=tl.load(V+((b*HK+hk)*T+j[:,None])*D+d[None,:],kmask,0)
    dk=tl.full((BN,BD),0,tl.float32);dv=tl.full((BN,BD),0,tl.float32)
    for group in range(HQ//HK):
        h=hk*(HQ//HK)+group
        for start in range(0,T,BM):
            i=start+ii;qmask=(i[:,None]<ql)&(d[None,:]<D)
            q=tl.load(Q+((b*HQ+h)*T+i[:,None])*D+d[None,:],qmask,0)
            o=tl.load(O+((b*HQ+h)*T+i[:,None])*D+d[None,:],qmask,0).to(tl.float32)
            do=tl.load(DO+((b*HQ+h)*T+i[:,None])*D+d[None,:],qmask,0)
            lse=tl.load(LSE+(b*HQ+h)*T+i,i<T,0);delta=tl.sum(o*do.to(tl.float32),1)
            z=tl.dot(q,tl.trans(k))*tl.rsqrt(float(D));mask=(i[:,None]<ql)&(j[None,:]<kl)
            if ALIBI: z=z-(h+1)*0.01*(i[:,None]-j[None,:])
            if CAUSAL: mask=mask&(j[None,:]<=i[:,None])
            if WINDOW>0: mask=mask&(j[None,:]>i[:,None]-WINDOW)
            if DOC>0: mask=mask&(i[:,None]//DOC==j[None,:]//DOC)
            p=tl.where(mask,tl.exp(z-lse[:,None]),0.)
            dp=tl.dot(do,tl.trans(v));ds=p*(dp-delta[:,None])*tl.rsqrt(float(D))
            dv+=tl.dot(tl.trans(p.to(do.dtype)),do)
            dk+=tl.dot(tl.trans(ds.to(q.dtype)),q)
    dst=((b*HK+hk)*T+j[:,None])*D+d[None,:];outmask=(j[:,None]<T)&(d[None,:]<D)
    tl.store(DK+dst,dk,outmask);tl.store(DV+dst,dv,outmask)

class Flash(torch.autograd.Function):
    @staticmethod
    def forward(ctx,q,k,v,ql,kl,causal,window,doc,alibi):
        assert q.is_contiguous() and k.is_contiguous() and v.is_contiguous()
        b,hq,t,d=q.shape;hk=k.shape[1]
        assert hq%hk==0 and k.shape==v.shape==(b,hk,t,d) and d<=128
        out=torch.empty_like(q);lse=torch.empty((b,hq,t),device=q.device,dtype=torch.float32)
        bm,bn,bd=16,32,triton.next_power_of_2(d)
        fwd[(triton.cdiv(t,bm),hq,b)](q,k,v,out,lse,ql,kl,hq,hk,t,d,causal,window,doc,alibi,bm,bn,bd)
        ctx.save_for_backward(q,k,v,out,lse,ql,kl);ctx.args=(causal,window,doc,alibi,bm,bn,bd)
        return out
    @staticmethod
    def backward(ctx,do):
        q,k,v,out,lse,ql,kl=ctx.saved_tensors;do=do.contiguous();b,hq,t,d=q.shape;hk=k.shape[1]
        causal,window,doc,alibi,bm,bn,bd=ctx.args
        dq=torch.empty_like(q);dk=torch.empty_like(k);dv=torch.empty_like(v)
        dq_kernel[(triton.cdiv(t,bm),hq,b)](q,k,v,out,do,lse,dq,ql,kl,hq,hk,t,d,causal,window,doc,alibi,bm,bn,bd)
        dkv_kernel[(triton.cdiv(t,bn),hk,b)](q,k,v,out,do,lse,dk,dv,ql,kl,hq,hk,t,d,causal,window,doc,alibi,bm,bn,bd)
        return dq,dk,dv,None,None,None,None,None,None

def attention(q,k,v,ql,kl,causal=False,window=0,doc=0,alibi=False):
    return Flash.apply(q,k,v,ql,kl,causal,window,doc,alibi)

def reference(q,k,v,ql,kl,causal,window,doc=0,alibi=False):
    b,h,t,d=q.shape;group=h//k.shape[1]
    kk=k.repeat_interleave(group,dim=1).float();vv=v.repeat_interleave(group,dim=1).float()
    scores=q.float()@kk.transpose(-2,-1)/math.sqrt(d)
    i=torch.arange(t,device=q.device);j=i
    mask=(i[None,:,None]<ql[:,None,None])&(j[None,None,:]<kl[:,None,None])
    if causal: mask=mask&(j[None,None,:]<=i[None,:,None])
    if window: mask=mask&(j[None,None,:]>i[None,:,None]-window)
    if doc: mask=mask&(i[None,:,None]//doc==j[None,None,:]//doc)
    if alibi: scores=scores-(torch.arange(h,device=q.device)[None,:,None,None]+1)*.01*(i[None,None,:,None]-j[None,None,None,:])
    scores=scores.masked_fill(~mask[:,None],-torch.inf)
    has=mask.any(-1);scores=torch.where(has[:,None,:,None],scores,torch.zeros_like(scores))
    p=torch.softmax(scores,dim=-1)*mask[:,None]
    return p@vv

if __name__=='__main__':
    torch.manual_seed(7);print(torch.__version__,triton.__version__,torch.cuda.get_device_name())
    for causal,window,heads,empty,doc,alibi in [(False,0,4,False,0,False),(True,0,4,False,0,False),(True,13,2,True,0,False),(True,13,2,False,32,True)]:
        b,h,t,d=2,4,65,32;ql=torch.tensor([65,53],device='cuda',dtype=torch.int32);kl=torch.tensor([0 if empty else 65,42],device='cuda',dtype=torch.int32)
        q=torch.randn(b,h,t,d,device='cuda',dtype=torch.bfloat16,requires_grad=True)
        k=torch.randn(b,heads,t,d,device='cuda',dtype=torch.bfloat16,requires_grad=True)
        v=torch.randn_like(k,requires_grad=True);up=torch.randn_like(q)
        y=attention(q,k,v,ql,kl,causal,window,doc,alibi);grads=torch.autograd.grad(y,(q,k,v),up)
        ref=reference(q,k,v,ql,kl,causal,window,doc,alibi);rg=torch.autograd.grad(ref,(q,k,v),up.float())
        torch.testing.assert_close(y.float(),ref,rtol=.04,atol=.04)
        for actual,expected in zip(grads,rg):torch.testing.assert_close(actual.float(),expected.float(),rtol=.06,atol=.06)
        print('causal/window/Hkv/keys-empty/doc/alibi',causal,window,heads,empty,doc,alibi,'max forward error',(y.float()-ref).abs().max().item(),flush=True)
    for causal in (False,True):
        b,h,t,d=1,4,128,64
        q=torch.randn(b,h,t,d,device='cuda',dtype=torch.bfloat16,requires_grad=True)
        k=torch.randn_like(q,requires_grad=True);v=torch.randn_like(q,requires_grad=True)
        lens=torch.full((b,),t,device='cuda',dtype=torch.int32);up=torch.randn_like(q)
        ours=attention(q,k,v,lens,lens,causal,0);og=torch.autograd.grad(ours,(q,k,v),up)
        for backend in (SDPBackend.MATH,SDPBackend.FLASH_ATTENTION):
            try:
                with sdpa_kernel(backend):
                    ref=F.scaled_dot_product_attention(q,k,v,is_causal=causal)
                    rg=torch.autograd.grad(ref,(q,k,v),up)
                    torch.testing.assert_close(ours.float(),ref.float(),rtol=.04,atol=.04)
                    for x,y in zip(og,rg):torch.testing.assert_close(x.float(),y.float(),rtol=.06,atol=.06)
                    ms=triton.testing.do_bench(lambda:F.scaled_dot_product_attention(q,k,v,is_causal=causal),warmup=20,rep=50,return_mode='median')
                    print('backend disponible',backend,'causal',causal,'forward ms',ms,flush=True)
            except RuntimeError as exc:
                print('backend no disponible',backend,str(exc).splitlines()[0],flush=True)
        ms=triton.testing.do_bench(lambda:attention(q,k,v,lens,lens,causal,0),warmup=20,rep=50,return_mode='median')
        pairs=t*(t+1)/2 if causal else t*t
        flop=4*b*h*pairs*d
        print('propio causal',causal,'forward ms',ms,'TFLOP/s efectivos',flop/(ms*1e9),flush=True)
        def forward_backward():
            out=attention(q,k,v,lens,lens,causal,0)
            return torch.autograd.grad(out,(q,k,v),up)
        whole=triton.testing.do_bench(forward_backward,warmup=20,rep=50,return_mode='median')
        print('propio causal',causal,'forward+backward ms',whole,flush=True)
    b,h,hk,t,d=1,4,2,64,32
    q=torch.randn(b,h,t,d,device='cuda',dtype=torch.bfloat16,requires_grad=True)
    k=torch.randn(b,hk,t,d,device='cuda',dtype=torch.bfloat16,requires_grad=True);v=torch.randn_like(k,requires_grad=True)
    lens=torch.full((b,),t,device='cuda',dtype=torch.int32);up=torch.randn_like(q)
    own=attention(q,k,v,lens,lens,True,0);own_grad=torch.autograd.grad(own,(q,k,v),up)
    with sdpa_kernel(SDPBackend.MATH):
        reference_gqa=F.scaled_dot_product_attention(q,k,v,is_causal=True,enable_gqa=True)
        expected_grad=torch.autograd.grad(reference_gqa,(q,k,v),up)
    torch.testing.assert_close(own.float(),reference_gqa.float(),atol=.04,rtol=.04)
    for actual,expected in zip(own_grad,expected_grad):torch.testing.assert_close(actual.float(),expected.float(),atol=.06,rtol=.06)
    print('GQA versus SDPA MATH: forward y gradientes correctos',flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In one run with Torch 2.11.0, Triton 3.6.0, and RTX 3060, maximum forward error was 0.00393 to 0.00930 over four tested cases and gradients passed tolerances. For batch 1, four heads, T=128, and d=64, the custom median was 0.009216 ms without a causal mask and 0.011264 ms with one. The data come from a shared GPU, not a performance constant. The causal rate counts only valid pairs, although a partial diagonal block may execute more operations.

Programmable masks

FlexAttention separates a score_mod function transforming each score from a block mask specifying which position pairs may exist. For example, a linear distance bias can be expressed with score_mod, while a causal window and document boundaries produce a mask allowing empty blocks to be skipped. Partial blocks still evaluate the condition element by element. Mask construction can cost time and it should be reused only while lengths and conditions remain valid. The FlexAttention publication describes the model and compilation; the exact API depends on PyTorch version.

In packed documents, two adjacent tokens in memory can belong to different documents. The mask must require equal document identifiers in addition to the causal constraint. A window also limits distance, for example 0≤i−j<w0\le i-j<w. An ALiBi-style bias can subtract a head-dependent slope multiplied by distance: it changes allowed values but does not make masked positions valid. Compare the composition against a small dense implementation applying exactly the three conditions and comparing output and gradients.

Full blocks allow some position checks to be omitted; empty blocks can be skipped. A partial block still needs an internal mask, and a mask changing each batch can have significant preparation cost. Measuring only the kernel after building a mask once answers a different question from measuring a full step that rebuilds it each time. The figure expresses an ideal block-work bound, not a prediction of torch.compile performance.

InteractiveFrom mask to blocks

Blue marks full blocks, green marks partial blocks, and gray marks empty blocks. The ideal speedup assumes identical cost for each active block and zero cost for constructing the mask.

Mask
Block
4
Empty blocks6 / 16
Active blocks10
Ideal block speedup1.60×
Compare masks over 16 positions with various block sizes. The ideal ratio counts only active blocks and excludes construction and control costs.

The next cell uses create_block_mask with blocks of 128, a causal window of 64, 128-position documents, and a head-dependent bias. It compares output and gradients with the dense reference and previous kernel. To isolate the effect of skipping blocks, it also compares a version applying the same mask inside score_mod without a block mask. Mask construction happens before measurement and is excluded from medians.

[ ]FlexAttention, documents and biasLocal GPU
"""FlexAttention: documentos, ventana causal y sesgo lineal; pendiente de ejecutar."""
import os
os.environ['TRITON_DISABLE_LINE_INFO']='1'
import torch
import triton.testing
from torch.nn.attention.flex_attention import flex_attention,create_block_mask

def run():
    torch.manual_seed(7);device='cuda';b,h,t,d=2,4,256,64;window=64
    q=torch.randn(b,h,t,d,device=device,dtype=torch.bfloat16,requires_grad=True)
    k=torch.randn_like(q,requires_grad=True);v=torch.randn_like(q,requires_grad=True)
    def mask_mod(batch,head,qi,ki):
        return (qi//128==ki//128)&(ki<=qi)&(ki>qi-window)
    def score_mod(score,batch,head,qi,ki):
        return score-(head+1)*0.01*(qi-ki)
    def dense_score(score,batch,head,qi,ki):
        return torch.where(mask_mod(batch,head,qi,ki),score_mod(score,batch,head,qi,ki),-float('inf'))
    mask=create_block_mask(mask_mod,B=b,H=h,Q_LEN=t,KV_LEN=t,device=device,BLOCK_SIZE=128)
    compiled=torch.compile(flex_attention)
    out=compiled(q,k,v,score_mod=score_mod,block_mask=mask)
    grad=torch.randn_like(out);g=torch.autograd.grad(out,(q,k,v),grad)
    a=q.detach().float().requires_grad_();c=k.detach().float().requires_grad_();e=v.detach().float().requires_grad_()
    pos=torch.arange(t,device=device);qi=pos[:,None];ki=pos[None,:]
    allowed=(qi//128==ki//128)&(ki<=qi)&(ki>qi-window)
    heads=torch.arange(1,h+1,device=device)[None,:,None,None]
    z=(a@c.transpose(-2,-1))/d**.5-heads*.01*(qi-ki)
    reference=z.masked_fill(~allowed,-torch.inf).softmax(-1)@e
    expected=torch.autograd.grad(reference,(a,c,e),grad.float())
    torch.testing.assert_close(out.float(),reference,atol=.04,rtol=.04)
    for x,y in zip(g,expected):torch.testing.assert_close(x.float(),y,atol=.06,rtol=.06)
    lengths=torch.full((b,),t,device=device,dtype=torch.int32)
    own=attention(q,k,v,lengths,lengths,True,window,128,True)
    own_grad=torch.autograd.grad(own,(q,k,v),grad)
    torch.testing.assert_close(own.float(),reference,atol=.04,rtol=.04)
    for x,y in zip(own_grad,expected):torch.testing.assert_close(x.float(),y,atol=.06,rtol=.06)
    dense=compiled(q,k,v,score_mod=dense_score)
    torch.testing.assert_close(dense.float(),reference,atol=.04,rtol=.04)
    ms=triton.testing.do_bench(lambda:compiled(q,k,v,score_mod=score_mod,block_mask=mask),warmup=20,rep=50,return_mode='median')
    own_ms=triton.testing.do_bench(lambda:attention(q,k,v,lengths,lengths,True,window,128,True),warmup=20,rep=50,return_mode='median')
    dense_ms=triton.testing.do_bench(lambda:compiled(q,k,v,score_mod=dense_score),warmup=20,rep=50,return_mode='median')
    print('GPU',torch.cuda.get_device_name(),'torch',torch.__version__,'Flex bloques/Flex denso/propio ms',ms,dense_ms,own_ms,'max abs err',float((out.float()-reference).abs().max().detach()),flush=True)

if __name__=='__main__':run()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

For one BF16 run with batch 2, four heads, T=256 and d=64 on the RTX 3060, medians were 0.014336 ms with block mask, 0.029696 ms with dense mask, and 0.019456 ms for the custom kernel. Maximum absolute Flex error against the reference was 0.008185. These results are for this shape and load, not a speedup guarantee; both Flex paths share the same semantics and exclude mask construction.

C++ CUDA and different hardware

A CUDA extension can compile C++ and CUDA code and expose it to PyTorch, for example through torch.utils.cpp_extension.load_inline. The kernel implements indices, launches, device checks, and types; the extension must also respect streams and tensor lifetimes. RoPE is a useful example: it rotates channel pairs with sine and cosine, and fusing read, rotation, and write can avoid intermediates. Before going lower-level compare with a Triton version and a PyTorch reference, including compilation separately. CUTLASS and CuTe offer matrix multiplication and tile organization components; choosing them does not guarantee a particular shape is fast.

For an adjacent pair (a,b)(a,b) with cosine cc and sine ss, the rotation is (ac−bs,as+bc)(ac-bs,as+bc). Both original values are read before writing output. The position index selects the appropriate sine and cosine, while the pair index selects frequency. Pairing conventions vary across implementations: some pair adjacent channels and others the two halves of the dimension. A test must use the same convention and check both coordinates of each pair, not only the norm preserved by an ideal rotation.

The host wrapper validates that all tensors are on the same device, have expected type and size, and use the layout assumed by the kernel. Launch uses PyTorch’s current CUDA stream: launching on another stream without establishing a dependency could read inputs not yet produced. Checking launch errors helps locate invalid configurations, but some asynchronous failures appear only at synchronization. Extension compilation can take much longer than a call and is measured separately from the benchmarking loop.

The next example requires a CUDA toolkit, C++ compiler, and Ninja compatible with the PyTorch version. Set CUDA_HOME before starting Python and let the extension compile for your architecture. The comparison first checks both outputs against the PyTorch reference and uses preallocated output buffers; compilation is excluded from timings. The example implements FP32 forward and does not register backward.

[ ]RoPE in CUDA C++ and TritonLocal GPU
"""RoPE de pares adyacentes, CUDA C++ frente a Triton; pendiente de compilación."""
import os
os.environ['TRITON_DISABLE_LINE_INFO']='1'
import torch,triton
import triton.language as tl
import triton.testing
from torch.utils.cpp_extension import load_inline

cpp='''#include <torch/extension.h>
torch::Tensor rope_cuda(torch::Tensor x, torch::Tensor c, torch::Tensor s, torch::Tensor out, int64_t T);'''
cuda='''#include <torch/extension.h>
#include <c10/cuda/CUDAStream.h>
#include <c10/cuda/CUDAException.h>
#include <c10/cuda/CUDAGuard.h>
__global__ void rope_kernel(const float* x,const float* c,const float* s,float* out,
                            int rows,int D,int T){
  int n=blockIdx.x*blockDim.x+threadIdx.x;
  int pairs=D/2;
  if(n<rows*pairs){
    int row=n/pairs, j=n%pairs; int pos=row%T;
    float a=x[row*D+2*j], b=x[row*D+2*j+1];
    float co=c[pos*pairs+j], si=s[pos*pairs+j];
    out[row*D+2*j]=a*co-b*si; out[row*D+2*j+1]=a*si+b*co;
  }
}
torch::Tensor rope_cuda(torch::Tensor x,torch::Tensor c,torch::Tensor s,torch::Tensor out,int64_t T){
  TORCH_CHECK(x.is_cuda() && c.is_cuda() && s.is_cuda() && out.is_cuda(),"CUDA tensors required");
  TORCH_CHECK(x.device()==c.device() && x.device()==s.device() && x.device()==out.device(),"same device required");
  TORCH_CHECK(x.is_contiguous() && c.is_contiguous() && s.is_contiguous() && out.is_contiguous(),"contiguous required");
  TORCH_CHECK(x.scalar_type()==torch::kFloat32 && c.scalar_type()==torch::kFloat32 && s.scalar_type()==torch::kFloat32 && out.scalar_type()==torch::kFloat32,"float32 required");
  TORCH_CHECK(x.dim()==2 && x.size(-1)>0,"expected 2D rows x channels");
  c10::cuda::CUDAGuard guard(x.device());
  int D=x.size(-1), rows=x.numel()/D; TORCH_CHECK(D%2==0 && T>0 && c.numel()==T*D/2 && s.numel()==T*D/2,"shape mismatch");
  TORCH_CHECK(out.sizes()==x.sizes(),"output shape mismatch"); int total=rows*D/2;
  rope_kernel<<<(total+255)/256,256,0,c10::cuda::getCurrentCUDAStream()>>>(x.data_ptr<float>(),c.data_ptr<float>(),s.data_ptr<float>(),out.data_ptr<float>(),rows,D,T);
  C10_CUDA_KERNEL_LAUNCH_CHECK(); return out;
}'''

@triton.jit
def rope_triton(X,C,S,O,ROWS:tl.constexpr,D:tl.constexpr,T:tl.constexpr,B:tl.constexpr):
    n=tl.program_id(0)*B+tl.arange(0,B);pairs=D//2;row=n//pairs;j=n%pairs;mask=n<ROWS*pairs
    a=tl.load(X+row*D+2*j,mask,0);b=tl.load(X+row*D+2*j+1,mask,0)
    c=tl.load(C+(row%T)*pairs+j,mask,0);s=tl.load(S+(row%T)*pairs+j,mask,0)
    tl.store(O+row*D+2*j,a*c-b*s,mask);tl.store(O+row*D+2*j+1,a*s+b*c,mask)

def run():
    ext=load_inline(name='oryon_m21_rope',cpp_sources=cpp,cuda_sources=cuda,functions=['rope_cuda'],verbose=False)
    torch.manual_seed(7);rows,t,d=2048,256,64
    x=torch.randn(rows,d,device='cuda');angles=torch.randn(t,d//2,device='cuda');c=angles.cos();s=angles.sin()
    o=torch.empty_like(x);out=torch.empty_like(x);grid=(triton.cdiv(rows*d//2,256),)
    def tri():rope_triton[grid](x,c,s,o,rows,d,t,256)
    tri();ext.rope_cuda(x,c,s,out,t)
    cc=c[torch.arange(rows,device='cuda')%t];ss=s[torch.arange(rows,device='cuda')%t]
    ref=torch.stack((x[:,0::2]*cc-x[:,1::2]*ss,x[:,0::2]*ss+x[:,1::2]*cc),-1).reshape(rows,d)
    torch.testing.assert_close(o,ref,rtol=1e-5,atol=1e-5);torch.testing.assert_close(out,ref,rtol=1e-5,atol=1e-5)
    print('GPU',torch.cuda.get_device_name(),'torch',torch.__version__)
    for name,fn in [('Triton',tri),('CUDA C++',lambda:ext.rope_cuda(x,c,s,out,t))]:
        print(name,'ms',triton.testing.do_bench(fn,warmup=20,rep=50,return_mode='median'),flush=True)

if __name__=='__main__':run()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

On Ubuntu 24.04 with CUDA 12.8, g++ 13.3, Torch 2.11.0, and RTX 3060, both paths matched the reference and their medians were 0.008192 ms in that shared campaign. The small size and measurement resolution do not justify concluding that one path is universally faster. The reader needs the compiler and headers; if missing, install a compatible combination before running and record the error rather than simulating a result.

Data-center GPU features influence the strategy. On Hopper, TMA can transfer tiles asynchronously, wgmma coordinates matrix operations across a warp group, and specialization assigns some warps data production and others consumption. FlashAttention-3 studies that overlap and FP8 on H100; these are results on its hardware, not a measurement of the local RTX 3060. Programming must check architecture and availability, not assume all GPUs expose the same instructions. ThunderKittens offers another way to express tiled kernels.

To compare kernels, fix seed, shape, type, mask, and tolerance; verify output and gradients before timing. SDPA selects among available implementations and may allow or reject specific backends depending on input and hardware: record the one requested and the one that actually ran. Separate compilation and warm-up from repetitions. For full dense attention, the approximate count for the two forward matrix products is 4BHT2d4BHT^2d FLOPs, excluding softmax and other operations. For a causal mask adjust the count to valid or executed work and state the convention.

An effective FLOP/s rate divides declared mathematical work by time; it does not directly measure executed instructions. Causal attention has T(T+1)/2T(T+1)/2 valid pairs per head, but a kernel with partial diagonal blocks may perform additional products. Counting only valid pairs makes semantic comparison easier and understates that kernel’s physical work. Counting all block products may overstate useful work. Publish the convention with timings, and compare forward separately from backward, which performs more products and recomputations.

A CUDA C++ path also needs a compatible compiler and toolkit in addition to the driver. Compilation failure due to a missing toolkit does not prove the algorithm wrong or provide a kernel time. Likewise, an SDPA backend unavailable for a shape must be recorded as such. An RTX 3060 result describes that machine; it does not validate Hopper TMA, wgmma, or native FP8. Those instructions are studied through their sources and executed only on supporting hardware.

Exercises

Numeric
For T=4096 and 128 × 128 blocks, what percentage of whole blocks does a causal mask skip?
Numeric
For B=4, H=16, T=2048 and d=64, how many effective TFLOP/s do 4BHT²d FLOPs in 3 ms represent?
Proof
Prove: Prove D_i = Σ_k dO_ik O_ik = Σ_j P_ij dP_ij.
0
O=PV and dP=dO Vᵀ.

Step 1 of 2. How does O_ik expand?

Quiz
Which options are reasonable first steps?

More than one answer may be correct.

Code
Implement flash_causal for contiguous Q, K and V of shape [H,T,D]. The grid is (ceil(T/BM), H). A program processes BM queries and traverses keys in BN blocks, skips whole future blocks, applies a per-position causal mask, and writes output O and per-row LSE. Accumulate softmax in FP32.
import os
os.environ['TRITON_DISABLE_LINE_INFO']='1'
import triton
import triton.language as tl
@triton.jit
def flash_causal(Q,K,V,O,L,T:tl.constexpr,D:tl.constexpr,BM:tl.constexpr,BN:tl.constexpr,BD:tl.constexpr):
  pass
Shift+Enter to run
Key idea
Fused attention saves materialization through online softmax and recomputation. Program design, masking, and gradient partitioning determine its correctness and performance.