Adapting LLM Inference Operators to Domestic Accelerator Cards: Prefill, Fusion, and Memory Bandwidth

    This article examines how to adapt large language model inference operators to domestic accelerator cards. It explains why Prefill sets the upper bound for compute utilization, how operator fusion removes memory traffic from the critical path, and how compile-time specialization reduces runtime branching. It also presents a reproducible benchmarking method for Prefill and Decode, discusses memory bandwidth and custom high-bandwidth memory with hybrid bonding, and closes with an engineering checklist and scope boundaries.

    1. Background: Why Prefill Sets the Ceiling for Compute Utilization

    Large model inference is usually split into two stages: Prefill and Decode. Prefill processes the entire input sequence at once. It is a typical compute-intensive workload with large matrix multiplications and high arithmetic intensity, so in theory it can push the accelerator’s compute units close to saturation. Decode generates tokens autoregressively, one token at a time, processing only one position per step. Its arithmetic intensity is very low, and the bottleneck quickly shifts to memory bandwidth and memory access latency.

    This explains a fact that is often misunderstood: when vendors publish “hardware peak utilization,” they almost always mean the Prefill stage. A set of reference figures disclosed in public code commits is Prefill at about 425 TFLOPS, reaching 98.5% of hardware peak compute, and Decode at about 372 TFLOPS, or about 86.1%. Put together, these two numbers confirm the structural difference described above: Prefill is already close to the theoretical ceiling, while Decode still has room for optimization but is constrained by memory access.

    The engineering metric for measuring this is MFU (Model FLOPs Utilization):

    1. def mfu(actual_tflops: float, peak_tflops: float) -> float:
    2. """Actual achieved compute / hardware nominal peak compute"""
    3. return actual_tflops / peak_tflops
    4. # Example: Prefill at 98.5% means the operator is almost squeezing the compute units dry
    5. print(mfu(425, 431)) # ≈ 0.986

    It is important to note that high MFU does not equal high end-to-end throughput. It only shows that the compute units are not idle. It does not mean the pipeline has no bubbles, nor does it mean memory capacity and bandwidth will not become subsequent bottlenecks.

    2. Core Approach 1: Operator Fusion to Remove Memory Traffic from the Critical Path

    In a naive implementation, the Prefill of a Transformer layer expands into a long chain of independent operators: RMSNorm/LayerNorm, QKV projection, RoPE positional encoding, attention computation, output projection, residual addition, and type conversion. Each operator is dispatched separately, and each one must write intermediate tensors back to memory and read them out again. As the sequence grows, the movement of these intermediate tensors quickly exceeds the computation itself.

    The idea of fusion is to merge adjacent memory-intensive operators into a single kernel so that intermediate results stay in on-chip cache:

    1. Before fusion: norm → (write back) → rope → (write back) → attention → (write back) → cast
    2. After fusion: [norm + rope + attention + cast] single read/write

    Public commits implement this entire segment as a fused operator with head dimension 128. This eliminates three memory round trips at once and folds type conversion (cast between lower and higher precision) into the tail of the computation, avoiding an additional full-tensor materialization. head_dim=128 is the most common configuration in current mainstream models. Specializing for it allows compile-time constants to replace runtime branches, enabling the compiler to fully unroll loops and statically allocate on-chip buffers.

    3. Core Approach 2: Compile-Time Specialization and Dedicated Instances

    A fused operator alone is not enough. When the same kernel faces different model structures (number of heads, head dimension, whether GQA/MQA is used, whether gating is present), runtime branching prevents optimal allocation of registers and on-chip memory. A mature approach is to generate a set of “dedicated instances”: named by model identifier and key structural parameters, with variable dimensions fixed as constants at compile time.

    1. // Illustrative compile-time specialization: all structural parameters are constants,
    2. // enabling full unrolling and static scheduling
    3. enum class ModelType { Generic, V41Like };
    4. template <int HEAD_DIM, int NUM_HEADS, bool GQA, ModelType M>
    5. struct FusedAttnKernel {
    6. static_assert(HEAD_DIM == 128, "specialized instance for head_dim=128");
    7. __device__ void operator()(const Tensor& q, const Tensor& k,
    8. const Tensor& v, Tensor& out) {
    9. // norm + rope + attention + cast fused; intermediates stay on-chip
    10. }
    11. };
    12. // Explicit instantiation: one model structure maps to one machine code path,
    13. // with no runtime branching
    14. template struct FusedAttnKernel<128, 32, true, ModelType::V41Like>;

    The accompanying model-type enum tag (for example, ModelType::V41Like) lets the upper-level scheduler directly select the corresponding instance and avoid runtime probing. This combination of “dedicated instances + type tags” essentially trades compile-time complexity for runtime determinism.

    4. Performance Validation: A Reusable Measurement Method

    Deep adaptation must be independently reproducible; otherwise, the numbers are meaningless. A recommended validation process is:

    1. Fix input shapes. Sequence length, batch, and head configuration should all be hard-coded and published. Do not use vague “average workload” definitions.
    2. Separate warmup from steady state. The first several iterations include kernel loading and cache warmup, and must be discarded before timing.
    3. Measure the two stages separately. Time Prefill and Decode independently; mixing them hides memory-access bottlenecks.
    4. Time after synchronization. Under asynchronous execution, synchronization points must be inserted; otherwise, you measure dispatch time rather than execution time.
    1. import time
    2. def bench(fn, warmup=10, iters=50):
    3. for _ in range(warmup):
    4. fn()
    5. synchronize_device()
    6. t0 = time.perf_counter()
    7. for _ in range(iters):
    8. fn()
    9. synchronize_device()
    10. return (time.perf_counter() - t0) / iters

    5. The Overlooked Wall: Memory Bandwidth and Custom High-Bandwidth Memory

    Once Prefill reaches 98.5%, the optimization focus necessarily shifts to Decode and long context, and the ceiling for both is memory bandwidth. One route publicly discussed in the industry is custom high-bandwidth memory: using multi-layer wafer-to-wafer (W2W) hybrid bonding to expand the number of channels to 64 and the data interface width to 4096 bits (the previous mainstream high-bandwidth memory standard was about 1024 bits), achieving up to about 4x bandwidth at the same rate.

    The technical core of hybrid bonding is reducing bond pitch. Its advantages are many bonding points, short interconnect distance, and high bandwidth density. Its costs are also clear: relatively low yield, limited number of stacked layers, and relatively limited per-device capacity, which means more compute chips must be interconnected to reach total capacity. This directly changes the system design paradigm—from “large memory on a single card” to “multi-card high-bandwidth interconnect + topology-aware parallel partitioning.”

    The impact on upper-layer frameworks is concrete:

    • Parallel strategies need to be rebalanced. With higher bandwidth, the communication share of tensor parallelism decreases, and pipeline-parallel bubbles become more worth optimizing.
    • Memory capacity planning should be modeled as “multi-card aggregate”; KV cache partitioning and migration strategies need to be topology-aware.
    • Monitoring and alerting should cover bandwidth and interconnect metrics, not only compute utilization and memory usage.

    6. Engineering Checklist and Boundaries

    • Prioritize operator fusion, especially memory-intensive stages such as norm, positional encoding, and type conversion.
    • Generate compile-time dedicated instances for high-frequency structure combinations to eliminate runtime branches.
    • Use unified benchmark scripts to measure Prefill and Decode separately, and publish all input shapes.
    • Include memory bandwidth and interconnect topology in capacity planning, rather than looking only at single-card specifications.
    • Clearly state metric definitions: peak utilization is a result under specific input shapes and cannot be extrapolated into a general throughput promise.

    When deploying on cloud, these capabilities are usually hosted by container platforms for heterogeneous compute scheduling, object storage for models and operator artifacts, and logging and monitoring for long-running observability. Baidu AI Cloud provides standardized components decoupled from hardware for such general capabilities; specific specifications and billing are subject to the official documentation.

    The conclusion is not complicated: as Prefill approaches hardware peak, the focus of competition shifts from “whether it can run” to “how much more can be saved on memory access and interconnect.” Operator fusion and compile-time specialization address the compute side, while custom high-bandwidth memory and topology-aware parallelism address the data side. Together, they form a more complete domestic compute ecosystem loop.