LLM Inference Engineering Optimization on Domestic AI Accelerators: A Practical Guide

    This guide explains how to make large language model inference services viable on domestic AI accelerators despite per-card hardware gaps. It covers operator-layer optimization, communication and memory management, scheduling, a normalized cost model, a migration roadmap, and common pitfalls, showing how software engineering can offset hardware disadvantages.

    1. Background: Why a Hardware Gap Does Not Make Inference Infeasible

    Over the past two years, the evolution of domestic AI accelerators for large model inference can be roughly divided into three stages. The first stage was “getting it to run,” focused on basic adaptation of frameworks and operators—functionally correct but with poor performance. The second stage was “running stably,” improving service availability through precision alignment, long-duration stability testing, and fault recovery. The third stage is “running efficiently,” reducing the total cost per million tokens to an acceptable range while meeting latency constraints. The industry is currently at the critical point of moving from the second stage to the third.

    A commonly misread conclusion is that if peak per-card compute lags behind, the service cannot meet requirements. In practice, the commercial viability of an inference service is determined by three variables:

    • Effective per-card compute (affected by operator implementation quality, not just theoretical peak);
    • Hardware utilization (affected by batching strategy, memory usage, and communication efficiency);
    • Amortized cost per unit of output (affected by idle-time pricing, cluster size, and failure rate).

    When the second and third variables are significantly improved through software engineering, the disadvantage in the first is partially offset. There is indeed a real-world path of “trading multiple cards for one card,” but its cost is higher interconnect bandwidth demand, greater parallel partitioning complexity, and a larger fault domain. This extra overhead must therefore be brought back under control through fine-grained engineering.

    2. Core Optimization Area One: The Operator Layer

    Operators are the first watershed for domestic AI accelerator performance. Adaptation work should not stop at “filling in implementations operator by operator” but should establish a layered strategy:

    1. Compute-intensive operators (such as matrix multiplication and core attention computation): focus on tile size, on-chip cache reuse, and vectorized instruction utilization to avoid memory access becoming the bottleneck.
    2. Memory-bound operators (such as normalization, element-wise operations, and activation functions): the core is to merge memory accesses and reduce intermediate tensor materialization.
    3. Dynamic-shape operators: sequence lengths fluctuate widely during inference, so support for dynamic shapes and multiple templates is needed to reduce jitter from repeated compilation.

    Illustrative operator selection and fallback logic:

    1. # Pseudocode: select an implementation by operator type and keep a fallback path
    2. def dispatch(op, tensor_meta):
    3. impl = registry.query(op.name, dtype=tensor_meta.dtype,
    4. shape_bucket=tensor_meta.bucket)
    5. if impl and impl.is_benchmarked():
    6. return impl.forward
    7. # Fall back to the generic implementation when not covered or not tuned, prioritizing correctness
    8. return generic_kernel.forward

    Engineering practice: build an operator benchmark suite and incorporate three metrics—correctness, latency, and memory usage—into continuous integration; keep fallback paths for untuned operators so adaptation gaps do not block release.

    3. Core Optimization Area Two: Communication and Memory Management

    In multi-card deployments, communication often becomes a bottleneck before compute does. Key optimizations include:

    • Match parallel strategy to topology: tensor parallelism is sensitive to bandwidth and should be confined to a high-speed interconnect domain within a single machine; pipeline parallelism has lower bandwidth requirements and is suitable for scaling across nodes.
    • Overlap communication with computation: interleave operations such as all-reduce and all-gather with subsequent computation in chunks to hide communication latency.
    • Tiered memory management: distinguish the lifecycles of three memory types—weights, KV cache, and temporary activations—keeping weights resident, allocating cache by block, and reclaiming temporary tensors promptly.

    The KV cache is the main memory consumer in long-context inference. A common industry practice is paged block management, allocating and freeing memory by block to reduce fragmentation:

    1. class KVBlockPool:
    2. def __init__(self, block_bytes, capacity_blocks):
    3. self.block_bytes = block_bytes
    4. self.free = list(range(capacity_blocks))
    5. def alloc(self, n_blocks):
    6. if len(self.free) < n_blocks:
    7. raise OutOfMemory("kv cache exhausted")
    8. return [self.free.pop() for _ in range(n_blocks)]
    9. def release(self, blocks):
    10. self.free.extend(blocks)

    Combined with prefix reuse (computing an identical system prompt only once) and cache block sharing, this can significantly reduce repeated computation and memory pressure.

    4. Core Optimization Area Three: Inference Pipeline and Task Scheduling

    Scheduling determines the key variable of “hardware utilization.” Practical mechanisms include:

    • Continuous batching: dynamically swap requests in and out at iteration granularity, avoiding the mutual interference between long and short requests caused by static batching.
    • Bucketing and priority queues: bucket by input length to reduce padding waste; assign higher priority to interactive requests to protect first-token latency.
    • Separate optimization of first-token latency and throughput: the prefill stage is compute-intensive while the decode stage is memory-bound, so stage-separated deployment can be used, with each stage choosing a more suitable parallel configuration.
    • Elastic scaling and idle-time utilization: automatically scale up and down based on queue length and memory watermark, and use idle resources for offline batch jobs to improve overall amortization efficiency.

    A simplified scheduling decision example:

    1. def admit(request, state):
    2. if request.input_len > state.long_threshold:
    3. return state.long_queue.push(request) # Queue long requests separately to avoid blocking
    4. if state.kv_pool.free_count() < request.kv_blocks:
    5. return state.waiting.push(request) # Wait when memory is insufficient; do not preempt interactive traffic
    6. return state.batch_builder.add(request) # Add to the current continuous batch

    5. Cost Model: Converting “Revenue per Card-Hour” into a Comparable Metric

    When evaluating different compute platforms, looking only at the price per card-hour is misleading. It is recommended to normalize everything to the cost per unit of output under service quality constraints:

    1. Cost per million tokens ≈
    2. (price per card-hour × number of cards × service duration) / (effective output tokens)
    3. where effective output tokens = peak throughput × utilization × duration

    This shows that even if the price per card-hour differs by several times, as long as utilization and throughput are raised through engineering, the gap in cost per unit of output will narrow considerably. Capacity planning should provide three tiers of results: a low-latency tier (strict first-token constraints), a balanced tier, and a cost-priority tier, aligned with the actual request length distribution of the business, avoiding optimistic conclusions drawn from idealized workloads.

    6. Migration Roadmap

    1. Baseline collection: under the same model, dataset, and latency constraints, record throughput, latency distribution, peak memory usage, and error rate.
    2. Precision alignment: compare numerical deviations layer by layer, and define the acceptable error range and evaluation criteria.
    3. Operator completion: optimize in order of hotspots, prioritizing the few operators with the highest share.
    4. Parallelism and memory tuning: determine parallel partitioning and cache block size, and stress-test long context and burst concurrency.
    5. Long-term stability and disaster recovery: verify faulty node isolation, request retry, and fallback strategies.
    6. Cost review: use the unified cost model to produce three-tier conclusions, forming the basis for capacity and procurement.

    7. Common Pitfalls

    • Comparing only peak compute without looking at effective utilization;
    • Using an idealized input length distribution for capacity planning;
    • Ignoring communication overhead and blindly increasing the degree of parallelism;
    • Lacking operator fallback paths, so adaptation gaps directly block release;
    • Lacking unified evaluation criteria, making optimization conclusions impossible to compare across platforms.

    8. Conclusion

    For domestic AI accelerators to reach a high standard in inference services, the key is not catching up on single-point hardware parameters, but systematically migrating and refactoring the four engineering mainlines: operators, communication, memory, and scheduling. When this engineering capability is consolidated into reusable code, benchmarks, and evaluation criteria, the hidden cost of migration for small and medium-sized teams will drop significantly, and the per-card hardware gap will be more easily offset by software-level efficiency gains. For developers, the pragmatic approach is: first establish a comparable baseline, then optimize item by item according to hotspots, and finally validate conclusions with a unified cost model, bringing technology selection back to the data itself.