Adapting and Deploying Large Language Models Across Diverse AI Chips
A practical guide to adapting and deploying large language models across diverse AI hardware, covering resource estimation, a layered adaptation architecture, unified backend abstraction, operator mapping with fallback strategies, precision alignment, and performance benchmarking.
1. Background: Why Multi-Chip Adaptation Matters
As large language models move from research to production, deployment environments are becoming increasingly diverse. The same set of model weights may need to run on high-performance accelerator cards in data centers, or on edge devices and dedicated inference chips. More hardware options reduce the risk of relying on a single supply chain, but they also force engineering teams to solve the “develop once, run everywhere” problem.
The main challenges of multi-chip adaptation fall into three categories:
- Differences in compute interfaces: Each hardware platform has its own low-level programming model, operator libraries, and compilation toolchains. The same matrix multiplication may require completely different implementation paths on different platforms.
- Differences in memory hierarchies: VRAM capacity, memory bandwidth, and on-chip cache structure directly determine the upper bounds of batch size and context length.
- Differences in numerical behavior: Low-precision computation varies subtly in rounding modes, accumulation order, and approximations of special functions, so final outputs can drift from expectations.
Understanding these three classes of differences is the prerequisite for designing an adaptation plan.
2. Estimate the Model’s Resource Profile First
Before starting adaptation work, estimate the resources the model needs at runtime. Take mainstream attention-based architectures as an example: during inference, VRAM is mainly consumed by three parts — model weights, KV cache, and intermediate activations.
Weight memory can be estimated as:
weight_bytes = num_params × bytes_per_param
For a 70B-parameter model, weights stored in FP16 or BF16 take up roughly 140 GB, or about 70 GB after INT8 quantization.
KV cache size is estimated as:
kv_cache_bytes = 2 × num_layers × num_kv_heads × head_dim × seq_len × batch_size × bytes_per_element
The factor of 2 accounts for the Key and Value parts. Using a set of example parameters — 40 layers, 8 KV heads, head dimension 128, sequence length 32768, batch size 1, and 2 bytes per element (FP16 or BF16) — the KV cache for a single request is about 5.4 GB. This grows linearly with the number of concurrent requests, so in long-context scenarios the KV cache can exhaust VRAM even sooner than the weights themselves.
When planning resources, pay attention to the following:
- The product of maximum context length and the number of concurrent requests determines peak VRAM demand;
- Use paged or chunked cache management to reduce memory fragmentation;
- Schedule requests in buckets by length, so short requests do not hold memory reserved for long ones.
3. A Layered Adaptation Architecture
A robust adaptation solution is typically split into layers, each with a single responsibility:
- Device and memory layer: Handles device discovery, VRAM allocation and release, host-to-device data copies, and management of asynchronous execution queues.
- Operator layer: Implements high-frequency operators such as attention, matrix multiplication, normalization, activation functions, and positional encoding. For operators not yet implemented, provide a reference implementation as a fallback.
- Graph and model layer: Handles weight loading, format conversion, quantization parameter mapping, and computation graph optimization.
- Inference engine layer: Handles request scheduling, continuous batching, KV cache management, and sampling strategies.
- Service layer: Handles API protocols, rate limiting, health checks, monitoring metrics, and logging.
The value of layering is that upper-layer logic stays independent of hardware changes. When a new hardware type is added, engineers only need to fill in the device and operator layers and validate them against a unified test suite.
Adaptation should follow the principle of “correct first, performance second.” Ensure every operator’s output matches the reference implementation before optimizing hot paths with fusion and tuning.
4. Designing a Unified Abstract Interface
Upper-layer code should depend only on a set of abstract interfaces, with concrete implementations plugged in via a registration mechanism. Here is a schematic example:
from abc import ABC, abstractmethodclass ComputeBackend(ABC):name: str = "base"@abstractmethoddef available(self) -> bool:"""Check whether this backend is available in the current environment."""@abstractmethoddef matmul(self, a, b):"""Matrix multiplication."""@abstractmethoddef attention(self, q, k, v, mask=None):"""Scaled dot-product attention."""_REGISTRY = {}def register(backend: ComputeBackend) -> None:_REGISTRY[backend.name] = backenddef select_backend(preferred: str | None = None) -> ComputeBackend:# Prefer the specified backend; otherwise pick the first available one in registration orderif preferred and preferred in _REGISTRY and _REGISTRY[preferred].available():return _REGISTRY[preferred]for backend in _REGISTRY.values():if backend.available():return backendraise RuntimeError("No compute backend available")
Three key points in this design:
- Upfront availability checks: Probe hardware and driver versions at startup to avoid discovering a missing environment mid-run.
- Observable selection: Log the final backend and its version for easier troubleshooting.
- Explicit priority override: Allow operators to override the default selection via configuration, which is convenient for canary testing.
5. Operator Mapping and Fallback Strategies
Operator coverage is the most labor-intensive part of adaptation. Start by taking inventory of all operators along the model’s inference path, ranked by call frequency and share of total latency. Implement native versions first for high-frequency, time-consuming operators; lower-frequency ones can initially use reference implementations.
A fallback strategy must meet two conditions. First, fallbacks must be logged and included in performance reports. Otherwise, operators silently falling back to slow paths cause hard-to-detect performance losses. Second, fallback implementations must pass the same precision validation as native ones — avoiding the trap of “it runs, but the results are wrong.”
For adjacent operators that can be fused — for example, normalization with linear transformations, or activation functions with elementwise multiplication — fusion reduces VRAM reads and writes and usually yields significant gains. Results before and after fusion still need to be compared item by item.
6. Precision Alignment and Validation
Precision validation is the most overlooked part of multi-chip adaptation. A combination of “layer-by-layer comparison plus end-to-end comparison” is recommended.
Layer-by-layer comparison works by fixing random seeds and inputs, exporting the output of every layer in both the reference and target environments, and computing error metrics. Common metrics include maximum absolute error, relative error, and cosine similarity.
def max_abs_diff(ref, out):return max(abs(r - o) for r, o in zip(ref, out))def check_tolerance(ref, out, atol: float = 1e-3):diff = max_abs_diff(ref, out)return diff <= atol, diff
Tolerances should be set based on data type. FP32 and FP16 allow different error ranges, and INT8 quantization scenarios require separate evaluation. Avoid applying a one-size-fits-all threshold.
End-to-end comparison is closer to the business perspective. Under greedy decoding (picking the highest-probability token at each step), the token sequences generated in the two environments should be identical, or diverge only at some position. Measuring the prefix agreement length quantifies how early divergence occurs. If divergence happens too early, trace back to the layer-by-layer comparison to locate the problem.
7. Performance Evaluation: Metrics and Methods
Performance metrics for LLM services typically include:
- Time to first token: The time from request arrival to the first output token, which directly affects interactivity;
- Per-token generation time: The latency of each token during steady-state generation;
- Throughput: The number of tokens processed or generated per unit of time, usually distinguishing input from output throughput;
- Peak VRAM usage: Determines the maximum supported concurrency and context length;
- Energy efficiency: Tokens generated per unit of energy, which affects long-term operating costs.
