Skip to content

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
fsdp/read-shards-from-safetensorsfrom
fsdp/read-lora-shards-from-safetensors
Draft

zhihengy wants to merge 34 commits into
fsdp/read-shards-from-safetensorsfrom
fsdp/read-lora-shards-from-safetensors

Conversation

@zhihengy

@zhihengy zhihengy commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

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

  • The adapter is built as on 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 on main.
  • What is new is that rank 0's base has no weights at that point. PEFT moves a new adapter to its base layer's device, and a meta base would drop the values, so base_stand_in_for_lora gives 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 full torch.empty would 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_state and dcp.load take 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_fsdp then 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_weights says 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:
    • PEFT must not read the base weights' values while it builds the adapter: --lora-init-weights gaussian or kaiming-uniform for 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.
    • A saved adapter must be a LoRA (by its PEFT type: AdaLoRA's config is a LoraConfig too) whose adapter_model.safetensors holds adapter tensors only. PEFT loads any other tensor it saved (a bias with bias="all", a module to save) into the base, where the read of the base checkpoint would replace it.
  • The rank agreement of perf(fsdp): every rank reads its own shards from the checkpoint's safetensors files instead of rank 0 loading and broadcasting them #389 (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 same all_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 on main.
  • build_component checks 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_grad the 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, .bin checkpoints and native-package backends take the existing path; for those LoRA models the one all_gather_object is 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.

check result
tests/fast/backends/fsdp_utils/test_safetensors_load.py saved adapters: no weights materialized, no full-model broadcast, base from the files, adapter values from the adapter files, nothing trainable. New adapter (gaussian, 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 .bin is 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 step
tests/fast-gpu/backends/fsdp_utils/test_safetensors_load.py 2x H200, NCCL, two components: for saved adapters and for a new adapter, each rank's adapter shards and generator state equal the ones the full broadcast leaves, and a forward on the model gives the dense result with the adapter, GPU-resident and CPU-offloaded; a LoRA model with a persistent buffer loads under both (moving the adapter broadcast after the buffers' move to the GPU fails this)
tests/fast/backends, tests/fast/test_train_diffusion.py (no GPU visible) 342 passed
two ranks whose adapter configs target different modules (same tensor count), 2x H200, not in CI rank 1 raises Missing key(s) in state_dict from the full broadcast, as on main; before the agreement compared the adapter it loaded with NaN adapter shards under --deterministic-mode
tests/fast-gpu/backends/fsdp_utils/test_reference_models.py passes
real WanTransformer3DModel + PEFT through DiffusersModelBackend and load_fsdp_models, 2x H200, not in CI new adapter (gaussian, 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_grad and sha256 of the full broadcast, and the same generator state on both ranks. PiSSA takes the broadcast
the same without LoRA (#389's comparisons, on this head): Wan in three layouts; SD3, Wan and Flux at fp32, bf16 and fp16 masters 24 and 36 scenario-ranks identical to the broadcast
H3 (no adapter) on 2x H200, critic + teacher, #389's harness sha256 of every parameter shard and buffer equal to main'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
DMD2 H3 e2e through Ray (no adapter), 2x H200, #366's recipe arguments and script, --deterministic-mode, at 0314dd6f (before the adapter agreement of b8337f87, which a model without an adapter passes with an empty value) the three models each log every rank reads 14 safetensors files; the 9 metric series (22 points) equal #366's recorded standard bit for bit
pre-commit run --files passes

Not 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 step
  • miles/backends/fsdp_utils/checkpoint.py: base_state, adapter_state, adapter_shapes; holds_on_every_rank(condition, same=); the adapter broadcast in load_safetensors_to_fsdp
  • tests/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-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)

…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
…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
… the norm of the base weights for any magnitude the file lacks
…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
@zhihengy zhihengy changed the title perf(fsdp): a model with LoRA reads its base shards from the safetensors files too; every rank builds the adapter as rank 0 does perf(fsdp): a model with LoRA reads its base shards from the safetensors files too; rank 0 broadcasts only the adapter Nov 17, 2026
…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
Rockdu force-pushed the fsdp/read-shards-from-safetensors branch from d833ec3 to 23babd5 Compare November 23, 2026 18:29

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant