Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Giving instructions to teams, not individuals
In CUDA you write instructions for one worker and must arrange how 32-worker squads share materials. Triton lets you instead write instructions for a team handling a whole tray of data at once: “load this tile, multiply these two tiles, add them up, store the result”. The compiler works out how the individual workers inside the team should do it efficiently. You decide the tray size; picking it well matters.
Triton is how most new GPU kernels in machine learning are written (FlashAttention variants, fused normalizations, quantized matmuls), and it is what torch.compile generates (C5.8). Scientists use it to write custom fused operations, such as a physics loss or a particle update, in Python syntax without learning CUDA’s details.
- 1. In Triton, one program instance processes…
- 2. Who decides how threads inside a block cooperate?
- 3. In the demo, why can a 128-row tile be bad for a 16-row matrix?
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.A first Triton kernel
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 this program handles
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, y):
out = torch.empty_like(x)
grid = lambda meta: (triton.cdiv(x.numel(), meta["BLOCK"]),)
add_kernel[grid](x, y, out, x.numel(), BLOCK=1024)
return outPointers plus offset blocks give blocks of addresses; masks guard the edges; tl.constexpr meta-parameters are compile-time constants (block sizes must be powers of two). The launch grid is a function of the meta-parameters.
- 1. Programs launched for n = 5000 with BLOCK = 1024?
- 2. What does the mask do in tl.load?
- 3. Block sizes in Triton must be…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 40 minUndergraduate students and practising engineers.Fused softmax
One program per row: load the row (padded to a power of two with other=-inf), subtract the max, exponentiate, divide by the sum, store. The row stays in registers, so it is read once and written once; a sequence of separate PyTorch operations (max, subtract and exp, sum, divide) reads and writes it several times.
Blocked matrix multiplication
@triton.jit
def matmul_kernel(a_ptr, b_ptr, c_ptr, M, N, K, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr):
pid_m, pid_n = tl.program_id(0), tl.program_id(1)
rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) # FP32 accumulator in registers
for k0 in range(0, K, BLOCK_K):
rk = k0 + tl.arange(0, BLOCK_K)
a = tl.load(a_ptr + rm[:, None] * K + rk[None, :], mask=(rm[:, None] < M) & (rk[None, :] < K), other=0.)
b = tl.load(b_ptr + rk[:, None] * N + rn[None, :], mask=(rk[:, None] < K) & (rn[None, :] < N), other=0.)
acc += tl.dot(a, b) # tensor cores
tl.store(c_ptr + rm[:, None] * N + rn[None, :], acc, mask=(rm[:, None] < M) & (rn[None, :] < N))The compiler stages tiles through shared memory, pipelines loads across num_stages, maps tl.dot onto tensor-core instructions and spreads the accumulator over num_warps warps.
- 1. For softmax rows of 781 columns, BLOCK should be…
- 2. In the matmul kernel, how many times is A read from global memory (without cache reuse)?
- 3. acc is kept in FP32 because…
Level 3: Advanced
★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.Performance knobs
- BLOCK_M, BLOCK_N, BLOCK_K: larger output tiles mean fewer re-reads of A and B (higher arithmetic intensity) but more registers and shared memory per program, fewer programs and more edge padding.
- num_warps (threads per program) and num_stages (software pipelining depth, each stage a copy of the A and B tiles in shared memory).
- Wave quantization: programs run in waves of SMs × programs-per-SM; 109 programs on 108 slots take two waves.
- Program ordering: grouping consecutive program ids along M (“GROUP_M” swizzling) makes neighbouring programs share A and B tiles in L2.
Autotuning
@triton.autotune(configs=[
triton.Config({"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 32}, num_warps=8, num_stages=3),
triton.Config({"BLOCK_M": 16, "BLOCK_N": 128, "BLOCK_K": 32}, num_warps=4, num_stages=4),
], key=["M", "N", "K"])
@triton.jit
def matmul_kernel(...): ...Triton benchmarks each configuration the first time a new key (shape) appears and caches the winner. The configuration that is best for a 4096³ GEMM can be several times too slow for a 16-row GEMM.
- 1. Shared memory for 3 stages of 128×32 A tiles and 32×128 B tiles in FP16?
- 2. triton.autotune's key=['M','N','K'] means…
- 3. GROUP_M program ordering improves…
Level 4: Expert
★★★★★ Expert⏱ 35 minResearchers: original papers and open problems.Kernels and tuning, measured
Exercise 1. The emulator’s add kernel over n = 5000 runs 5 programs, loads 2n and stores n elements (the masks stop at n). Fused softmax over 7 rows of 781 columns (BLOCK = 1024) reads and writes each element exactly once. A 37×29 by 29×50 blocked matmul with 16×16×16 tiles runs 12 programs, matches NumPy, and loads 8642 elements for 2523 distinct inputs: A is re-read once per column of tiles and B once per row.
Exercise 2: autotuning with a cost model. 80 candidate configurations (BLOCK_M 16–256, BLOCK_N 32–256, BLOCK_K 32/64, 4 or 8 warps, 3 stages) are filtered by A100 shared-memory and register limits (72 fit) and scored by a roofline-style model that includes edge padding, wave quantization and DRAM traffic (pessimistically assuming no L2 reuse):
| Shape (M × N × K) | best (BM, BN, BK, warps) | model TFLOP/s | fixed 128×128×32 | worst / best time |
|---|---|---|---|---|
| 4096 × 4096 × 4096 | (128, 256, 32, 8) | 170 | 128 | 7.9× |
| 8192 × 4096 × 4096 (prefill) | (128, 256, 32, 8) | 170 | 128 | 7.9× |
| 16 × 4096 × 4096 (decode) | (16, 128, 32, 4) | 28.9 | 5.8 | 10.0× |
The decode-shaped GEMM wants 16-row tiles: a 128-row tile is 88% padding and yields only 32 programs for 108 SMs, so the “good” square configuration is 5× too slow; the tuned one reaches about 90% of the shape’s memory bound. The 8 rejected configurations need more registers per thread than the 255 available (or more than 164 KB of shared memory). For softmax over a 4096 × 4096 FP16 tensor, the fused kernel moves 67 MB and the four-kernel version 201 MB: fusion saves 3× the traffic, and since softmax is memory-bound, about 3× the time. (Absolute TFLOP/s values come from the model; real kernels gain from L2 reuse.)
Triton in AI, robotics and aerospace
- Attention and normalization kernels: FlashAttention-style fused attention, RMSNorm, rotary embeddings, written in a few dozen lines.
- Quantized inference: INT4/INT8 dequantize-and-multiply kernels for running models on smaller GPUs.
- torch.compile’s backend: Inductor generates Triton for fused element-wise and reduction chains (C5.8).
- Scientific ML: custom fused kernels for physics-informed losses or particle interactions without leaving Python.
References
- P. Tillet, H. T. Kung, D. Cox (2019). “Triton: an intermediate language and compiler for tiled neural network computations.” MAPL Workshop (PLDI).
- Triton documentation and tutorials (triton-lang.org): vector addition, fused softmax, matrix multiplication.
- T. Dao, D. Y. Fu, S. Ermon, A. Rudra, C. Ré (2022). “FlashAttention: fast and memory-efficient exact attention with IO-awareness.” NeurIPS.
- J. Ansel et al. (2024). “PyTorch 2: faster machine learning through dynamic Python bytecode transformation and graph compilation.” ASPLOS.
- NVIDIA. CUTLASS documentation (github.com/NVIDIA/cutlass), for the tile hierarchy Triton automates.