Adapting LLM Inference to Dedicated AI Accelerators
Running large language models on dedicated AI accelerators is not a one-token demo. This article defines what “done” means for production inference: graph coverage, memory planning, numerical contracts, and service behavior—plus a practical sequence from greedy alignment to long-running stability.
Dedicated AI accelerators can host large language models only when the compute graph, memory hierarchy, numeric path, and serving shape close together. Many teams treat adaptation as a backend swap: load a device plugin, load weights, and declare success at the first generated token. In production, uncovered operators silently fall back to a general-purpose CPU under long context or unusual batch sizes, memory fragmentation accumulates across requests, and low-precision accumulation drifts over long decode. Finished adaptation is a repeatable, observable, rollback-capable inference path.
Define done before you start
Write acceptance criteria before changing kernels. At least four contracts should be fixed.
Model shape. Decoder-only autoregressive, or with vision/multimodal branches; context limit, vocabulary size, speculative decoding, and prefix cache all change memory and communication.
Precision contract. Published weights are often higher precision; serving may use low-bit weights with higher-precision accumulation. Specify which layers may drop precision and which normalization, embedding, and sampling paths must stay at original precision.
Serving contract. Interactive low latency versus offline high throughput. The former cares about time to first token and tail latency; the latter cares about tokens per unit time and device utilization.
Failure semantics. Missing operators, OOM, or overflow: reject, shrink batch, shorten context, or fail over. Encode this in runtime policy so the service does not silently slow down.
Without these contracts, later optimization has no baseline, and a demo config is easy to mistake for capacity.
Align the compute graph
LLM graphs are hard mainly because of dynamic shapes: sequence length, batch, and KV-cache length. Do not “translate” the whole graph at once. Slice it statically:
- Prefill processes the full prompt; compute-dense, suited to large matmuls.
- Decode usually advances one step; memory-bound, often limited by cache traffic and bandwidth.
- Sampling, repetition penalty, and stop conditions often stay on the host; do not force them onto accelerator kernels, but bound host–device syncs.
Export a framework-agnostic graph: tensor names, symbolic shapes, dtypes, operator kinds. Classify each op as: efficient native impl, composable from existing kernels, must write a new kernel, or allowed on the host. Fallbacks should be limited to control flow and tiny tensors. Frequent fallback on attention, norm, or large matmul means adaptation is not done.
A schematic coverage check:
for op in graph.ops:impl = registry.lookup(op.kind, op.dtype, op.shape_pattern)if impl is None:record_gap(op)elif impl.device != "accelerator":record_fallback(op)assert no_critical_fallback(["attention", "matmul", "norm"])
This is not a vendor API. Gaps should be summarized by operator class, not by incidental log warnings.
Operator and kernel strategy
Attention and FFN dominate. Attention must handle causal masks, variable lengths, and cache append. If the chip prefers certain head dims or alignment, pad in graph optimization and document the extra compute so padding is not treated as free. If gated activations in FFN lack a native op, compose vector ops rather than writing a kernel per model variant; check that intermediates can be reused in place.
Norm, residual, and rotary embeddings are small in FLOPs but precision-sensitive. Reduction order that diverges from the reference drifts logits over long context. Keep a switchable “strict reference” path: small batch, short sequence for per-op compare; large batch, long sequence for fused kernels. Fusion is a performance tool, not a correctness prerequisite.
Memory planning
The usual ledger is weights, KV cache, peak activations, communication buffers, and framework overhead. A completion signal is being able to compute the maximum cacheable sequence for a given context and concurrency—not discovering OOM by trial.
Keep weights resident when possible. If they do not fit, split by layer or tensor so cut points sit after attention output or after FFN, not inside a reduction. Allocate KV cache for the request lifetime; prefer block allocation: append blocks as sequences grow, free whole blocks when requests end. Activation checkpointing is mainly for extremely long prefill; decode rarely justifies recompute for memory.
More parallelism is not always faster. Tensor parallel adds per-step communication, pipeline parallel adds bubbles, expert parallel adds routing imbalance. Interactive serving often prefers fewer devices plus cache reuse; offline jobs can scale batch and device count together. Set a memory watermark: reduce batch or reject new requests before allocation fails.
Precision and consistency
Low precision is common; validate in layers:
- Operator: fixed-seed inputs; max absolute and relative error versus reference. Tighter thresholds for reductions than for large matmuls.
- Module: one attention layer, one FFN, one residual block—compare hidden states.
- Sequence: fixed prompt and decode settings; compare tokens for several steps. With sampling, compare logits before temperature/top-k, not sampled tokens.
On mismatch, check accumulation order, scales, and saturation first, then masks and cache indices. “Answers look fine” is not a numeric contract. For tool calls, code, and structured output, token-level drift breaks format; greedy step-wise match should be a release bar.
Version quantization parameters with weights. Calibration sets should cover domain language and short/long prompts. If a layer stays out of spec, keep that layer in higher precision rather than forcing a uniform format.
Serving and observability
The end state is a service, not a script. Split the path: queue and rate limit, tokenize, prefill, decode loop, stop and post-process. The device should run regular tensor work; session state, auth, and safety policy stay in the service layer.
Observe at least: queue time, prefill time, per-step decode time, batch size, cache hit rate, fallback counts, utilization, and memory watermark. Non-zero fallbacks on critical ops should alert, not sit in debug logs. Keep the previous weights and runtime config; shift traffic by proportion. On numeric regression, roll back the full path—do not mix two kernel sets in one process.
Elastic compute, containers, object storage, and monitoring stay generic: images for the runtime, object storage for weights and calibration records, metrics as above. A cloud platform such as Baidu AI Cloud can host those capabilities; whether adaptation is complete still depends on the graph, kernels, and acceptance data—not on whether an instance was created.
A stable rollout order
Fix the model and input set. Land short-sequence greedy decode with per-token alignment. Close prefill and decode memory paths. Then add dynamic batching, cache reuse, and low precision. Finally stress tail latency and long-run stability. Keep independently runnable checks so issues are not stacked in one un-debuggable release.
Done is not a press-release timestamp. It is a set of facts: no surprise fallbacks on critical ops, a memory ledger that holds at target concurrency, greedy decode matching the reference, and explicit behavior on failure. That is how LLM inference on dedicated accelerators moves from a demo to sustainable operation.
