Estimate memory traffic saved by fusing elementwise kernels

Why it matters Fusing bias, activation, residual and normalization ops is one of the biggest wins in LLM inference, and compilers decide it with this arithmetic.

Elementwise ops are memory bound: each separate kernel reads its inputs from global memory and writes its output back. Fusing a chain into one kernel keeps the intermediate values in registers.

Write fusion_traffic(n, bytes_per_elem, extra_inputs). A chain of len(extra_inputs) ops runs on one tensor of n elements; op i also reads extra_inputs[i] other tensors of the same size (for example a bias or a residual). Unfused, op i reads 1 + extra_inputs[i] tensors and writes 1. Fused, the single kernel reads the starting tensor once, every extra tensor once, and writes the final result once. Return (unfused_bytes, fused_bytes, ratio = unfused / fused). For an empty chain return (0, 0, 1.0).

Signaturedef fusion_traffic(n, bytes_per_elem, extra_inputs)

Example

n 1000, 2 bytes, extra_inputs [1, 0, 0] (add bias, then gelu, then scale) gives (14000, 6000, 2.3333).

Understand the idea

Running separate kernels is like cooking a dish by carrying the pot back to the fridge after every step: chop, back to the fridge, take it out, fry, back to the fridge, and so on. Fusion keeps the pot on the stove for all steps. Worked example: 1000 fp16 values through add-bias, gelu and scale. Unfused: add reads 2 tensors and writes 1 (3 units), gelu reads 1 and writes 1 (2), scale 2, total 7 units of 2000 bytes = 14000. Fused: read the input and the bias, write once, 3 units = 6000 bytes. Ratio 2.33. Rule: unfused = sum(2 + e_i), fused = 2 + sum(e_i), in tensor-sized units. Because these ops do very little math per byte, the time is almost all memory traffic, so the byte ratio is close to the speedup.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplefusion_traffic(1000, 2, [1, 0, 0])
  • Sample 2: residualfusion_traffic(4096, 4, [0, 1, 1, 0])
  • Test 3: single opfusion_traffic(10, 2, [2])
  • Test 4: emptyfusion_traffic(10, 2, [])