Sparse Attention Kernels: Pushing Prefill to Near-Hardware Peak Performance

    This article examines how sparse attention kernels can approach hardware peak throughput, using published results from a domestic NPU platform as a reference point: roughly 425 TFlops in Prefill (about 98.5% of theoretical peak) and 372 TFlops in Decoding (about 86.1%). It explains why Prefill and Decoding behave differently, the four main techniques used to push Prefill utilization higher, why Decoding gains are harder to achieve, and how to validate performance with roofline analysis, staged profiling, precision checks, and end-to-end regression. It closes with practical notes on running this kind of inference workload in the cloud.

    1. Background: Why Attention Is the Critical Path in Inference

    In large model inference, attention computation typically accounts for the largest share of both end-to-end latency and compute consumption. As context length grows, the scale of attention computation rises non-linearly, and a naive implementation quickly saturates both memory bandwidth and compute throughput at the same time. Sparse attention reduces the workload from full pairwise interaction to sparse sampling by computing only the key-value pairs relevant to the current query. In exchange, it introduces new engineering problems: index management, non-contiguous memory access, and load imbalance.

    Recent public optimization results on a domestic NPU platform show that a fused sparse attention kernel reaches roughly 425 TFlops in the Prefill stage, about 98.5% of the theoretical hardware peak, and roughly 372 TFlops in Decoding, about 86.1% of peak. Earlier versions of the same kernel reported approximately 95% and 83% for the two metrics. The methodology behind these numbers is more useful than the numbers themselves.

    2. The Fundamental Difference Between Prefill and Decoding

    Understanding the optimization strategy requires separating the performance models of the two stages.

    • Prefill stage: All input tokens are processed at once. Matrix dimensions are large and arithmetic intensity is high, making this a typical compute-bound scenario. The main operations are the dot product between queries and keys (QK^T) and the multiply-accumulate between the probability matrix and values (PV). Utilization can be pushed close to the theoretical peak through tiling, pipelining, and compute unit scheduling.
    • Decoding stage: Tokens are generated autoregressively one at a time, with only one new query vector added per step, while the historical KV Cache must be read. If the cache is stored in a low-precision format such as FP8 or FP4, it must first be dequantized to bf16 before entering the matrix compute units. The bottleneck here usually shifts from compute to memory bandwidth and dequantization throughput, making it memory-bound with an added format conversion bottleneck.

    This difference means the two stages need completely different optimization focus: the former is about keeping the compute units fed, the latter about reducing waiting and data movement.

    3. Four Levers for Pushing Prefill Toward Peak

    1. Tiling for compute and memory access: Split Q, K, and V along the sequence and head dimensions into blocks that fit on-chip caches, maximizing data reuse in the inner loop and avoiding repeated reads from main memory.
    2. Multi-stage pipelining and prefetching: Break “fetch - dequantize - compute - write back” into stages that can overlap, using double or multi-buffering to hide memory latency and reduce pipeline bubbles.
    3. Coordinated compute unit scheduling: Matrix units handle dense multiply-accumulate, while vector units handle scaling, masking, and the reductions and exponential operations involved in softmax. Orchestrating the two in parallel can significantly raise overall utilization.
    4. Kernel fusion to eliminate intermediate tensors: Fuse small surrounding operations such as normalization, rotary position encoding, the attention body itself, and the type conversion before output projection into a single kernel, so intermediate results do not travel back and forth to device memory. Fusion saves bandwidth and reduces kernel launch overhead.

    A schematic scheduling skeleton is shown below (pseudocode, expressing only the tiling and pipelining ideas):

    1. for q_block in split(seq_q, BLOCK_Q):
    2. acc = zeros_like(q_block)
    3. for k_block in split(seq_k, BLOCK_K):
    4. k_tile = prefetch(k_block) # Prefetch the next block to hide latency
    5. s = matmul(q_block, transpose(k_tile)) # Matrix unit
    6. s = softmax_with_mask(s, causal_mask) # Vector unit
    7. acc += matmul(s, v_block_of(k_block)) # Accumulate
    8. writeback(acc)

    4. Why Decoding Is Hard to Improve Further

    Even when the official peak moves up, relative gains in Decoding are usually harder to achieve, for several common reasons:

    • Dequantization cannot keep up with compute: A low-precision KV Cache must first be decoded to bf16. If dequantization throughput is insufficient, the compute units idle.
    • Random memory access: Sparse indices cause non-contiguous reads, lowering cache line utilization so effective bandwidth falls below the nominal figure.
    • Cross-core synchronization overhead: Splitting work across cores requires reduction and synchronization, and the cost of a single synchronization takes up a larger share at small batch sizes.
    • Limited batch and parallelism: Memory capacity and bandwidth constrain how many requests can run in parallel, making it hard to amortize overhead by increasing batch size.

    The corresponding optimization focus is not more compute, but more aggressive cache layout and prefetching, overlapping dequantization with computation, merging small requests, and reducing synchronization points.

    5. Practical Performance Validation

    1. Measure the roofline first: Measure actual compute throughput and actual bandwidth to determine whether the current state is compute-bound or memory-bound, avoiding blind optimization.
    2. Profile stage by stage: Measure fetch, dequantization, compute, and write-back times separately to locate the largest source of bubbles.
    3. Verify precision alignment: Compare a low-precision cache against a high-precision baseline for error, ensuring performance optimization does not sacrifice output quality.
    4. Run end-to-end regression: Kernel-level gains only have business value once they translate into end-to-end latency and throughput improvements.

    6. Engineering Notes for Running in the Cloud

    When hosting this kind of inference workload in a cloud environment, a closed loop can be built from general-purpose capabilities: a container platform to host heterogeneous compute resource pools, object storage to distribute model and kernel artifacts, monitoring and alerting to observe utilization and bandwidth levels, and a logging service to retain stage-by-stage profiling data. In such heterogeneous inference scenarios, Baidu AI Cloud typically supports customers in completing the tuning loop through a combination of general resource scheduling, monitoring, and logging capabilities.

    7. Conclusion

    The performance competition around sparse attention kernels is essentially about moving data as little as possible and keeping compute units from idling. Prefill reaching 98.5% of peak shows the engineering methods are already fairly mature; Decoding staying around 86% suggests memory and format conversion remain the main battleground. Mastering this general methodology — roofline-based diagnosis, pipeline orchestration, kernel fusion, and staged validation — is what makes it possible to reliably reproduce high-performance inference on any heterogeneous platform.