The Triton programming model: blocks, masks and pointers
How Triton turns CUDA's thousands of threads into one program per block of data, what tl.program_id, tl.arange, masks and pointer arithmetic do, how to write vector add and a row-wise softmax, how to debug with the interpreter, and what Triton decides for you (coalescing, shared memory, warps) versus what you still decide.
By Sandip Maity, Applied AI Engineer
You now know what a fast kernel needs: coalesced loads, data reuse through shared memory and registers, enough parallelism, tensor cores for the maths. Writing all of that by hand in CUDA takes a lot of code, much of it about one thread's slice of the work. Triton lets you write the same kernels in Python, at the level of blocks of data, and compiles them to efficient GPU code. It's what torch.compile generates, and it's what many custom kernels in vLLM and SGLang are written in.
#The big idea: programs over blocks
In CUDA you write code for one thread and think about what the warp does. In Triton you write code for one program, which handles a whole block of elements with vector operations. The compiler decides how to spread that block across threads and warps.
| CUDA | Triton | |
|---|---|---|
| You write code for | one thread | one program (a block of data) |
| Index of my work | blockIdx, threadIdx |
tl.program_id(axis) |
| My elements | one index, i |
a vector of indices, tl.arange(0, BLOCK) |
| Coalescing, vector loads | your job | the compiler's job |
Shared memory, __syncthreads() |
your job | the compiler's job |
| Tensor cores | WMMA, MMA or PTX | tl.dot |
| Block size, warps, pipeline depth | your job | your job (and the autotuner's) |
#Vector add in Triton
import torch, triton, triton.language as tl
@triton.jit
def add_kernel(x_ptr, y_ptr, out_ptr, n, BLOCK: tl.constexpr):
pid = tl.program_id(axis=0) # which block am I?
offs = pid * BLOCK + tl.arange(0, BLOCK) # the BLOCK indices I handle
mask = offs < n # the last block may run past the end
x = tl.load(x_ptr + offs, mask=mask)
y = tl.load(y_ptr + offs, mask=mask)
tl.store(out_ptr + offs, x + y, mask=mask)
def add(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
out = torch.empty_like(x)
n = out.numel()
grid = lambda meta: (triton.cdiv(n, meta["BLOCK"]),)
add_kernel[grid](x, y, out, n, BLOCK=1024)
return out
x = torch.randn(1 << 26, device="cuda"); y = torch.randn_like(x)
torch.testing.assert_close(add(x, y), x + y)
ms = triton.testing.do_bench(lambda: add(x, y))
print(f"{ms:.3f} ms, {3 * x.numel() * 4 / ms / 1e6:.0f} GB/s")Read it line by line, because every Triton kernel uses the same pieces:
@triton.jitcompiles the function for the GPU the first time it's called with a given set of argument types and constants.- Tensors arrive as pointers.
x_ptris the address of the first element.x_ptr + offsis a block of addresses. tl.program_id(0)is this program's index in the grid, likeblockIdx.x.tl.arange(0, BLOCK)is a vector . Its length must be a power of two and known at compile time.maskswitches off lanes past the end of the data. Masked lanes neither read nor write.BLOCK: tl.constexprmarks a compile-time constant. Each distinct value compiles a separate, specialised kernel.- The grid is a tuple (or a function of the constexpr values) saying how many programs to launch.
triton.cdivis a rounded-up division.
This kernel should run at essentially the same speed as your CUDA vector add from the programming model lesson: it's bandwidth-bound, and Triton issues coalesced, vectorised loads for you. Check that your two numbers agree.
#Debugging with the interpreter
Indexing bugs are the most common Triton bugs, and the interpreter is the fastest way to find them. Set the variable before importing Triton and use CPU tensors:
import os
os.environ["TRITON_INTERPRET"] = "1"
import torch, triton, triton.language as tl
@triton.jit
def show(x_ptr, n, BLOCK: tl.constexpr):
offs = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
x = tl.load(x_ptr + offs, mask=offs < n, other=0.0)
print("pid", tl.program_id(0), "offs", offs, "x", x)
x = torch.arange(10, dtype=torch.float32) # CPU tensor
show[(3,)](x, 10, BLOCK=4)Each program prints its offsets and values, and you can set breakpoints. On a GPU, tl.device_print does the same (output can be large; print from one program only, inside an if). The interpreter tells you nothing about speed, so don't time anything with it.
Pro content
Keep reading with Inference Academy Pro
Unlock the rest of this lesson, including 1 animated diagram, plus every advanced lesson, hands-on lab, the larger playground models and completion certificates.
Still to come in this lesson
- Blocks, masks and padding, visually
- Row-wise softmax
- What Triton does for you, and what it doesn't
- Reading Triton code in engines
- What you can now do
- Common mistakes
- Exercise
- Going deeper
You will be able to answer
- In Triton, what does one program instance correspond to?
- Why is the mask argument needed in tl.load(x_ptr + offs, mask=offs < n)?
- Why must BLOCK_SIZE be marked tl.constexpr?
- A row-wise softmax kernel uses BLOCK = triton.next_power_of_2(n_cols). Why load with other=-float('inf')?
- What does TRITON_INTERPRET=1 let you do?