A vector addition kernel in Triton

ResearchGPU accelerationCustom GPU kernels

Goal: Writing a GPU kernel in Python instead of CUDA C++.

Python — example.py
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(0)
    offs = pid * BLOCK + tl.arange(0, BLOCK)
    mask = offs < n
    tl.store(out_ptr + offs, tl.load(x_ptr + offs, mask=mask) + tl.load(y_ptr + offs, mask=mask), mask=mask)

x = torch.rand(98432, device="cuda"); y = torch.rand_like(x); out = torch.empty_like(x)
add_kernel[(triton.cdiv(x.numel(), 1024),)](x, y, out, x.numel(), BLOCK=1024)
print("Matches PyTorch:", torch.allclose(out, x + y))

Code explanation

Each program instance processes a block of BLOCK elements, and the mask protects against reading out of bounds. This pattern is the basis of more complex kernels such as fused attention. It needs a supported GPU, so it was not run in the test environment.

Requirements

Shell
pip install triton torch

How to run

Save the code in a file example.py then run it:

Shell
python example.py

This example was not run in the test environment: needs a GPU supported by Triton. Check it against the library documentation before relying on it.

Libraries used

Related examples