v9.1.1
Menu

Triton Autotuned Vector Add

mediumFREEAdvanced KernelsTriton Programming

Problem Statement

Add two vectors but let Triton pick the best BLOCK_SIZE using @triton.autotune.

Background

@triton.autotune benchmarks a list of triton.Configs (keyed on input sizes) and caches the fastest. The grid becomes a lambda over meta so it can read the chosen BLOCK_SIZE.

Your Task

Decorate add_kernel with @triton.autotune over at least two block sizes and implement run(n=4096) that launches with a meta-aware grid.

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 = 4096
Output
True
Reasoning
  • n = 4096 is the length of two random float vectors xx and yy; the target is zi=xi+yiz_i = x_i + y_i for every index ii from 00 to n−1n-1.
  • Each kernel instance handles one contiguous block of BB = BLOCK_SIZE elements (instance pp covers pBpB to pB+B−1pB + B - 1). So the launch needs ⌈n/B⌉\lceil n / B \rceil instances, and that count depends on which BB wins the benchmark.
  • With B=256B = 256 there are ⌈4096/256⌉=16\lceil 4096/256 \rceil = 16 instances; with B=1024B = 1024 there are 44. Since 16×256=4×1024=409616 \times 256 = 4 \times 1024 = 4096, each index is covered once.
  • The second test, n=10000n = 10000, is not a multiple of either size: B=1024B = 1024 gives 1010 instances and B=256B = 256 gives 4040, both spanning 1024010240 slots, so the last 240240 slots lie past the end of the vectors and must contribute nothing.
  • The output True says every ziz_i equals xi+yix_i + y_i to within 10−510^{-5}. Notice that BB changes speed, never the values.

Constraints

  • Use @triton.autotune with configs of differing BLOCK_SIZE, key=['n']
  • grid = lambda meta: (triton.cdiv(n, meta['BLOCK_SIZE']),)
  • BLOCK_SIZE is supplied by the config, not passed explicitly

Learn this in

More from Triton Programming

solution.py

Test results

Sign in to run your code against the test cases.