Thursday, November 12, 2026

Writing GPU Kernels in Python With Triton

TL;DR

Triton lets you write GPU kernels in Python instead of C++ CUDA, with each program handling a block of data rather than a single thread. This guide walks through the vector addition kernel from the official tutorials, shows how to benchmark it, and explains why fusion is where the real speedups live. Spoiler: adding two vectors will not beat PyTorch, and it is not meant to.

Where the real lessons are:

Say a training run spends a surprising share of its time in one custom operation: a few element-wise steps and a row-wise normalization that PyTorch runs as several separate GPU kernels. Each kernel reads the whole tensor from GPU memory and writes it back, so the GPU spends more time moving data than doing math. The usual fix is a custom CUDA kernel, written in C++ by someone who knows the hardware well.

Triton offers a shorter path. Triton is an open-source language and compiler for writing GPU kernels in Python. You write a function that works on one block of data, decorate it with @triton.jit, and Triton compiles it to GPU code, handling details such as memory coalescing and shared memory that CUDA leaves to you. This guide walks through the vector addition kernel from the official Triton tutorials line by line, shows how to benchmark it against PyTorch, and explains when a custom kernel is worth writing at all.

Key Takeaways

  • Triton kernels are Python functions compiled for the GPU. Each kernel instance (a “program”) processes one block of elements, not one element like a CUDA thread.
  • The core pattern is always the same: find your block with tl.program_id, build offsets with tl.arange, mask the edges, then tl.load, compute and tl.store.
  • The biggest wins come from fusion: doing several steps in one kernel so data is read from memory once. Plain vector addition will not beat PyTorch, and it is not meant to.
  • Always check a kernel against a PyTorch reference and benchmark it with triton.testing.do_bench before using it.
  • Triton needs a supported GPU. Interpreter mode (TRITON_INTERPRET=1) runs kernels on the CPU for debugging, slowly.

What Is Triton?

Triton started as research by Philippe Tillet, H. T. Kung and David Cox, described in the 2019 paper Triton: An Intermediate Language and Compiler for Tiled Neural Network Computations. The project moved to OpenAI, which released Triton 1.0 in 2021, and it is now developed in the open at triton-lang/triton on GitHub. It supports NVIDIA and AMD GPUs.

The key idea is the block. In CUDA you write code for a single thread and coordinate thousands of them yourself. In Triton you write code for a program that handles a whole block of elements at once, such as 1,024 values of a vector or one tile of a matrix. The compiler decides how to spread that block across the GPU’s threads and memory.

You may already be running Triton without knowing it. When you call torch.compile on a model running on a GPU, PyTorch’s default backend generates Triton kernels for many operations. Writing your own kernel makes sense when the compiler does not fuse the steps you need or when you want full control over one hot spot.

Install Triton

Triton is published on PyPI as triton, and PyTorch’s Linux builds with GPU support install it as a dependency. Check what you have:

pip install torch triton
python -c "import triton; print(triton.__version__)"

The examples below were checked against Triton 3.8 and PyTorch 2.14. They follow the official tutorial, which picks the GPU with triton.runtime.driver.active.get_active_torch_device() so the same code works on NVIDIA and AMD hardware.

Your First Triton Kernel: Vector Addition

Adding two vectors is the “hello world” of GPU programming. The code below follows the vector addition tutorial in the Triton documentation, with comments added:

import torch
import triton
import triton.language as tl

DEVICE = triton.runtime.driver.active.get_active_torch_device()


@triton.jit
def add_kernel(x_ptr, y_ptr, output_ptr, n_elements, BLOCK_SIZE: tl.constexpr):
    # Each program instance handles one block of BLOCK_SIZE elements.
    pid = tl.program_id(axis=0)
    block_start = pid * BLOCK_SIZE
    offsets = block_start + tl.arange(0, BLOCK_SIZE)
    # The last block may run past the end of the vectors, so mask it.
    mask = offsets < n_elements
    x = tl.load(x_ptr + offsets, mask=mask)
    y = tl.load(y_ptr + offsets, mask=mask)
    output = x + y
    tl.store(output_ptr + offsets, output, mask=mask)


def add(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
    output = torch.empty_like(x)
    assert x.device == DEVICE and y.device == DEVICE and output.device == DEVICE
    n_elements = output.numel()
    # One program per block: ceil(n_elements / BLOCK_SIZE) programs in a 1D grid.
    grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),)
    add_kernel[grid](x, y, output, n_elements, BLOCK_SIZE=1024)
    return output


torch.manual_seed(0)
size = 98432
x = torch.rand(size, device=DEVICE)
y = torch.rand(size, device=DEVICE)
output_torch = x + y
output_triton = add(x, y)
print(f"Max difference between torch and triton: "
      f"{torch.max(torch.abs(output_torch - output_triton))}")

How the Kernel Works

Take the test size of 98,432 elements and a block size of 1,024. The grid function asks for triton.cdiv(98432, 1024) = 97 programs (96.1 rounded up). Each program runs add_kernel once:

  • tl.program_id(axis=0) returns which of the 97 programs this is, from 0 to 96.
  • offsets is a block of 1,024 indices. Program 0 covers 0 to 1,023, program 1 covers 1,024 to 2,047, and so on.
  • mask matters for the last program. Program 96 covers indices 98,304 to 99,327, but only the first 128 of those exist. The mask tells tl.load and tl.store to skip the rest instead of reading or writing past the end of memory.
  • BLOCK_SIZE: tl.constexpr marks the block size as a compile-time constant. Triton compiles a specialized version of the kernel for each value, which is why shapes inside a kernel must be known at compile time and powers of two.

The pointers x_ptr, y_ptr and output_ptr are the PyTorch tensors themselves. Triton passes their memory addresses to the kernel, and x_ptr + offsets is a block of addresses to load from.

Check It Against PyTorch

The last lines compare the Triton result with PyTorch’s own x + y. We do not have a GPU in our test setup, so we ran the kernel in Triton’s interpreter mode on the CPU (setting TRITON_INTERPRET=1 and using a CPU device). The output was:

Max difference between torch and triton: 0.0

On a GPU you should see the same zero difference. Interpreter mode is useful for exactly this kind of check: you can add print statements and use a debugger inside the kernel, at the cost of running far slower than real GPU code.

Benchmark the Kernel

A custom kernel is only worth keeping if it is faster than what you had. triton.testing.do_bench handles warm-up and repeated timing and returns the mean runtime in milliseconds:

import torch
import triton

from vector_add import DEVICE, add

x = torch.rand(2**24, device=DEVICE, dtype=torch.float32)
y = torch.rand(2**24, device=DEVICE, dtype=torch.float32)

ms_torch = triton.testing.do_bench(lambda: x + y)
ms_triton = triton.testing.do_bench(lambda: add(x, y))

# Two reads and one write of 4-byte floats per element.
gbps = lambda ms: 3 * x.numel() * x.element_size() * 1e-9 / (ms * 1e-3)
print(f"torch:  {ms_torch:.3f} ms, {gbps(ms_torch):.0f} GB/s")
print(f"triton: {ms_triton:.3f} ms, {gbps(ms_triton):.0f} GB/s")

This needs a GPU, so we only checked that it compiles. Vector addition is memory-bound: each element needs two reads and one write of 4 bytes and a single addition, so the speed limit is memory bandwidth, not compute. That is why the benchmark reports GB/s. Expect Triton and PyTorch to land close to each other, because both are already limited by how fast the GPU can move data. The official tutorial shows the same result in its benchmark plot.

Where Triton Pays Off: Kernel Fusion

If vector addition does not beat PyTorch, why write kernels at all? Because real workloads chain operations. Computing a softmax over each row of a matrix with separate PyTorch calls means a pass to find the row maximum, another to subtract it and exponentiate, another to sum, and another to divide. Each pass reads the matrix from GPU memory and most write a new one.

A fused Triton kernel loads each row once, does all the steps while the data sits in fast on-chip memory, and writes the result once. The second tutorial in the official Triton tutorial series, fused softmax, builds exactly this kernel. The pattern from vector addition carries over: each program handles whole rows instead of a flat block, with tl.max and tl.sum doing the reductions inside the block.

Good candidates for a custom Triton kernel share three traits:

  1. Several memory-bound steps in a row, such as activations, normalizations, masking or custom attention variants.
  2. A real share of runtime. Profile first. A kernel that is twice as fast but only covers 2% of runtime saves 1%.
  3. No existing fused version. Check whether torch.compile already fuses the steps for you before writing anything by hand.

Tips for Writing Triton Kernels

  • Start from a tutorial kernel. Vector addition, fused softmax and matrix multiplication cover the three main patterns: element-wise, row reduction and tiled matrix math.
  • Tune block sizes. The best BLOCK_SIZE depends on the GPU and the input shape. The @triton.autotune decorator tries a list of configurations and keeps the fastest.
  • Test edge cases. Use sizes that are not multiples of the block size, like the tutorial’s 98,432, so the mask path gets exercised.
  • Compare against a reference every time. Keep the PyTorch version of the operation as the ground truth in your tests.

If your bottleneck is model serving rather than one operation, the gains usually come from the serving stack. Our guide to serving multiple LoRA adapters with vLLM covers that side. And if you prefer letting a compiler do the work, reproducing NanoGPT in JAX shows a framework that compiles whole programs for you.

Back to the Slow Operation

The training run from the opening does not need a CUDA expert. The team can profile it, confirm the custom operation is a real share of runtime, and check whether torch.compile already fuses it. If not, they can write one Triton kernel in Python that reads each row once and writes it once, check it against the PyTorch version, and benchmark it with do_bench. The vector addition kernel above is the template for all of it.

Frequently Asked Questions

Is Triton Made by NVIDIA?

No. The Triton language and compiler came out of research at Harvard and is developed at OpenAI and by an open-source community. NVIDIA has a different product called Triton Inference Server, which serves trained models and is unrelated to the kernel language.

Does Triton Work Without a GPU?

Triton compiles kernels for GPUs, so real runs need a supported NVIDIA or AMD GPU. For debugging, interpreter mode (TRITON_INTERPRET=1) simulates kernels on the CPU. It is far too slow for real work, but good for checking logic.

Is Triton Faster Than CUDA?

Not by default. Expert hand-written CUDA can match or beat Triton, especially for unusual memory layouts. Triton’s advantage is that you reach good performance with much less code and without managing threads and shared memory yourself.

What Is the Difference Between Triton and torch.compile?

torch.compile is a compiler for whole PyTorch programs, and on GPUs it generates Triton kernels for you. Writing Triton directly is the manual option for when you need a specific fusion or algorithm the compiler does not produce.

Disclaimer: The content on this website reflects the views of contributing authors and not necessarily those of Generative AI Lab. This site may contain sponsored content, affiliate links, and material created with generative AI. Thank you for your support.

Generative AI Lab mascot
Generative AI Lab Editorial Team
Articles researched, written and edited by the Generative AI Lab team. About Generative AI Lab

Must read

- Advertisement -spot_img

More articles

- Advertisement -spot_img

Latest articles

Available for Amazon Prime