ELLMEngineering Large
Language Models
Download PDF

Chapter 45

Distributed Checkpoints, Recovery, and Elasticity

On this page

A recoverable checkpoint contains matching model and optimizer state from one committed step. This chapter describes shard identity, atomic publication, asynchronous writes, and restore onto a changed topology.

What must be recoverable

A training restart commonly needs:

  • model parameters and nonparameter buffers;
  • optimizer moments, master weights, and step counters;
  • learning-rate and loss-scale scheduler state;
  • data-loader epoch, shard, sample, and packing position;
  • random-number states for data, dropout, and model operations;
  • parallelism metadata and tensor layout;
  • training recipe, code/artifact version, and global progress;
  • any curriculum, mixture weights, or dynamic routing state.

Saving only weights supports inference or a warm start, not an exact training continuation. Define checkpoint classes such as recovery, milestone, export, and evaluation artifact. They have different contents, retention, and compatibility promises.

Logical versus physical state

A logical tensor has a global name, shape, dtype, and semantic role. A physical checkpoint contains shards written by ranks under one parallel plan. The manifest maps logical ranges to immutable objects with checksums and ownership metadata.

This separation enables resharded restore. A checkpoint saved with DP8-TP8-PP4 may load into a different compatible plan by computing intersections between stored logical ranges and destination ranges. Avoid formats that encode only rank-local filenames without global offsets.

Optimizer state follows parameter identity, not current rank. Flattening, padding, expert placement, or pipeline cuts can change physical layout. Stable logical IDs and versioned transformation rules are essential.

Atomic publication

Every required shard must be durable and validated before publication. The atomic pointer selects a complete manifest; a reader must never discover a partially written step through the latest-checkpoint pointer.
Open full diagram ↗

Every required shard must be durable and validated before publication. The atomic pointer selects a complete manifest; a reader must never discover a partially written step through the latest-checkpoint pointer.

One safe protocol is:

  1. coordinator allocates a unique checkpoint ID and immutable object prefix;
  2. every rank writes assigned shards and reports size/checksum;
  3. metadata validation confirms complete logical coverage without illegal overlap;
  4. a manifest is written after all required objects are durable;
  5. a small atomic pointer or catalog entry publishes the manifest;
  6. retention removes unreachable older objects only after a grace period.

Readers see either the previous complete pointer or the new complete pointer. A partially written checkpoint is never named as latest. Object stores may provide atomic creation of one manifest object even when directory rename is unavailable.

Manifest publication must be idempotent. A retry with the same checkpoint ID either discovers the same complete contents or writes a new immutable attempt; it must not mix shards from different steps.

Checkpoint bandwidth model

For total checkpoint bytes C, aggregate sustainable storage bandwidth B, and fixed coordination overhead L, a lower bound is:

2026-10-12T12:02:56.174972 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

The slowest writer, metadata service, shared network, or storage partition may determine B. Per-rank bandwidth multiplied by ranks can exceed the storage system's aggregate limit.

Checkpoint traffic also contends with training collectives and input reads. A burst of synchronized writers can collapse the shared filesystem. Stagger writes, aggregate locally, use topology-aware writers, or provision a separate path when necessary.

Measure time paused, time until durable publication, device-to-host staging bytes, pending checkpoint memory, and impact on concurrent training steps.

Synchronous and asynchronous save

A synchronous save pauses training until required state is durable. It is simple and bounds the version of tensors being written, but the pause can be large.

An asynchronous save first snapshots or stages a consistent state, then writes while training continues. The snapshot must remain immutable. Copying to host frees device state sooner but consumes host memory and link bandwidth. Copy-on-write or double buffering can reduce pause but may temporarily double large state.

Backpressure is mandatory. If storage is slower than checkpoint production, do not queue unbounded snapshots. Skip a nonessential interval, block at a safe point, or lower frequency while preserving the recovery objective.

The asynchronous boundary has two different completion events. Staging complete means the checkpoint owns a stable snapshot that later parameter updates cannot alter. Upload complete means that snapshot has reached its storage destination; publication still follows the manifest protocol. PyTorch's asynchronous distributed-checkpoint recipe exposes staging and upload completion separately for its asynchronous stager.

Wait for staging before the next operation that can mutate captured state, not merely before the next checkpoint. If a forward pass mutates buffers, its boundary matters as well as optimizer.step(). Limit concurrent saves so pinned host snapshots do not exhaust memory. A process that exits after staging but before durable upload has not produced a remote recovery point. Inject failure at both boundaries and verify which checkpoint a replacement job can discover.

Incremental and local checkpoints

Incremental checkpoints store only changed chunks relative to a base. They save bytes when change is sparse or compression/deduplication is effective, but optimizer tensors often change everywhere. Long dependency chains slow restore and complicate retention; periodically compact into a full base.

Local node or rack checkpoints provide fast recovery from process failure but disappear with larger failure domains. Remote durable checkpoints cover rack or site loss at higher cost. A tiered policy can write frequent local recovery points and less frequent durable milestones.

Parity or erasure coding can tolerate lost shards without full replication, but encoding consumes compute/network and recovery reads many fragments. Use it when object loss risk and storage economics justify the complexity.

Restore and resharding

A restore planner should:

  1. validate manifest, recipe, and requested topology compatibility;
  2. allocate destination tensors in their new layouts;
  3. assign read ranges across ranks to balance storage and network;
  4. stream stored chunks directly into destination shards where possible;
  5. transform dtype, padding, or layout only under a versioned rule;
  6. reconstruct optimizer, RNG, data, and scheduler state;
  7. run cross-rank validation before the next optimizer step.

Avoid loading a full tensor onto one rank and broadcasting it. Parallel reads and range intersection scale better. Test restore into the actual disaster topology, not only the same healthy cluster.

Validate checksums, finite values, representative tensor hashes, global step, optimizer ownership, and a deterministic short replay when feasible.

Derive shard intersections during restore

For a logical flattened tensor of length N, let an old shard own half-open interval [a,b) and a new shard require [c,d). Their transferable segment is [max(a,c),min(b,d)) when the lower endpoint is smaller than the upper endpoint. The source offset is max(a,c)-a; the destination offset is max(a,c)-c. Repeat across old owners until the destination interval is covered exactly once.

Coverage and nonoverlap are correctness conditions independent of checksum validity. A checksum can validate the wrong shard perfectly. Record logical tensor name, shape, dtype, flattening order, interval, and parameter identity; physical rank number is insufficient after a parallel-degree change. Apply the same mapping to optimizer tensors whose axes track parameter elements, while handling scalar step counters according to their own replication contract.

A resharding implementation also needs a bounded staging schedule. Reading all old shards at once can exceed host memory even when the final local shard fits. Stream intersections in a bounded order and publish the restored state only after every required parameter and optimizer component passes validation.

Failure interval and checkpoint frequency

Checkpointing too often wastes time; too rarely loses expensive work. If a synchronous checkpoint costs C_time and the mean time between relevant failures is M, a common first-order heuristic places the useful interval on the order of:

sqrt(2 C_time M)

One derivation minimizes the first-order overhead fraction C_time / interval + interval / (2*M): the first term is checkpoint work per useful-time interval, and the second is expected lost work when a failure lands uniformly within that interval. Differentiating gives the square-root expression. This approximation assumes rare independent failures, roughly constant checkpoint cost, and intervals large relative to the checkpoint pause; it omits failures during recovery and checkpointing. Large jobs have a lower job-level mean time between failures than one device. Include restart time, queue reacquisition, local versus durable failures, and asynchronous overlap before applying the heuristic.

Optimize expected time to a valid model, not only average step throughput. A plan with slightly slower steps but much faster checkpoint and recovery can finish sooner.

Coordinated failure handling

Synchronous model-parallel groups usually fail as a unit. When one rank faults:

  • stop launching new collectives;
  • surface the first known error, not a cascade of timeouts;
  • capture rank and communicator state;
  • terminate or fence all group members;
  • release cluster resources and stale rendezvous state;
  • restart from a verified checkpoint or a documented in-memory recovery point.

Trying to keep healthy ranks alive indefinitely can make recovery slower and state ambiguous. Use bounded timeouts and a control-plane lease so an old group cannot rejoin after replacement.

Elasticity

Data-parallel replicas are the easiest axis to change because model ownership within each replica remains complete. Even then, changing DP changes global batch or accumulation unless adjusted, and it changes sample assignment and random streams.

Changing TP, PP, CP, or EP requires resharding model and optimizer state, rebuilding communicators, and possibly recompiling engines. Treat this as a coordinated restart unless the framework explicitly supports a safe online transition.

Elastic recovery is not free capacity. Keep spare nodes or accept scheduler wait, and include rendezvous, artifact load, cache warmup, and checkpoint read in recovery time.

Recovery drills

Automate tests for:

  • rank process crash during compute and collective;
  • node loss during checkpoint write;
  • corrupt or missing shard;
  • restore with different DP or model-parallel degree;
  • stale latest pointer and duplicate publication retry;
  • storage throttling and unavailable metadata service;
  • data-loader and RNG continuation correctness.

A checkpoint that has never been restored is an untested backup. Track restore success and duration as release metrics.

Design Exercises

  1. Design atomic publication for a multi-terabyte sharded checkpoint.
  2. What distinguishes a recovery checkpoint from a model export?
  3. How can asynchronous checkpointing corrupt state or cause OOM?
  4. Design topology-independent resharded restore.
  5. How would you choose checkpoint frequency for a large cluster job?
  6. What does safe elasticity require beyond restarting with fewer data-parallel ranks?

Worked Solutions

1. Atomic checkpoint

Write all shards under a unique immutable attempt ID, each with logical ranges, size, and checksum. Validate complete tensor coverage and required global state, then write one immutable manifest and atomically publish a pointer/catalog record. Readers ignore unreferenced partial attempts. Publication and retries are idempotent, and garbage collection waits past a grace period so it cannot delete shards still referenced by readers or the previous checkpoint.

2. Recovery versus export

A recovery checkpoint includes optimizer, scheduler, loss scale, global step, data position, RNG, parallel-layout metadata, and recipe identity needed to continue training. An export may contain only inference weights, tokenizer/configuration, and serving metadata in a consolidated or quantized form. A milestone may retain additional audit lineage. Name the class so operators do not attempt exact continuation from an artifact that lacks state.

3. Async risks

If training mutates tensors while writers read them, one checkpoint contains mixed steps. Staging solves consistency but consumes device/host memory and bandwidth; multiple pending stages can OOM. Copy completion and object durability are different boundaries. Use an immutable snapshot, explicit stream synchronization, bounded outstanding saves, checksummed shards, and publish only after durability. Apply backpressure when storage falls behind.

4. Resharded restore

Describe tensors globally by stable identity, shape, dtype, and logical ranges. The destination allocates its new shards and a planner intersects them with stored ranges, assigning parallel reads directly to consumers. Versioned transformations handle flattening, padding, dtype, pipeline cuts, and experts. Rebuild optimizer ownership, RNG, data, and schedulers, then validate hashes and a short replay. Never require one rank to materialize every full tensor.

5. Frequency

Estimate synchronous or exposed checkpoint cost, job-level failure interval, restart/queue time, and value of lost work. The square-root heuristic gives a starting interval near sqrt(2 C_time M) under simple assumptions. Simulate failure domains and tiered local/durable saves, then optimize expected time to valid completion under storage limits. Revisit as cluster size, checkpoint bytes, or failure rate changes.

6. Elasticity

Changing DP requires consistent new rank membership, adjustment of local batch or accumulation to preserve the intended global batch, sample reassignment, RNG policy, optimizer ownership, and scheduler progress. Changing model-parallel axes additionally needs resharding, communicator rebuild, engine compatibility, and new placement. Fence the old group, publish one membership epoch, and resume only after all ranks validate the same checkpoint and plan.

A publication boundary that can be executed

The two-process lab stages one set of model tensors per rank and publishes a manifest only after both files are complete. Loading follows the manifest, checks the complete parameter key set, and compares restored logits with the reference. Its additional orphan-file check is a narrow visibility example, not an injected writer crash.

The separate examples/checkpoint_publication.py drill supplies that missing experiment. It first commits a complete two-shard generation. A child writer starts a candidate generation, signals after its first shard is staged, and blocks. The parent terminates that process before publication and restores the previously committed bytes through CURRENT. It then corrupts and removes a committed shard in separate checks: the reader rejects the digest mismatch and missing file. All four checks passed in the recorded local run.

Each generation has an immutable directory and a manifest listing the exact expected shard set and SHA256 digests. A candidate becomes discoverable only when a local rename replaces CURRENT. A reader resolves that pointer once, validates the complete manifest and checks every payload before returning it. Concurrent writers additionally need a compare-and-swap or ownership fence; this single-writer drill does not implement that policy.

This is a local atomic-rename example for weights. It does not implement distributed optimizer recovery, checksummed object uploads, lease fencing, or elastic resharding. A real checkpoint protocol must add those state and storage requirements; its reader should retain the same rule that staged objects are not independently discoverable checkpoints.

Process interruption and power failure are different fault models. The local drill does not call fsync on shard files, manifests or directories, and therefore makes no claim that a committed generation survives power loss. A durable local protocol must order those flushes before acknowledging publication and validate the filesystem's guarantees; an object store requires its own conditional-write and consistency protocol. The separate decoder lab checks optimizer next-step continuation, not crash durability.