Distributed Checkpoint & Flight Recorder

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Training a large model across many GPUs fails in two characteristic ways: the job dies and you must restart from the last good state, and the job hangs because one rank stopped taking part in a collective. This page covers the PyTorch tools for both. Distributed Checkpoint (DCP, torch.distributed.checkpoint) saves and loads state that is sharded over ranks, and can load it on a different number of ranks than it was saved with. The Flight Recorder records recent NCCL collectives so that a timeout can be traced to the rank that did not join. Single-process saving (torch.save, weights_only) is covered in Saving & Loading Models.

The checkpoint examples need a torchrun launch (see Distributed Overview). They were run on Python 3.13 with PyTorch 2.15 on 2026-10-31 as CPU processes with the Gloo back end, with "cuda" replaced by "cpu" and "nccl" by "gloo"; the Flight Recorder commands need NCCL on GPUs and were not executed. The Flight Recorder tutorial is published in the unstable section of the tutorials and describes itself as a new tool, so treat the details as likely to change.

Why not torch.save

With FSDP2 or tensor parallelism (see FSDP2 and DTensor, Tensor & Pipeline Parallelism) each rank holds only a shard of every parameter and of the optimiser state. Saving with torch.save means first gathering everything onto one rank, which costs memory and time and may not fit at all. DCP differs from torch.save and torch.load in two documented ways:

  • It writes multiple files, at least one per rank, in parallel, together with a .metadata file that describes where every piece of every tensor is.

  • It loads in place: you build the destination state dictionary first (with tensors already allocated on their final device) and DCP fills it. Because the metadata records the global layout, each rank reads only the bytes for its own shards. This also allows resharding: save on 64 GPUs, load on 8 or on a different parallelism layout.

Saving and loading

# torchrun --nproc-per-node 4 dcp_basic.py
import torch
import torch.distributed as dist
import torch.distributed.checkpoint as dcp
import torch.nn as nn

dist.init_process_group("nccl")
torch.cuda.set_device(dist.get_rank() % torch.cuda.device_count())

model = nn.Linear(16, 16).cuda()
state_dict = {"model": model.state_dict()}

# Every rank calls save; each writes its own shards under the directory.
dcp.save(state_dict, checkpoint_id="/tmp/ckpt/step_100")

# Load: build a destination with the same keys, then fill it in place.
dest = {"model": model.state_dict()}
dcp.load(dest, checkpoint_id="/tmp/ckpt/step_100")
model.load_state_dict(dest["model"])   # post-process the loaded values
dist.destroy_process_group()

The documented entry points:

  • save(state_dict, *, checkpoint_id=None, storage_writer=None, planner=None, process_group=None, no_dist=False, use_collectives=True) returns the checkpoint metadata. checkpoint_id is a path for the file system storage; if it is None you must pass storage_writer explicitly.

  • load(state_dict, *, checkpoint_id=None, storage_reader=None, planner=None, process_group=None, no_dist=False) returns nothing; it modifies state_dict in place.

  • no_dist=True saves or loads from a single process without collectives, which is useful for offline conversion.

  • use_collectives=False skips cross-rank coordination, is documented as experimental and changes the checkpoint format; leave it alone unless you know why you need it.

Pitfalls from the documentation: all ranks must pass state dictionaries with the same keys (otherwise the call can hang or fail), tensors must already be on the destination device before load, and the writer expects the target directory to be empty or absent. The older save_state_dict and load_state_dict functions are deprecated aliases for this API.

Stateful objects

Anything with state_dict() and load_state_dict() methods satisfies the Stateful protocol and can be placed directly in the dictionary passed to save and load. DCP calls state_dict() when saving, and calls state_dict() first and load_state_dict() afterwards when loading (the first call is needed because loading is in place). A small wrapper makes model, optimiser and counters one unit, and handles the FSDP/TP naming differences through the helper functions in torch.distributed.checkpoint.state_dict:

import torch
import torch.distributed.checkpoint as dcp
from torch.distributed.checkpoint.state_dict import get_state_dict, set_state_dict
from torch.distributed.checkpoint.stateful import Stateful


class TrainState(Stateful):
    def __init__(self, model, optimizer, step: int = 0) -> None:
        self.model = model
        self.optimizer = optimizer
        self.step = step

    def state_dict(self):
        model_sd, optim_sd = get_state_dict(self.model, self.optimizer)
        return {"model": model_sd, "optim": optim_sd, "step": self.step}

    def load_state_dict(self, state_dict) -> None:
        set_state_dict(
            self.model,
            self.optimizer,
            model_state_dict=state_dict["model"],
            optim_state_dict=state_dict["optim"],
        )
        self.step = state_dict["step"]


def save_checkpoint(model, optimizer, step: int, root: str) -> None:
    dcp.save({"app": TrainState(model, optimizer, step)}, checkpoint_id=f"{root}/step_{step}")


def load_checkpoint(model, optimizer, path: str) -> int:
    state = TrainState(model, optimizer)
    dcp.load({"app": state}, checkpoint_id=path)
    return state.step

Why use get_state_dict and set_state_dict instead of model.state_dict() directly:

  • They return canonical fully qualified names, independent of whether the model is wrapped in DDP, FSDP2 or TP, and convert optimiser state from parameter ids to those names. A checkpoint is therefore portable between differently wrapped runs.

  • StateDictOptions tunes the result: full_state_dict (gather to full tensors), cpu_offload, ignore_frozen_params, strict, broadcast_from_rank0 and others. For a sharded DCP checkpoint leave full_state_dict at its default False.

  • set_state_dict and set_optimizer_state_dict must be called before the first backward() or after an optimizer.step(), as the documentation states, so that the optimiser state is initialised correctly.

  • The module is documented as experimental.

Asynchronous checkpointing

Writing a large checkpoint stalls training. async_save first stages the state to CPU memory (blocking the training loop only for that copy), then writes in the background and returns a future:

import torch.distributed.checkpoint as dcp

checkpoint_future = None
for step in range(1, 1001):
    train_step()                                   # your training code
    if step % 100 == 0:
        if checkpoint_future is not None:
            checkpoint_future.result()             # never have two saves in flight
        checkpoint_future = dcp.async_save(
            {"app": TrainState(model, optimizer, step)},
            checkpoint_id=f"/tmp/ckpt/step_{step}",
        )
if checkpoint_future is not None:
    checkpoint_future.result()                     # wait before the process exits

Notes:

  • async_save takes async_checkpointer_type (a thread by default, or a separate process) and an optional async_stager. DefaultStager with StagingOptions (pinned memory, shared memory, non-blocking copies) tunes the staging step; the CUDA-dependent options raise an error when CUDA is not available. If you pass your own stager you own it and must call its close() after the last checkpoint.

  • Staging copies the state into CPU buffers, which raises CPU memory use by roughly the per-rank checkpoint size; the pinned-memory variant keeps its staging buffer alive for the life of the program. DefaultStager and the async_stager argument need PyTorch 2.9 or later, according to the recipe.

  • The recipe recommends allowing only one asynchronous checkpoint request at a time, and in its fully asynchronous example waits for staging_completion before optimizer.step() so that the weights are not modified during the copy (the object returned by async_save there carries staging_completion and upload_completion futures).

  • Wait for the previous future before starting the next save, and before leaving the program.

Storage, planners and resharding

DCP separates what to write from where to write it:

  • A storage writer or reader implements the I/O. FileSystemWriter(path, single_file_per_rank=True, thread_count=1, ...) and FileSystemReader(path) are the built-in implementations; checkpoint_id in save and load selects them automatically. The documentation also lists Hugging Face storage classes for reading and writing safetensors-style checkpoints, whose details were not verified for this page.

  • A planner (DefaultSavePlanner, DefaultLoadPlanner) decides how the state dictionary is turned into write and read items. Useful options include dedup_replicated_tensors on the save side (do not write the same replicated tensor from every rank) and allow_partial_load on the load side (do not fail when a key of the destination is absent from the checkpoint, for example when adding a new head).

  • Resharding is implicit: the loader compares the saved chunk metadata with the chunks each rank now needs and reads exactly the overlapping byte ranges. This is why a checkpoint written under one world size can be loaded under another, as long as the logical (global) tensor shapes match.

Custom storage (for example an object store) is added by subclassing StorageWriter and StorageReader and implementing the documented call sequences (set_up_storage_writer, prepare_local_plan, write_data, finish and the reader counterparts).

For interoperability with ordinary tooling, DCP checkpoints can be converted to and from a single torch.save file; the conversion helpers live in torch.distributed.checkpoint.format_utils (names and signatures were not verified on the 2.15 page, so check the module before relying on them). When the final artefact is meant for inference it is usually cleaner to save a consolidated file, as described in Saving & Loading Models, or an exported program, as in torch.export.

Flight Recorder

When an NCCL collective does not complete, every rank that did join waits until the watchdog timeout, then the job aborts with little information about who was missing. The Flight Recorder keeps a circular in-memory buffer of the most recent collective calls on each rank (operation, process group, sizes, state and optional stack trace). When the timeout fires the buffer is written to disk, and an analyser compares the dumps of all ranks.

Enabling it

Set the environment variables before launching the job:

export TORCH_NCCL_TRACE_BUFFER_SIZE=2000         # entries per rank; > 0 turns recording on
export TORCH_NCCL_DUMP_ON_TIMEOUT=true           # write the buffer when a collective times out
export TORCH_FR_DUMP_TEMP_FILE=/tmp/nccl_trace_rank_   # per-rank file prefix (this is the default)
# optional
export TORCH_NCCL_ENABLE_TIMING=true             # record per-collective durations (some CPU overhead)
export TORCH_NCCL_TRACE_CPP_STACK=true           # include C++ stacks (pair with TORCH_SYMBOLIZE_MODE)
torchrun --nnodes=1 --nproc_per_node=8 train.py
  • TORCH_NCCL_TRACE_BUFFER_SIZE is the number of entries kept; the tutorial recommends 2000.

  • TORCH_NCCL_DUMP_ON_TIMEOUT defaults to false; with true each rank writes one file at timeout.

  • TORCH_FR_DUMP_TEMP_FILE is the dump path prefix (the rank is appended); the default is /tmp/nccl_trace_rank_. The tutorial’s own example script sets a variable named TORCH_NCCL_DEBUG_INFO_TEMP_FILE instead and does not explain how it relates to TORCH_FR_DUMP_TEMP_FILE; this is an unreconciled inconsistency in the tutorial, so set the documented TORCH_FR_DUMP_TEMP_FILE and check which files appear.

  • TORCH_SYMBOLIZE_MODE selects how C++ stacks are resolved: dladdr, addr2line (default) or fast (experimental, much faster).

  • The data can also be read programmatically with torch._C._distributed_c10d._dump_nccl_trace(includeCollectives=True, includeStackTraces=True, onlyActive=False), which returns pickled data. This is a private function and may change.

  • The recorder applies to the NCCL backend. The tutorial states a minimum of PyTorch 2.5.

Analysing the dumps

Copy the per-rank dump files of a job into one directory and run the analyser. It is installed as the torchfrtrace command (available on nightly builds or source builds with USE_DISTRIBUTED=1) and also exists as the script fr_trace.py; it needs the tabulate package.

pip install tabulate
torchfrtrace /tmp/dumps                              # heuristic report of likely culprits
torchfrtrace /tmp/dumps -j --selected-ranks 0 1 2    # raw mode, restricted to some ranks
torchfrtrace /tmp/dumps -j --pg-filters 0 2          # raw mode, restricted to some process groups
torchfrtrace --prefix "trace_" /tmp/                 # files named trace_0, trace_1, ... in /tmp

Without -j the analyser applies heuristics to the dumps and prints a report of the likely cause (for example a rank that never issued a collective that the others are waiting on, or ranks that issued collectives in a different order or with mismatched sizes). With -j it prints the raw per-rank records. The tutorial does not explain the meaning of -j beyond using it for raw output, so confirm with torchfrtrace --help on your installed version.

The tutorial’s reproduction uses two processes where rank 0 calls an extra all_reduce that rank 1 never joins, with a one-second timeout; the analyser then reports that rank 1 did not join that collective.

Other hang and crash tools

  • Set TORCH_DISTRIBUTED_DEBUG=DETAIL to add consistency checks to collectives (slower), as covered in Distributed Overview.

  • Use NCCL_DEBUG=INFO for NCCL’s own log, and read the profiles in Profiling with torch.profiler to see whether a straggler rather than a deadlock is the problem.

  • Elastic launch (torchrun with --max-restarts) restarts the whole worker group after a failure; combined with periodic DCP checkpoints it gives a basic fault-tolerant training loop.