Triton 让你用 Python 写 GPU kernel,编译器(MLIR)负责生成 接近手写 CUDA 的性能。代价是你需要理解它的抽象:block 级别的 program + 向量化的 tl 算子。
向量加法
import triton
import triton.language as tl
@triton.jit
def add_kernel(x_ptr, y_ptr, out_ptr, n, BLOCK: tl.constexpr):
pid = tl.program_id(0) # 第几个 block
offs = pid * BLOCK + tl.arange(0, BLOCK) # 本 block 的元素下标
mask = offs < n # 边界掩码
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)
n = x.numel()
add_kernel[(triton.cdiv(n, 1024),)](x, y, out, n, BLOCK=1024)
return out
对照 CUDA 的差异很明显:
| 概念 | CUDA | Triton |
|---|---|---|
| 调度单位 | 线程、warp | block(program) |
| 索引 | threadIdx.x | tl.arange |
| 边界处理 | 手写 if | mask= |
| 内存 | 手动管理 | tl.load / tl.store |
三个入门建议
- 从
tl.arange开始——它替代了 CUDA 里最易错的索引计算; BLOCK: tl.constexpr是编译期常量,调优时改它比改代码更常见;- 用
triton.testing.Benchmark对照 PyTorch 的torch.add, 感受内存带宽上限离你有多近。
Triton 已进入 PyTorch 2 的 torch.compile 后端,学会它等于
同时拿到一套可读性更好的 kernel 开发工具。