Simulate a multi-stage load and compute pipeline
Why it matters Choosing the number of pipeline stages trades shared memory for latency hiding in modern matmul and attention kernels.
Fast kernels overlap loading the next tile with computing the current one, using several shared-memory buffers (stages). With too few buffers, the loader must wait for compute to free a buffer.
Write pipeline_time(load, compute, stages). load[i] and compute[i] are the times for tile i, processed in order. One loader and one compute unit run in parallel. Tile i uses buffer i % stages. Its load starts when the loader has finished load i - 1 and its buffer is free, meaning compute of tile i - stages has finished (no wait for i < stages). Its compute starts when its own load has finished and compute i - 1 has finished. Return (total_time, compute_idle) where total_time is when the last compute ends and compute_idle is total_time minus the sum of compute times. For no tiles return (0.0, 0.0).
def pipeline_time(load, compute, stages)Example
load [2, 2, 2], compute [3, 3, 3], stages 1 gives (15.0, 6.0); with stages 2 it gives (11.0, 2.0).
Understand the idea
A pipeline with buffers is like a cook with plates. A helper fetches ingredients onto a plate, the cook cooks from the plate, then the plate is free again. With one plate, the helper waits for the cook and the cook waits for the helper, so nothing overlaps. With two plates, the helper fills the next plate while the cook works. Worked example: loads 2, computes 3, three tiles. One stage: load 0 to 2, compute 2 to 5, load 5 to 7, compute 7 to 10, load 10 to 12, compute 12 to 15. Two stages: load tile 1 runs 2 to 4 during compute, compute ends at 5, 8, 11. Rule: load_end[i] = max(load_end[i-1], comp_end[i-stages]) + load[i]; comp_end[i] = max(load_end[i], comp_end[i-1]) + compute[i]. Real kernels pick 2 to 4 stages, limited by shared memory size.