Repository navigation
Native FSDP2: sync initial trainable weights across ranks; shard FastSentenceTransformer and FastDiffusionModel - #15012
Conversation
device_map defaulted to "auto", so under torchrun / accelerate launch every rank spread the model over all visible cards. A 2-rank native FSDP2 run died in transformers' infer_auto_device_map (IndexError) before training, in LoRA, QLoRA and full finetuning. An automatic map now becomes the rank's own device, as in FastLanguageModel / FastModel; a device the caller named is kept.
…P2=1 Native FSDP2 shards inside Unsloth's Trainer.__init__ wrapper, which only FastLanguageModel / FastModel loads (and DecisionTrainer) installed. A FastSentenceTransformer encoder (BERT, ModernBERT) never loads through them, so under UNSLOTH_FSDP2=1 torchrun its SentenceTransformerTrainer trained with plain DDP: nothing sharded, no message. import unsloth now installs the wrapper when the flag selects native FSDP2.
…fast encoder path get_peft_model accepted random_state but never used it for BERT / ModernBERT style encoders, so the adapters depended on the RNG history and every torchrun rank drew its own. FastModel seeds with transformers.set_seed(random_state); this path now does the same.
DDP broadcasts rank 0's parameters when it wraps the model. fully_shard keeps each rank's own slice, so a trainable tensor initialised without a common seed (an unseeded adapter, a fresh head) was sharded as a mix of the ranks' values and the ranks trained a model none of them started from. shard_model compares a checksum per trainable tensor over the mesh and broadcasts the first rank's values of those that differ, with a one-line notice.
…ank sync NaN != NaN, so a checkpoint with non-finite weights (tiny Llama4) was reported as differing across ranks and re-broadcast. The checksum comparison is now NaN-aware.
|
@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: c7e93f0fb0
ℹ️ 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".
| torch.stack( | ||
| ( | ||
| p.detach().sum(dtype = torch.float64), | ||
| torch.linalg.vector_norm(p.detach(), 1, dtype = torch.float64), | ||
| ) |
There was a problem hiding this comment.
Compare full parameter contents before skipping synchronization
When ranks hold different tensors with the same sum and L1 norm, this check treats them as identical and skips the broadcast; for example, [1, -1] and [-1, 1] both produce (0, 2). Likewise, if both tensors contain a NaN, both statistics can be NaN and the later NaN-aware comparison masks differences in all remaining elements. In these cases FSDP2 still shards a mixture of rank-local initial weights, defeating the synchronization this change is intended to provide, so the decision needs a collision-resistant/full-content comparison or an unconditional broadcast.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 14402bb. The per-tensor check is now a content fingerprint: sum, L1 norm, a sum weighted by a position-dependent cos(i * golden ratio), and the count of non-finite elements, with non-finite values mapped to fixed finite stand-ins first. A permutation such as [1, -1] vs [-1, 1] now differs in the weighted term, and a NaN shared by both ranks no longer hides differences elsewhere, while identical NaN patterns still agree. A full finetune whose ranks agree still sends only the fingerprints. New cases test_a_permuted_adapter_is_not_mistaken_for_the_same and test_a_shared_nan_does_not_hide_other_differences fail on the previous head and pass now.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 14402bbbf7
ℹ️ 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".
| chunk = flat[start : start + _FINGERPRINT_CHUNK].to(torch.float64) | ||
| bad = ~torch.isfinite(chunk) | ||
| chunk = torch.nan_to_num(chunk, nan = 3.0, posinf = 5.0, neginf = -7.0) | ||
| index = torch.arange(start, start + chunk.numel(), dtype = torch.float64, device = chunk.device) | ||
| weight = torch.cos(index * 0.6180339887498949) |
There was a problem hiding this comment.
Bound the fingerprint's temporary allocation
When full-finetuning a model with a trainable tensor of at least 16,777,216 elements on GPU, one iteration creates several 128 MiB float64 buffers (chunk, index, weight, and the multiplication temporary), plus the finite mask. Because this runs before fully_shard while the complete model is still resident, the roughly 400–500 MiB peak can OOM a job whose model would otherwise fit under FSDP2; use a substantially smaller chunk or a fingerprint implementation that does not materialize multiple float64 arrays.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in ece2522: the fingerprint chunk is now 1,048,576 elements, so each iteration holds a few 8 MiB float64 buffers (chunk, index, weight, product, mask), about 40 MiB in total, before fully_shard, whatever the tensor size. A large tensor just takes more chunks; the result is the same.
…ffers before sharding) [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! 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". |
|
The They reach a real CUDA call under the CPU spoof. Either keep the model on CPU in the test, or gate it on
|
The loader reads device properties even with device_map = "cpu", so the CPU-only CI job failed with "Torch not compiled with CUDA enabled". [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! 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". |
…wrapped the Trainer (#15427) ## Problem On a non-CUDA install (Intel XPU, Ascend NPU, MLU, ...), `UNSLOTH_FSDP2=1` is routed to accelerate's FSDP2 at import time, and `unsloth_fsdp2_native_requested()` is False. #14760 added `reclaim_native_fsdp2_for_cpu_trainer` so that a `TrainingArguments(use_cpu=True)` Trainer still shards natively (accelerate runs it as MULTI_CPU, which never builds its FSDP plugin). That reclaim lives inside the `Trainer.__init__` wrapper, but the import-time installer `install_native_fsdp2_trainer_init` (#15012) returns early whenever native FSDP2 is not requested, so it never installs the wrapper on this route. FastLanguageModel / FastModel loads install the wrapper themselves, so they are unaffected. A plain `Trainer` after `import unsloth`, or a FastSentenceTransformer encoder that loads without FastModel, trains with the model unsharded and no message, even though the launch step printed that FSDP2 shards it. ## Fix `install_native_fsdp2_trainer_init` also installs the wrapper while the non-CUDA export is pending (`_NON_CUDA_EXPORT is not None`). It still returns False there, and a non-CPU Trainer on that install keeps accelerate's FSDP2 exactly as before (the reclaim returns False and changes nothing). ## Before / after 2-rank gloo CPU world, XPU build markers (`torch.version.xpu`), only the two import-time steps of `unsloth/__init__.py` run, then a plain Trainer on a tiny Llama LoRA with `use_cpu=True`. | Check | main (0ea0473) | this branch | |---|---|---| | Trainer wrapper installed | no | yes | | Model sharded by native FSDP2 | no | yes | | `ACCELERATE_USE_FSDP` left exported | true | unset | | Accelerator distributed type | MULTI_CPU | MULTI_CPU | | `test_xpu_install_cpu_trainer_shards_natively_without_a_loader` | FAIL | PASS | Head also passes `tests/test_fsdp2_native_trainer_args_gloo.py`, `tests/test_fsdp2_native_trainer_init_any_loader_gloo.py` and `tests/test_fsdp2_non_cuda_accelerate_route.py` (29 passed) on torch 2.13 / transformers 5.17, and the two XPU reclaim tests on torch 2.6 CPU / transformers 4.57.6, torch 2.10 and torch 2.14. ## Not covered - No real XPU / NPU / MLU hardware: the non-CUDA install is simulated through `torch.version` build markers, as the existing #14760 test does. - `import unsloth` itself cannot run on a CPU-only host, so the test executes the real `fsdp2_launch` functions in the order `unsloth/__init__.py` calls them, with the real `_unsloth_trainer_init` source.
Native FSDP2 (
UNSLOTH_FSDP2=1under torchrun) already shards and trains models loaded through FastLanguageModel, FastModel, FastVisionModel and FastTextModel. A loader sweep over tiny copies of every supported architecture found four gaps for the other loaders and one that affects every loader.Changes
fully_shardkeeps each rank's own slice. A trainable weight initialised without a common seed on each rank (an adapter whose loader ignoredrandom_state, a fresh head) therefore became a mix of the ranks' values, and the ranks trained different models without any error.shard_modelnow compares a float64 checksum per trainable tensor across the mesh and broadcasts the first rank's values for the tensors that differ (only those, so a full finetune is not re-sent). Identical non-finite weights count as agreeing.__init__wrapper that the FastLanguageModel / FastModel loaders install. An encoder loaded through FastSentenceTransformer never installed it, so its Trainer silently trained as plain DDP with nothing sharded. The wrapper is now installed atimport unslothwhen the flag selects native FSDP2.random_stateon the fast encoder path, asFastModel.get_peft_modeldoes. Before, the adapters depended on whatever ran first, and every rank drew its own.device_map = "auto"spread every rank over all visible cards and crashed at load.FastDecisionModel is still refused under native FSDP2 with a clear message at Trainer init. Single GPU and DDP paths are unchanged.
Tests
Each new test fails on main and passes here (CPU gloo, 2 ranks where distributed):
tests/test_fsdp2_native_sync_initial_weights_gloo.py: ranks with different trainable weights end bitwise equal aftershard_model(main: max difference 0.084), agreeing ranks are left untouched, identical NaN weights count as agreeing.tests/test_fsdp2_native_trainer_init_any_loader_gloo.py: a Trainer built on a model that no Unsloth loader patched still shards under the flag (6 cases).tests/python/test_fast_sentence_transformer_lora_seed.py: the samerandom_stategives the same adapters.tests/diffusion/test_diffusion_distributed_device_map.py: under a distributed launch each rank'sdevice_mapis its own device.GPU (2 ranks, fp32): ModernBERT LoRA and full finetuning match one GPU with a step-0 grad-norm difference of 0.0; a Qwen3 sentence-transformer LoRA matches to 2e-7; DiffusionGemma LoRA and BERT-tiny QLoRA differ from one GPU exactly as much as plain DDP does.
Not covered
The CPU FSDP2 suite was run to 40% on this branch (139 passed, 7 skipped, 4 gloo timeouts that pass alone on both main and this branch). Not measured here: gradient accumulation parity and graph-break counts for these loaders.