Skip to content

Check your own model

trainfuzz check answers one question about your training code: does your model, sharded the way you shard it, train to the same numbers as the same model on one process? You write a small Python file that builds the model, makes batches and computes the loss. trainfuzz trains it for a few steps across several ranks and in a single process, from the same initial weights and batches, and after every step compares the loss, every gradient, every parameter and every optimizer state tensor. If they differ, it tells you the first step and tensor where they do, and which rank's shard holds the difference. If a rank raises or hangs, it names that rank and the call each other rank was waiting in.

It runs on CPU with the Gloo backend, so a laptop or a CI runner is enough. Every tensor is compared through full_tensor(), so sharding bugs show up regardless of how the parameter is split.

1. Write a setup file

A setup file is a plain Python file with three functions. This one is examples/check/mlp.py:

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributed.tensor.parallel import ColwiseParallel, RowwiseParallel


class MLP(nn.Module):
    def __init__(self, d=16, hidden=64):
        super().__init__()
        self.fc1 = nn.Linear(d, hidden)
        self.fc2 = nn.Linear(hidden, d)

    def forward(self, x):
        return self.fc2(F.gelu(self.fc1(x)))


def build_model():
    return MLP()


def make_batch(step):
    g = torch.Generator().manual_seed(1000 + step)
    x = torch.randn(8, 16, generator=g)
    return x, torch.sin(x)


def loss_fn(model, batch):
    x, y = batch
    return F.mse_loss(model(x), y)


def tp_plan(model):  # only needed for --parallel tp and fsdp2+tp
    return {"fc1": ColwiseParallel(), "fc2": RowwiseParallel()}
Function Required What check does with it
build_model() yes Called after torch.manual_seed(--seed) on every rank and in the single process, then cast to --dtype.
make_batch(step) yes The global batch for that step: a tensor, or a tuple, list or dict of tensors (other values pass through). Floating-point tensors are cast to --dtype. Under data parallelism each rank gets an equal slice along dim 0.
loss_fn(model, batch) yes Runs the forward pass and returns the loss as a one-element tensor. It receives the parallelized model and this rank's slice.
make_optimizer(params) no Receives the trainable parameters and returns the optimizer. Default: AdamW(lr=1e-3).
tp_plan(model) for tp, fsdp2+tp A parallelize_module plan: module names to ColwiseParallel, RowwiseParallel and the other styles. Modules the plan leaves out are replicated across the tensor-parallel ranks, as torchtitan's NoParallel does.
fsdp_units(model) no The modules to fully_shard before the root. Default: every child of an nn.Sequential, nn.ModuleList or nn.ModuleDict that has parameters, innermost first.

Before any rank starts, check builds your model twice and calls make_batch(0) twice to confirm that both are deterministic. It also confirms that the batch splits evenly over the data-parallel ranks and that the loss is a scalar. A setup that fails one of these checks exits with status 3 and a message that says what to change.

For the comparison to mean anything, the sharded run and the single process must compute the same thing in exact arithmetic. Two rules follow from that, and check tests both on batch 0 in float64 before any rank starts:

  • The forward pass must not draw random numbers. check runs loss_fn twice on the same weights and batch under two different seeds and rejects the setup if the losses differ. Dropout is the usual cause; set its probability to 0 for the check.
  • Under data parallelism the loss has to be a mean over samples, so that averaging the per-rank gradients gives the gradient of the whole batch. check computes the loss and gradients of the whole batch and of each data-parallel slice, and rejects the setup if the mean over the slices differs. BatchNorm, a reduction="sum" loss and an MoE load-balancing term over the whole batch all fail this, and the message names BatchNorm modules when it finds them. Under --parallel tp or none every rank sees the whole batch, so the rule does not apply.

check also notes which parameters get no gradient at step 0 and builds DDP with find_unused_parameters=True when there are any, as you would.

2. Run it

Install trainfuzz (pip install -e . in a clone) and run:

trainfuzz check examples/check/gpt.py --parallel fsdp2,tp,fsdp2+tp --ranks 4

python -m trainfuzz check is the same command. The ranks are local processes. On a laptop, run it inside the Docker image instead (make docker builds trainfuzz:cpu), because ranks that crash can bring up OS crash dialogs. Mount the folder that holds your setup file:

docker run --rm --memory 4g --cpus 4 --shm-size 1g -v "$PWD:/work" -w /work trainfuzz:cpu \
  trainfuzz check my_setup.py --parallel fsdp2 --ranks 4

To check another PyTorch release, build the image with --build-arg TORCH_SPEC=torch==2.13.0 (see Install). The setup file can import anything installed in the image.

The GPT example (token and position embeddings, two pre-norm blocks with causal attention, a vocabulary head) on 4 ranks:

trainfuzz check examples/check/gpt.py: fsdp2 on 4 ranks, 3 steps, f64
  running fsdp2, 4 ranks, steps 0-2
  step 0  loss 4.29138  (single process 4.29138)  matched
  step 1  loss 4.33085  (single process 4.33085)  matched
  step 2  loss 4.30582  (single process 4.30582)  matched
all 3 steps matched the single-process run: loss, 37 gradients, 37 parameters and buffers, 111 optimizer state tensors per step (rtol 1e-07, atol 1e-09)
trainfuzz check examples/check/gpt.py: tp on 4 ranks, 3 steps, f64
  ...
all 3 steps matched the single-process run: loss, 37 gradients, 37 parameters and buffers, 111 optimizer state tensors per step (rtol 1e-07, atol 1e-09)
trainfuzz check examples/check/gpt.py: fsdp2+tp on 4 ranks, 3 steps, f64
  ...
all 3 steps matched the single-process run: loss, 37 gradients, 37 parameters and buffers, 111 optimizer state tensors per step (rtol 1e-07, atol 1e-09)

Each configuration takes a few seconds for models of this size.

3. Read the result

Exit status Meaning
0 Every step matched.
1 A value differed. The output names the first one.
2 A rank raised, hung or crashed. The output says which rank, at which step and phase, and where the other ranks waited.
3 The setup file or the arguments cannot be checked.

With a comma-separated --parallel, the exit status is the worst one.

A value differs

Here a test setup makes rank 1 scale its local gradient of fc2.weight by 1.001 at step 1, after check compared the gradients and before the optimizer step (tests/check/setups/mutate.py):

trainfuzz check tests/check/setups/mutate.py: fsdp2 on 4 ranks, 3 steps, f64
  running fsdp2, 4 ranks, steps 0-2
  step 0  loss 6.91892  (single process 6.91892)  matched
  step 1  loss 23.7335  (single process 23.7335)  DIFFERS
first difference: step 1, param of fc2.weight
  max abs diff 3.56e-05, max rel diff 0.127 (tolerance rtol 1e-07, atol 1e-09)
  worst element [4, 27]: single process 0.057497, sharded 0.0574614, held by rank 1
  the elements outside the tolerance are in rank 1's shard

Within a step the phases come in training order: loss, grad (before clipping), clip (the total norm clip_grad_norm_ returned), param (parameters and buffers after the step) and optim (optimizer state), and within a phase the tensors come in model order. init is the state before the first step and load the state right after a checkpoint load. The worst element is the one furthest outside the tolerance. For a sharded parameter the last line lists every rank whose shard holds an element outside the tolerance, which points at a rank when only one is involved. A difference can also be between ranks: every rank's full_tensor() must return the same bytes, and when one does not, the output says rank 1's full tensor differs from rank 0's.

--keep keeps the run directory with each rank's log and the gathered state of every step, and --json PATH writes the same results as JSON.

A rank raises or hangs

From the inf-norm clipping bug (§30, pytorch/pytorch#207025): FSDP2 splits the 5 rows of Linear(8, 5) over 4 ranks as 2, 2, 1 and 0, and the clip raises on the rank with no rows.

trainfuzz check examples/check/known_bugs/clip_inf_empty_shard.py: fsdp2 on 4 ranks, 3 steps, f64, clip inf-norm to 1
  running fsdp2, 4 ranks, steps 0-2
hang: rank 3 raised and the others waited for it
  rank 3 at step0:clip: RuntimeError: _foreach_norm cannot compute the infinity norm on an empty tensor because the operation does not have an identity
  rank 0 at step0:clip, waiting in clip_grad.py:_no_grad_wrapper > _functional_collectives.py:wait_tensor
  rank 1 at step0:clip, waiting in clip_grad.py:_no_grad_wrapper > _functional_collectives.py:wait_tensor
  rank 2 at step0:clip, waiting in clip_grad.py:_no_grad_wrapper > _functional_collectives.py:wait_tensor

check gives the other ranks 15 seconds after the first error, then reads each rank's stack. A run that hangs with no error is cut off after --timeout seconds (300 by default) and reported the same way. A rank whose process dies is a crash, reported with its signal or exit code and the phase each rank was in. Here tests/check/setups/one_rank.py sends rank 1 a SIGSEGV at step 1:

crash: rank 1 exited with SIGSEGV (signal 11)
  rank 0 was running, at step1:fwd
  rank 1 was at step1:fwd

When every rank raises, the output lists each rank's error:

error: every rank raised
  rank 0 at step0:opt: NotImplementedError: Operator aten._fused_sgd_.default does not have a sharding strategy registered.
  rank 1 at step0:opt: NotImplementedError: Operator aten._fused_sgd_.default does not have a sharding strategy registered.

Checkpoints

--checkpoint K trains K steps, saves model and optimizer state with torch.distributed.checkpoint (get_state_dict and dcp.save, sharded), and loads it on a fresh set of ranks into a new model whose parameters were all shifted by 7, so anything the load fails to restore shows up. The loaded state must equal what was saved, bit for bit. Then the remaining steps run and are compared with the single process as before. --load-ranks and --load-parallel change the world size and the layout for the load:

trainfuzz check examples/check/gpt.py --ranks 4 --steps 4 --checkpoint 2 --load-ranks 2
trainfuzz check examples/check/gpt.py: fsdp2 on 4 ranks, 4 steps, f64, checkpoint after step 1 loaded on fsdp2, 2 ranks
  running fsdp2, 4 ranks, steps 0-1
  loading on fsdp2, 2 ranks, steps 2-3
  step 0  loss 4.29138  (single process 4.29138)  matched
  step 1  loss 4.33085  (single process 4.33085)  matched
  step 2  loss 4.30582  (single process 4.30582)  matched
  step 3  loss 4.45352  (single process 4.45352)  matched
all 4 steps matched the single-process run: loss, 37 gradients, 37 parameters and buffers, 111 optimizer state tensors per step (rtol 1e-07, atol 1e-09)

Options

Option Default Meaning
--parallel P fsdp2 fsdp2, tp, fsdp2+tp, ddp or none. none trains the whole model on the whole batch on every rank, a control for the harness itself. A comma-separated list checks each one in turn.
--ranks N 2 Number of ranks.
--tp N 2 Tensor-parallel degree of fsdp2+tp; the other N / tp ranks are data parallel.
--steps N 3 Optimizer steps.
--dtype f64 f64, f32 or bf16, for the model and the floating-point batch tensors on both sides.
--clip NORM_TYPE off clip_grad_norm_ with this norm type (2, 1, inf) before every step. Write a negative value as --clip=-inf.
--max-norm X 1.0 max_norm of the clip.
--checkpoint K off Save after K steps and load on new ranks, as above.
--load-ranks N, --load-parallel P --ranks, --parallel World size and layout that load the checkpoint.
--seed S 0 torch.manual_seed before build_model().
--timeout S 300 Seconds before a run counts as hung.
--rtol, --atol by dtype Override the tolerance.
--json PATH off Also write the results as JSON.
--keep off Keep the run directory.

Choosing a dtype

The default is f64. In double precision the sharded run and the single process differ only by rounding near 1e-15, so the tolerance can be tight (rtol 1e-7, atol 1e-9) and anything above it is a real difference. Use f32 or bf16 to check a run in the precision you train in, with looser tolerances (rtol 2e-4 and atol 2e-5 for f32, 5e-2 for bf16).

How small a difference each dtype catches, measured with the mutation setup above (rank 1 scales its gradient shard of fc2.weight by 1 + ε at step 1; FSDP2, 4 ranks, --steps 2 so the change is measured at the step it is made):

ε f64 f32
1e-2 caught (param) caught (param)
1e-3 caught (param) caught (param)
1e-4 caught (param) not caught
1e-5 caught (param) not caught
1e-6 caught (param) not caught
1e-7 caught (param) not caught
1e-8 not caught not caught

Over more steps a change below the threshold can still surface: with 3 steps, ε = 1e-8 in f64 shows up at step 2 in one element of the momentum buffer, where 0.9 times the old buffer and the new gradient nearly cancel and the relative change grows to 1.6e-6.

In f32 one difference is expected and is not a bug. A parameter whose gradient is zero up to rounding, such as the key bias of attention (softmax ignores a shift that is the same for every key), gets a gradient of about 1e-10 from each side, of random sign. Adam divides by the gradient's own magnitude, so that noise becomes a full-size update, and the two runs move the bias apart. check says so when it happens:

first difference: step 0, param of blocks.1.attn.k.bias
  max abs diff 3.54e-05, max rel diff 0.0115 (tolerance rtol 0.0002, atol 2e-05)
  worst element [24]: single process -0.00440555, sharded -0.00443095, held by rank 3
  the elements outside the tolerance are in rank 3's shard
  the single-process gradient of blocks.1.attn.k.bias is zero up to rounding (max |grad| 3.1e-10, below atol 2e-05); optimizers that normalize by the gradient, such as Adam, scale such noise up to a full update. Run with --dtype f64 to tell rounding from a bug

In f64 the same gradient is about 1e-19, below Adam's epsilon, and the GPT example matches.

What it has caught

Each of these setup files reaches a verified PyTorch bug (the list) from training code, and each has a control that changes one setting and matches. All eleven give the same verdicts on 2.14.0 and on the 2.16.0.dev20261128 nightly. tests/check/test_check_known.py runs them, and python tests/check/test_check_known.py prints the table for the installed torch.

Setup Bug Result Control that matches
clip_inf_empty_shard.py --ranks 4 --clip inf §30: inf-norm clip with an empty FSDP2 shard hang at step0:clip, rank 3 raised --clip 2
clip_inf_nan_off_rank0.py --ranks 4 --clip inf §25: Gloo all_reduce MAX drops a NaN that is not on rank 0 total norm NaN in one process, 0.357 sharded --clip 2
tp_mse_loss.py --parallel tp --ranks 2 §72: F.mse_loss backward on DTensors is world-size times too large gradient of 0.weight doubled MSE=manual
tp_loss_uneven_shards.py --parallel tp --ranks 2 §11: smooth L1 and Huber loss on uneven shards loss differs at step 0 LOSS=manual
fused_adamw_noncontig_grad.py --parallel tp --ranks 2 §26: CPU fused AdamW reads a non-contiguous gradient as contiguous parameter proj.w differs after step 0 (the single process is the wrong side) FUSED=0
fused_sgd.py --ranks 2 §8: SGD(fused=True) has no DTensor sharding strategy every rank raises at step0:opt FUSED=0
tp_rowwise_small_input.py --parallel tp --ranks 4 §9: RowwiseParallel with fewer input features than ranks every rank raises at step0:opt IN=4
tp_embedding_empty_shard.py --parallel tp --ranks 4 §15: vocabulary-parallel embedding with an empty shard hang at step0:fwd, rank 3 raised VOCAB=8
fsdp2_tp_empty_dim.py --parallel fsdp2+tp --ranks 3 --tp 3 §31: FSDP2 over a TP shard that is empty in its other dim hang in full_tensor() before the first step HIDDEN=3
sp_sgd_momentum_checkpoint.py --parallel tp --ranks 2 --steps 2 --checkpoint 1 §34: SGD momentum under sequence parallelism cannot be saved every rank raises at save OPT=adamw, or no --checkpoint
ddp_buffer_odd_stride.py --parallel ddp --ranks 2 §74: DDP buffer broadcast with an odd-stride buffer (#68407) every rank raises at step0:fwd CANON=1

The §26 row shows a limit of any differential check: under DDP every rank runs the same fused kernel on the same non-contiguous gradient as the single process, both sides are wrong the same way, and check says they match.

How check is tested

These numbers come from runs on CPU in the repository's Docker images, torch 2.14.0 and 2.16.0.dev20261128 (Nov 28, 2026). The scripts are in tests/check/.

Recall on known bugs

check reports all 11 of the verified bugs that its layouts can reach, on both builds, and all 11 controls match (the table above). No setup was written for the other entries of the bug list. Most need something check does not run: NCCL (§75, §76), pipeline parallelism (§33), torch.compile (§35, §50 to §53), full or broadcast state dicts and planner options (§4, §6, §7, §10, §32), or Gloo calls on strided tensors that FSDP2 and DDP never make (§1, §5). The DTensor operator bugs (§2, §3, §12 to §14, §16, §17, §19 to §24, §70, §71, §73) need model or loss code that runs those operators on DTensors, as §11 and §72 do for losses; I did not write such setups for them.

False positives

tests/check/stress.py builds random correct setups: MLPs and small language models with widths from 1 to 13 (often uneven against the world size), one to three blocks, four activations, optional LayerNorm, tied and frozen weights, SGD (with and without momentum), Adam and AdamW (single-tensor and foreach), every clip type, f64 and f32, 2 to 4 ranks and all five layouts, with a checkpoint resume into another layout in 75 of 250. The same 250 seeds ran on both builds:

Result 2.14.0 nightly
matched 209 209
#150336, uneven tensor-parallel widths (known upstream) 28 28
§31 6 6
§30 5 5
§9 1 1
§15 1 1
a difference that no PyTorch bug explains 0 0

Every seed got the same verdict on both builds. Five of the 41 failures matched no known pattern at first; with the widths that did not divide by the tensor-parallel degree raised to a multiple of it, four matched and one moved on to §30.

Completeness

tests/check/setups/mutate.py changes exactly one thing on one rank, and the tests require check to report it at that step, phase and tensor, and to match when the same hook changes nothing: the loss, a gradient, a parameter before the optimizer step, the initial state, the state right after a load, a buffer the forward pass never reads, exp_avg_sq, the optimizer's step counter, the one row the last rank holds of an uneven shard, a frozen parameter, a gradient on a parameter that should have none, and momentum after a load.

Hostile setups

Dropout, BatchNorm under data parallelism, reduction="sum" and a whole-batch term are setup errors (exit 3) before any rank starts. Tied embeddings and unused parameters match. One rank raising is a hang that names it under FSDP2, DDP and tensor parallelism; one rank dying of SIGSEGV or os._exit(3) is a crash that names the signal or exit code; no rank process is left behind afterwards.

Mutation testing

tests/check/mutation.py applies 22 hand-written mutants to check's comparison, runner, rank worker and validation (skip a phase, ignore buffers or keys only the sharded run has, compare rank 0 only, swap the two runs, blame every rank, widen the tolerance tenfold, skip the last step or the initial state, compare a load against the single process only, drop the rank hashes, report the local loss, put check's own collectives on the training group, build DDP without find_unused_parameters, drop either validation rule, compare NaN norms with !=). The first run killed 21. The survivor, skipping the comparison of the initial state, showed that no test changed the state before step 0; with that test added, all 22 are killed and the unmutated code passes.

Determinism

The four examples under FSDP2, tensor parallelism, FSDP2 with tensor parallelism and DDP, and one injected fault, each ran 5 times on 4 ranks (tests/check/determinism.py). All 17 gave the same verdict and the same numbers bit for bit in every run.

What these runs fixed in check

  • A DCP failure on a rank (CheckpointException is a BaseException) was reported as a bare crash; it is now an error with the underlying message.
  • check's own collectives ran on the training's process group, so a rank that raised could pair its error report with another rank's FSDP2 all-gather and abort Gloo. They now run on a group of their own.
  • The cross-rank comparison of the clip's total norm called NaN on every rank a difference.
  • Dropout, BatchNorm and sum losses showed up as a difference at step 0; they are now setup errors.
  • DDP with an unused parameter raised at step 1; check now passes find_unused_parameters=True when a parameter gets no gradient.

Limits

  • CPU and Gloo only. The NCCL path of the fuzzers (--device cuda) is not wired into check yet.
  • The layouts are FSDP2, tensor parallel, FSDP2 with tensor parallel, DDP and none. Pipeline parallel, expert parallel, HSDP, mixed-precision policies, activation checkpointing, gradient accumulation and torch.compile are covered by the training profile on its template models; check does not configure them for your model.
  • Tensor parallelism needs tp_plan(model). A module whose own parameters are left plain while the plan shards its children is rejected with a message, because its forward would mix plain tensors and DTensors.
  • Under FSDP2, every rank must run the same modules in each step. An expert or branch that runs on some ranks and not others leaves the rest waiting in its all-gather; examples/check/moe.py runs every expert on every token for this reason.
  • Each rank gathers the full parameters, gradients and optimizer state after every step, and the single process holds them for every step, so the model has to fit in memory several times over. check is meant for a scaled-down copy of your model with the same structure and parallel plan.
  • Checkpoints use the sharded get_state_dict path only. The DCP fuzzer (python -m trainfuzz.dcp fuzz) covers full state dicts, broadcast loads, async saves and the other options.
  • A model with a parameter that never gets a gradient cannot be checked with --checkpoint: DCP's default load planner rejects the checkpoint (Missing key in checkpoint state_dict: optim.state.<name>.momentum_buffer), on 2.14.0 and on the nightly. check reports it as an error at load; examples/repros/dcp/unused_param_optim_state.py reproduces it without trainfuzz.
  • check compares two runs, so a bug that makes both runs wrong in the same way is invisible to it. The §26 setup under DDP is one example. The single process is the reference, and when PyTorch's single-process code is the wrong side (§26 under tensor parallelism), the report still reads "single process X, sharded Y".
  • A rank that raises while the others wait in a collective is reported as a hang that names it, after a 15-second grace period. A rank that dies (a segfault, os._exit) is a crash that names its signal or exit code and the phase it was in.