Adapting Large Model Operator Libraries to New Compute Architectures: Inference Optimization in Practice
Porting large language models to new compute architectures—such as domestic accelerators or in-house inference chips—poses real engineering challenges, since upstream model implementations are deeply tied to specific hardware ecosystems. This article walks through a three-layer migration approach covering the model structure layer, the compute path layer, and the runtime layer. Using sparse attention (DSA) as a concrete example, it explains how to adapt index selection operators, redesign KV cache layouts, and separately optimize the prefill and decode stages. It also shares practical lessons on operator library integration, DSL-based kernel development, and compiler-driven graph optimization for building efficient inference services on new hardware.
Adapting Large Model Operator Libraries to New Compute Architectures: Inference Optimization in Practice
1. Background: The Real Challenges of LLM Inference Migration
As large language models keep growing in parameter scale, the cost and latency pressure on inference services has become increasingly acute. When an organization needs to deploy mainstream open-source models on a new compute architecture—such as a domestic accelerator card or an in-house inference chip—it typically runs into a common problem: upstream community model implementations are deeply bound to a particular hardware ecosystem. Their operators, memory layouts, and scheduling strategies are all designed around a specific platform, making direct migration nearly impossible.
Migration work typically involves three layers. The first is the model structure layer: taking over the upstream model implementation code while ensuring that the network topology, weight loading logic, and numerical semantics remain consistent. The second is the compute path layer: replacing key operators such as matrix multiplication, attention, and normalization with high-performance implementations tailored to the new architecture. The third is the runtime layer: solving system-level problems such as memory management, batching and scheduling, and KV cache allocation.
In practice, completing these three layers of migration relies on a set of complementary software stack components: a foundational operator library for the new architecture, an operator development framework based on a general-purpose GPU programming language, a domain-specific language (DSL) for tiled computation, and a model compiler responsible for graph-level optimization and code generation. Together, these four components form a complete path from upper-layer models down to hardware instructions. The rest of this article uses the integration of a sparse attention model as an example to explain the engineering methods for each stage.
2. Overall Integration Architecture: From Upstream Adoption to Operator Deployment
2.1 Adopting Upstream Model Implementations
The first step of migration is not rewriting, but adoption. The sensible approach is to keep the upstream model definitions and weight formats unchanged in a branch of the inference framework, and only abstract the hardware-dependent compute calls behind pluggable interfaces. This offers two benefits:
- Maintainability: when upstream models iterate, you only need to merge diffs, avoiding large-scale conflicts;
- Verifiability: you can first run the reference implementation on the original hardware and use its outputs as the accuracy baseline for the new architecture.
2.2 Identifying and Replacing Critical Compute Paths
Not every operator needs immediate optimization. From an engineering standpoint, you should first run profiling to identify the compute paths with the highest time share—such as attention computation and large-dimension matrix multiplication—and prioritize replacing them with optimized implementations from the high-performance operator library. Long-tail operators can be quickly filled in via the general-purpose operator development framework, with correctness taking priority.
The compiler plays the “last mile” role: it compiles the framework-side computation graph into executable code for the target architecture, and performs graph-level optimizations such as operator fusion and memory planning. Ultimately, community model code can serve inference requests on the new architecture’s accelerator cards.
3. Deep Adaptation of Sparse Attention (DSA)
Sparse attention is a key technique for reducing inference overhead in current long-context models. Its core idea: instead of computing attention between each query token and all historical tokens, an index selection mechanism first filters out the top-k most important key-value pairs, and attention is then computed only over the selected entries. This mechanism imposes three adaptation requirements on the software stack.
3.1 Adapting the Index Selection Operator
The index selection stage is essentially a “scoring + top-k filtering” process. Key adaptation points include:
- Efficient scoring computation: the lightweight scoring between queries and keys is usually a small-dimension matrix operation, requiring specialized tiling strategies to avoid underutilizing the hardware;
- Top-k selection: you can reuse existing sorting/selection primitives in the operator library, or quickly implement custom kernels via the general-purpose operator framework;
- Variable-length handling within a batch: different sequences may select different numbers of indices, so kernel design must support irregular index tensors.
3.2 Redesigning the KV Cache Layout
Sparse attention accesses the KV cache in a non-contiguous, index-based gather pattern, which is fundamentally different from the sequential access of dense attention. If the original contiguous cache layout is kept, the gather operation becomes a bottleneck. Common optimization techniques include:
- Adopting a paged KV cache, where fixed-size pages are the unit of allocation. Index selection directly outputs page numbers and intra-page offsets, converting the gather into page-level reads and improving memory access locality;
- Pre-aggregating copies of the selected tokens’ K/V so that the attention kernel reads them in contiguous blocks, trading a small amount of memory for compute continuity;
- Placing cache metadata (page tables, sequence lengths) in a storage tier with lower memory access latency to reduce indirect addressing overhead inside kernels.
3.3 Differentiated Handling of Prefill and Decode Paths
The two stages of inference have markedly different operator requirements and must be adapted separately:
The prefill stage is compute-intensive. Input sequences can reach tens of thousands of tokens, and sparse selection operates over the full historical context. The priorities in this stage are: highly parallelizing the scoring computation for index selection, enabling attention kernels to support large-batch, long-sequence tiled computation, and using operator fusion to reduce the memory footprint of intermediate tensors.
The decode stage is memory-bandwidth-intensive. Each step generates only one token, so the amount of KV cache read far exceeds the amount of computation, making memory bandwidth the bottleneck. The priorities here are: fusing index selection, KV gather, and attention computation into a single kernel as much as possible to avoid multiple round trips to memory; and using smaller thread blocks with higher occupancy configurations to saturate bandwidth even at small batch sizes.
A typical fused decode kernel in pseudocode looks like this:
def fused_sparse_attention_decode(q, kv_cache, page_table, scores):# 1. Lightweight scoring: dot product of q with down-projected candidate keyssel_scores = light_score(q, kv_cache.keys_down_proj)# 2. Top-k index selectiontopk_idx = top_k(sel_scores, k=SPARSE_TOPK)# 3. Gather selected K/V by page tablek_sel = gather_pages(kv_cache.key, page_table, topk_idx)v_sel = gather_pages(kv_cache.value, page_table, topk_idx)# 4. Standard attention over the selected entriesreturn softmax(q @ k_sel.T / sqrt(d)) @ v_sel
4. Assembling the Complete Execution Pipeline
Sparse attention does not exist in isolation; it must combine with other mechanisms in the model to form a complete execution pipeline:
- Linear attention state management: some new-architecture models mix linear attention (which maintains a fixed-size recurrent state) with sparse full attention. The runtime must manage separate state buffers for the two mechanisms and ensure consistent cross-step state reads and writes;
- Cross-layer residual connections: some architectures introduce additional residual pathways between layers. During adaptation, you need to confirm that the operator library’s residual addition and normalization implementations match the target numerical precision (such as BF16 accumulation strategies) to avoid precision drift;
- Multimodal visual attention: visual encoders typically still use dense attention, whose operators can directly reuse the dense implementations in the operator library—but pay attention to the batching and scheduling logic that stitches visual and text portions together.
Once the pipeline is assembled, end-to-end validation is mandatory. On one hand, compare against the reference implementation to verify that each operator’s output error stays within tolerance; on the other hand, run load tests under real request traffic to confirm that throughput, time-to-first-token, and per-token latency meet service targets.
5. Engineering Recommendations and Summary
Looking back at the entire migration process, several general lessons emerge:
- Adopt rather than rewrite: maximize reuse of upstream model code and confine changes to the hardware-related layers;
- Correctness first, performance second: use the DSL and general-purpose frameworks to quickly make all operators functional, then deeply optimize the hot paths;
- Design sparse operators around memory access: the benefit of sparsification depends on gather efficiency, so the KV cache layout should be co-designed with the indexing mechanism;
- Tune prefill and decode separately: the two stages have different bottlenecks, so kernel fusion strategies and parallelism configurations should differ accordingly;
- Build a regression-ready validation system: maintain both accuracy baselines and performance baselines to enable fast re-adaptation after upstream iterations.
Migrating large models to new compute architectures is, at its core, a “translation” effort between model semantics and hardware capabilities. Only with a high-performance operator library as the foundation, the compiler and DSL as the bridge, and model features such as sparsification as the entry point, can you achieve inference on new architectures that is both correct and fast—ultimately supporting stable and efficient inference services.
