Migrating LLMs to Domestic AI Accelerators: An Engineering Practice Guide

    Migrating large language models to domestic AI accelerators requires more than just getting inference scripts to run. This guide walks through a four-stage engineering workflow—operator coverage assessment, numerical alignment, performance tuning, and production-grade serving with observability—along with practical code patterns and an acceptance checklist to turn a one-off migration effort into a repeatable capability.

    1. Problem Definition: Why “It Runs” ≠ “It Works”

    When a large model needs to be migrated onto a domestic AI accelerator, the most common mistake teams make is setting the goal as “the inference script runs without errors.” In reality, a qualified adaptation must satisfy four sets of constraints:

    • Functional completeness: Every operator in the model has an implementation on the target backend or can be replaced with an equivalent.
    • Numerical fidelity: Outputs match the reference backend within a business-acceptable error bound.
    • Performance targets met: Throughput and latency satisfy the production SLA—not just a single successful forward pass.
    • Engineering maintainability: Images, dependencies, configurations, and monitoring can be reproduced in other environments.

    These four are sequential. Skipping numerical alignment to chase performance often exposes “wrong answer” issues during a canary rollout; skipping engineering work leads to full-blown failures at scale-up due to environment drift.

    2. Stage One: Operator Coverage Audit

    The first step of migration is a static audit, not a test run. Export the model’s computation graph to an intermediate representation, tally the operator type distribution and call frequency, then compute the set difference against the target backend’s operator registry.

    1. # Pseudocode: operator coverage audit
    2. ops = collect_ops(model_graph) # Tally operators and call counts
    3. supported = backend.op_registry() # Operators supported by the target backend
    4. missing = {k: v for k, v in ops.items() if k not in supported}
    5. print("Missing operators:", missing)

    For missing operators, there are typically three paths, in descending priority:

    1. Equivalent replacement: Express the operator as a composition of existing backend operators—e.g., replace a hand-written convolution with matrix multiply-accumulate, or replace certain scan-type operations with cumulative sums.
    2. Custom operators: Only invest in custom development for high-frequency operators that cannot be replaced (such as certain normalization variants or paged-attention variants), and pair them with unit tests and regression cases.
    3. Fallback to a general-purpose compute device: Low-frequency operators can fall back, but you must assess the latency amplification from data round-trips, so a single fallback doesn’t drag down the entire pipeline.

    It’s worth emphasizing that dynamic control flow (conditional branches, variable-length loops) is the most common source of trouble on static-graph backends and should be flagged separately during the audit.

    3. Stage Two: Numerical Alignment Methodology

    Precision issues must be localized layer by layer, and layer-wise comparison is the only reliable approach. Fix the inputs (including extreme values and long-tail samples), then compare layer outputs under identical weights:

    1. def check_layer(layer, x, ref, tgt, atol=1e-3, rtol=1e-3):
    2. y_ref, y_tgt = ref.run(layer, x), tgt.run(layer, x)
    3. diff = (y_ref - y_tgt).abs()
    4. print(layer.name, "max:", diff.max().item(), "mean:", diff.mean().item())
    5. assert diff.max() <= atol + rtol * y_ref.abs().max(), layer.name

    Common sources of error and their remedies:

    • Low-precision accumulation: Reduction errors accumulate over long sequences in half precision—use higher-precision accumulation while keeping storage in low precision.
    • Numerically sensitive operators: Differences in normalization, exponential, and max/min reduction implementations require aligning computation order and epsilon handling.
    • Non-deterministic reductions: Undefined parallel reduction order causes result jitter—use statistical intervals from multiple runs for acceptance, not single-run values.
    • Quantization error: Weight quantization and activation quantization errors must be evaluated separately; decide mixed-precision strategy based on per-layer sensitivity.

    Acceptance criteria should be defined by the business, not engineering intuition. For example, classification tasks can check Top-1 agreement rates, while generation tasks should check the consistency distribution of the first token and long-form outputs, with explicit tolerable deviation boundaries.

    4. Stage Three: Four Levers for Performance Tuning

    Once functionality and precision pass, proceed with performance optimization in the following order—typically the highest return with the lowest risk:

    1. Batch scheduling: Replace static batching with continuous batching to significantly improve accelerator utilization.
    2. Key-value cache management: Paged caching reduces fragmentation; prefix reuse cuts redundant computation.
    3. Operator fusion and memory layout: Merge element-wise operations into adjacent compute kernels to reduce intermediate tensors and memory accesses.
    4. Parallelism strategy: Tensor parallelism within a node, pipeline parallelism across nodes; avoid splitting communication-heavy layers across nodes.

    An illustrative serving configuration (fields are generic semantics, not a product-specific interface):

    1. serving:
    2. dtype: bf16
    3. tensor_parallel: 2
    4. kv_cache: { paging: true, block_size: 16, prefix_reuse: true }
    5. scheduler: { continuous_batching: true, max_num_seqs: 256 }
    6. quantization: { weight: int8, activation: int8, skip_layers: [lm_head] }

    Tuning must close the loop: after every change, rerun precision test cases and load tests, so you don’t end up with “performance up, quality down.”

    5. Stage Four: Serving and Observability

    Adaptation results should be delivered as a standard service. Containerize the runtime and driver dependencies, with image versions mapped one-to-one to model versions for traceability. Store model weights and datasets in object storage, orchestrate elastic scaling through a container platform, and cover four categories of metrics with logging and monitoring: request latency percentiles, throughput, cache hit rate, and device temperature plus memory usage.

    Adopt a canary rollout strategy: small-traffic validation → dual-run comparison against the reference backend → full rollout. Dual-run comparison is the most effective way to surface long-tail precision issues.

    6. Acceptance Checklist

    • All missing operators are closed or have a documented fallback plan;
    • Layered precision reports and end-to-end business metrics both pass;
    • Latency percentiles and throughput at target concurrency meet the SLA;
    • Sustained load testing over several hours shows no memory leaks or performance degradation;
    • Images, configurations, and rollback plans are in place, and monitoring alerts are active.

    7. Conclusion

    Adapting large models to domestic accelerators is, at its core, a test of heterogeneous computing engineering capability. By breaking the process into four stages—audit, alignment, tuning, and delivery—and constraining each stage with quantifiable standards, migration shifts from a “one-time heroic effort” into a “repeatable capability.” This is also the direction Baidu AI Cloud continues to invest in for heterogeneous compute scheduling and model serving: letting hardware choice be driven by business needs rather than ecosystem lock-in.