Repository navigation
Native FSDP2: memory-scalable 16-bit loading (each rank reads only its shard), and the fp16 start scale on sub-meshes - #15225
Conversation
sharded_loading(tp_mesh) / load_tensor_parallel(...) make from_pretrained build the model on meta and stream the safetensors checkpoint: replicated tensors whole, attention / MLP projections as this rank's slices (per-part slices for fused qkv and packed gate_up). The slices stay plain tensors tagged with their full shape, so get_peft_model creates full-size LoRA factors with the same init as one GPU; apply_tensor_parallel then wraps them into the DTensors v1 builds. A forward before apply_tensor_parallel is refused. 16-bit safetensors checkpoints only; quantized loads are refused.
shard_model(model, FSDP2Config(mesh = mesh['dp'])) now accepts a model sharded by apply_tensor_parallel(model, mesh['tp']) when the two meshes are the dimensions of one (dp, tp) mesh covering the world. The frozen tp shards stay replicated over dp (fully_shard(ignored_params), torch 2.7+); FSDP2 shards the trainable LoRA DTensors over dp and reduces their tp Partial gradients itself. Refused: no mesh / a mesh that is not the dp dimension, shard_frozen, cpu_offload, torch < 2.7, and trainable per-head norms (their tp sum is a Parameter hook, and FSDP2 replaces the Parameters). - The trainable-weight agreement compares and broadcasts the local tensors of DTensor parameters. - Fused / packed layouts are also recorded on the owning module, so adapter saving and gathered grads keep the 1-GPU order after FSDP2 replaces the Parameter objects. - tp_clip_grad_norm_ handles 2-D gradients (each element counted once over its replicas). - native_clip_grad_norm_ counts FSDP2's _StridedShard as a shard dimension: newer torch does not report it as is_shard(), so those norms were not reduced over dp. - save_tp_adapter accepts a tp mesh smaller than the world when the dp dimension covers the rest.
The Trainer no longer refuses a model sharded by apply_tensor_parallel (tp only, or dp x tp after shard_model over mesh['dp']). tp_native.tp_trainer_setup runs around Trainer.__init__: - accelerate does not wrap the tp ranks in DDP (prepare_model keeps only the autocast wrap; native FSDP2 prepares a dp x tp model itself), - the dataloader is sharded over dp only, so the tp ranks of a replica read the same batches, - clip_grad_norm_ uses tp_clip_grad_norm_, and float16 gets a ShardedGradScaler (one inf decision for all ranks, initial scale divided by dp), - trainer.save_model() writes the standard 1-GPU adapter (collective), - the generated TRL trainers skip their trailing model.for_inference() (it would route the decoder layers onto decode paths outside the tensor parallel regions). The loss needs no change: the token count gathered over the world counts each replica's tokens tp times and the Trainer's loss scale multiplies by dp * tp, which FSDP2's mean over dp turns into the token mean over the dp replicas. Refused with a reason: Trainer checkpoints / resume, evaluation, bitsandbytes / paged / GaLore optimizers, DeepSpeed, accelerate FSDP / ParallelismConfig, iterable datasets, model_init, and a tp mesh that does not cover the world without shard_model over the dp dimension.
…A init on sharded_loading slices [skip ci]
…cheduler [skip ci]
…allel setup [skip ci]
…inear weights fsdp2_sharded_loading() / load_fsdp2_sharded() / UNSLOTH_FSDP2_SHARDED_LOAD=1 build the model on meta and read every nn.Linear weight except the output head as this rank's FSDP2 dim-0 chunk from safetensors (the rest whole), reusing the tensor parallel sharded loader (now shared: _fill_from_checkpoint, _SliceReader.rows, _sharded_from_pretrained). shard_model swaps the chunks for full-shape meta placeholders, fully_shards and installs each chunk as its FSDPParam local shard; chunks the layout keeps replicated are all-gathered back. 16-bit only.
…multiplier, not the mesh size The Trainer multiplies each rank's loss by num_processes (over tp), so on a sub-mesh smaller than the world (two 2-rank meshes of 4 ranks) dividing by the mesh size left the start scale 2x too large and the first step overflowed. CP = 2, DP = 1 shards over the world, where both agree (pinned by a gloo test).
… renames (VLMs) transformers 5 VLMs save model.layers.* for model.language_model.layers.*; the sharded reader now applies the model's WeightRenaming mapping (and 4.x _checkpoint_conversion_mapping) to find each tensor, and refuses keys a WeightConverter builds from several tensors. Adds a tiny Qwen2.5-VL native FSDP2 sharded-load parity case.
# Conflicts: # unsloth/models/tp_native.py
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1327596e68
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| for module, name in where: | ||
| module._parameters[name] = meta | ||
| pending[(id(module), name)] = (local, info) |
There was a problem hiding this comment.
Remap ignored parameters when replacing preloaded weights
When FSDP2Config.ignored_params contains a sharded-loaded linear weight, replacing that parameter with meta leaves the configuration pointing to the old chunk. Subsequently, gather_replicated cannot match the replacement against the replicated set, and shard_model_layout filters the stale parameter out because it is no longer in module.parameters(). The explicitly ignored weight is therefore sharded instead of reconstructed and kept replicated. Update the ignored-parameter references alongside these replacements so this existing configuration option retains its semantics.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in the latest push. begin_shard now remaps FSDP2Config.ignored_params when it swaps a sharded-loaded chunk for its meta placeholder. The caller's set is updated in place, and any other iterable is copied into a new set on the config. shard_model then passes that set to gather_replicated along with the internal ignored set. The result: an explicitly ignored weight is all-gathered whole, stays out of fully_shard, and the caller's set ends up holding the live replicated parameter, the same as on the full-load path.
Test: test_sharded_loading_matches_full_load_shard_model has two new cases (llama-...-full-ignore and llama-...-lora-ignore), 2 gloo ranks, intermediate_size = 37 so the chunks are uneven. Each one ignores layers.0.mlp.down_proj (trainable in full FT, frozen base under LoRA). It checks that every ignored_params entry is a live, non-DTensor, whole parameter on both paths, that every parameter and padded FSDP2 shard is bitwise equal to the full load, and that 3 training steps match bitwise. Both cases failed before the fix (the set still held the stale chunk) and pass now.
| start, stop = _chunk_rows(rows, world, rank) | ||
| local = reader.rows(key, start, stop).to(device = device, dtype = old.dtype) | ||
| new = nn.Parameter(local.contiguous(), requires_grad = old.requires_grad) |
There was a problem hiding this comment.
Handle DoRA initialization before exposing partial base weights
With more than one rank, attaching an adapter with LoraConfig(use_dora=True) after sharded loading fails during get_peft_model, before shard_model can run. The linear retains its full out_features, so PEFT creates a full-sized lora_B @ lora_A, but DoRA's initialization adds that matrix to this partial base weight to compute its magnitude, causing a row-dimension mismatch. Native FSDP2 already supports DoRA through the full-load path. Provide shard-aware magnitude initialization or explicitly reject this combination before PEFT initializes the adapter; the current check of init_lora_weights does not cover DoRA with its default initialization.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in the latest push by refusing the combination with a clear error. A sharded load with more than one rank wraps PEFT's DoraLinearLayer.update_layer, which is where DoRA computes its magnitude. If the base layer's weight is a sharded-loaded chunk, get_peft_model now raises a ValueError before PEFT computes the norm. The message names use_dora and says to load the full model (drop fsdp2_sharded_loading / UNSLOTH_FSDP2_SHARDED_LOAD) to train DoRA under native FSDP2. The wrapper does nothing for any other base layer, so DoRA on a full load is unchanged. begin_shard also refuses use_dora on a sharded-loaded model as a backstop, next to the existing init_lora_weights check.
Test: test_sharded_loading_refuses_dora (2 gloo ranks, llama with intermediate_size = 37, LoraConfig(use_dora = True) with its default init) checks that get_peft_model on the sharded-loaded model raises the use_dora message, and that the same config on a full load in the same process still succeeds. Before the fix it failed with PEFT's The size of tensor a (8) must match the size of tensor b (16).
…arly FSDP2Config.ignored_params naming a sharded-loaded weight now follows the meta placeholder and the gathered whole parameter, so it stays replicated exactly as on the full load. DoRA's magnitude init on a sharded-loaded chunk is refused at get_peft_model time with a message naming use_dora. [skip ci]
…ai/unsloth into dh/s6-fsdp2-sharded-load # Conflicts: # unsloth/models/fsdp2_load.py [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 674e0d6bdc
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| for module in model.modules(): | ||
| if isinstance(module, nn.Linear) and id(module._parameters.get("weight")) in owners: | ||
| guards.append(module.register_forward_pre_hook(_refuse_unsharded_forward)) | ||
| model.__dict__[_GUARD] = guards |
There was a problem hiding this comment.
Handle sharded linear copies created by modules_to_save
When PEFT is attached with a sharded linear in modules_to_save (for example, target_modules=["q_proj"] and modules_to_save=["down_proj"] through plain PEFT or FastModel), ModulesToSaveWrapper.update deep-copies that linear, including this forward pre-hook. However, begin_shard removes only the original handles stored on the root model, leaving the copied layer's hook installed. Consequently, the first training forward still raises “shard it first” after shard_model has completed. Handle these copied layers explicitly, including preserving their chunk metadata, or reject this combination before PEFT copies the partial weights.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in the latest push. Two parts: Parameter.__deepcopy__ drops the chunk tag, so begin_shard now gives each modules_to_save copy that is still identical to its sharded-loaded original the original's tag, and the copy is then swapped to a full-shape placeholder and sharded like the full load's copy. The deep-copied forward guard is removed by function from every module, not only through the handles stored on the root. New parity case llama ... lora_mts (target_modules = ["q_proj"], modules_to_save = ["down_proj"], uneven chunks, 2 gloo ranks): it failed with "shard it first" before, and now every parameter, padded shard and 3 training steps are bitwise equal to the full load, with the same byte counters.
…ed-loaded linears [skip ci]
…ai/unsloth into dh/s6-fsdp2-sharded-load [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7c8f69c503
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| rename_source_key, | ||
| ) | ||
|
|
||
| transforms = get_model_conversion_mapping(model) |
There was a problem hiding this comment.
Preserve load-specific key mappings during checkpoint lookup
When sharded loading is used with a load-specific key_mapping, this reconstructs only the model's default conversions and drops the mapping passed to from_pretrained. This affects existing text-only loading paths: FastModel.from_pretrained calls _apply_text_only_key_mapping to map VLM checkpoint prefixes such as language_model.model.* onto standalone decoder keys such as model.*. The initial meta load honors that mapping, but _fill_from_checkpoint subsequently cannot resolve those parameters and raises “found no checkpoint tensor,” preventing the new native FSDP2 loading path from loading these models. Pass the load's mapping into alias resolution, or reuse the conversions retained by the loaded model.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in the latest push. _fill_from_checkpoint now passes the load's key_mapping (from the from_pretrained kwargs) into _checkpoint_aliases: on transformers 5 it goes into get_model_conversion_mapping(model, key_mapping = ...), so it is applied with the model's own renames in one pass, and on 4.x it replaces _checkpoint_conversion_mapping as from_pretrained does. New parity case llama ... lora remap: the checkpoint is saved with VLM-style keys (language_model.model.*, language_model.lm_head.*) and loaded with the text-only mapping Unsloth uses. It failed with "found no checkpoint tensor for 'model.embed_tokens.weight'" before; now the shards, 3 training steps and byte counters match the full load bitwise.
…int keys [skip ci]
…ai/unsloth into dh/s6-fsdp2-sharded-load [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
## Summary `studio/backend/tests/test_model_memory_settings.py::TestNoNestedHelperIsUsedBeforeItsDef::test_every_nested_def_precedes_its_calls` fails on main, so `(Python 3.13, g-r)` is red on unrelated PRs (for example #15225): ``` AssertionError: UnboundLocalError at runtime: _try_auto_vulkan_cpu_fallback called at 8198, defined at 8232 ``` #14521 (load GGUF on CPU when the auto-selected Vulkan driver hangs) added the nested `_recover_vulkan_stall` inside `load_model`. It calls `_try_auto_vulkan_cpu_fallback`, which is defined about 40 lines further down. Today this does not raise: all three callers of `_recover_vulkan_stall` sit below both definitions, and a closure looks the name up when it runs. But the guard's rule is "a nested helper is defined above every textual use", because the looser version (the call is fine as long as every caller of the caller runs late enough) already shipped broken once and aborted every full-offload launch. Keeping that simple rule true is cheaper than teaching the guard call-graph ordering. ## Change - Move `_recover_vulkan_stall` (unchanged, 19 lines) from just above `_vulkan_stall_pending` to just below `_try_auto_vulkan_cpu_fallback`. It is still above its first caller. Only `def`s sit between the old and new spots, and the defaults are literals, so nothing evaluates differently. ## Verification - The diff is a pure move: every removed line is added back once. - `test_every_nested_def_precedes_its_calls`: fails on main, passes with this change. - `test_vulkan_no_device_cpu_route.py`, `test_gpu_init_crash_message.py`, `test_load_mode_fit_matrix.py`, `test_vram_budget_settings.py`, `test_model_memory_settings.py`: `1 failed, 2402 passed` on main (the guard), `2403 passed` with this change.
…d copy (#15264) `tests/test_tp_native_gloo.py::test_tp2_x_fsdp2_dp2_matches_one_process[llama-True-lora_kwargs4]` fails now and then in `Repo tests (CPU, rest)` on unrelated PRs (#15159, #15174, #15217, #15218, #15222, #15225) with only `AssertionError: base_model.model.lm_head.weight`. Gradients, losses and norms all match in those runs. Only the saved `lm_head` copy differs. ## Cause The test, not the product. That case trains a full `lm_head` copy (`modules_to_save`, 512000 entries) with AdamW at lr 1e-2 and the default eps of 1e-8. At g = 0, Adam's `g / (sqrt(v) + eps)` has slope lr / eps = 1e6. Measured on main on this host: | | value | | --- | --- | | median step-0 lm_head grad | 5.7e-6 | | entries with step-0 grad below 1e-8 | 313 | | step-0 grad of the 10 worst saved-weight entries | 4e-11 to 7e-9 | | worst saved-weight diff / tolerance | 0.46 | So reduction-order noise of about 1e-12 on a near-zero gradient becomes about 5e-6 of weight. That is already half the `atol = 1e-5` here. A runner whose CPU kernels sum in a different order goes over it. ## Fix - Both arms use `AdamW(eps = 1e-6)`. The optimizer is still identical on both sides, and 1e-6 is small next to the typical gradient, so the head still trains. The worst entry drops to 0.0075 of the tolerance (60x headroom). - The saved-weight assert now keeps `assert_close`'s mismatch detail. It used to print only the key, which is why the CI logs never showed how far off the weight was. ## Verification - `tests/test_tp_native_gloo.py`: 38 passed. - Sabotage on the last step, after the norms are taken, so only the saved weight can catch it: - TP arm skips the lm_head update: fails, 511627 / 512000 mismatched, max abs diff 1.0e-2. - Each dp half's lm_head gradient scaled by +/-15% (a stand-in for a missing dp reduction): fails, 493693 / 512000 mismatched, max abs diff 8.1e-4. - No sabotage: passes.
Builds on #15174 (tensor parallel v2, merged): it reuses and generalises its safetensors slice reader.
Why
Under native FSDP2 (
UNSLOTH_FSDP2=1) every rank loads the whole model beforeshard_model, so a model that doesnot fit one GPU cannot be loaded at all, even though FSDP2 would only keep 1 / world of it per rank afterwards.
Qwen3-8B in 16-bit (16.4 GB) on 2x T4: every rank runs out of memory at load.
What
Sharded loading (opt-in).
or
UNSLOTH_FSDP2_SHARDED_LOAD=1next toUNSLOTH_FSDP2=1, which runs FastLanguageModel / FastModel /FastVisionModel
from_pretrainedinside the context (outermost call only). Nothing changes without either.nn.Linearweight except the output head is read from safetensors as thisrank's FSDP2 dim-0 chunk (the rows
fully_shardkeeps,torch.chunksemantics, so uneven and empty chunksmatch), via
get_slice, so only those bytes are read. Everything else (embeddings, norms, biases, buffers) isread whole, as the full load does.
nn.Linearkeeps its full features, soget_peft_modelbuilds full-size LoRA with the same init as one GPU. A forward beforeshard_modelis refused.shard_modelswaps each chunk for a full-shape meta placeholder (so the layout planner sees the whole model),runs
fully_shard, and installs the chunk as the FSDPParam local shard (padded asfully_shardpads it). Thefull weight never exists on any rank. A chunk the layout keeps replicated (fit layout frozen weights,
minority-dtype parameters) is all-gathered back, which is exactly what the full load holds.
tp_native.pyis now shared (_fill_from_checkpoint,_SliceReader.rows,_sharded_from_pretrained) and maps checkpoint keys through transformers' conversion renames, so VLMs whosecheckpoints use the legacy names (
model.layers.*formodel.language_model.layers.*) load; tensors aWeightConverterbuilds from several checkpoint tensors are refused with a clear message.rank-0 CPU quantize + scatter is a follow-up), 2-D (HSDP) meshes,
cpu_offload,shard_placement_fn, amesh other than the one loaded over, and weight-dependent LoRA inits (PiSSA, OLoRA, ...).
fp16 start scale. The Trainer multiplies every rank's loss by
num_processes(over the tensor parallelsize), so the fp16 start scale must be divided by that, not by the FSDP2 mesh size. They differ on a sub-mesh
smaller than the world: two 2-rank meshes of 4 ranks started 2x too high and the first step overflowed. CP = 2,
DP = 1 shards over the world, where both agree (now pinned by a test).
Tests (CPU gloo, 2 and 4 ranks; every new test fails before except the CP = 2 pin)
tests/test_fsdp2_native_sharded_load_gloo.pyagainst the full load +shard_modelon the same checkpoint(tiny models saved as multi-file safetensors):
intermediate_size = 37(uneven chunks), LoRA, sharded layoutByte counters: each rank's sliced bytes equal its own chunk sizes, the two ranks together read every sharded
tensor exactly once, and whole reads equal the replicated parameters. Plus refusals,
_chunk_rowsagainsttorch.chunkfor many shapes, and the env flag being inert withoutUNSLOTH_FSDP2.tests/test_fsdp2_native_fp16_scale_mesh_gloo.py: CP = 2, DP = 1 (passes before and after: no bug there) and two2-rank sub-meshes of 4 ranks (before: start scale 32768 instead of 16384).
Existing suites unchanged:
test_tp_native_gloo.py+test_tp_native_oracle.py86 passed, 1 skipped;test_fsdp2_native_*+test_fsdp2_perf_layout_gloo.py+test_context_parallel_fsdp2_gloo.py268 passed,2 skipped.
GPU (Kaggle 2x T4, torch 2.14.1, transformers 5.17.0, PEFT 0.21.2)
Qwen3-0.6B, LoRA r16 on all 7 projections, fp16 autocast, AdamW 2e-4, seq 512, bs 2 per rank, 20 steps, sharded
layout, custom loop:
shard_modelhash identically (sha256 over every local tensor) on both ranksfor the full and the sharded load.
loss diff 0.0094 (mean 0.0021) over 20 steps, inside the A/A pair's 0.0082 (mean 0.0018).
UNSLOTH_FSDP2=1,SFTTrainer, fp16 GradScaler, 10 steps) withUNSLOTH_FSDP2_SHARDED_LOAD=1vswithout: the sharded path engaged on both ranks (byte counters recorded), load peak 0.708 vs 1.118 GiB, max abs
loss diff 2.5e-4.
Qwen3-8B 16-bit (16.4 GB, does not fit one T4):
Each rank read 6.95 GB of linear-weight rows (exactly half of all linear weights) and 2.49 GB whole (embeddings,
head, norms). Load took 26 to 40 s per rank.
Not covered
cpu_offload: refused for now.