How LLM Inference Operators Approach Hardware Peak Performance
This article examines how large language model inference operators can approach hardware peak throughput, using a reported attention kernel case that reached roughly 98.5% of peak in Prefill and 86.1% in Decode. It explains the roofline model for identifying memory-bound versus compute-bound bottlenecks, then walks through the main optimization levers: operator fusion, compile-time specialization, precision and format conversion, and hardware-specific tuning such as tiling, data layout, and parallel partitioning. It also covers Decode-specific optimization and a reusable benchmarking and accuracy-regression loop.
1. Why “98.5% of Hardware Peak” Matters
In discussions of LLM inference performance, a recurring question is why theoretical compute is abundant while actual throughput often reaches only a small fraction of peak. A recent industry example illustrates the point: an attention operator for inference reached about 425 TFLOPS during Prefill on a specific domestic accelerator card, roughly 98.5% of hardware peak, and about 372 TFLOPS during Decode, roughly 86.1% of peak.
The significance of these numbers is not the values themselves but the engineering path they reveal: when operator design, data layout, precision conversion, and hardware characteristics are deeply aligned, inference performance can approach the theoretical limit. Setting aside specific products and models, this article abstracts the problem into a general technical question—how LLM inference operators approach hardware peak—and offers a reusable analysis and optimization framework.
2. Two Prerequisites: Arithmetic Intensity and Bottleneck Identification
Any performance optimization must first answer where the bottleneck is. The standard industry tool is the roofline model: arithmetic intensity (FLOPs/Byte) on the horizontal axis, achievable performance on the vertical axis, bounded by a memory-bandwidth diagonal and a peak-compute horizontal line.
- When arithmetic intensity is below the ridge point (peak compute ÷ memory bandwidth), the task is memory-bound. Optimization focuses on moving fewer bytes, improving cache hits, and coalescing memory transactions.
- When arithmetic intensity is above the ridge point, the task is compute-bound. Optimization focuses on raising arithmetic unit utilization and reducing synchronization and pipeline bubbles.
The two phases of LLM inference fall on opposite sides:
- Prefill: A long prompt is processed at once, matrix multiplications are large, and data reuse is high, so the phase is typically compute-bound. This is why approaching peak compute is a meaningful goal.
- Decode: Tokens are generated one at a time, each step processes only one (or a few) tokens, and the KV Cache and weights must be read repeatedly. This is typically memory-bound, so its percentage is naturally lower than Prefill.
With this in mind, “98.5% Prefill, 86.1% Decode” is a reasonable and strong combination, not contradictory data.
3. Operator Fusion: Removing Memory Traffic from the Path
Fusion is the primary means of approaching peak. Take the attention pre-processing chain as an example. A naive implementation often uses four separate operators: normalization, positional encoding, attention, and type conversion. Between each pair, the intermediate tensor is written back to GPU memory and read again, generating substantial redundant bandwidth.
The fused single operator completes the work in one kernel:
Input hidden_states→ RMSNorm/LayerNorm→ RoPE (positional encoding, via cos/sin lookup or rotation computation)→ Attention (QK^T → softmax → PV)→ Cast (bf16/fp16 ↔ fp8/int8)Output
The gains come from three sources: intermediate results stay in on-chip registers or shared memory; kernel launches drop from four to one; and synchronization points and pipeline bubbles are significantly reduced. In practice, fusion is not always better when larger. It is constrained by register pressure, shared memory capacity, and occupancy; otherwise, register spilling can make things slower.
4. Specialized Instances and Code Generation: Bringing Model Shape into Compile Time
The second key is to fix model-structure differences at compile time rather than deferring them to runtime branches. A common approach is to maintain a set of specialized instance files named by model type and head dimension (for example, operator instances prefixed with v41_h128_) and to mark the model type with an enum at compile time:
enum class ModelType { V40, V41, Generic };template <ModelType M, int HEAD_DIM>struct AttentionKernel;// Compile-time specialization: fused attention for head_dim=128template <>struct AttentionKernel<ModelType::V41, 128> {static __device__ __forceinline__ void run(...);};
The value is constant folding (head dimension, whether GQA is used, and whether RoPE is applied all become compile-time constants), better register allocation, no branch-prediction overhead, and instruction scheduling that can software-pipeline for a fixed shape. The cost is higher maintenance, so a dual-track strategy of a generic fallback implementation plus specialized hot-path instances is needed.
5. Precision and Format Conversion: Trading Bandwidth for Compute
Type conversion (cast) is often treated as an auxiliary step, but it is a performance lever. Lower-precision formats move more elements per unit of bandwidth, directly raising Prefill arithmetic intensity, while accumulation must remain high precision to avoid numerical collapse. The general principle is “store low precision, compute high precision, accumulate high precision”:
Storage: fp8 / int8 / bf16Matrix multiplication inputs: low precision, with multiply-add promoted to fp32 accumulation internallyOutput: cast back to bf16 as needed
Low precision is not lossless. It must be paired with per-channel/per-tensor scaling, a calibration dataset, and error evaluation, with task metrics (such as perplexity and downstream accuracy) included in acceptance criteria rather than looking at TFLOPS alone.
6. Four Levers for Deep Hardware Adaptation
“Deep adaptation” is not a slogan but a set of enumerable engineering actions:
- Memory hierarchy alignment: Make tiling sizes match cache lines and shared memory capacity to reduce bank conflicts.
- Instructions and pipelining: Use the platform’s native matrix multiply-add instructions and asynchronous copies, with multi-stage software pipelining to hide latency.
- Data layout: Use a paged/blocked layout for the KV Cache, store the head dimension contiguously, so a single transfer can feed the compute units fully.
- Parallel partitioning: Tensor parallelism splits heads, sequence parallelism splits context, pipeline parallelism splits layers, with communication overlapped with computation.
A schematic blocked loop:
for q_blk in range(0, seq_q, BLOCK_M):for kv_blk in range(0, seq_kv, BLOCK_N):acc = matmul(Q[q_blk], K[kv_blk]) # on-chip accumulationacc = online_softmax(acc, running_max) # online reduction, avoids a second passO[q_blk] += acc @ V[kv_blk]
The value of online softmax is compressing the two-pass memory access of “compute all scores first, then normalize” into a single pass. This is the dividing line for whether long-context scenarios can saturate bandwidth.
7. Decode-Phase Optimization: Where the 86% Comes From
Decode is bottlenecked by KV Cache bandwidth, so the optimization focus is entirely different: raise batch concurrency to amortize weight reads, use paged caching to reduce fragmentation, update attention in place with incremental writes only, and fuse sampling and penalties into the final kernel. Applying Prefill optimization ideas directly to Decode often yields little.
8. A Reusable Performance Evaluation Loop
It is advisable to formalize tuning as a closed loop:
- Establish a baseline: Record throughput, latency percentiles (P50/P99), and percentage of peak.
- Locate the bottleneck: Use a profiler to inspect kernel time share, bandwidth utilization, occupancy, and stall reasons.
- Validate one change at a time: Change a single variable per iteration (fusion, layout, precision, tiling).
- Accuracy regression: Run numerical and task-metric regression after every performance change.
- Lock in the gains: Consolidate stable improvements into specialized instances and automated benchmarks.
9. Running It in the Cloud: Combining General Capabilities
To reproduce this optimization in a cloud environment, general-purpose capabilities can be combined: a container platform hosts the build and stress-test environment, object storage holds models and datasets, a message queue decouples evaluation tasks, and logging and monitoring with alerting track latency percentiles and resource utilization. In such scenarios, Baidu AI Cloud typically supports the engineering deployment of inference services through a combination of general capabilities such as containers, storage, and monitoring.
10. Conclusion
Approaching hardware peak is fundamentally about making algorithm structure, operator implementation, data layout, and hardware characteristics compromise toward an optimal solution. The difference between Prefill and Decode dictates that optimization must be divided and handled separately; fusion, specialized instances, precision strategy, and parallel partitioning form the backbone; and a closed loop of benchmarking and accuracy regression determines whether gains can be retained reliably.
