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:

    1. import math
    2. class OperatorDispatcher:
    3. """Registers operator implementations by backend. Falls back to reference if custom is missing."""
    4. PRIORITY = ("custom", "reference")
    5. def __init__(self):
    6. self._impls = {}
    7. self.fallback_count = {}
    8. def register(self, op_name, backend, fn):
    9. table = self._impls.setdefault(op_name, {})
    10. if backend in table:
    11. raise KeyError(f"Duplicate registration: {op_name}/{backend}")
    12. table[backend] = fn
    13. def dispatch(self, op_name, *args, **kwargs):
    14. impls = self._impls.get(op_name)
    15. if not impls:
    16. raise KeyError(f"Unregistered operator: {op_name}")
    17. for backend in self.PRIORITY:
    18. if backend in impls:
    19. if backend != "custom":
    20. self.fallback_count[op_name] = self.fallback_count.get(op_name, 0) + 1
    21. return impls[backend](*args, **kwargs)
    22. raise KeyError(f"No available implementation for {op_name}")
    23. def softmax_ref(xs):
    24. m = max(xs)
    25. exps = [math.exp(x - m) for x in xs]
    26. s = sum(exps)
    27. return [e / s for e in exps]
    28. def softmax_custom(xs):
    29. # Placeholder for platform-specific implementation. Replace with actual kernel calls in real scenarios.
    30. return softmax_ref(xs)
    31. def gelu_ref(x):
    32. return 0.5 * x * (1.0 + math.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * x ** 3)))
    33. d = OperatorDispatcher()
    34. d.register("softmax", "reference", softmax_ref)
    35. d.register("softmax", "custom", softmax_custom)
    36. d.register("gelu", "reference", gelu_ref) # No custom implementation, demonstrates fallback
    37. x = [0.5, -1.2, 3.3, 0.0]
    38. assert d.dispatch("softmax", x) == softmax_ref(x)
    39. assert d.dispatch("gelu", 0.7) == gelu_ref(0.7)
    40. 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_count must 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:

    1. Fix random seeds, dataset samples, and input tensors. Send the same inputs simultaneously to both the reference implementation and the new platform.
    2. 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.
    3. Compare layer outputs sequentially, recording the maximum absolute error, maximum relative error, and cosine similarity.
    4. 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:

    1. THRESHOLDS = {
    2. "fp32": {"rtol": 1e-5, "atol": 1e-6},
    3. "fp16": {"rtol": 1e-3, "atol": 1e-4},
    4. "bf16": {"rtol": 1e-2, "atol": 1e-3},
    5. }
    6. def compare_outputs(ref, out, dtype):
    7. th = THRESHOLDS[dtype]
    8. if len(ref) != len(out):
    9. raise ValueError("Output length mismatch")
    10. max_abs = 0.0
    11. max_rel = 0.0
    12. dot = norm_ref = norm_out = 0.0
    13. passed = True
    14. for r, o in zip(ref, out):
    15. diff = abs(r - o)
    16. max_abs = max(max_abs, diff)
    17. max_rel = max(max_rel, diff / max(abs(r), 1e-12))
    18. dot += r * o
    19. norm_ref += r * r
    20. norm_out += o * o
    21. if diff > th["atol"] + th["rtol"] * abs(r):
    22. passed = False
    23. cosine = dot / (math.sqrt(norm_ref) * math.sqrt(norm_out) + 1e-12)
    24. return {"max_abs": max_abs, "max_rel": max_rel, "cosine": cosine, "passed": passed}
    25. x = [0.5, -1.2, 3.3, 0.0]
    26. ref = softmax_ref(x)
    27. out = d.dispatch("softmax", x)
    28. 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:

    1. import time
    2. def measure_steps(step_fn, n_steps, warmup=20, sync=lambda: None):
    3. times = []
    4. for i in range(n_steps):
    5. sync()
    6. t0 = time.perf_counter()
    7. step_fn()
    8. sync()
    9. if i >= warmup:
    10. times.append(time.perf_counter() - t0)
    11. return times
    12. def summarize(times, tokens_per_step):
    13. if not times:
    14. raise ValueError("Zero valid steps, please increase n_steps or decrease warmup")
    15. ordered = sorted(times)
    16. n = len(ordered)
    17. avg = sum(ordered) / n
    18. return {
    19. "tokens_per_s": tokens_per_step / avg,
    20. "step_avg_s": avg,
    21. "step_p50_s": ordered[n // 2],
    22. "step_p99_s": ordered[min(n - 1, int(n * 0.99))],
    23. }

    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:

    1. Write to a temporary file first, and only atomically replace the official file after fsync, without directly overwriting the old checkpoint.
    2. Write a manifest file for each checkpoint, recording the training step, configuration, random number state, data reading position, and sha256.
    3. Validate the hash before loading; if validation fails, refuse to load and fall back to an earlier checkpoint.
    4. Retain several recent checkpoints, not just one.
    5. 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.

    1. import hashlib
    2. import json
    3. import os
    4. import tempfile
    5. def _write_atomic(path, data):
    6. directory = os.path.dirname(os.path.abspath(path))
    7. fd, tmp = tempfile.mkstemp(dir=directory, prefix=".tmp_")
    8. try:
    9. with os.fdopen(fd, "wb") as f:
    10. f.write(data)
    11. f.flush()
    12. os.fsync(f.fileno())
    13. os.replace(tmp, path)
    14. except BaseException:
    15. if os.path.exists(tmp):
    16. os.remove(tmp)
    17. raise
    18. def save_checkpoint(state, path, meta):
    19. digest = hashlib.sha256(state).hexdigest()
    20. _write_atomic(path, state)
    21. manifest = {**meta, "sha256": digest, "bytes": len(state)}
    22. _write_atomic(path + ".manifest.json",
    23. json.dumps(manifest, ensure_ascii=False, indent=2).encode("utf-8"))
    24. def load_checkpoint(path):
    25. with open(path + ".manifest.json", encoding="utf-8") as f:
    26. meta = json.load(f)
    27. with open(path, "rb") as f:
    28. data = f.read()
    29. if hashlib.sha256(data).hexdigest() != meta["sha256"]:
    30. raise ValueError(f"Checkpoint validation failed: {path}")
    31. 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.