Prefill Operator Fusion and Compute Utilization: Practical Measurement and Kernel Design

    A practical guide to measuring and improving compute utilization in large-model inference. It explains why prefill and decode must be evaluated separately, what hardware peak and utilization actually measure, how to choose a maintainable operator-fusion boundary, and how the memory hierarchy, numerics, and layout constrain real performance. Readers get a four-layer metrics framework, a vendor-agnostic host-side schedule, and an executable order of operations for validating fused attention kernels against both phase-level and end-to-end targets.

    Large-model inference is not a single problem of “the fuller the compute, the better.” A request is usually split into two phases: prefill and decode. Prefill ingests the entire context in one pass, and the compute for matrix multiplication and attention rises quickly with sequence length, so it tends to hit the accelerator’s compute ceiling. Decode generates token by token, adding only a few tokens each step, yet it repeatedly moves the key-value cache, so it tends to hit memory bandwidth and launch overhead. Advertising both phases with the same “percentage of hardware peak” often yields incomparable conclusions. The more reliable engineering approach is to first separate the phases, then separate the operator boundaries, and only then discuss utilization.

    What the Peak Actually Measures

    Hardware peak usually refers to the number of floating-point operations that can be completed per unit time under ideal conditions: a given data type, tensor cores or vector units running at full load, and data already on-chip. It is not business throughput, nor is it end-to-end latency. Utilization is the measured effective compute divided by this theoretical peak. A slight change in the denominator shifts the percentage dramatically: do you use the chip’s nominal dense compute, or the achievable peak at that precision; do you count activation recomputation; is attention counted by the multiply-add count of a standard implementation, or by the instructions actually issued inside the fused kernel. Without these definitions, 98% and 60% cannot be compared.

    It helps to split the metrics into four layers and publish them together in the same test description:

    • Microbenchmark compute: run only the target fused kernel, keep inputs and outputs in device memory, and exclude framework scheduling.
    • Roofline position: record both arithmetic intensity (operations per byte of memory access) and measured bandwidth to judge whether the workload is compute-bound or bandwidth-bound.
    • Phase latency: report prefill latency, first-token latency, and steady-state decode latency separately, rather than merging them into a single “composite peak.”
    • End-to-end throughput: fix batch size, sequence length, output length, and concurrency, then report tokens/s and tail latency.

    The roofline can be written as a simple relationship: when arithmetic intensity falls below the ridge line of “peak compute / peak bandwidth,” piling on compute optimizations beyond operator fusion yields limited benefit, and you should prioritize reducing data movement. Prefill with long context often crosses the ridge line into the compute region; decode with short steps often stays in the bandwidth region. This is exactly why the two phases need separately designed kernels.

    Why Fuse Multiple Steps into a Single Launch

    A typical attention forward pass goes through normalization, rotary position encoding, attention scores and weighted summation, and then a cast of the result into the downstream data type at the framework layer. If each step is an independent kernel, four kinds of overhead recur: global-memory round trips, kernel launch and synchronization, intermediate-tensor footprint, and layout conversion back and forth between row-major and tiled layouts. The goal of fusion is not to “make the operator count look smaller,” but to keep intermediate results in registers or on-chip cache and read/write global memory only at the boundaries.

    A maintainable fusion boundary usually looks like this: before entering the kernel, the query, key, and value are already tiled by head dimension; inside the kernel, normalization statistics, rotary, score computation, softmax, and weighting are completed; on write-out, the result lands directly in the precision and layout the downstream expects. Too wide a boundary, and register pressure and compile time spin out of control while numerical errors become hard to localize; too narrow a boundary, and launch overhead returns. Fixing the head dimension (for example, preparing a dedicated instance for a specific head width in the implementation) is a common tradeoff: specialization can unroll loops and align vector width, but you must maintain one implementation and test per head width.

    The illustrative host-side schedule can stay vendor-agnostic:

    1. for each batch tile:
    2. load Q, K, V tiles into on-chip buffers
    3. normalize Q (and K if required) in registers
    4. apply rotary embedding with precomputed frequencies
    5. compute attention scores, scale, mask, softmax
    6. accumulate output
    7. cast and store in the layout expected by the next GEMM

    No instruction set is prescribed here; the only rule is that data must not fall back to global memory between steps. In implementation, use the register spills, shared-memory usage, and occupancy reported by the compiler to choose the tile, rather than hardcoding an “optimal block size” up front.

    Do Not Share the Same Assumptions for Prefill and Decode

    In prefill, the query length equals the context length, and the attention compute is on the order of the square of the sequence length (including batch and head count). Here the fused kernel must prioritize keeping the tensor cores fed: tiling should match the native shape of the compute units, masks should be generated on-chip as much as possible, and you should avoid issuing a separate memory access for each row’s mask. Causal masks, variable-length sequences, and prefix caching make the effective compute smaller than the nominal length; if you still use “full-sequence dense attention” as the numerator, utilization will be artificially lowered or inflated. Acceptance should record the true non-zero score ratio.

    In decode, the query length is usually 1 (or a very small speculative step), and the key-value cache already resides in high-bandwidth memory, stored by layer and by head. The bottleneck is mostly cache-read bandwidth, whether the indices are contiguous, and the bubbles caused by inconsistent cache lengths across requests in the batch. Moving prefill’s large tiles straight into decode often only adds synchronization without adding throughput. A more reasonable approach: shrink the compute tiling in the decode kernel, merge the cache reads across multiple heads, and use continuous batching to pack requests of different lengths into the same wave. Prefill pursues the compute ceiling; decode pursues bandwidth and latency. Their “good numbers” were never the same percentage.

    How the Memory Hierarchy Caps the Ceiling

    The accelerator’s external memory bandwidth determines whether the key-value cache and activations can keep up with compute. A first-order approximation of bandwidth is interface bit width times per-pin data rate, times the number of channels; stacking layers, bonding pitch, and interconnect distance affect whether that width can be built at acceptable power and yield, not the formula itself. When reading a performance report, you should ask: does the test use the chip’s theoretical bandwidth, the stream-copy measured bandwidth, or the effective bandwidth inside the attention kernel. The three often differ by a fair margin, because access stride, library allocation alignment, and cache-line conflicts eat into the nominal value.

    When high-bandwidth memory capacity is limited, long context forces the key-value cache to swap out to a slower tier of storage. At that point no operator fusion can keep prefill utilization near the compute ceiling, and the system reverts to a bandwidth or capacity problem. Capacity planning should be done alongside kernel optimization: per-layer cache bytes, batch size, context limit, and whether to quantize should all be worked out before talking about peak.

    Numerics, Layout, and Regression

    Fusion changes the order of operations. The mean and variance in normalization, the max shift in softmax, and half-precision accumulation can all make bit-exact results diverge from the unfused reference. The acceptance criterion should be task-relevant error, not element-wise bit identity. Keep an unfused reference path, compare the maximum absolute and relative error of logits on small shapes, and then sample only on the target shapes. The frequency table for rotary position encoding, the scale factor, and the inclusion endpoints of the mask are the most common sources of silent errors and should be locked down with unit tests.

    Layout must also be written into the contract: whether the head dimension is contiguous, whether the sequence or batch dimension is the outer one, and whether writes are 128-byte aligned. If a dedicated-instance file is named after the model structure, its comments should state the head width, precision, and mask type it serves, to avoid reusing the wrong instance for a later shape. Performance regression should at minimum fix: device, driver, data type, batch and sequence, whether a mask is included, whether timing is warmed up, the repeat count, and whether you take the median or the best. Reporting only a single “best run” cannot distinguish noise from optimization.

    An Executable Order of Operations

    1. Use the roofline to confirm the prefill target kernel is in the compute region and the decode target is in the bandwidth region; stop any optimization that is not in its corresponding region.
    2. Choose a narrow, stable fusion boundary. First fuse normalization, rotary, attention, and the write-out cast; do not force the large matrix multiplications before and after into the same kernel.
    3. Specialize for the main head widths, route the remaining shapes through a general implementation, and validate both against the same numerical threshold.
    4. Publish microbenchmark utilization, phase latency, and end-to-end throughput separately, stating the peak denominator and the timing method.
    5. Put cache capacity, batch strategy, and quantization into the same capacity budget, so the kernel meets its target without the service falling short.

    The same judgment applies regardless of accelerator vendor: whether the ecosystem is closed-loop is not about slogans, but about whether the fused kernel is compilable and reproducible in a public implementation and whether the phase metrics and end-to-end metrics hold at the same time. A single microbenchmark near the compute ceiling only shows that this kernel’s arithmetic intensity and instruction mapping are well done; it cannot substitute for decode bandwidth, cache capacity, and scheduling latency. Write the definitions clearly, and only then do the performance numbers carry engineering meaning.