Skip to content

perf(fsdp): every rank reads its own shards from the checkpoint's safetensors files instead of rank 0 loading and broadcasting them - #389

Merged
Rockdu merged 3 commits into
mainfrom
fsdp/read-shards-from-safetensors
Nov 23, 2026
Merged

Rockdu merged 3 commits into
mainfrom
fsdp/read-shards-from-safetensors

Conversation

@zhihengy

@zhihengy zhihengy commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Trainer start-up optimization for DMD2 (three MiniMax H3 DiTs through the FSDP loader), independent of #381 and #383. Today rank 0 loads the whole checkpoint on the CPU, shards it with the weights in place, and torch broadcasts it one tensor at a time. With this PR every rank builds the component on the meta device, shards it there, and reads its own slice of every parameter straight from the checkpoint's safetensors files (torch.distributed.checkpoint with HuggingFaceStorageReader, the mechanism torchtitan's initial load uses). No rank holds the full model and no weight is broadcast.

What

  • model_backend.safetensors_files(component, checkpoint_path=...): the backend says which local safetensors files hold a component, or None for "rank 0 loads it". The base class returns None, so the native packages (LTX) keep the broadcast. DiffusersModelBackend returns the files from_pretrained reads with no variant (diffusers_weight_files): the ones diffusion_pytorch_model.safetensors.index.json lists, else the single diffusion_pytorch_model.safetensors; a Hub id is resolved to its snapshot first (snapshot_download of that component's weight files and index only). A checkpoint with only .bin weights, or with a listed file missing, gives None; so does a local folder with a single weights file at its root (from_pretrained reads that one before the component's own) and a checkpoint that is neither a folder nor a repo the Hub or the offline cache resolves (load_component then reports it, as on main). A subclass whose load_component loads other weights overrides the hook too, and a backend that names files owes every tensor its final dtype when it builds without weights (docs/user-guide/customization.md).
  • checkpoint.load_safetensors_to_fsdp: to_empty on the sharded meta model (the buffers computed by the constructor are kept), then dcp.load of the model's state dict; with cpu_offload the shards land on the host and the buffers go to the GPU, as broadcast_full_state_to_fsdp leaves them. A buffer the constructor left on meta is filled by the read when the files hold it, and a tensor two modules share keeps its value on both. A buffer no file holds keeps the value this rank's constructor computed. Before the read the ranks exchange whether their files hold the state dict (one all_gather_object): a tensor of the model missing from the files or saved with another shape, or a buffer outside the state dict still on meta, on any rank, makes every rank raise, so no rank enters the collective read alone; a file may hold tensors the model does not have. The reader takes every safetensors file of one folder, so it is pointed at a temporary folder of links to the chosen files; a variant file beside them (diffusion_pytorch_model.fp16.safetensors) is not read.
  • The choice is made before any weight is read, per component, and the broadcast path is untouched as the other branch. Files are read when all of these hold; otherwise rank 0 loads and broadcasts as before:
    • no LoRA on the model (neither --use-lora on a trainable model nor adapter paths);
    • the backend names the files;
    • checkpoint.holds_on_every_rank: every rank sees the files (one all_gather_object, before any build). Files that only some ranks see are an error raised on every rank, not a silent broadcast; a rank that cannot see the checkpoint at all still fails in load_component, as on main.
  • Files that exist but do not hold the model's state dict are an error, not a fallback, so the choice is final before the build: every rank builds once, on meta when the files are read and rank 0 with weights otherwise, in the order main builds in.
  • DiffusersModelBackend.load_component: a component built without weights now gives every floating tensor of its state dict, parameters and persistent buffers, the dtype a load with weights gives it: the master dtype, or fp32 under _keep_in_fp32_modules (diffusers' load_model_dict_into_meta). With rank 0 on meta too there is no loaded model to copy those dtypes from. SD3's pos_embed shows why the buffers count: the constructor makes it in fp32 and a load casts it to a bf16 master.

Why

One load_fsdp_models of the H3 DiT (62 GB on disk, 626 bf16 + 12 fp32 tensors; 124 GB as the fp32 master) on 2x H200 with --fsdp-cpu-offload --teacher-cpu-offload takes ~350 s: rank 0's from_pretrained (56 s), fully_shard over 124 GB of fp32 CPU tensors (111 s), the broadcast of 638 tensors one at a time (183 s). DMD2 does it three times.

Critic group (critic then teacher), same harness as #381, page cache warm:

main this PR
critic 354 s 49 s
teacher 349 s 49 s
both models 703 s 99 s
peak host RSS, rank 0 / rank 1 373 / 244 GB 191 / 191 GB
peak GPU allocated during the loads, rank 0 / rank 1 2.9 / 1.3 GB 0 / 0 GB
sha256 of every parameter shard and buffer, per rank reference identical on both ranks, both models (639 tensors)

The main column is the run of 2026-11-12 on the same GPU pair; the PR column is the first commit on an idle box, so the comparison of the times is indicative and the digests are the exact part. Run again at the top of the stack (#391 48f0ab83, which contains this PR's head d833ec34; torch 2.11.0): 50 s and 49 s, 190 / 191 GB, and the same digests. Of the 49 s, the earlier prototype measured ~46 s in to_empty (FSDP2 pins the offloaded shards as it allocates them) and ~3.5 s of reading; that split was not measured again here.

Behaviour ledger: a model that meets the conditions gets, on every rank, the parameter shards and buffers the broadcast produced, bit for bit and in the same dtypes (H3 above; Wan, Flux and SD3 at fp32, bf16 and fp16 masters below); LoRA runs, .bin checkpoints and native-package backends take the existing path unchanged; files that exist but do not match the built model, or that only some ranks see, are an error on every rank. --load resume still overwrites the shards afterwards. No flag added: the path follows from the checkpoint. Rank 0 logs which path each component took.

Boundary: each rank now reads its own copy of the files, and the ranks compare names and shapes only. Nodes that hold different weights under the same names would give a model mixed by rows, where on main rank 0's copy alone defined the weights; the copies have to be the same files, as for any other path every node opens.

With this in, #381's copy (58 s for the critic) and a direct read (49 s) cost about the same on H3, and #383 saves less; both still help where this path does not apply.

Validation

In an environment built from the CI recipe (Python 3.12, torch 2.11.0+cu129, diffusers 0.41.0, safetensors 0.8.0, sglang-miles tip), not in the CI image itself. Head d833ec34 unless a row names another.

check result
tests/fast/backends/fsdp_utils/test_safetensors_load.py real FSDP2 on a one-rank CPU mesh: the index's files and the single file each fill fp32 shards from bf16 with no weights materialized and no broadcast, a variant file beside either and a tensor the model lacks are not read, the constructor's buffer survives; a missing listed file and LoRA go to the broadcast (a frozen model in a run that trains a LoRA does not), decided before the build; another name, another shape and a buffer on meta that no file holds raise; the ranks' agreement holds for all-yes and all-no and raises for a split. The variant has another shape, so a reader that took it fails in any listing order. A state-dict buffer the constructor left on meta is read from the files, from a checkpoint in two files; a buffer two modules share keeps its value on both. 60 tests pass at 23babd5a together with test_model_backend.py and test_reference_models.py
tests/fast-gpu/backends/fsdp_utils/test_safetensors_load.py 2x H200, NCCL: rank 0 holds rows [0:2] and rank 1 rows [2:4] of each weight, GPU-resident and CPU-offloaded, forward matches the dense result; with another name in the files, in rank 1's files only, or files rank 0 does not see, both ranks raise the same error; a buffer no file holds keeps each rank's constructor value. Not yet run at 23babd5a: queued in CI under run-ci-fsdp
test_model_backend.py real SD3 (a persistent buffer made in fp32), real Wan (modules pinned to fp32) and a class with a persistent buffer under the pin: built without weights, every parameter and buffer has the dtype a load with weights gives, at bf16, fp16 and fp32 masters, a buffer outside the state dict included (no load casts it). The files the hook names hold the state a real diffusers load gives (single file and sharded, alone and beside a variant with other weights), and a real load reads a root-level weights file. A Hub id resolves to the weight files of its snapshot; a weights file at the root of a local checkpoint and a path that is neither a folder nor a resolvable repo id name no files
tests/fast/backends, tests/fast/test_train_diffusion.py (no GPU visible) 322 passed
tests/fast-gpu/backends/fsdp_utils 37 passed at 0414fefd; test_safetensors_load.py and test_reference_models.py again at the head
pre-commit run --files passes
real WanTransformer3DModel through DiffusersModelBackend and load_fsdp_models, 2x H200, not in CI single file, single file + fp16 variant, sharded + fp16 variant; fp32 and bf16 master; GPU-resident and CPU-offloaded: every parameter shard and buffer (98 tensors per rank) has the dtype, shape, device and sha256 the broadcast gives. The variant holds other weights
real SD3, Wan and Flux (tiny Hub snapshots) the same way, at fp32, bf16 and fp16 masters, not in CI 36 scenario-ranks identical to the broadcast per tensor, SD3's pos_embed buffer included (fp32 against bf16 before the dtype fix)
H3 on 2x H200, critic + teacher the table above; digests again equal to main's at #391 48f0ab83 (this head plus the LoRA PR)
DMD2 H3 e2e through Ray, 2x H200 (#366's recipe arguments, --deterministic-mode, #366's recipe script), at 0414fefd and again at #391 0314dd6f (this head plus the LoRA PR) critic, teacher and student each log every rank reads 14 safetensors files; the 9 metric series (22 points) equal #366's recorded standard bit for bit, both times
real Hub ids on a cold cache, 2 ranks, not in CI, at 0414fefd hf-internal-testing/tiny-wan-pipe, tiny-flux-pipe, tiny-sd3-pipe: identical to the broadcast per tensor; tiny-stable-diffusion-xl-pipe (.bin only) gives no files

Not run: more than one node; more than two ranks through the loader. The cold-cache Hub run predates the review fixes (0414fefd..d833ec34). The devbox rows were measured at d833ec34 or earlier; 23babd5a keeps the read path and changes the error cases, and runs run-ci-fsdp and run-ci-e2e in CI.

Files

  • miles/backends/fsdp_utils/model_backend.py: safetensors_files on the base class and on DiffusersModelBackend, diffusers_weight_files; the dtypes of a component built without weights
  • docs/user-guide/customization.md: what a backend that names files owes: the hook override when load_component loads other weights, final dtypes without weights, errors for files that do not match or that only some ranks see
  • miles/backends/fsdp_utils/checkpoint.py: holds_on_every_rank, load_safetensors_to_fsdp with its state check
  • miles/backends/fsdp_utils/model_loader.py: the choice and the two branches
  • tests/fast/backends/fsdp_utils/test_safetensors_load.py, tests/fast-gpu/backends/fsdp_utils/test_safetensors_load.py, _safetensors_load_worker.py, test_model_backend.py; test_reference_models.py (the test backend names no files; the loader fixture replaces the new collective)

Checklist

  • pre-commit hooks pass on the changed files
  • Added/updated tests for new behaviour
  • pytest tests/fast/backends is green
  • If launch flags changed, python3 train_diffusion.py --help still parses (no flag changed)
  • If a public flag was added, it appears in the CLI reference docs (no flag added)
  • If an example was added, it has a real walkthrough (no example added)

zhihengy and others added 3 commits November 23, 2026 00:23
…nent, and a build without weights gets the dtypes a load gives

Co-authored-by: rockdu <kangrdu@gmail.com>
…etensors files instead of rank 0 loading and broadcasting

Co-authored-by: rockdu <kangrdu@gmail.com>
… its final dtype when it builds without weights

Co-authored-by: rockdu <kangrdu@gmail.com>
@Rockdu
Rockdu force-pushed the fsdp/read-shards-from-safetensors branch from d833ec3 to 23babd5 Compare November 23, 2026 18:29
@Rockdu

Rockdu commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Reviewed and filtered important comments by Claude Code.

I force-pushed a trimmed version of this PR onto this branch (new head 23babd5a; the previous head stays reachable at d833ec3). Same mechanism and same read path, three commits by intent (the backend names the files and the dtypes of a build without weights / the loader reads the shards / docs); production diff +148 −8 instead of +199 −29. What I changed in behaviour:

  • files that exist but do not hold the model's state dict are an error on every rank, not a fallback to the broadcast; a file may hold tensors the model lacks;
  • files that only some ranks see are an error too, raised on every rank before any build;
  • so no second build on rank 0, no RNG save/restore, no build_component; safetensors_hold_state is gone;
  • the type(self).load_component subclass guard is replaced by a sentence in customization.md;
  • a buffer outside the state dict keeps the value this rank's constructor computed (no trailing broadcast).

60 CPU tests pass locally. I added run-ci-fsdp for the two-rank GPU test and run-ci-e2e to check the recipes stay bitwise. #391 is based on this branch and needs a rebase: holds_on_every_rank now takes what= and raises when the ranks disagree, and safetensors_hold_state no longer exists. I updated the description to this head.

@Rockdu Rockdu added run-ci-fsdp Run FSDP domain tests on this PR run-ci-e2e Run e2e metric-regression tests on this PR labels Nov 23, 2026
@Rockdu
Rockdu merged commit 4cb1a29 into main Nov 23, 2026
34 of 40 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

run-ci-e2e Run e2e metric-regression tests on this PR run-ci-fsdp Run FSDP domain tests on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants