Speeding up a Python loop with Numba JIT
Compiling a numerical function to machine code with a single decorator.
Goal: Writing a GPU kernel in Python instead of CUDA C++.
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))
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.
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.
Compiling a numerical function to machine code with a single decorator.
Running NumPy-style code on the GPU.
Sections
No section has this name. Press “Search” to search all site content.
Favourites
My results & certificates
My academy progressMy quiz resultsKids’ progressAcademy certificatesQuiz certificatesStart any lesson or quiz and it will show up here so you can get back to it quickly.
Settings
I am the AI Frameworks & Libraries Assistant. Describe your project or ask me about a library, a comparison or a code example, and I will answer from the encyclopedia's database with links and sources.
Answers from the encyclopedia's database only, without a language model and without sending your question to any third party.
The assistant can make mistakes, so check the attached sources.