Repository navigation
perf(fsdp): a model with LoRA reads its base shards from the safetensors files too; rank 0 broadcasts only the adapter - #391
Draft
zhihengy wants to merge 34 commits into
Conversation
…etensors files instead of rank 0 loading and broadcasting them
… so Hub ids, single-file checkpoints and folders with a variant are read per rank too The model backend now says which files hold a component (safetensors_files): the ones the diffusers index lists, else the single diffusion_pytorch_model.safetensors, the files from_pretrained reads with no variant. A Hub id resolves to its snapshot first. The reader is pointed at a folder of links to those files, since it takes every safetensors file of one folder. Backends that do not say (the native packages) keep rank 0's broadcast.
…ts first, so a fallback after a meta build draws what one build draws
…ors files too; every rank builds the adapter as rank 0 does Every rank lets PEFT build the adapter (a new one from rank 0's generator state, a saved one from its files) on a base that has uninitialized storage instead of weights, then reads its own shards of the base under the names the checkpoint gives them. An initialization that decomposes the base weights (PiSSA, OLoRA, LoftQ...) keeps rank 0's load and broadcast. The ranks now agree that the files are there before any of them builds.
…uffers the dtype a load gives them, as it does the parameters
…aves the load to rank 0, since from_pretrained reads it before the component's
…no files, so load_component reports it as before
… the broadcast; one the files hold is read; one two modules share keeps its value on both
…name what they hold
…ithout no longer gets base storage and the generator broadcast
…dapter rules that out, so a rank's own adapter config cannot change the collectives it runs
…er is built, so --deterministic-mode's NaN fill no longer writes a copy of the model on every rank
…oRA whose file holds adapter tensors alone; one with a bias or a saved module, or another PEFT type, leaves the load to rank 0
…me, the helper weight sync already uses
6 tasks done
… the norm of the base weights for any magnitude the file lacks
…after the read, as the broadcast leaves it
…nent names no files, so the files cannot replace the weights it loads
…s no files, so load_component reports a mistyped folder as before
…he broadcast, through the real rank agreement
…eading it fails whatever order the folder lists
…iffusers load gives, alone and beside a variant; a root-level file is the one diffusers reads
…h would leave it on meta whatever the backend built
…ding adapter's draws on meta, and rank-local adapter files
…se config is a LoraConfig too, leaves the load to rank 0 without a first build on every rank
…ozen model without an adapter reads per rank whatever the actor's LoRA flags
…s base, and broadcasts it after the per-rank read of the base Every rank building the adapter needed rank 0's generator state on every rank, an agreement before the build, a rebuild on every rank in the fallback, and left two boundaries (an Embedding adapter's draws on meta, rank-local adapter files). The adapter is small: rank 0 builds it as on main, the other ranks stay on meta as on main, and after each rank has read its shards of the base, torch's set_model_state_dict broadcasts the adapter from rank 0. A model without an adapter loads exactly as in the PR below.
…rains a LoRA, and a buffer no load casts: three changes of the loader that passed every test now fail one
…type when it builds without weights
…efore rank 0 broadcasts them; a rank whose own adapter config gave other tensors takes the full broadcast, which names the missing keys as before
…ffer, which the adapter broadcast needs on the parameters' device under CPU offload
Rockdu
force-pushed
the
fsdp/read-shards-from-safetensors
branch
from
November 23, 2026 18:29
d833ec3 to
23babd5
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stacked on #389. #389 lets every rank read its own shards of a component from the checkpoint's safetensors files, except when the model carries a LoRA: PEFT renames the base parameters and adds ones the files do not hold, so those models still had rank 0 load everything and broadcast it. With this PR every rank reads the base of such a model too, and only the adapter, which is small, is broadcast from rank 0.
What
main: rank 0 lets PEFT create and initialize it (apply_lora) or load it from its files (load_lora_adapter), the other ranks build it on meta. Nothing of PEFT's initialization or dtype handling is reimplemented, rank 0's files and rank 0's generator define the adapter as before, and every rank's generator ends where it ends onmain.base_stand_in_for_loragives each base parameter of rank 0 a CPU stand-in for that step, one uninitialized element expanded to the parameter's shape, and returns it to meta afterwards. For the adapters this path accepts, PEFT reads only the base layer's device and dtype there. A fulltorch.emptywould be free by default but is written through under--deterministic-mode(torch fills uninitialized memory with NaN): a copy of the model in host memory.checkpoint.base_state: the state dict without the adapter, under the names the checkpoint uses (to_hf_name, the helper weight sync already has).safetensors_hold_stateanddcp.loadtake it, so the same check decides for models with and without LoRA, and a name the mapping gets wrong sends the component to the broadcast.load_safetensors_to_fsdpthen gives every rank its shards of rank 0's adapter:set_model_state_dict(..., full_state_dict=True, broadcast_from_rank0=True, strict=False), the call the broadcast path makes for the whole model, here with the adapter's tensors only (0.03 s beside 8 GiB of base shards per rank; the base shards are untouched).lora_needs_no_base_weightssays whether rank 0 can build the adapter on a base without weights; otherwise rank 0 loads everything and broadcasts as before, and the backend is not asked for files:--lora-init-weightsgaussianorkaiming-uniformfor a new adapter, the same in a saved one's config, and no DoRA. PiSSA, OLoRA, LoftQ... decompose the base weights and DoRA takes their norm.LoraConfigtoo) whoseadapter_model.safetensorsholds adapter tensors only. PEFT loads any other tensor it saved (a bias withbias="all", a module to save) into the base, where the read of the base checkpoint would replace it.holds_on_every_rank, after the build) now runs for every component, also when a rank found that its adapter rules the files out: each rank reads its own adapter config to decide, and no rank may skip a collective on its own. The ranks also compare the names and shapes of the adapter tensors each one built from that config (same=adapter_shapes(model), in the sameall_gather_object). The adapter broadcast fills the names rank 0 sends and reports nothing about the others, so a rank whose own config gave other tensors would keep them uninitialized; such ranks take the full broadcast, which names the missing keys as onmain.build_componentchecks that the base is on meta before the adapter step, which would otherwise leave rank 0's base on meta whatever the backend built.Behaviour ledger
A model with LoRA that meets #389's conditions and the two above gets, on every rank, bitwise the parameter shards, buffers, dtypes and
requires_gradthe broadcast produced, and leaves every rank's generator in the same state (checked below). Models without LoRA load exactly as in #389: same code path, same collectives. Adapters that read the base weights or hold more than adapter tensors,.bincheckpoints and native-package backends take the existing path; for those LoRA models the oneall_gather_objectis new. No flag added.An earlier version of this PR built the adapter on every rank instead (see the commits before
795d1e2f). That needed rank 0's generator state on every rank, an agreement before the build and a rebuild on every rank in the fallback, and it made the adapter depend on each rank's own copy of its files. Review replaced it with the broadcast.Validation
At
48f0ab83, in an environment built from the CI recipe (Python 3.12, torch 2.11.0+cu129, diffusers 0.41.0, peft 0.18.1), not in the CI image itself.tests/fast/backends/fsdp_utils/test_safetensors_load.pygaussian,kaiming-uniform): the values rank 0 builds with weights, and the same generator state after. PiSSA: the backend is never asked for files, and every rank still answers the agreement. The agreement carries the adapter's tensor names and shapes and fails when a rank's differ. A saved adapter with a bias, with a saved module, with an initialization from the base weights, with DoRA, of another PEFT type (LoHa, AdaLoRA) or saved as.binis not built without base weights. A model without an adapter, trainable or frozen under the actor's LoRA flags, skips the adapter step. The base takes one element of memory while the adapter is built. A base the backend built with weights is refused before the adapter steptests/fast-gpu/backends/fsdp_utils/test_safetensors_load.pytests/fast/backends,tests/fast/test_train_diffusion.py(no GPU visible)Missing key(s) in state_dictfrom the full broadcast, as onmain; before the agreement compared the adapter it loaded with NaN adapter shards under--deterministic-modetests/fast-gpu/backends/fsdp_utils/test_reference_models.pyWanTransformer3DModel+ PEFT throughDiffusersModelBackendandload_fsdp_models, 2x H200, not in CIgaussian,kaiming-uniform), saved adapter (frozen, trainable); fp32 and bf16 master; GPU-resident and CPU-offloaded: 134 tensors per rank (36 of the adapter) with the dtype, shape, device,requires_gradand sha256 of the full broadcast, and the same generator state on both ranks. PiSSA takes the broadcastmain's on both ranks, both models (639 tensors); 50 s and 49 s per model, 190 GB peak host RSS per rank, 0 GB GPU--deterministic-mode, at0314dd6f(before the adapter agreement ofb8337f87, which a model without an adapter passes with an empty value)every rank reads 14 safetensors files; the 9 metric series (22 points) equal #366's recorded standard bit for bitpre-commit run --filesNot run: a training run with LoRA through Ray; a large model with LoRA (the adapter broadcast alone was timed beside a 16 GiB base); more than two ranks; more than one node.
Files
miles/backends/fsdp_utils/model_loader.py: the choice for models with LoRA,lora_needs_no_base_weights,peft_init_lora_weights,base_stand_in_for_lora,replace_base_parameters; the meta check before the adapter stepmiles/backends/fsdp_utils/checkpoint.py:base_state,adapter_state,adapter_shapes;holds_on_every_rank(condition, same=); the adapter broadcast inload_safetensors_to_fsdptests/fast/backends/fsdp_utils/test_safetensors_load.py,tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py,test_safetensors_load.py;test_reference_models.py(the fixture's stand-in for the agreement takes the new argument)Checklist
pre-commithooks pass on the changed filespytest tests/fast/backendsis greenpython3 train_diffusion.py --helpstill parses (no flag changed)