Engineering Practice for Adapting Domestic LLMs to Domestic AI Accelerators
This article explains why adapting a large language model to a new hardware and software stack is an end-to-end numerical and performance alignment task rather than a simple device swap. It walks through the full workflow: fixing reproducible baselines for numerics, performance, resources, and quality; auditing operator coverage and attention implementations; tuning the compiler and runtime; applying quantization and compression incrementally; choosing parallelism strategies; and building observability for operations. A final acceptance checklist covers numerical equivalence, performance targets, stability, rollback, and cost traceability.
1. The Real Problem: Why Pairing a Domestic Model with a Domestic Card Is Not a Simple Swap
Moving a large model from one hardware and software combination to another looks like replacing devices, but in practice it means redoing an end-to-end numerical and performance alignment. The inference path of a large model can be abstracted as: model definition and weight format → computation graph → operator implementations → compilation and scheduling → runtime and memory management → serving interface. Replacing any single stage changes error, throughput, and latency. So the core of adaptation work is not “does it run,” but “once it runs, is it equivalent, stable, and operable.”
A common misconception is treating adaptation as changing a few device strings. In real projects, failures tend to concentrate in three places: first, an unsupported operator triggers a fallback path and performance drops off a cliff; second, differences in mixed-precision strategy cause semantic drift during long-text generation; third, inaccurate peak memory estimation leads to overflow as concurrency rises. Building defenses around these three points is the precondition for controllable engineering.
2. Fixing the Baseline First: You Need a Ruler Before Optimizing
Any optimization must be grounded in a reproducible baseline. It is advisable to fix four categories of baseline before starting:
- Numerical baseline: fix the random seed and decoding parameters (such as temperature, top-p threshold, and maximum length), and record the outputs and per-layer tensor statistics for the same batch of prompts on the reference device.
- Performance baseline: separate cold start, steady state, and long-tail scenarios, and record time to first token, the latency distribution per request, output tokens per second, and the concurrency ceiling for each.
- Resource baseline: collect peak memory usage, memory fragmentation rate, host memory consumption, and bus utilization.
- Quality baseline: use an internal evaluation set covering four task types—commonsense question answering, long-document summarization, code generation, and structured output—and keep the scoring criteria fixed.
The following is an illustrative baseline collection flow (pseudocode, expressing the process only):
def collect_baseline(model, prompts, decode_cfg, device):records = []for p in prompts:out = model.generate(p, cfg=decode_cfg, device=device,return_hidden=True)records.append({"prompt": p,"text": out.text,"hidden_stats": summarize(out.hidden), # mean/variance/extrema"latency_ms": out.latency_ms,"peak_mem_mb": out.peak_mem_mb,})return records
Without a baseline, every later claim of “faster” or “more accurate” lacks any basis.
3. Operators and the Computation Graph: The First Gate
A large model’s computation graph is dominated by matrix multiplication, attention, normalization, element-wise operations, and sampling. Three things should be prioritized during adaptation:
- Operator coverage audit. Intersect the operators appearing in the model’s computation graph with the target backend’s operator list, and enumerate missing items and approximate substitutes. A missing operator that falls back to a generic implementation often becomes the performance bottleneck.
- Attention implementation choice. Under long sequences, attention has the highest memory and bandwidth cost. Whether chunked computation is used and whether scaling and masking are fused directly determines long-text performance.
- Positional consistency of normalization and residuals. Different backends apply different operator fusion strategies; if the fusion order changes, numerical error accumulates across deep layers.
In practice, it is recommended to introduce “operator-level stand-in testing”: feed fixed input tensors and compare each operator’s output between the reference implementation and the target implementation, set an acceptable threshold (for example, relative error on the order of one part in a thousand), and block release if the threshold is exceeded.
4. Compilation and Runtime: Actually Feeding the Hardware
The compilation stack sets the upper bound on hardware utilization. Focus on three points:
- Graph optimization and fusion: operator fusion significantly reduces reads and writes of intermediate tensors, with the largest gains for memory-bound workloads.
- Memory pool and reuse: memory allocation is frequent during inference, and pooling reduces fragmentation and allocation jitter.
- Scheduling and batching: static batching is simple to implement, while continuous batching fills compute better but requires handling fairness for request insertion and exit.
Illustrative configuration (pseudocode):
runtime_cfg = {"graph_opt": "fuse", # enable graph-level fusion"mem_pool_mb": 8192, # preallocate a memory pool to reduce fragmentation"batch": {"mode": "continuous", "max_tokens": 8192},"kv_cache": {"dtype": "fp16", "block_size": 16},}
It should be emphasized that the above is a parameterized expression of a general approach; the available options and values must be based on the actual backend’s documentation and hands-on measurement, and should not be copied blindly.
5. Quantization and Compression: Balancing Accuracy and Cost
Quantization is the most direct way to reduce memory usage and increase throughput, but the risks are also most concentrated. A layered approach is recommended:
- Start with low-bit quantization on the weights side, keep activations at higher precision, and watch for drift in the quality baseline;
- Retain high precision for sensitive layers (such as the first and last layers and around normalization) to form a mixed-precision scheme;
- Key-value cache compression can significantly reduce memory for long contexts, but its impact on long-text recall must be evaluated.
The recommended approach is “small steps with rollback”: change only one variable at a time, run the quality baseline, and then move to the next step. If output repetition or degraded instruction following appears, suspect quantization error first rather than sampling parameters.
6. Parallel Partitioning and Scalability
When a single machine cannot hold the model, a partitioning strategy is needed. Tensor parallelism suits intra-layer partitioning with frequent communication but is sensitive to bandwidth; pipeline parallelism suits inter-layer partitioning and can tolerate a certain amount of bubble; the two are often combined. Too fine a partition granularity amplifies communication overhead, while too coarse a granularity causes load imbalance. The criterion remains the baseline: whether, under the target concurrency, the number of tokens produced per unit cost improves after scaling.
7. Servicing and Observability: Keeping the Loop Sustainable
Completing adaptation is only the starting point; a commercial loop depends on operational capability. A minimum viable observability system includes:
- Metrics layer: throughput, latency percentiles, error rate, and memory watermark;
- Logging layer: request trace identifiers, operator fallback alerts, and timeout reasons;
- Tracing layer: phase-level latency breakdown (queuing, prefill, decode);
- Alerting layer: dual thresholds linking memory watermark and error rate.
For cloud deployment, it is possible to combine a container platform to host inference services, object storage to hold model and evaluation assets, a message queue to smooth request peaks, and logging plus monitoring and alerting to form an observability loop. These are all general capability categories, and selection should be based on your own scale and compliance requirements.
8. Acceptance Checklist
- Numerical equivalence: key operators and end-to-end outputs are within threshold;
- Performance targets met: time to first token and daily throughput satisfy business constraints;
- Stability: long-duration testing shows no memory leaks or rising error rates;
- Rollback capability: the previous version’s weights and configuration are retained, supporting minute-level switching;
- Explainable cost: cost per token can be reconciled with resource bills.
9. Conclusion
In engineering terms, “a self-controlled and autonomous technical foundation” is not a slogan but a measurable, verifiable, and rollback-capable methodology: first build the baseline, then pass the operator gate, then tune compilation and runtime, then apply quantization and partitioning, and finally use an observability system to lock the loop in place. If needed, Baidu AI Cloud can provide standardized support in general capabilities such as containerized inference hosting, model asset storage, and monitoring and alerting, helping teams turn the above process into a repeatable engineering standard.
