Operator Fusion and Bandwidth Coordination in LLM Prefill
This article breaks down why prefill, not decode, is where operator fusion pays off, and how to draw a fusion boundary that actually reduces memory traffic. It covers the three recurring losses in one-kernel-per-layer scheduling, a concrete fusion boundary for causal attention prefill, how to define peak utilization with an explicit measurement basis (timing window, counted operations, precision and shape, roofline position), what wide-interface and wafer-scale/bonded memory trade away, why prefill and decode need separate acceptance criteria, a low-to-high-risk rollout order with the failure modes to test for, and how to turn "peak" from a slogan into a review checklist.
Where the Problem Comes From
LLM inference is usually split into two phases: prefill, which pushes the entire prompt through the model at once, and decode, which generates tokens autoregressively one at a time. The prefill compute graph is “thicker” and has higher arithmetic intensity for matmuls and attention, so in theory it runs closer to the chip’s compute peak. Decode is bound by bandwidth and latency, and is often limited by reading and writing the key-value cache.
A common engineering misjudgment is to estimate the whole inference run from the chip’s nominal peak floating-point performance, then find that time-to-first-token is still slow after launch. The cause is usually not “not enough compute.” It is that normalization, rotary position embedding, attention, and dtype conversion are split across multiple kernel launches, with intermediate results moving in and out of on-chip storage repeatedly, so effective compute is consumed by memory traffic and launch overhead.
A more useful goal, then, is not to claim “we hit some percentage of peak,” but to build a verifiable chain: determine whether the bottleneck is compute or bandwidth, fuse the steps that must execute consecutively by semantics into fewer kernels, and then regress with the same shapes, precision, and timing method.
Why Prefill Is a Better Fit for Fusion
Prefill processes far more tokens per step than decode. The query, key, and value projections and the softmax attention that follows scale quickly with sequence length once batch size and sequence length are large enough, while some intermediate tensors can stay resident in on-chip cache or registers for reuse. If scheduling still follows “one kernel per operator per layer,” three kinds of loss recur:
- Kernel launch and synchronization: every small operator has to configure a grid, move descriptors, and wait for completion; fixed overhead dominates short kernels.
- Intermediate write-back: normalized hidden states, rotated queries and keys, and attention scores, if all are written to global memory and read back, fill bandwidth with pointless traffic.
- Precision round-trips: training or exported graphs commonly compute in higher precision and store in lower precision. If the conversion is its own kernel, it adds a full read-write pass.
Fusion means placing normalization, rotary position embedding, the main attention computation, and any necessary dtype conversion into one kernel or a few tightly pipelined kernels, without changing the mathematical definition, so intermediate values travel through registers, shared memory, or on-chip cache. Fusion does not mean cramming every layer into one giant kernel; it means cutting an operator chain that “just fits” according to data dependencies and on-chip capacity.
A Practical Fusion Boundary
For causal attention prefill, a reasonably safe fusion boundary is usually:
- Normalize the hidden state of the current block, folding in scale and bias parameters if present.
- Generate or apply rotary position embedding. Frequency terms can be precomputed by sequence position, but the elementwise rotation of queries and keys should stay inside the kernel rather than writing out the full rotated tensors first.
- Within the block, compute the query-key dot product, apply the mask, and do the softmax normalization and weighted sum. Block size is determined jointly by head dimension, sequence tiling, and on-chip storage.
- Perform the conversion to the target storage precision before writing the output, so downstream layers consume the final layout directly.
Head dimension is a hard constraint on tiling. With a large head dimension, a single head’s key-value block more easily exceeds shared memory; with a small head dimension, compute density may be too low to hide latency. In practice, estimate resident footprint as head dimension × tile length × bytes per element, and leave room for double buffering and reduction scratch space. Do not assume one tiling covers all sequence lengths: short sequences should take a low-launch-overhead path, long sequences a tiled pipeline path.
The scheduling pseudocode below expresses only the data flow and does not correspond to any specific chip interface:
for each sequence tile:load hidden tile into on-chip buffernormalize in registers or bufferapply rotary to q and k tilesfor each kv tile that fits:compute scores, apply mask, update running softmaxaccumulate outputcast and store output tile
A running softmax must maintain each row’s maximum and normalization denominator; only these scalar states and partial outputs may pass between tiles. Writing the entire score matrix out and reading it back in is the dividing line for whether fusion actually saves bandwidth.
How Peak Utilization Should Be Defined
“Hardware peak” is not comparable without a stated basis. At minimum, specify:
- Timing window: whether it includes host dispatch, host-to-device transfer, the kernel itself, and result transfer back. Compare kernel efficiency using device-side kernel time only; for end-to-end, transfers must be included.
- What is counted: which operations go in the numerator. In attention, exponentials, comparisons, and masking are often excluded from matmul peak; counting them into “percentage of peak” biases the number systematically high or low.
- Precision and shape: the achievable peak on the same chip differs across precisions and matrix sizes. When the application shape is far from the kernel’s tuning point, the percentage drops sharply, which does not mean the implementation is wrong.
- Roofline position: first estimate arithmetic intensity (floating-point operations per global memory access). Above the machine balance point, the bottleneck is compute; below it, no amount of instruction reduction approaches the compute peak, so reduce traffic first.
For validation, fix a shape family: short, medium, and long sequences, single-head and multi-head, two storage precisions. For each shape, record kernel time, global memory bytes read and written (if performance counters are available), and output verification error. Use relative error and latency percentiles as regression gates, not a single benchmark run. Cache warm-up, frequency variation, and noisy neighbors all distort a single percentage.
Bandwidth Side: What Wide-Interface Memory Solves and What It Costs
When sequences are long and there are many heads, key-values are re-read repeatedly even when tiled; decode scans the cache almost every step. Whatever the packaging, the core metrics of high-bandwidth memory are interface width, channel count, per-pin data rate, access granularity, and capacity. Increasing width raises theoretical bandwidth at the same per-pin rate, but brings more data channels, tighter timing, and more complex interconnect.
Wafer-scale or near-memory bonded approaches typically trade shorter interconnect distance for bandwidth and energy efficiency, and the costs are explicit: the smaller the bond pitch, the less likely defects are repairable through redundancy; stacked layers are limited by heat, mechanical stress, and yield; per-die capacity does not necessarily grow in step with bandwidth. Compute chips therefore often rely on multiple interconnected dies to spread capacity, and the system bottleneck shifts from “single-die bandwidth” to inter-die links, coherence or explicit copies, and fault isolation. When evaluating, look at four things at once: effective bandwidth (not the theoretical pin value), addressable capacity, fault domain size, and whether software must change its cache layout.
The corresponding software actions are: align the key-value cache by head and block to the memory access granularity; use the same layout for prefill writes and decode reads to avoid a transpose kernel; keep reductions that can be done on-chip off global memory; and bucket sequences of different lengths within a batch to reduce wasted bandwidth from padding.
Do Not Reuse One Set of Optimization Conclusions Across Prefill and Decode
A successful prefill optimization shows compute time growing roughly linearly with prompt tokens, with a slope near the compute ceiling given by the roofline, while intermediate write-back bytes drop noticeably. A successful decode optimization shows per-step latency constrained by cache read bandwidth and batch size; fused attention only reduces launch overhead and will hardly “saturate compute peak.” Extrapolating a prefill peak percentage directly to decode overestimates generation speed.
The two phases should also be accepted separately: for prefill, look at time to first token and prompt throughput; for decode, look at steady-state tokens per second and the batch-size scaling curve. Cache hits, continuous batching, and paged caches change the decode curve but should not be mixed into a microbenchmark of the prefill kernel.
Rollout Order and Common Failures
Proceed from low to high risk.
- Profile first: confirm whether time goes to small-kernel launches, repeated reads and writes, or the main attention computation. Without counters, use ablation — removing a segment while keeping numerics correct — to estimate it.
- Then align numerics: compare outputs before and after fusion on the same random input, examining normalization, rotary, and attention separately. Set error budgets per precision; low-precision storage allows larger absolute error, but the relative trend should be stable.
- Then sweep tiling parameters: sweep only tile length, head grouping, and the double-buffering switch, avoiding simultaneous algorithm changes.
- Only then go end-to-end: put the kernel into real batching with variable-length sequences and watch for on-chip overflow, deadlock, or tail-block errors.
Failure modes are concentrated. Too large a fusion scope causes register spilling, the compiler inserts local-memory round-trips, and performance drops. Mishandled masking and variable-length sequences cause tail blocks to be recomputed or skipped. The rotary position offset is not adjusted by the block start after tiling. Rounding in the dtype conversion differs from the standalone kernel and amplifies error in later layers. Workspace reuse under multi-stream concurrency produces intermittent errors. All of these should be test cases, not discoveries after launch.
How to Write This Into Engineering Standards
Teams can turn “peak” from a slogan into a checklist item: every fused kernel must ship with a shape table, a timing basis, an arithmetic intensity estimate, a numerical error threshold, and the sequence lengths where it is known not to apply. Changing head dimension or position encoding forces a rerun of that table. Capacity and bandwidth tradeoffs belong in capacity planning: for long context, compute cache bytes first, then check whether the link can feed the compute, rather than assuming memory bandwidth is sufficient.
Done this way, prefill optimization becomes maintainable engineering: fusion removes pointless traffic, tiling guarantees the working set fits on-chip, the roofline explains whether a percentage is high or low, and separate benchmarks prevent mistaking a decode problem for a compute problem. When hardware interfaces get wider or narrower, the same method still applies — only the balance point and access granularity change, without tying conclusions to one generation’s marketing numbers.
