Triton kernels I: programming the GPU in blocks
Triton enables GPU kernels in Python expressed in blocks instead of threads, with a compiler handling coalescing, shared memory and synchronization. We prepare a compatible environment and record the actual GPU used; this run uses an RTX 3060 with WSL2 Ubuntu. We debug on CPU with interpreter mode and write first kernels: vector addition, fused elementwise operations and row softmax, measured against actual bandwidth, PyTorch and torch.compile.
After this lesson you can
- Translate an elementwise or rowwise problem into Triton's block-program model.
- Write kernels with correct masks, strides and pointer arithmetic for noncontiguous tensors.
- Measure effective kernel bandwidth with do_bench and compare it with the measured GPU peak.
- Apply autotuning and explain how the best configuration changes with problem size.
- Debug a kernel on CPU in interpreter mode before executing it on the GPU.
Before you start
Think in blocks
An addition, GELU, and dropout can form one mathematical expression, but if each operation materializes its output in global memory, data travels several times. Fusion reduces reads, writes, and launches. It does not itself promise greater speed: the kernel may lose occupancy, use registers, or perform expensive operations. Compare actual work, not just the number of Python calls.
In the Triton programming model, each program instance processes a block of indices. The launch grid has as many instances as the problem requires blocks. tl.program_id identifies an instance and tl.arange creates a vector of local indices; the compiler decides how to distribute work among threads and which instructions to emit. The CUDA execution model helps explain that translation without identifying a Triton element with a particular thread. The author remains responsible for shapes, masks, types, dependencies, and launch dimensions. There is no general barrier between independent programs in one grid.
For a vector of length and block , program covers , with mask . The grid has programs. For a matrix, a two-dimensional grid can assign one tile per program; the address of is base + i * stride_row + j * stride_col. Strides are measured in elements, not bytes. A transpose often shares storage and changes strides, so a formula assuming contiguity can read the wrong position.
For example, a contiguous matrix has strides : element is 13 elements from the base using zero-based code indices. Its transposed view has shape and strides ; element reaches the same offset 13. A new output may be contiguous even when the input is not, so its formula must use its own strides. Passing read and write strides separately avoids confusing a view with a copy.
Triton memory operations include masked tl.load and tl.store. other defines the value of lanes that are not loaded. For addition, zero is usually neutral; for the softmax maximum use negative infinity. Mask writes too. An invalid index can silently corrupt data without an obvious failure. Coalescing details depend on compiled assignment and hardware: the figure’s sector model illustrates addresses, not a substitute for GPU counters.
Fusion, traffic, and limits
This lab’s fused elementwise kernel computes addition, approximate GELU, dropout, and scaling in one program. The generator uses seed and index to reconstruct a reproducible mask. During training retain or regenerate that same mask for backward, and vary the seed between steps when appropriate. The example writes the mask as a byte for comparison; a production kernel may not save it.
In the figure’s FP32 model, reading and bias, writing output, and writing one mask byte costs 13 bytes per element. Each break materializing an intermediate tensor adds 4 bytes written and 4 read. This sum excludes cache traffic, instructions, internal temporaries, and bandwidth variation. The 62.74 GB/s copy reference and 4.524 ms fused kernel come from one run with 2^24 elements in WSL on a shared GPU. PyTorch eager in the same test uses the already generated mask, so its work differs from the kernel which also generates it. The arithmetic-intensity model and bottleneck taxonomy help interpret, not guarantee, speed.
Reduce a row without overflow
A row reduction must coordinate the elements of a row. For , define and compute . Subtracting does not change softmax and prevents exponential overflow. If the row fits in the block, each program loads a row, reduces maximum and sum, and writes once. Otherwise a program can traverse tiles in several passes: global maximum, exponential sum, and output. That solution is correct but reads input several times; another implementation can use online softmax and combine block statistics.
The equality follows by canceling the same factor: . The right-hand expression is a real-number identity; the left-hand expression is evaluated because it avoids forming large exponentials. In the third pass of the kernel below, every input is read again to produce its output. That read cost may be acceptable when a full row does not fit in local resources, but it must be measured.
Triton autotuning tries configurations and stores a choice per key. num_warps, block size, and num_stages can change occupancy, registers, and memory. The autotuner runs each candidate multiple times: if a kernel updates rather than overwrites its output, reset it between tests. Compilation cost is not part of steady-state kernel latency. Official documentation describes keys and hooks.
Lab: a small interpreter
Before running on GPU, model sequential programs with NumPy. This interpreter counts logical bytes of valid accesses: it does not model parallelism, cache, warps, instructions, or performance. A mask protects access even when the index vector contains values outside the array.
import numpy as np
class Memory:
def __init__(self,a):
self.a=np.asarray(a).reshape(-1); self.read=self.written=0
def load(self,offsets,mask,other=0):
offsets=np.asarray(offsets); mask=np.asarray(mask,dtype=bool)
valid=offsets[mask]
if np.any((valid<0)|(valid>=self.a.size)): raise IndexError('lectura fuera del buffer')
out=np.full(offsets.shape,other,dtype=self.a.dtype)
out[mask]=self.a[valid]; self.read+=valid.size*self.a.itemsize
return out
def store(self,offsets,values,mask):
offsets=np.asarray(offsets); mask=np.asarray(mask,dtype=bool)
valid=offsets[mask]
if np.any((valid<0)|(valid>=self.a.size)): raise IndexError('escritura fuera del buffer')
self.a[valid]=np.asarray(values)[mask]; self.written+=valid.size*self.a.itemsize
def launch(grid,kernel):
for pid in np.ndindex(*grid): kernel(*pid)
def add(x,y,block):
a,b=Memory(x),Memory(y); out=Memory(np.zeros_like(x)); n=x.size
def kernel(pid):
i=pid*block+np.arange(block); mask=i<n
out.store(i,a.load(i,mask)+b.load(i,mask),mask)
launch(((n+block-1)//block,),kernel)
return out.a,a.read+b.read+out.written
rng=np.random.default_rng(5)
x=rng.normal(size=1003).astype('float32'); y=rng.normal(size=1003).astype('float32')
z,bytes_add=add(x,y,128)
assert np.allclose(z,x+y)
print('programas:',(1003+127)//128,'carriles vacíos:',8*128-1003,'bytes:',bytes_add)def transpose(x,tile):
rows,cols=x.shape; a=Memory(x.copy()); out=Memory(np.zeros(cols*rows,dtype=x.dtype))
def kernel(pr,pc):
r=pr*tile+np.arange(tile)[:,None]; c=pc*tile+np.arange(tile)[None,:]
rr=np.broadcast_to(r,(tile,tile)); cc=np.broadcast_to(c,(tile,tile))
mask=(rr<rows)&(cc<cols)
out.store(cc*rows+rr,a.load(rr*cols+cc,mask),mask)
launch(((rows+tile-1)//tile,(cols+tile-1)//tile),kernel)
return out.a.reshape(cols,rows),a.read+out.written
def softmax_rows(x,block):
rows,cols=x.shape
if block<cols: raise ValueError('la fila debe caber en el bloque')
a=Memory(x.copy()); out=Memory(np.zeros_like(x))
def kernel(row):
c=np.arange(block); mask=c<cols
z=a.load(row*cols+c,mask,other=-np.inf)
e=np.exp(z-np.max(z)); e/=np.sum(e)
out.store(row*cols+c,e,mask)
launch((rows,),kernel)
return out.a.reshape(x.shape),a.read+out.written
a=rng.normal(size=(37,51)).astype('float32')
t,bt=transpose(a,16); sm,bs=softmax_rows(a,64)
reference=np.exp(a-a.max(1,keepdims=True)); reference/=reference.sum(1,keepdims=True)
assert np.array_equal(t,a.T) and np.allclose(sm,reference,atol=1e-7)
print('bytes transposición:',bt,'softmax:',bs,'error máximo:',np.max(np.abs(sm-reference)))In the first cell, elements with block 128 need eight programs and 21 masked lanes. Two reads and one FP32 write total bytes. The matrix uses bytes for one read and one write in each of the two examples. These are not physical GPU transactions.
def sectors(offsets,mask,itemsize=4,segment=32,warp=32):
offsets=np.asarray(offsets).ravel(); mask=np.asarray(mask,dtype=bool).ravel()
return sum(len(set((offsets[i:i+warp][mask[i:i+warp]]*itemsize//segment).tolist()))
for i in range(0,len(offsets),warp))
lane=np.arange(32)
print('contiguo:',sectors(lane,lane<32),'stride 4:',sectors(4*lane,lane<32))The model counts four 32-byte sectors for 32 contiguous, aligned FP32 reads, versus 16 at stride 4. It assumes an aligned base and one transaction per distinct sector, with no cache or combining across warps. A profiler and the actual architecture determine which traffic reaches memory.
For a contiguous matrix, the next control compares two idealized orders. The naive one assigns a warp to each input row: it reads contiguously but writes a scattered output column. The tiled version assumes values are rearranged in nearby memory after loading and each warp writes a contiguous output row. The count includes only global sectors, not rearrangement or synchronization cost. The compiler does not automatically guarantee this pattern for every kernel.
c=np.arange(32); mask=c<32
read=sum(sectors(r*32+c,mask) for r in range(32))
naive_write=sum(sectors(c*32+r,mask) for r in range(32))
tiled_write=sum(sectors(r*32+c,mask) for r in range(32))
print('lecturas:',read,'escrituras ingenuas:',naive_write,'escrituras reordenadas:',tiled_write)
assert (read,naive_write,tiled_write)==(128,1024,128)Local lab: real Triton
You need PyTorch and Triton in a CUDA-compatible Linux environment. On Windows you can use WSL2; this run used Ubuntu with PyTorch 2.11.0+cu128, Triton 3.6.0, and an RTX 3060. The following measurements concern that GPU. These cells install nothing. The addition tutorial explains grids and masks; the softmax tutorial develops row reduction.
In this environment the cell’s virtual name contains non-ASCII characters, and the ptxas version rejects that name in line information. Before importing Triton, TRITON_DISABLE_LINE_INFO=1 is enabled, an option documented by Triton that omits this information from compiled code. The consequence is losing that debugging information; in a file with a compatible ASCII path you can omit the option to retain it. This does not change operations or inputs.
import os
os.environ['TRITON_DISABLE_LINE_INFO']='1'
import json, torch, triton, triton.language as tl
import triton.testing
import torch.nn.functional as F
@triton.jit
def add_kernel(X,Y,O,N,SX:tl.constexpr,SY:tl.constexpr,B:tl.constexpr):
i=tl.program_id(0)*B+tl.arange(0,B); mask=i<N
x=tl.load(X+i*SX,mask,other=0); y=tl.load(Y+i*SY,mask,other=0)
tl.store(O+i,x+y,mask)
@triton.jit
def fused(X,Bias,O,Keep,N,P:tl.constexpr,SEED:tl.constexpr,B:tl.constexpr):
i=tl.program_id(0)*B+tl.arange(0,B); mask=i<N
x=tl.load(X+i,mask,other=0).to(tl.float32)
bias=tl.load(Bias+i,mask,other=0).to(tl.float32)
z=x+bias
t=0.7978845608028654*(z+0.044715*z*z*z)
gelu=0.5*z*(1+2/(1+tl.exp(2*(-t)))-1)
keep=tl.rand(SEED,i)>=P
tl.store(O+i,tl.where(keep,gelu/(1-P),0),mask)
tl.store(Keep+i,keep,mask)
@triton.jit
def row_softmax(X,O,N,XR:tl.constexpr,XC:tl.constexpr,OR:tl.constexpr,OC:tl.constexpr,B:tl.constexpr):
row=tl.program_id(0); c=tl.arange(0,B); mask=c<N
x=tl.load(X+row*XR+c*XC,mask,other=-float('inf')).to(tl.float32)
ex=tl.exp(x-tl.max(x,0)); y=ex/tl.sum(ex,0)
tl.store(O+row*OR+c*OC,y,mask)
@triton.jit
def long_softmax(X,O,N:tl.constexpr,XR:tl.constexpr,XC:tl.constexpr,OR:tl.constexpr,OC:tl.constexpr,B:tl.constexpr):
row=tl.program_id(0); c=tl.arange(0,B)
maximum=tl.full((),-float('inf'),tl.float32)
for start in range(0,N,B):
k=start+c
x=tl.load(X+row*XR+k*XC,k<N,other=-float('inf')).to(tl.float32)
maximum=tl.maximum(maximum,tl.max(x,0))
denom=tl.full((),0,tl.float32)
for start in range(0,N,B):
k=start+c
x=tl.load(X+row*XR+k*XC,k<N,other=-float('inf')).to(tl.float32)
denom+=tl.sum(tl.exp(x-maximum),0)
for start in range(0,N,B):
k=start+c
x=tl.load(X+row*XR+k*XC,k<N,other=-float('inf')).to(tl.float32)
tl.store(O+row*OR+k*OC,tl.exp(x-maximum)/denom,k<N)
@triton.autotune(configs=[triton.Config({},num_warps=w,num_stages=s)
for w in (2,4,8) for s in (2,3)],key=['N'])
@triton.jit
def tuned(X,O,N,XR:tl.constexpr,XC:tl.constexpr,OR:tl.constexpr,OC:tl.constexpr,B:tl.constexpr):
row=tl.program_id(0); c=tl.arange(0,B); mask=c<N
x=tl.load(X+row*XR+c*XC,mask,other=-float('inf')).to(tl.float32)
ex=tl.exp(x-tl.max(x,0))
tl.store(O+row*OR+c*OC,ex/tl.sum(ex,0),mask)npm run lab and open the connection link.The dropout kernel uses tl.rand(seed, índice). The same seed reproduces the same mask for that indexing; it does not promise to reproduce PyTorch generator bits. To compare values, we save the generated mask and apply it to the reference. The dropout documentation explains generation by index. The test uses two views with different strides and transposed matrices; it also checks rows longer than the three-pass version’s block.
assert torch.cuda.is_available()
torch.manual_seed(5)
device='cuda'
a=torch.randn(2006,device=device)[::2]; b=torch.randn(3009,device=device)[::3]
out=torch.empty(a.numel(),device=device)
add_kernel[(triton.cdiv(a.numel(),128),)](a,b,out,a.numel(),a.stride(0),b.stride(0),128)
torch.testing.assert_close(out,a+b)
x=torch.randn(1003,device=device); bias=torch.randn_like(x)
out=torch.empty_like(x); keep=torch.empty_like(x,dtype=torch.uint8)
fused[(triton.cdiv(x.numel(),128),)](x,bias,out,keep,x.numel(),.2,33,128)
reference=F.gelu(x+bias,approximate='tanh')*keep/(1-.2)
torch.testing.assert_close(out,reference,rtol=2e-5,atol=2e-6)
out2=torch.empty_like(x); keep2=torch.empty_like(keep)
fused[(triton.cdiv(x.numel(),128),)](x,bias,out2,keep2,x.numel(),.2,33,128)
assert torch.equal(keep,keep2) and torch.equal(out,out2)
for length in (127,513,4097):
x=torch.randn(length,7,device=device).T
y=torch.full_like(x,float('nan'),memory_format=torch.contiguous_format)
long_softmax[(x.shape[0],)](x,y,length,*x.stride(),*y.stride(),256)
torch.testing.assert_close(y,torch.softmax(x,dim=1),rtol=2e-5,atol=2e-6)
row_softmax[(x.shape[0],)](x,y,length,*x.stride(),*y.stride(),triton.next_power_of_2(length))
torch.testing.assert_close(y,torch.softmax(x,dim=1),rtol=2e-5,atol=2e-6)
print('suma con strides, fusión y ambas softmax correctas en',torch.cuda.get_device_name())npm run lab and open the connection link.The one-row version needs a power-of-two block at least as large as the row length; that can consume too many resources for very long rows. The three-pass variant uses block 256 with length 4097 and keeps the reduction numerically stable. Every row in these examples is nonempty. A fully masked row would need an explicit policy to avoid .
results=[]
for length in (128,512,1024,4096):
x=torch.randn(256,length,device='cuda'); y=torch.empty_like(x)
for block in (triton.next_power_of_2(length),2*triton.next_power_of_2(length)):
for warps in (2,4,8):
def call():
row_softmax[(x.shape[0],)](x,y,length,*x.stride(),*y.stride(),block,num_warps=warps)
call()
torch.testing.assert_close(y,torch.softmax(x,dim=1),rtol=2e-5,atol=2e-6)
ms=triton.testing.do_bench(call,warmup=20,rep=50,return_mode='median')
results.append(dict(length=length,block=block,warps=warps,ms=ms))
print('longitud:',length,'bloque:',block,'warps:',warps,'mediana ms:',ms)
tuned[(x.shape[0],)](x,y,length,*x.stride(),*y.stride(),triton.next_power_of_2(length))
torch.testing.assert_close(y,torch.softmax(x,dim=1),rtol=2e-5,atol=2e-6)
print('autotune:',tuned.best_config)
with open('triton-landscape.json','w',encoding='utf-8') as f:
json.dump(results,f,indent=2)npm run lab and open the connection link.The figure uses an earlier run of that cell: 256 FP32 rows, four lengths, and six combinations per length. Observed minima change with length, but ties occur and load from other processes alters results. The autotuner also tries two num_stages values; its choice may differ from the lowest displayed cell because they are different measurements. Your output replaces that evidence with your device’s, but does not change the packaged figure.
n=16*1024*1024
x=torch.randn(n,device='cuda'); bias=torch.randn_like(x); y=torch.empty_like(x)
keep=torch.empty_like(x,dtype=torch.uint8)
def fused_call():
fused[(triton.cdiv(n,1024),)](x,bias,y,keep,n,.2,33,1024)
fused_call()
def eager(a,b,k): return F.gelu(a+b,approximate='tanh')*k/(1-.2)
expected=eager(x,bias,keep)
torch.testing.assert_close(y,expected,rtol=2e-5,atol=2e-6)
compiled=torch.compile(eager)
torch.testing.assert_close(compiled(x,bias,keep),expected,rtol=2e-5,atol=2e-6)
src=torch.randn_like(x); dst=torch.empty_like(x)
copy_ms=triton.testing.do_bench(lambda:dst.copy_(src),warmup=20,rep=50,return_mode='median')
for name,fn in [('triton',fused_call),('eager',lambda:eager(x,bias,keep)),('compile',lambda:compiled(x,bias,keep))]:
ms=triton.testing.do_bench(fn,warmup=20,rep=50,return_mode='median')
print(name,'mediana ms:',ms)
print('referencia de copia, GB/s:',2*n*4/(copy_ms*1e6))npm run lab and open the connection link.The Triton kernel computes and writes the mask; the PyTorch functions receive that mask already calculated. The comparison verifies arithmetic with the same mask, but does not charge eager or torch.compile for generating randomness. Count 13 logical bytes per element in this example’s Triton kernel: two FP32 reads, one FP32 write, and a one-byte write. Dividing those bytes by time gives model-effective bandwidth, not a direct measurement of physical traffic. do_bench excludes warm-up and returns milliseconds; one campaign under load cannot establish which version always wins.
Debug before compiling
The Triton interpreter executes each program sequentially using equivalent CPU operations. TRITON_INTERPRET=1 must be set before importing Triton, so this cell starts a subprocess and saves a small Python file. The interpreter helps inspect indices and masks; it does not simulate GPU races, performance, instructions, or synchronization. Here its addition is compared with CPU PyTorch.
import os, sys, subprocess
from pathlib import Path
source = '''import torch
import triton
import triton.language as tl
@triton.jit
def add(X,Y,O,N,B:tl.constexpr):
i=tl.program_id(0)*B+tl.arange(0,B)
mask=i<N
tl.store(O+i,tl.load(X+i,mask,other=0)+tl.load(Y+i,mask,other=0),mask)
torch.manual_seed(5)
x=torch.randn(1003); y=torch.randn(1003); out=torch.empty_like(x)
add[(triton.cdiv(x.numel(),128),)](x,y,out,x.numel(),128)
torch.testing.assert_close(out,x+y)
print('intérprete CPU: suma correcta; programas:',triton.cdiv(x.numel(),128))
'''
path=Path('triton_interprete.py'); path.write_text(source,encoding='utf-8')
env=os.environ.copy(); env['TRITON_INTERPRET']='1'; env['PYTHONUTF8']='1'
result=subprocess.run([sys.executable,str(path)],env=env,text=True,encoding='utf-8',capture_output=True,check=True)
print(result.stdout.strip())npm run lab and open the connection link.Do not confuse Dynamo graph capture with the kernel: torch.compile can generate or select fused code, but can also recompile when shapes change. A fair test separates initial compilation from later runs, verifies results, controls the seed, and synchronizes before reading times. The effect of operator fusion and compilation and CUDA graph options depends on version and actual shapes. Continually changing a tl.constexpr value can create many specializations.
Exercises
More than one answer may be correct.
Step 1 of 3. What factor appears in every numerator after shifting?
transpose_blocks(x, tile) with NumPy: for each input tile copy values to their transposed positions, including incomplete edges. Return a new matrix and do not use the full transpose as the implementation.import numpy as np
def transpose_blocks(x, tile):
passsoftmax_long(X, O, N, XR, XC, OR, OC, B), one program per row, using three passes over blocks of B: global maximum, exponential sum, and output. N and B are constexpr; strides are in elements. Tests use noncontiguous inputs and rows exceeding B.import triton
import triton.language as tl
@triton.jit
def softmax_long(X,O,N:tl.constexpr,XR:tl.constexpr,XC:tl.constexpr,OR:tl.constexpr,OC:tl.constexpr,B:tl.constexpr):
pass