Repository navigation
perf(fsdp): every rank reads its own shards from the checkpoint's safetensors files instead of rank 0 loading and broadcasting them - #389
Conversation
…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>
d833ec3 to
23babd5
Compare
I force-pushed a trimmed version of this PR onto this branch (new head
60 CPU tests pass locally. I added |
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.checkpointwithHuggingFaceStorageReader, 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, orNonefor "rank 0 loads it". The base class returnsNone, so the native packages (LTX) keep the broadcast.DiffusersModelBackendreturns the filesfrom_pretrainedreads with no variant (diffusers_weight_files): the onesdiffusion_pytorch_model.safetensors.index.jsonlists, else the singlediffusion_pytorch_model.safetensors; a Hub id is resolved to its snapshot first (snapshot_downloadof that component's weight files and index only). A checkpoint with only.binweights, or with a listed file missing, givesNone; so does a local folder with a single weights file at its root (from_pretrainedreads 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_componentthen reports it, as onmain). A subclass whoseload_componentloads 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_emptyon the sharded meta model (the buffers computed by the constructor are kept), thendcp.loadof the model's state dict; withcpu_offloadthe shards land on the host and the buffers go to the GPU, asbroadcast_full_state_to_fsdpleaves 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 (oneall_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.--use-loraon a trainable model nor adapter paths);checkpoint.holds_on_every_rank: every rank sees the files (oneall_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 inload_component, as onmain.mainbuilds 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'spos_embedshows why the buffers count: the constructor makes it in fp32 and a load casts it to a bf16 master.Why
One
load_fsdp_modelsof 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-offloadtakes ~350 s: rank 0'sfrom_pretrained(56 s),fully_shardover 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:
mainThe
maincolumn 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 (#39148f0ab83, which contains this PR's headd833ec34; 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 into_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,
.bincheckpoints 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.--loadresume 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
mainrank 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-milestip), not in the CI image itself. Headd833ec34unless a row names another.tests/fast/backends/fsdp_utils/test_safetensors_load.py23babd5atogether withtest_model_backend.pyandtest_reference_models.pytests/fast-gpu/backends/fsdp_utils/test_safetensors_load.py23babd5a: queued in CI underrun-ci-fsdptest_model_backend.pytests/fast/backends,tests/fast/test_train_diffusion.py(no GPU visible)tests/fast-gpu/backends/fsdp_utils0414fefd;test_safetensors_load.pyandtest_reference_models.pyagain at the headpre-commit run --filesWanTransformer3DModelthroughDiffusersModelBackendandload_fsdp_models, 2x H200, not in CIpos_embedbuffer included (fp32 against bf16 before the dtype fix)main's at #39148f0ab83(this head plus the LoRA PR)--deterministic-mode, #366's recipe script), at0414fefdand again at #3910314dd6f(this head plus the LoRA PR)every rank reads 14 safetensors files; the 9 metric series (22 points) equal #366's recorded standard bit for bit, both times0414fefdhf-internal-testing/tiny-wan-pipe,tiny-flux-pipe,tiny-sd3-pipe: identical to the broadcast per tensor;tiny-stable-diffusion-xl-pipe(.binonly) gives no filesNot 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 atd833ec34or earlier;23babd5akeeps the read path and changes the error cases, and runsrun-ci-fsdpandrun-ci-e2ein CI.Files
miles/backends/fsdp_utils/model_backend.py:safetensors_fileson the base class and onDiffusersModelBackend,diffusers_weight_files; the dtypes of a component built without weightsdocs/user-guide/customization.md: what a backend that names files owes: the hook override whenload_componentloads other weights, final dtypes without weights, errors for files that do not match or that only some ranks seemiles/backends/fsdp_utils/checkpoint.py:holds_on_every_rank,load_safetensors_to_fsdpwith its state checkmiles/backends/fsdp_utils/model_loader.py: the choice and the two branchestests/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-commithooks pass on the changed filespytest tests/fast/backendsis greenpython3 train_diffusion.py --helpstill parses (no flag changed)