Decoding attention kernel for long context
Implement a Triton decode-attention kernel that splits the sequence into parallel chunks with online softmax and final reduction, supports paged cache and GQA, and compare it with PyTorch attention.
After this lesson you can
- Derive the combination of partial softmaxes from per-chunk maxima and sums.
- Implement sequence splitting, GQA and paged-cache reads in the kernel.
- Verify against a reference across shapes, lengths and block sizes.
- Measure effective bandwidth and speedup against PyTorch attention.
Before you start
One query, many chunks
During decode there is one new query per sequence. The K/V cache can be long, but parallelizing only across queries and batch leaves few programs available. Flash-Decoding proposes splitting the key sequence into chunks processed in parallel, then combining their results. Additional splits cost temporary memory and a reduction; speedup is not guaranteed for every length or GPU.
Let and be the value vector. For each chunk calculate maximum , sum and vector numerator . With , the exact output in real arithmetic is
This works because ; the common factor does not change the ratio. Subtracting the maximum prevents large exponentials from overflowing. In finite precision, different reduction orders produce rounding differences. The online normalizer also updates maximum, denominator and numerator as each tile arrives without storing the score matrix.
The quantity is not yet the normalized chunk output: it is the numerator associated with . If each is first divided by , those weights must be restored when combining. Giving all partial outputs equal weight is incorrect even for equal-size chunks, because their scores can have very different scales. For example, a chunk with scores near 10 should contribute far more than one with scores near 0.
Two phases with paging and GQA
In the split-attention kernel, one first-phase program processes a query head and a sequence chunk. For each position it translates the logical block through a page table, then loads the physical key and value. In GQA, multiple query heads share a KV head: if is a multiple of , the corresponding KV head is . An FP32 accumulator retains during the scan. The second phase rescales and reduces all chunk results for each head.
The last block may be incomplete: positions outside the length must be masked in the table, K/V and softmax. The example requires a nonempty sequence, a power-of-two dimension and a valid table; a real engine must handle batches, variable lengths, concurrency and page management. FlashAttention explains reducing memory accesses using tiles, although decode parallelism follows a different pattern.
With length and chunks of 512 positions, the first phase launches programs. More chunks expose parallelism when there are few queries, but also produce more partials and second-phase work. Here each head and chunk stores two scalars and a vector of dimension , all FP32: temporary storage is bytes in addition to the output. This excludes input tensors, tables and internal compiler allocations.
Page size and chunk size are separate choices. A page defines address translation and cache fragmentation; a chunk defines how much work a program groups. A chunk can cross multiple scattered physical pages. The table must remain valid until the kernel completes, since freeing or reusing a page before synchronization can produce apparently numeric results using data from another sequence.
Local lab
Kernel verification and measurement requires PyTorch with CUDA and Triton. The block generates permuted BF16 pages, tests non-multiple lengths and GQA, compares against FP32 softmax and measures against scaled_dot_product_attention with K/V gathered and expanded outside the timer. The 1 GiB free-memory threshold applies only to this trial; insufficient memory is reported as deferred. Timing warms autotuning configurations. Bandwidth uses logical bytes per query head: GQA may physically reuse data, so it does not directly measure DRAM traffic. Kernel temporary allocations are included in the timed function; page gathering for the reference is excluded. These conditions are insufficient to conclude full-server speed.
For verification, the reference converts to FP32 before products and reduction. Maximum absolute error captures the worst output component but does not replace checks of shapes, masks and heads. Therefore the trial includes contexts not divisible by page size and different head ratios. An engine should also test extreme values, shared blocks and more sequences, and compare with contiguous attention at the same input precision.
In one shared RTX 3060 run, maximum absolute error against the FP32 oracle was below on all five shapes. Measured times were 0.0152, 0.0184, 0.0277, 0.0526 and 0.1992 ms for lengths 65, 509, 2049, 8192 and 32000 respectively; SDPA took 0.0947, 0.0804, 0.6992, 1.2498 and 3.5111 ms. Shapes, heads and pages vary between cases as shown in the code, and the GPU was shared: these ratios do not establish that speedup grows with length. Repeat with one shape, more samples and controlled load before drawing that conclusion.
import os
os.environ.setdefault('TRITON_DISABLE_LINE_INFO','1')
import math, torch, triton, triton.language as tl
@triton.autotune(configs=[triton.Config({'B':64},num_warps=4),triton.Config({'B':128},num_warps=4)],key=['D','PAGE'])
@triton.jit
def partial(Q,K,V,T,M,L,A, N:tl.constexpr, HQ:tl.constexpr, HK:tl.constexpr, D:tl.constexpr, PAGE:tl.constexpr, NS:tl.constexpr, SPLIT:tl.constexpr, B:tl.constexpr):
h=tl.program_id(0);part=tl.program_id(1);kv=h//(HQ//HK);ds=tl.arange(0,D)
q=tl.load(Q+h*D+ds).to(tl.float32);m=tl.full((),-float('inf'),tl.float32);l=tl.full((),0,tl.float32);a=tl.full((D,),0,tl.float32)
for start in range(0,SPLIT,B):
t=part*SPLIT+start+tl.arange(0,B);phys=tl.load(T+t//PAGE,mask=t<N,other=0)
off=((phys[:,None]*PAGE+(t%PAGE)[:,None])*HK+kv)*D+ds[None,:]
keys=tl.load(K+off,mask=(t<N)[:,None],other=0).to(tl.float32);vals=tl.load(V+off,mask=(t<N)[:,None],other=0).to(tl.float32)
scores=tl.sum(keys*q[None,:],1)*tl.rsqrt(float(D));scores=tl.where(t<N,scores,-float('inf'))
nm=tl.maximum(m,tl.max(scores,0));alpha=tl.exp(m-nm);p=tl.exp(scores-nm)
l=l*alpha+tl.sum(p,0);a=a*alpha+tl.sum(p[:,None]*vals,0);m=nm
tl.store(M+h*NS+part,m);tl.store(L+h*NS+part,l);tl.store(A+(h*NS+part)*D+ds,a)
@triton.jit
def merge(M,L,A,O, NS:tl.constexpr,D:tl.constexpr,S:tl.constexpr):
h=tl.program_id(0);s=tl.arange(0,S);d=tl.arange(0,D);valid=s<NS
m=tl.load(M+h*NS+s,mask=valid,other=-float('inf'));l=tl.load(L+h*NS+s,mask=valid,other=0)
a=tl.load(A+(h*NS+s[:,None])*D+d[None,:],mask=valid[:,None],other=0);mx=tl.max(m,0);scale=tl.exp(m-mx)
denom=tl.sum(l*scale,0);out=tl.sum(a*scale[:,None],0)/denom;tl.store(O+h*D+d,out)
def run_attention(q,k,v,table,n,page):
h,d=q.shape;hk=k.shape[2];assert h%hk==0 and d in (32,64,128) and n>0
ns=triton.cdiv(n,512);m=torch.empty((h,ns),device=q.device,dtype=torch.float32);l=torch.empty_like(m);a=torch.empty((h,ns,d),device=q.device,dtype=torch.float32);o=torch.empty((h,d),device=q.device,dtype=torch.float32)
partial[(h,ns)](q,k,v,table,m,l,a,n,h,hk,d,page,ns,512);merge[(h,)](m,l,a,o,ns,d,triton.next_power_of_2(ns));return o
def verify():
assert torch.cuda.is_available();free,_=torch.cuda.mem_get_info()
if free<1024*2**20:print('GPU con menos de 1 GiB libres; prueba aplazada');return
torch.manual_seed(33);device='cuda'
for n,page,h,hk,d in [(65,16,4,2,32),(509,32,8,2,64),(2049,16,4,1,128),(8192,32,8,2,64),(32000,16,4,1,64)]:
pages=triton.cdiv(n,page);order=torch.randperm(pages,device=device);table=order.to(torch.int32)
k=torch.randn(pages,page,hk,d,device=device,dtype=torch.bfloat16);v=torch.randn_like(k);q=torch.randn(h,d,device=device,dtype=torch.bfloat16)
pos=torch.arange(n,device=device);K=k[order[pos//page],pos%page].permute(1,0,2);V=v[order[pos//page],pos%page].permute(1,0,2)
kq=K.repeat_interleave(h//hk,dim=0);vq=V.repeat_interleave(h//hk,dim=0)
ref=torch.softmax((q.float()[:,None,:]*kq.float()).sum(-1)/math.sqrt(d),dim=-1);ref=(ref[...,None]*vq.float()).sum(1)
out=run_attention(q,k,v,table,n,page);err=(out-ref).abs().max().item();assert err<1e-3,(n,err)
f=lambda:run_attention(q,k,v,table,n,page)
g=lambda:torch.nn.functional.scaled_dot_product_attention(q[None,:,None,:],kq[None],vq[None])
f();g();torch.cuda.synchronize();ms=triton.testing.do_bench(f);base=triton.testing.do_bench(g)
bytes_kv=2*n*h*d*2
print('N',n,'page',page,'Hq/Hkv',h,hk,'D',d,'error',f'{err:.7g}','split ms',round(ms,4),'SDPA ms',round(base,4),'ratio',round(base/ms,3),'lectura lógica GB/s',round(bytes_kv/(ms*1e6),3),flush=True)
if __name__=='__main__':verify()
npm run lab and open the connection link.To compare length without changing head shape, the second test fixes 8 query heads, 2 KV heads, dimension 64, page size 16 and BF16. PyTorch receives contiguous K/V with GQA, gathered before timing; the custom kernel reads permuted pages and returns FP32, while SDPA returns BF16. Both are compared with an FP32 oracle using tolerances appropriate to output precision. The two paths do not include the same temporaries or cache preparation, and the SDPA backend depends on installation.
On an RTX 3060 with no other intentional GPU load, SDPA/kernel ratios for 256, 1024, 4096, 8192 and 32000 positions were 7.98, 19.44, 11.91, 17.92 and 21.85. They did not increase monotonically and do not prove a universal trend. This is a specific comparison of these implementations, not a service measurement; retain warmup and repeat on the system being evaluated.
import math, torch, triton
torch.manual_seed(33)
assert torch.cuda.is_available()
h, hk, d, page = 8, 2, 64, 16
print('GPU',torch.cuda.get_device_name(),'Hq/Hkv',h,hk,'D',d,'página',page,'bf16')
for n in (256,1024,4096,8192,32000):
pages=triton.cdiv(n,page)
order=torch.randperm(pages,device='cuda'); table=order.to(torch.int32)
k=torch.randn(pages,page,hk,d,device='cuda',dtype=torch.bfloat16); v=torch.randn_like(k)
q=torch.randn(h,d,device='cuda',dtype=torch.bfloat16)
pos=torch.arange(n,device='cuda')
kc=k[order[pos//page],pos%page].permute(1,0,2).contiguous()
vc=v[order[pos//page],pos%page].permute(1,0,2).contiguous()
qsdpa=q[None,:,None,:]; ksdpa=kc[None]; vsdpa=vc[None]
f=lambda:run_attention(q,k,v,table,n,page)
g=lambda:torch.nn.functional.scaled_dot_product_attention(qsdpa,ksdpa,vsdpa,enable_gqa=True)
ref_k=kc.repeat_interleave(h//hk,0).float();ref_v=vc.repeat_interleave(h//hk,0).float()
scores=(q.float()[:,None,:]*ref_k).sum(-1)/math.sqrt(d)
ref=(torch.softmax(scores,-1)[...,None]*ref_v).sum(1)
split=f();sdpa=g()[0,:,0,:].float()
es=(split-ref).abs().max().item();et=(sdpa-ref).abs().max().item()
assert es<1e-3 and torch.allclose(sdpa,ref,atol=.01,rtol=.02),(n,es,et)
f();g();torch.cuda.synchronize()
ms=triton.testing.do_bench(f,warmup=300,rep=1000)
base=triton.testing.do_bench(g,warmup=300,rep=1000)
print('N',n,'errores split/SDPA',es,et,'ms split/SDPA',ms,base,'factor',base/ms,flush=True)npm run lab and open the connection link.Exercises
Step 1 of 2. How is exp(sᵢ−mⱼ) transformed when using global maximum m?
import numpy as np
def attention_chunks(scores, values, size):
...