Large Model Serving on Domestic AI Accelerator Clusters: Implementation Practices
This article covers the practical challenges of running large model inference in production on domestic AI accelerator clusters. It describes a five-layer serving architecture, a three-level approach to verifying correctness after hardware migration, and performance techniques including continuous batching, KV cache management, and parallelism strategies. It also addresses traffic governance, observability, fault handling, and a pre-launch checklist.
1. Background and Problem Definition
After large model services move from experimental environments to production, traffic volume and stability requirements rise at the same time. A model that performs well in offline evaluation may run into trouble once it faces sustained high concurrency, inputs and outputs of varying lengths, and strict latency constraints. Resource utilization, queuing behavior, and fault recovery then become the main bottlenecks.
Serving on domestic AI accelerator clusters raises three additional considerations. First, the hardware architecture differs from that of common general-purpose accelerator ecosystems, so operator coverage and compilation optimization must be verified separately. Second, interconnect bandwidth, memory capacity, and scheduling granularity within the cluster directly affect the choice of parallelism strategy. Third, supply chain diversification and data compliance requirements push companies to build inference infrastructure that can be replaced and migrated.
The core question this article addresses is how to keep model outputs correct, responses timely, and resource use controllable on heterogeneous compute, while keeping the service available during traffic fluctuations.
2. Overall Architecture
A production-ready inference service typically consists of five layers:
Client│Access gateway (authentication, rate limiting, routing, auditing)│Scheduling layer (queue management, priority, batch assembly, instance selection)│Inference execution layer (model instances, KV cache management, parallel partitioning)│Compute resource layer (domestic accelerator card cluster, high-speed interconnect, local storage)│Cross-cutting support: monitoring and alerting, log collection, configuration release, capacity planning
The access gateway verifies identity, checks quotas, and performs content safety review at the entry point. This keeps invalid requests from consuming compute. The scheduling layer decides when requests join a batch and which instance they go to, making it a key factor in performance. The inference execution layer performs the actual computation and manages intermediate state in device memory. The compute resource layer exposes a unified device abstraction to the layers above it, hiding differences between devices.
Layered design lets each layer be replaced and load-tested independently. When compute supply or driver versions change, only the execution and resource layers need to be revalidated. The gateway and business interfaces can remain stable.
3. Operator Adaptation and Correctness Verification
After migrating to new hardware, first confirm that computation results are correct. Three types of verification are recommended:
- Operator-level verification: For each key operator, generate inputs with a fixed random seed and compare the error between the reference implementation and the target implementation.
- Model-level verification: On representative datasets, compare output distributions, key evaluation metrics, and text differences on typical samples.
- End-to-end verification: Replay real requests and check whether format constraints, stop conditions, and structured outputs remain stable.
Error judgment should consider both relative error and statistical metrics, not individual samples alone. The following is a schematic code for operator error checking:
import numpy as npdef check_operator(ref_fn, test_fn, shape, dtype="float16",rtol=1e-3, atol=1e-3, trials=20, seed=0):rng = np.random.default_rng(seed)failures = []for i in range(trials):x = rng.standard_normal(shape).astype(dtype)ref = ref_fn(x.astype("float32"))out = test_fn(x).astype("float32")max_err = float(np.max(np.abs(ref - out)))if not np.allclose(ref, out, rtol=rtol, atol=atol):failures.append((i, max_err))return {"passed": len(failures) == 0, "failures": failures}
In this code, test_fn points to the implementation on the target hardware, and ref_fn is the baseline implementation. Failed samples should record the random seed and the maximum error to make reproduction and diagnosis easier.
4. Inference Performance Optimization
Performance optimization centers on three goals: improving device utilization, reducing time to first token, and controlling the cost per unit of output.
4.1 Continuous Batching
Static batching requires all requests in a batch to start and finish together. When short and long requests are mixed, long requests slow down short ones, and devices sit idle while waiting. Continuous batching allows requests to join or leave a batch at any point during generation, which reduces idle time. Implementation requires attention to two points: the upper limit on total context length within a batch, and the impact on the latency of existing requests when new requests are inserted.
4.2 KV Cache Management
The KV cache uses more device memory than any other component in long-context inference. A sound approach allocates the cache in blocks, rather than reserving space in advance for the longest possible sequence. For requests that share the same prefix, previously computed prefix cache can be reused. Cache eviction should consider both request priority and recent access time.
4.3 Quantization and Parallel Partitioning
Quantization reduces memory footprint and bandwidth pressure, but it must pass the correctness verification described above before going live. For models that exceed the capacity of a single card, tensor parallelism splits the computation of a single layer across multiple cards. Pipeline parallelism assigns different layers of the model to different devices. The finer the partitioning, the higher the communication overhead between devices. For this reason, tensor parallelism should preferably run within the same high-speed interconnect domain.
4.4 Batch Assembly Example
The code below shows batch assembly logic based on a token budget. It can serve as a reference for scheduler design:
from dataclasses import dataclass, fieldfrom collections import deque@dataclassclass Request:req_id: strprompt_tokens: intmax_new_tokens: intpriority: int = 0@dataclassclass BatchBuilder:token_budget: intmax_batch_size: intwaiting: deque = field(default_factory=deque)def submit(self, req: Request):self.waiting.append(req)def next_batch(self):batch, used = [], 0ordered = sorted(self.waiting, key=lambda r: -r.priority)for req in ordered:cost = req.prompt_tokens + req.max_new_tokensif len(batch) >= self.max_batch_size:breakif used + cost > self.token_budget:continuebatch.append(req)used += costfor req in batch:self.waiting.remove(req)return batch
This example sorts requests by priority and estimates each request’s cost from its prompt length plus its maximum generation length. In real systems, generation length can usually only be estimated. The scheduler should therefore reclaim budget at runtime based on the number of tokens actually generated. Sorting by priority alone can also leave large requests unscheduled for long periods. Weighting priority by waiting time can prevent this starvation.
5. Traffic Governance and Elastic Scaling
Real traffic has clear time-of-day patterns and sudden bursts. Governance strategies typically include the following:
- Tiered rate limiting: Set quotas by tenant, interface, and request type. Requests that exceed a quota receive clear retry information.
- Priority queues: Process interactive requests first. Place offline batch jobs in a low-priority queue that runs during idle periods.
- Degradation strategies: Under high load, disable non-core capabilities, such as extra-long outputs or supplementary analysis modules, to keep the main path available.
- Canary release: Route a small share of traffic to a new model or version first. Compare latency, error rate, and output quality, then increase the share gradually once results are confirmed.
Scaling decisions should not rely on device utilization alone. Queue time and time to first token better reflect what users actually experience. Adding resources also takes time, so instances should be warmed up in advance to avoid widespread timeouts during cold start.
6. Stability and Observability
Collect at least the following metrics:
| Metric | Definition | Purpose |
|---|---|---|
| Time to first token | Time from request arrival to the first output token | Measures interactive experience |
| Output throughput | Number of tokens generated per unit of time | Measures service capacity |
| Queue time | Time a request waits in the scheduling queue | Informs scaling timing |
| Device utilization and memory usage | Compute and memory consumption | Informs batch and cache configuration |
| Error rate and timeout rate | Statistics broken down by error type | Locates faults |
Fault handling requires a layered design. When a single card fails, remove it from the resource pool and either migrate its unfinished requests or return a retryable error code to the client. When a node fails, the scheduling layer should stop assigning new batches to that node. Fault domains should be divided by rack or switch unit, so that a group of critical instances does not share a single point of failure.
7. Launch Checklist
- Correctness: Key operators and end-to-end samples pass error and structured output checks.
- Performance: Under load tests that approximate the real traffic distribution, latency and throughput meet targets, and the traffic level at the performance inflection point is recorded.
- Capacity: Scaling plans, instance warm-up duration, and maximum concurrency are confirmed.
- Degradation: Every degradation switch has been rehearsed.
- Observability: Metrics, logs, and alerting rules cover both the main path and the fault path.
- Rollback: Version switch
