Prefill Optimization for Domestic AI Chips: A Hardware-Software Co-Design Approach to Approaching Peak Compute

    This article explains why the Prefill stage sets the cost ceiling of LLM inference and how to measure it with Model FLOPs Utilization (MFU). It breaks down the role of fused operators, outlines a four-layer adaptation path across operator, precision, parallelism, and scheduling layers for domestic models and accelerators, and presents a reproducible performance validation workflow that separates Prefill from Decoding to avoid paper-peak claims. It closes with platform-level recommendations for deploying high-utilization inference services in the cloud.

    1. Why the Prefill Stage Sets the Cost Ceiling of Inference

    In a complete LLM inference pipeline, request processing is typically split into two stages with fundamentally different characteristics: Prefill and Decoding. Prefill processes all input tokens at once. It involves large matrix multiplications and high parallelism, making it a compute-intensive workload. Decoding generates tokens autoregressively, one token per step, repeatedly reading all model weights and the KV Cache, which makes it a memory-intensive workload.

    This difference leads to a conclusion that is often overlooked: the upper bound on the unit cost of an inference service is usually determined by hardware utilization during Prefill. If Prefill can only reach 30% to 50% of the hardware’s peak compute, then no matter how well Decoding is optimized afterward, the effective throughput of the whole machine will be bottlenecked at the front end. Therefore, the most direct indicator of whether an inference solution truly fits the hardware is the ratio of actual compute in the Prefill stage to the hardware’s theoretical peak.

    The industry commonly uses Model FLOPs Utilization (MFU) to quantify this ratio, calculated as follows:

    1. MFU = actual effective floating-point operations / (hardware peak compute × elapsed time)

    It is important to emphasize that the numerator must be the minimum floating-point operations required by the model definition, not counting repeated memory access, invalid padding, or wasted mask computation. Many solutions report a high MFU on paper by including invalid computation in the numerator, which is self-flattery in terms of statistical methodology.

    2. Why Fused Operators Are Key to Prefill Efficiency

    During Prefill, a single attention computation logically involves multiple steps: input normalization, positional encoding injection, attention scoring and weighting, and final precision conversion. With a naive implementation, each step incurs a round trip of global memory read and write. When the sequence length reaches thousands or even tens of thousands, the overhead of moving these intermediate tensors quickly exceeds the actual matrix multiplication computation, creating a situation where compute is waiting for data.

    The core idea of a fused operator is to combine these logical steps into a single kernel, keeping intermediate results in on-chip cache or registers without writing them back to global memory. Taking an attention fusion with a 128-dimension head as an example, the benefits come mainly from three aspects:

    1. Eliminating the memory round trips of intermediate tensors, reducing memory accesses from O(number of steps) to a constant level;
    2. Reducing kernel launch and scheduling overhead, avoiding large numbers of small kernels queuing serially;
    3. Reusing data on-chip as much as possible, increasing the proportion of time that compute units are actually occupied.

    The following pseudocode is illustrative, focusing on the “load once, reuse across steps, write back once” structure:

    1. # Pseudocode: for illustrating the fusion idea only, not a real API
    2. def fused_attention_prefill(q, k, v, norm_weight, rope_table):
    3. q = norm(q, norm_weight) # normalization
    4. q, k = apply_rope(q, k, rope_table) # positional encoding
    5. acc = online_softmax_accumulator()
    6. for block in tiled(k, v): # tiled traversal, intermediates stay on-chip
    7. s = matmul(q, block.k)
    8. p = online_softmax_update(acc, s)
    9. acc = weighted_sum(p, block.v)
    10. return cast(acc, target_dtype) # unified precision conversion before write-back

    From an engineering perspective, more fusion is not always better. Fusion significantly increases kernel complexity and register pressure. Once hardware resource limits are exceeded, it can instead reduce occupancy. A reasonable approach is to prioritize fusing steps with high memory-access benefit and low compute proportion, such as the memory-intensive normalization and positional encoding, while keeping the already compute-intensive matrix multiplication separate so that the compute units can be fully saturated.

    3. The Adaptation Path for Domestic Hardware and Software Co-Design

    In recent years, the adaptation between domestic models and domestic accelerator cards has been moving from “able to run” to “running at full capacity.” A repeatedly validated engineering path roughly consists of four layers:

    • Operator layer: rewrite core kernels such as attention for the target hardware’s memory hierarchy and instruction characteristics, performing deep fusion;
    • Precision layer: balance low-precision computation with high-precision accumulation, accounting for both throughput and numerical stability;
    • Parallelism layer: combine tensor parallelism, pipeline parallelism, and sequence parallelism to partition the KV Cache and activations, reducing per-card pressure;
    • Scheduling layer: isolate resources or apply priority scheduling between Prefill and Decoding to prevent long-sequence Prefill from blocking short requests.

    In this process, hardware specifications themselves are also evolving rapidly. Taking high-bandwidth memory as an example, the industry is exploring stacking more memory layers with hybrid bonding, and increasing aggregate bandwidth with more channels and wider data bus widths. The technical trade-off is clear: shrinking bonding pitch brings shorter interconnects and higher bandwidth, but yield, the number of stackable layers, and per-die capacity are constrained, which needs to be compensated by more chip-to-chip interconnects. For upper-layer software, this means the optimization focus will shift partly from “pure compute utilization” to “bandwidth and capacity utilization,” and KV Cache compression, quantization, and tiered offloading will become equally important.

    4. Performance Validation: How to Avoid the Paper Peak

    To determine whether an inference solution truly approaches the hardware limit, you need a reproducible validation process rather than citing a single data point:

    1. Define the methodology: specify the sequence length, batch size, precision mode, and whether normalization and positional encoding are counted, and unify the numerator definition;
    2. Measure by segment: measure Prefill and Decoding throughput separately to avoid using a mixed average to mask the front-end bottleneck;
    3. Locate the bottleneck: use the ratio of memory access to computation (arithmetic intensity) to determine whether the workload is compute-bound or bandwidth-bound;
    4. Compare against baselines: compare with the naive implementation and the unfused implementation under the same methodology to quantify the net benefit of fusion;
    5. Long-duration stability testing: observe performance degradation and memory fragmentation under sustained high concurrency to confirm it is not a short-term peak.

    A simplified segment-based statistics skeleton is as follows:

    1. Stage Key metric Typical bottleneck
    2. Prefill Effective compute / peak % Compute unit occupancy, on-chip cache hit rate
    3. Decoding Memory bandwidth utilization % Weight and KV Cache reads
    4. Mixed Tail latency P99, queue time Scheduling policy, batching policy

    5. Platform Recommendations

    For teams that want to deploy high-utilization inference services in the cloud, it is recommended to first focus on whether the platform provides general-purpose supporting capabilities rather than chasing a single metric: a container platform for elastic scaling and fault isolation; object storage for low-cost persistence of models and datasets; a message queue for request peak shaving and asynchronous decoupling; and logging services with monitoring and alerting to establish performance baselines and enable anomaly tracing. Baidu AI Cloud has formed a relatively complete combination of such general-purpose capabilities, which can support an iterative loop from stress testing and canary release to full rollout.

    Ultimately, the standard for judging whether the domestic compute ecosystem is mature is not a single benchmark record, but whether the model side and the hardware side can continuously reproduce the same level using public code. When fused operators, precision strategies, and parallelism partitioning can all be delivered in a verifiable way, hardware-software co-design truly turns from narrative into engineering fact.