v9.1.1
Menu

Triton Fused Multiply-Add Kernel

mediumPROTriton FundamentalsTriton Programming

Problem Statement

Implement a fused multiply-add kernel: out = a * x + b * y for two 1D tensors and two runtime scalars a, b.

Background

Fusing multiple elementwise operations into one kernel means each element is read and written exactly once, saving memory bandwidth versus separate multiply and add passes.

Your Task

Implement fma_kernel and run(n=1024, a=2.0, b=-1.0).

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, a = 2.0, b = -1.0
Output
True
Reasoning
  • Inputs: n = 1024 is the length of two random vectors xx and yy; a = 2.0 and b = -1.0 are plain scalars that weight them.
  • Math: every position ii is independent, outi=a xi+b yiout_i = a\,x_i + b\,y_i. With the sample scalars that is outi=2xi−yiout_i = 2x_i - y_i, so if xi=0.5x_i = 0.5 and yi=1.5y_i = 1.5 then outi=1.0−1.5=−0.5out_i = 1.0 - 1.5 = -0.5.
  • Fusion: each xix_i and yiy_i is read once and each outiout_i written once, with no intermediate vectors for a xa\,x or b yb\,y.
  • Tiling: if each program instance handles a block of BB elements, you need ⌈n/B⌉\lceil n/B \rceil blocks. For n=1500n = 1500 and B=1024B = 1024 that is 2 blocks, and the second has only 1500−1024=4761500 - 1024 = 476 real elements; the other 548 positions must not be read or written.
  • Output: True means your outout matches a x+b ya\,x + b\,y to within an absolute tolerance of 10−510^{-5}. Notice the scalars can be negative or fractional, so they are runtime values, not constants.

Constraints

  • Single kernel computing ax + by
  • Two tensor pointers, two scalar args
  • Mask the tail block

Learn this in

More from Triton Programming

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.