v9.1.1
Menu

Triton Vector Addition Kernel

easyFREETriton FundamentalsTriton Programming

Problem Statement

Write a Triton kernel that adds two 1D float tensors element-wise: out = x + y.

Background

A Triton program instance handles one block of BLOCK_SIZE elements. Use tl.program_id(0) to get the block index, build per-element offsets with tl.arange, guard out-of-bounds lanes with a mask, then tl.load / tl.store.

Your Task

Implement add_kernel and a run(n=1024) that launches it over a 1D grid and returns whether the result matches x + y.

How it is tested

Your solution must define a top-level function run(...) that allocates inputs on the GPU, launches your Triton kernel, and returns a boolean from torch.allclose(triton_out, torch_reference, ...). The grader prints run(...); the expected output is True.

Example

Input
n = 1024
Output
True
Reasoning
  • n = 1024 is the length of the two random float vectors xx and yy; the target is outi=xi+yi\text{out}_i = x_i + y_i for every index i=0,…,n−1i = 0, \dots, n-1.
  • The vector is cut into blocks of BLOCK_SIZE =B= B elements and each program instance owns one block: program pp covers indices pB,pB+1,…,pB+B−1pB, pB+1, \dots, pB + B - 1.
  • With B=1024B = 1024, the number of programs is ⌈1024/1024⌉=1\lceil 1024 / 1024 \rceil = 1, and program 00 covers indices 00 to 10231023 — exactly the whole vector, so every lane is a real element.
  • For n=1000n = 1000 there is still ⌈1000/1024⌉=1\lceil 1000/1024 \rceil = 1 program, but its last 1024−1000=241024 - 1000 = 24 lanes (indices 10001000–10231023) point past the end and must neither read nor write; for n=4096n = 4096 there are 44 programs and no spare lanes.
  • The output True means every computed outi\text{out}_i agrees with xi+yix_i + y_i to within a tiny tolerance (about 10−510^{-5}). Notice that a single wrongly covered or out-of-range index would make the comparison fail.

Constraints

  • Use @triton.jit and tl.program_id(0)
  • offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
  • Mask out-of-bounds lanes with mask = offsets < n
  • Launch grid = (triton.cdiv(n, BLOCK_SIZE),)

Learn this in

More from Triton Programming

solution.py

Test results

Sign in to run your code against the test cases.