Migrating LLMs to New Compute Platforms: An Engineering Guide to Inventory, Verification, and Rollback
This article provides a comprehensive engineering guide for migrating large language models to new compute platforms. It covers essential practices including capability inventorying, operator dispatching and fallback monitoring, precision comparison using strict thresholds, communication performance instrumentation, checkpoint fault tolerance, and a phased migration roadmap with clear rollback strategies. By embedding decisions into code and tests, teams can mitigate knowledge loss and ensure stable model training on alternative hardware.
1. Inventory Capabilities Before Migration
When core team members leave or rotate, teams often lose the rationale behind migration decisions. For instance, why an operator was reverted to a fallback implementation, which precision thresholds were verified, or which communication parameters cause training hangs. If this information only exists in personal memory, the risk of knowledge loss is high. Therefore, migration work must embed decisions into code, tests, and processes—forming migration documentation, unit tests, and decision records—rather than supplementing them after the fact.
Before starting, list the capabilities typically required by a mature ecosystem and verify their status item by item. Below is a capability inventory template that can be directly copied and used:
| Capability | Current Status | Handling Method | Owner | Acceptance Criteria |
|---|---|---|---|---|
| Base Operator Library (MatMul, Normalization, Attention) | Available / Missing / To Confirm | Replace / Custom Build / Fallback | TBD | Single operator error within threshold |
| Compiler (Graph Optimization, Operator Fusion) | To Confirm | Replace / Disable Fusion / Custom Build | TBD | Output consistent before and after fusion |
| Collective Communication Library (Topology Aware) | To Confirm | Replace / Manual Topology Config | TBD | Multi-card bandwidth and latency meet baseline ratio |
| Profiling and Debugging Tools | To Confirm | Replace / Custom Instrumentation | TBD | Can locate time distribution within a single step |
| Checkpoint and Fault Tolerance | To Confirm | Custom Build / Reuse | TBD | Recoverable and passes validation after interruption |
The inventory should not merely compare theoretical single-card compute power. Whether a model can train stably on a new platform depends on operator coverage, graph optimization effectiveness, and multi-card communication performance. Costs do not disappear; they simply shift from model innovation to underlying engineering.
2. Operator Coverage and Dispatching
When a model contains a few niche or novel operators, the new platform’s operator library may lack corresponding implementations. There are three common approaches: composing equivalent computations using existing operators; handwriting high-performance operators for critical paths; and retaining a generic implementation as a fallback for non-critical paths.
The dispatcher below registers implementations by backend, falling back to the reference implementation when a custom one is missing, and tracks the fallback count:
import mathclass OperatorDispatcher:"""Registers operator implementations by backend. Falls back to reference if custom is missing."""PRIORITY = ("custom", "reference")def __init__(self):self._impls = {}self.fallback_count = {}def register(self, op_name, backend, fn):table = self._impls.setdefault(op_name, {})if backend in table:raise KeyError(f"Duplicate registration: {op_name}/{backend}")table[backend] = fndef dispatch(self, op_name, *args, **kwargs):impls = self._impls.get(op_name)if not impls:raise KeyError(f"Unregistered operator: {op_name}")for backend in self.PRIORITY:if backend in impls:if backend != "custom":self.fallback_count[op_name] = self.fallback_count.get(op_name, 0) + 1return impls[backend](*args, **kwargs)raise KeyError(f"No available implementation for {op_name}")def softmax_ref(xs):m = max(xs)exps = [math.exp(x - m) for x in xs]s = sum(exps)return [e / s for e in exps]def softmax_custom(xs):# Placeholder for platform-specific implementation. Replace with actual kernel calls in real scenarios.return softmax_ref(xs)def gelu_ref(x):return 0.5 * x * (1.0 + math.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * x ** 3)))d = OperatorDispatcher()d.register("softmax", "reference", softmax_ref)d.register("softmax", "custom", softmax_custom)d.register("gelu", "reference", gelu_ref) # No custom implementation, demonstrates fallbackx = [0.5, -1.2, 3.3, 0.0]assert d.dispatch("softmax", x) == softmax_ref(x)assert d.dispatch("gelu", 0.7) == gelu_ref(0.7)print(d.fallback_count) # {'gelu': 1}
When using such a dispatcher, note the following:
- Key Conflicts: Registering the same operator for the same backend twice will raise an error immediately, preventing new code from silently overriding old implementations.
- Version Management: Backend names can include version numbers, such as
custom-v2, making it easier to retain multiple implementations for comparison. - Thread Safety: Registration should occur during process startup. If dynamic registration is needed at runtime, locking is required.
- Fallback Monitoring: Fallbacks on critical paths should never occur silently.
fallback_countmust be integrated with monitoring, otherwise performance will degrade unnoticed.
3. Precision Comparison: Use Thresholds, Not the Naked Eye
Precision issues typically stem from low-precision data types, different reduction orders, and operator implementation differences. When comparing, follow these steps:
- Fix random seeds, dataset samples, and input tensors. Send the same inputs simultaneously to both the reference implementation and the new platform.
- Estimate the noise floor first. Run the reference platform twice using different reduction orders or different devices; the difference between the two results is the noise. The threshold must be higher than the noise, otherwise normal fluctuations will be flagged as errors.
- Compare layer outputs sequentially, recording the maximum absolute error, maximum relative error, and cosine similarity.
- Apply thresholds based on data types, and locate the specific operator if limits are exceeded.
Below are starting thresholds. They are merely starting points and need to be calibrated according to the model and task:
| Data Type | Starting rtol | Starting atol | Description |
|---|---|---|---|
| FP32 | 1e-5 | 1e-6 | More mantissa bits, strictest threshold |
| FP16 | 1e-3 | 1e-4 | Fewer mantissa bits, error amplification is obvious |
| BF16 | 1e-2 | 1e-3 | Even fewer mantissa bits, threshold needs to be relaxed |
Cosine similarity of layer outputs can serve as an auxiliary metric; teams can start by observing it at 0.999. If a layer exceeds the limit, first check if it uses a fallback operator, then verify if its data type matches the reference implementation.
The following function continues from the code in the previous section:
THRESHOLDS = {"fp32": {"rtol": 1e-5, "atol": 1e-6},"fp16": {"rtol": 1e-3, "atol": 1e-4},"bf16": {"rtol": 1e-2, "atol": 1e-3},}def compare_outputs(ref, out, dtype):th = THRESHOLDS[dtype]if len(ref) != len(out):raise ValueError("Output length mismatch")max_abs = 0.0max_rel = 0.0dot = norm_ref = norm_out = 0.0passed = Truefor r, o in zip(ref, out):diff = abs(r - o)max_abs = max(max_abs, diff)max_rel = max(max_rel, diff / max(abs(r), 1e-12))dot += r * onorm_ref += r * rnorm_out += o * oif diff > th["atol"] + th["rtol"] * abs(r):passed = Falsecosine = dot / (math.sqrt(norm_ref) * math.sqrt(norm_out) + 1e-12)return {"max_abs": max_abs, "max_rel": max_rel, "cosine": cosine, "passed": passed}x = [0.5, -1.2, 3.3, 0.0]ref = softmax_ref(x)out = d.dispatch("softmax", x)print(compare_outputs(ref, out, "fp32"))
4. Communication Efficiency and Performance Instrumentation
The most common issue after migration is throughput degradation, but the cause could be in computation, communication, or data loading. Therefore, instrumentation must use a unified standard to compare different platforms and versions.
| Metric | Definition | Measurement Notes |
|---|---|---|
| Throughput (tokens/s) | Global tokens per step divided by average step time | Only count steps after warmup |
| Step Latency | Average, P50, P99 | Synchronize devices before and after timing, otherwise you measure submission time |
| Communication Ratio | Communication time divided by total step time | When communication and computation overlap, cumulative communication time overestimates exposed communication overhead |
| Peak Memory | Max allocated memory per device | Record per device separately, don’t just look at the first card |
The following code implements warmup skipping, synchronized timing, and statistical summarization:
import timedef measure_steps(step_fn, n_steps, warmup=20, sync=lambda: None):times = []for i in range(n_steps):sync()t0 = time.perf_counter()step_fn()sync()if i >= warmup:times.append(time.perf_counter() - t0)return timesdef summarize(times, tokens_per_step):if not times:raise ValueError("Zero valid steps, please increase n_steps or decrease warmup")ordered = sorted(times)n = len(ordered)avg = sum(ordered) / nreturn {"tokens_per_s": tokens_per_step / avg,"step_avg_s": avg,"step_p50_s": ordered[n // 2],"step_p99_s": ordered[min(n - 1, int(n * 0.99))],}
The troubleshooting order for communication issues is usually: first confirm if the topology mapping matches the physical connection, then check the algorithm selection for collective communication, and finally see if computation and communication can overlap. Change only one variable at a time, and retain metric records for each run.
5. Checkpoint Fault Tolerance
Long-running training will inevitably encounter interruptions. The goals of checkpointing are: interruptions during writing should not corrupt old files, loading should detect corruption, and the recovery process should be rehearsed periodically.
Recommended practices:
- Write to a temporary file first, and only atomically replace the official file after
fsync, without directly overwriting the old checkpoint. - Write a manifest file for each checkpoint, recording the training step, configuration, random number state, data reading position, and sha256.
- Validate the hash before loading; if validation fails, refuse to load and fall back to an earlier checkpoint.
- Retain several recent checkpoints, not just one.
- Conduct a recovery drill periodically: load the checkpoint in a new process, run for several steps, and compare whether the loss curve matches the original process.
The following code illustrates the concept of atomic writing and validation. In actual training, states are usually generated by the framework’s serialization interface and need to support sharded saving.
import hashlibimport jsonimport osimport tempfiledef _write_atomic(path, data):directory = os.path.dirname(os.path.abspath(path))fd, tmp = tempfile.mkstemp(dir=directory, prefix=".tmp_")try:with os.fdopen(fd, "wb") as f:f.write(data)f.flush()os.fsync(f.fileno())os.replace(tmp, path)except BaseException:if os.path.exists(tmp):os.remove(tmp)raisedef save_checkpoint(state, path, meta):digest = hashlib.sha256(state).hexdigest()_write_atomic(path, state)manifest = {**meta, "sha256": digest, "bytes": len(state)}_write_atomic(path + ".manifest.json",json.dumps(manifest, ensure_ascii=False, indent=2).encode("utf-8"))def load_checkpoint(path):with open(path + ".manifest.json", encoding="utf-8") as f:meta = json.load(f)with open(path, "rb") as f:data = f.read()if hashlib.sha256(data).hexdigest() != meta["sha256"]:raise ValueError(f"Checkpoint validation failed: {path}")return data, meta
This code cannot prevent silent disk errors, so recovery drills remain essential. If data is written to shared storage, also verify the consistency semantics of that storage.
6. Phased Migration Roadmap
Migration proceeds in phases, each with clear exit conditions. Teams should set target values on the baseline; below are the judgment criteria without presetting specific numbers.
| Phase | Main Work | Exit Criteria |
|---|---|---|
| 1. Capability Inventory | Fill out the capability table, map every operator in the model | Every operator has a handling method and owner |
| 2. Single Operator & Small Model Verification | Compare precision per operator, run full training curve on a small model | Single operator passes corresponding threshold; small model loss curve deviation from baseline is within team-set range |
| 3. Parallel Training Stress Test | Test throughput, communication ratio, and checkpoint time under multi-card, multi-node | Throughput reaches agreed-upon baseline ratio; continuous running without unexpected interruptions |
| 4. Canary Cutover | Run a small percentage of tasks on the new platform, keep the rest on the original platform | Metrics during canary period remain stable compared to baseline |
| 5. Full Cutover | Migrate all tasks, retain old environment for a period | Rollback drill passed, old environment can recover within agreed time |
Before moving to the next phase, archive the metrics, thresholds, and anomaly records from the current phase into the migration documentation. This ensures that even if the owner changes, successors can see the rationale behind every decision.
7. Rollback Plan and Pacing Assessment
Migration pacing should be determined by metrics, not by schedules. The table below can serve as a reference during weekly reviews:
| Observed Signal | Judgment | Action |
|---|---|---|
| Precision exceeds threshold, and cause cannot be located immediately | Rollback related operator or model | Switch back to reference implementation, log the issue and reproduction steps |
| Throughput below target, and communication ratio significantly higher than baseline | Pause scaling | Check topology mapping, communication algorithm, and compute-communication overlap |
| Training interruption count exceeds agreed value | Pause | Check fault tolerance path, checkpoint validation logs, and hardware alerts |
| Metrics stable, and current phase exit criteria met | Continue | Move to the next phase |
The rollback plan must be prepared in advance, not designed after an incident:
- Old environment images, dependency versions, and startup configurations must be retained and launchable within the agreed time.
- Toggle switches should be placed in configurations or environment variables. The dispatcher’s priority can also be used to temporarily disable custom implementations.
- Before switching, confirm that the new platform can read the old checkpoint format, or provide a conversion tool.
- Save checkpoints and logs from the new platform before rolling back.
