Accelerating Large Language Models with Domestic AI Chips: A Practical Guide to Model-Hardware Co-Optimization
This article explains why model-hardware co-optimization has become the key to compute efficiency for large language models, and how to apply it in practice. It covers the distinct workloads of the prefill and decode stages, the three layers for approaching hardware peak performance, and the role of fused operators such as attention kernels in reducing memory traffic. It also discusses matrix multiplication and collective communication optimization, a layered performance evaluation framework with simple utilization and per-token cost formulas, and practical deployment recommendations centered on a measure-locate-optimize-regress loop. The content is intended for engineers optimizing large model training and inference on constrained hardware.
1. Why Model-Hardware Co-Optimization Is the Key to Compute Efficiency
Over the past few years, gains in large model capability have relied heavily on expanding parameter counts and training data volume, while compute supply has not grown at the same pace. Once per-card compute, memory bandwidth, and inter-card interconnect bandwidth all become hard constraints, simply adding more cards yields rapidly diminishing returns. The real efficiency gains are shifting away from optimizing the model alone or upgrading the hardware alone, toward systematic co-development across model structure, compiler optimization, operator implementation, and hardware features.
Model-hardware co-optimization refers to joint optimization across model structure design, operator implementation, compilation and scheduling, and hardware microarchitecture. Its core premise is that hardware peak performance can never be fully utilized by a generic implementation automatically. Only when the algorithm implementation fully understands the memory hierarchy, the ratio of compute units, and the interconnect topology can actual throughput approach the theoretical upper limit.
1.1 The Two Inference Stages Have Completely Different Workloads
Large model inference is typically split into two stages:
- Prefill: processes the entire input at once. It is compute-intensive, with large matrix sizes and high arithmetic intensity, and its main pressure comes from the combined demand on compute and memory bandwidth.
- Decode: generates output autoregressively token by token, processing only one token per step. It is memory-access-intensive, and its main pressure comes from memory bandwidth and scheduling overhead.
Therefore, applying the same optimization strategy to both stages inevitably leads to one stage being saturated while the other sits idle. The more common engineering practice is to set optimization goals per stage: Prefill targets compute utilization, while Decode targets bandwidth utilization and batching efficiency.
1.2 Three Layers for Approaching Hardware Peak Performance
- Operator layer: reduce unnecessary memory round trips and increase compute unit occupancy.
- Framework layer: orchestrate the computation graph sensibly and reduce synchronization points and host-side scheduling overhead.
- System layer: overlap compute, communication, and storage to avoid serial waiting.
2. Fused Operators: Making Memory Access the Primary Optimization Target
The attention mechanism is the most concentrated source of inference overhead. Take common multi-head attention as an example: a naive implementation repeatedly reads and writes intermediate results to memory, causing bandwidth to be consumed by large amounts of ineffective traffic. The idea behind fused operators is to combine multiple steps into a single kernel so that intermediate results stay in on-chip cache as much as possible.
The following illustrative pseudocode only expresses the general idea of “tiling + online normalization + completion in a single kernel”:
# Pseudocode: tiled attention computation, intermediates never written back to memoryfor q_block in split(queries, BLOCK_M):acc = zeros_like(q_block) # on-chip accumulatorm_prev = -inf # running maximumfor kv_block in split(keys_values, BLOCK_N):s = q_block @ kv_block.T * scalem_new = max(m_prev, rowmax(s))p = exp(s - m_new) # online normalizationacc = acc * exp(m_prev - m_new) + p @ kv_block.Vm_prev = m_newout[q_block] = acc / rowsum(acc)
The benefits of this approach come from three places: intermediate matrices are not written back to memory; the number of memory accesses drops from being related to the square of the sequence length to linear tiling; and the on-chip accumulator has a high reuse rate. In engineering practice, the following details also need to be handled:
- Match tile sizes to on-chip cache capacity: too large causes overflow, too small leaves compute units idle.
- Data type strategy: use high precision for accumulation and low precision for storage, balancing stability and bandwidth.
- Pad or trim non-aligned dimensions to avoid a sharp drop in efficiency for tail blocks.
- Skip blocks that are fully masked by the causal mask to avoid computing them.
3. General Matrix Multiplication and Collective Communication: Approaching Bandwidth and Interconnect Limits
Matrix multiplication is the main consumer of compute, and the key to optimizing it lies in the memory hierarchy and pipelining: multi-level tiling, data prefetching, register-level reuse, and overlapping asynchronous copies with computation. When evaluating it, do not look only at the time of a single operator; look at its share of the whole network and whether it becomes a serial bottleneck.
Collective communication (such as all-reduce, all-gather, and reduce-scatter) is equally critical in distributed training and parallel inference. Common optimization directions include:
- Overlapping communication with computation by splitting the transfer of gradients or activations into small pipelined chunks.
- Topology-aware communication ordering to reduce cross-node hops.
- Bucketing and fusing small messages to lower launch overhead.
- Precision and compression strategies to reduce transfer volume within acceptable error bounds.
It is worth emphasizing that any conclusion about “approaching the limit” must be tied to a specific test configuration: sequence length, batch size, parallelism degree, precision mode, and interconnect method can all significantly change results. Throughput numbers detached from their configuration are not comparable, which is why performance reports should always include an environment description.
4. Performance Evaluation: How to Tell Whether an Optimization Actually Works
It is recommended to build a layered evaluation system and avoid looking at a single metric:
- Operator level: single-operator throughput, memory read/write volume, and compute unit occupancy.
- Model level: end-to-end latency, time to first token, time per token, and the throughput-concurrency curve.
- System level: speedup, scaling efficiency, failure recovery time, and cost per token.
A simplified way to estimate utilization:
Compute utilization ≈ measured throughput / theoretical peak throughputBandwidth utilization ≈ measured effective memory access volume / theoretical peak bandwidth
If compute utilization is high but bandwidth utilization is low, the bottleneck lies in scheduling and parallelism; otherwise, prioritize operator fusion and memory access compression. The cost per token can be approximated as:
Cost per token ≈ (price per card-hour × number of cards × elapsed time) / total tokens generated
This formula explains why improvements in operator efficiency translate directly into cost reductions: with the denominator unchanged, a drop in elapsed time means a drop in cost.
5. Practical Recommendations
- Measure before optimizing, and establish a reproducible benchmark environment with a fixed dataset.
- Set goals per stage, tuning Prefill and Decode separately.
- Prioritize the hottest operators with the largest share, and avoid premature optimization.
- Overlap communication with computation and reduce synchronization points.
- Make explicit trade-offs among precision, stability, and throughput, and keep a fallback path.
- Combine general cloud capabilities such as elastic container platforms, object storage, message queues, logging services, and monitoring and alerting to build an observable, elastically scalable training and inference pipeline.
Overall, the value of hardware-software co-optimization lies not in any single-point number, but in forming a closed loop of “measure - locate - optimize - regress.” Only when the model implementation continuously fits hardware characteristics will the utilization of compute infrastructure steadily improve and inference costs fall accordingly, providing sustainable support for larger-scale training and inference.
