Repository navigation
Native FSDP2: fully_shard per block and root for every model, LoRA, QLoRA and full finetuning (UNSLOTH_FSDP2=1) - #14273
Conversation
…lass and 3D shape FSDP2 rebuilds the gathered weight as a plain nn.Parameter and the FSDPParam wrapper only carried the bitsandbytes quant attributes, so the unsloth-zoo 4-bit MoE paths, which pick their kernel with isinstance(w, Params4bit) and read a 3D expert stack's logical shape from _original_shape, fed the packed bytes to a dense matmul (ModuleList experts: contraction dimension of mat_a and mat_b must match; transformers v5 3D experts: size mismatch). gpt-oss bnb-4bit experts silently fell back to the per-expert loop. The wrapper now restores the class the weight was sharded from on the gathered parameter (same object and storage), carries _original_shape and Params4bit.module, and marks the gathered weight _unsloth_fsdp2_gathered so unsloth-zoo re-keys its address-keyed NF4 pointer tables per call.
load_state_dict recorded the outer DTensor while offload() looks a DTensor up by its local shard, so a resume from an offloaded sharded checkpoint left the state on the host untracked and the next step failed on a cuda/cpu device mismatch.
…-in UNSLOTH_FSDP2=1 under torchrun
Native FSDP2 all-gathers every block's frozen LoRA base weights in forward and again for the backward / checkpoint recompute, which DDP never moves. When the model fits on one GPU, pass frozen params as ignored_params (replicated like DDP), keep gathered trainable weights resident (reshard_after_forward False), collapse a small trainable set (LoRA) into one root unit, and prefetch the next block explicitly. Standalone module; native shard_model opts in.
…cated, split mixed optimizer groups, env config, bnb optimizer swap
Under FSDP2 the 4-bit weights are packed in float16 / bfloat16. The vision loader's patch_model_and_tokenizer then runs module.to(_pre_set_compute_dtype) (gpt-oss bnb-4bit down_projs in float16, forced float32 models), which cast the packed words to float32 values and corrupted the weights. Show them as uint8, the bitsandbytes default, for that pass and restore the float view afterwards.
save_pretrained_merged gathered the shards with offload_to_cpu, which moves everything except the packed 4-bit weights to the CPU. merged_4bit merges with PEFT's Linear4bit.merge, so the dequantized base weight stayed on the GPU while the LoRA delta was on the CPU, and the save raised a device mismatch. Do not offload for the merged_4bit methods.
…n the GPU [skip ci]
…lly_shard wrap fsdp2_native_quant.native_quant_context goes around the fully_shard calls of the native wrap (fully_shard per block, then the root): packed 4-bit bytes are stored in the compute dtype so they shard, the all-gathered weight is a Params4bit with its QuantState, and mixed precision never casts packed bytes. The accelerate source check that decides float storage is skipped for the native wrap, which never upcasts the model. after_native_shard installs the DCP handling of 4-bit weights and reports any trainable parameter FSDP2 does not manage. A model without 4-bit weights is not touched.
Under FSDP2 the packed NF4 bytes are stored as the compute dtype (bnb_4bit_quant_storage) so they can be sharded. _eligible accepted only uint8, so every NF4 Linear4bit forward under FSDP2 fell back to bitsandbytes. Accept a contiguous (N, 1) float buffer of the same bytes, size checks in bytes, and hand the kernels the uint8 view. uint8 weights take the same path as before.
The adapter save gathers the frozen embeddings PEFT writes. They were matched by parameter identity, recorded before the gather resharded the model; a parameter an eval forward left unsharded is a different object from the DTensor the gather then sees, so the embeddings stayed sharded and the save failed. Match them by the embedding module's name instead.
…n full DCP state dicts, uint8 gathered 4-bit weights - reduce_unsharded_trainable_grads summed fp16 / bf16 gradients in their own dtype before dividing by the world size: two fp16 gradients of 40000 became inf. Sum in float32. - A full (not adapter-only) DCP state dict of a sharded 4-bit model dropped bitsandbytes' absmax and quant_state entries, so the checkpoint could not be dequantized after a reload. Build it without them (DCP cannot name them on a DTensor) and add them back under their usual keys; loading drops them again. - Gathered 4-bit weights are rebuilt as the uint8 bitsandbytes writes without FSDP2 (and keep _original_shape), so a merged_4bit save matches a single-GPU checkpoint instead of writing float typed packed bytes.
…te dicts installed shard_model's 4-bit context is native_quant_context with the mixed precision param_dtype as the packed storage dtype (the accelerate source check no longer decides it), and a 4-bit model gets the DCP state dict handling of sharded bitsandbytes weights after the wrap.
…models FastBaseModel.post_patch_model switched every distributed run to torch non-reentrant checkpointing, for DDP's 'marked ready twice' (#3713). FSDP2 has no DDP reducer: each unit reduce-scatters in its own post-backward hook, recompute included. Under FSDP2 the non-reentrant path also crashed hybrid GDN models (Qwen3.5: CheckpointError, different number of saved tensors on recompute of the compiled block) and dropped unsloth_stream / the offloaded checkpointer. Keep the reentrant Unsloth checkpointer when FSDP2 is requested; DDP keeps non-reentrant.
…ch, per-unit reshard, placement fn), default-path test
…her cast), float64 clip accumulation, root reshard_after_forward=False explicit
… skipped in a no-sync micro-step
…ABC-safe fully_shard retry, replicate_minority_dtype knob, cross-rank drift tests
… untouched Under FSDP2, prepare_fsdp2_qlora stores the packed NF4 bytes as the compute dtype so they can be sharded. _eligible accepts only uint8, so every Linear4bit forward of a FastModel family (Gemma3, Gemma4, Qwen3.5) fell back to bitsandbytes' dequant under FSDP2. When FSDP2 QLoRA prepared the model (kernels.utils._FSDP2_QLORA_PREPARED), _forward hands the eligibility check and the kernels the uint8 view of a contiguous (N, 1) float buffer; _eligible and _linear are unchanged, so without FSDP2 the override runs exactly as before. Tests from f99c672 (bit exact vs bitsandbytes on float-packed bytes) plus: without FSDP2 a float-packed weight still falls back, uint8 keeps the override.
On torch 2.10 / 2.11 a plain fully_shard of a uint8 4-bit weight raises (only floating point tensors can require gradients); later torch shards it but gathers a plain Parameter. The control accepts either.
…frozen FP8 kept replicated / trainable refused, generate runs gathered
…not blocks, _no_split_modules only as a fallback
# Conflicts: # unsloth/models/fsdp2_native.py
Keep the reentrant gradient checkpointing fix (vision.py). For the NF4 override on float-packed 4-bit bytes keep B's version (f99c672: _eligible accepts a contiguous (N, 1) float buffer and _linear reads its uint8 view). E's 9074d6f gated the same change on the process-global _FSDP2_QLORA_PREPARED, which open PR #14231 removes (it made compiled dense LoRA lookups guard on it).
Ranks 2 and 3 wait at a world barrier while ranks 0 and 1 shard a model; on CI that took over the 30 s gloo timeout. The process group timeout is now 150 s, and the test's own deadline still reports a real hang.
They spawn 2 to 4 ranks per test and took the catch-all shard from about 1300 s to 1850-2090 s of pytest, against a 2100 s step cap. A new fsdp2 shard runs tests/test_fsdp2*.py beside it, and the catch-all ignores them by glob. The partition test now understands glob roots and --ignore-glob.
|
The NCCL failure is gone on the latest push, but The same shard finishes in 17 to 25 minutes on the other PRs that ran it today (#14280, #14288, #14290, #14307, #14310, #14312), so the extra time comes from this PR's tests: it adds 25 |
|
@codex security review |
|
The account paying for this security review has reached its Codex usage limits. The payer can check the Codex usage dashboard. For personal accounts, using credits requires enabling “Use credits for security reviews” in Code review settings. If you do not manage the paying account, contact this repository's admins. |
|
Codex Review: Didn't find any major issues. 👍 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 new shard in That test pins the number of parallel pytest commands the workflow scan finds, so it needs the new count (and its message the new repo-cpu shard), alongside the |
repo-cpu-tests now has four parallel shards, so the scan expects seven parallel pytest runs and four repo-root ones.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 732f73b19f
ℹ️ 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".
| """UnslothTrainer builds QGaLoreAdamW8bit in its own create_optimizer when q_galore_config is set, | ||
| bypassing args.optim (so _swap_bnb_optimizer never sees it). Its 8-bit states and 2-D projections | ||
| expect plain tensors, not DTensor shards.""" | ||
| if getattr(training_args, "q_galore_config", None) is not None: |
There was a problem hiding this comment.
Reject layerwise GaLore and APOLLO before sharding
When TrainingArguments.optim is galore_adamw_layerwise, galore_adamw_8bit_layerwise, galore_adafactor_layerwise, or apollo_adamw_layerwise, this guard does not fire because it only checks Unsloth's separate q_galore_config. Trainer consequently creates a per-parameter, post-gradient-hook optimizer after the parameters have become multi-rank DTensors, even though Transformers documents layerwise optimization as single-GPU-only and unsupported with distributed training; the run can fail during optimizer setup/step after the model has already been mutated. Reject these optimizer names alongside Q-GaLore before calling shard_model. Transformers optimizer documentation
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c30a0b4: optim = 'galore_' / 'apollo_' (layerwise or not) is refused in the pre-shard checks, next to Q-GaLore, before the model is touched. Covered for all four layerwise names plus galore_adamw.
| if requested is not None and torch.device(requested).type == "cpu": | ||
| return torch.device("cpu") |
There was a problem hiding this comment.
Reject GPU-resident quantized weights for CPU training
When TrainingArguments(use_cpu=True) is combined with a 4-bit model that was already loaded on CUDA, this early return selects a CPU mesh before the later quantized-placement checks run. The CPU layout does not replicate frozen weights, so fully_shard then attempts to move the packed Params4bit storage to CPU while its quantization state remains associated with the CUDA load (and older-torch unmanaged weights can remain on CUDA entirely), leading to a device mismatch or invalid quantized weight on the first forward. Validate quantized parameters against the requested CPU device here and reject this placement before initializing or mutating the model.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c30a0b4: _shard_device refuses a CPU mesh (use_cpu = True or ACCELERATE_USE_CPU) when any bitsandbytes quantized weight is on the GPU, before any process group or mesh exists. Unquantized GPU weights keep moving to the CPU mesh as before.
| if path is not None and should_save: | ||
| torch.save(state, path) | ||
| return state |
There was a problem hiding this comment.
Wait for the optimizer checkpoint writer
During every native Trainer checkpoint, all ranks participate in get_optimizer_state_dict, but only the main rank enters this potentially very large torch.save; all other ranks return immediately and can reach the next FSDP all-gather or reduce-scatter while rank 0 is still serializing. For large full-finetuning optimizer states, that wait can exceed the process-group timeout and abort an otherwise successful run. Synchronize completion through the long-timeout store mechanism already used by fsdp2_gathered before non-writers leave this helper.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c30a0b4: native_save_optimizer now makes the non-writing ranks wait for rank 0's torch.save through the store key mechanism fsdp2_gathered uses (long save timeout, not a barrier), and the wait runs in a finally so a failed write cannot strand them. tests/test_fsdp2_native_optim_save_wait_gloo.py slows rank 0's write by 3 s and checks rank 1 sees the complete file on return; it fails before the fix.
…-bit on a CPU mesh - native_save_optimizer: the non-writing ranks wait for rank 0's torch.save through the store (as fsdp2_gathered does), so a long write cannot let them run ahead into the next collective and hit its timeout. - optim = 'galore_*' / 'apollo_*' is refused before sharding: they project whole 2-D weights, and the layerwise variants are single-GPU only. - use_cpu = True with bitsandbytes quantized weights already on the GPU is refused before the CPU mesh would move them off their quantization state.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c30a0b4bf8
ℹ️ 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".
| state_dict = native_full_state_dict(root) | ||
| if self.args.should_save: | ||
| _save_unwrapped(self, root, output_dir, state_dict = state_dict) |
There was a problem hiding this comment.
Wait for the full-model checkpoint writer
For non-PEFT full-finetuning checkpoints, only the main rank enters _save_unwrapped, while every other rank returns from save_model immediately after the collective state-dict gather. Those ranks can then enter the optimizer-state collective—or the next training collective—while rank 0 is still serializing a multi-gigabyte model; on slow storage this can exceed the process-group timeout and abort the run. Synchronize completion with the long-timeout store mechanism already used by fsdp2_gathered and native_save_optimizer before non-writers leave this branch.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f2566ac: the full-finetuning branch of save_model now makes the non-writing ranks wait for rank 0's _save_unwrapped through the same store key mechanism (in a finally, so a failed write cannot strand them). New case in tests/test_fsdp2_native_trainer_ckpt_gloo.py slows rank 0's write by 3 s and checks rank 1 finds model.safetensors on return; it fails before the fix.
| package = row.get("package") | ||
| if package and importlib.util.find_spec(package) is not None: | ||
| off = os.environ.get(row.get("unless_env_false", ""), "") | ||
| if str(off).strip().lower() not in _FALSY: | ||
| reasons.append(f"{package} installed") |
There was a problem hiding this comment.
Check TPU availability instead of package presence
When torch_xla is installed but no TPU/XLA device is active—for example, a CUDA environment retaining the package, or an explicit TrainingArguments(use_cpu=True) run—this package-only check still reports an XLA conflict and refuses native FSDP2 before sharding. Accelerate selects its XLA backend based on actual TPU availability and the CPU selection, not merely find_spec("torch_xla"); use the equivalent runtime predicate and honor uses_cpu here so valid CUDA and CPU launches are not rejected.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Keeping this one as is. In accelerate (checked on 1.15.0) the XLA choice does not depend on a TPU being present or on use_cpu: PartialState._prepare_backend takes elif is_torch_xla_available(): -> DistributedType.XLA before the LOCAL_RANK / not cpu branches, and is_torch_xla_available() with no check flag returns True whenever torch_xla.core.xla_model and torch_xla.runtime import (utils/imports.py, gated only by USE_TORCH_XLA). So a CUDA or use_cpu launch with torch_xla installed does end up on the XLA backend, and refusing it is correct. The documented way out is the same one accelerate offers: USE_TORCH_XLA=0, which this row already honours via unless_env_false.
Trainer.save_model on a full-finetuning model gathers the state dict on every rank, but only rank 0 serializes it. The other ranks now wait through the store, as fsdp2_gathered and native_save_optimizer do, so a multi-GB write cannot let them run ahead into the optimizer save or the next step and hit the collective timeout.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
…e vision results atomically (#14334) ## Problem `Repo tests (CPU, fsdp2)`, the shard added with #14273, failed on two of the first three PRs that ran it, each time in a test unrelated to the PR: - #14326: `test_fsdp2_native_submesh_gloo.py::test_replicated_grads_average_over_the_model_mesh_only` ``` torch.distributed.DistNetworkError: The server socket has failed to listen on any local network address. port: 33653, useIpv6: false, code: -98, name: EADDRINUSE ``` - #14280: `test_fsdp2_native_vision_gloo.py::test_without_dummy_vision_desyncs[lora-blocks]` ``` json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) ``` Two separate causes: 1. **Port race.** Each distributed test picks `MASTER_PORT` with `bind(("127.0.0.1", 0))` and closes the socket before rank 0 listens. `bind(0)` returns a port from the kernel's ephemeral range (32768-60999 on Linux), which is also where gloo's own peer connections get their local ports. Those connections come from this test and from the other three xdist workers running the same kind of test, so one of them can take the port first. 2. **Half-written result.** The vision harness kills a surviving rank as soon as its peer dies (the expected failure mode in the desync cases). A rank killed inside `json.dump` leaves an empty `result.json.<rank>`, which the reader parsed and crashed on instead of taking its "no result" branch. ## Fix - `tests/_rendezvous_port.py` (new): picks a free port from 20000-31999, below every OS's default ephemeral range (Linux 32768+, macOS and Windows 49152+). Each xdist worker draws from its own 1000-port slice, so two tests running side by side cannot pick the same port either. Taken or TIME_WAIT ports are skipped, and `bind(0)` remains the fallback if a slice is exhausted. - The `_free_port()` helper in the 18 distributed test files (the FSDP2, context-parallel and GRPO scoring-head ones that set `MASTER_PORT`) now returns that port. Their unused `socket` imports are dropped. - `test_fsdp2_native_vision_gloo.py`: each rank writes its result to a temp file and `os.replace`s it into place, and the reader treats unreadable JSON like a missing file. Test-only; no product code changes. ## Testing - `tests/test_rendezvous_port.py` (new, 3 tests): the port is below 32768 and inside the worker's slice, the no-xdist case uses the first slice, and a port with a listener on it is skipped. With the old `bind(0)` helper all three fail. - `ruff check` passes on every touched file, and the formatter is a fixed point. - The changed distributed tests run on staging CI, linked below. A local run was not usable: this host's spawned ranks import a stale checkout of `unsloth_zoo`, which is unrelated to the change.
… full DCP load (unslothai#14739) ## Summary Two fixes for FSDP2 saves of bitsandbytes 4-bit models (follow-up to unslothai#13895, unslothai#14273). Nothing changes without FSDP2 or without 4-bit weights. 1. save_pretrained / push_to_hub of a sharded NF4 model kept every gathered packed weight on rank 0's accelerator (offload_to_cpu skipped any parameter with a quant_state), so the whole quantized base had to fit on one GPU next to its shards. These saves only write the packed bytes, so the gather now stages them on the CPU together with a CPU copy of their QuantState (QuantState.to moves in place, so the live one is copied first and stays where the sharded weight computes). The written state dict is byte for byte the same. Merged saves still dequantize on the device and keep the previous placement. 2. A full DCP load dropped the QuantState entries the full state dict carries, then reported all keys matched: the loaded packed bytes were paired with whatever scales the live model had (for example a base that was requantized or initialized differently). The saved entries are now copied into the live QuantState in place before they are dropped (rank 0 broadcasts them under broadcast_from_rank0), and a QuantState that does not fit the model (shape, blocksize, quant type, nesting) raises instead of loading. ## Tests - tests/test_fsdp2_save_gloo.py: test_packed_4bit_save_stages_bytes_and_quant_state_on_the_cpu and test_full_dcp_load_restores_the_saved_quant_state (two gloo CPU ranks, real bitsandbytes NF4, nested and not, with and without broadcast_from_rank0). Both fail on main. - tests/test_fsdp2_save_coverage.py: test_only_saves_that_write_packed_bytes_stage_4bit_on_the_cpu (only save_pretrained and push_to_hub request it; merged saves do not). Fails on main. - Existing FSDP2 save tests: same results as main. test_a_slow_writer_does_not_time_out_the_other_ranks fails on main and here alike under host load (4 s gloo timeout). Not covered: merged saves still hold the packed base on the writing GPU (needs per-layer gather and merge); no NCCL or GPU peak-memory run.
…port unsharded generation on torch 2.6 / 2.7 (unslothai#14882) Since unslothai#14273, `UNSLOTH_FSDP2=1` shards natively inside the Trainer and no longer exports accelerate's FSDP env. A custom loop that builds its own `Accelerator` and calls `accelerator.prepare(model, optimizer)` therefore gets a plain DDP wrap, with no parameter or optimizer sharding, where it used to get accelerate's FSDP2 wrap. - The first `Accelerator` built outside a Trainer gets the accelerate FSDP2 launch env again, the same as `UNSLOTH_FSDP2_BACKEND=accelerate`, with a rank-0 message. It is left alone when `UNSLOTH_FSDP2_BACKEND` is set explicitly, when a distributed plugin is passed, on a CPU run, when an `AcceleratorState` already exists, or when `shard_model` already sharded a model. The Trainer path is unchanged. - One behaviour change: a script that builds `Accelerator()` only for `is_main_process` and then a Trainer now runs accelerate's FSDP2 again, as before unslothai#14273. `UNSLOTH_FSDP2_BACKEND=native` keeps native. - `native_fsdp2_unsharded` (generation and merges) called `FSDPModule.set_reshard_after_forward`, which only exists from torch 2.8 (absent at the v2.6.0 and v2.7.0 tags). On torch 2.6 / 2.7 it now sets the param group's post-forward mesh directly and restores the saved value on exit; 2.8+ keeps the public setter. Tests: `tests/test_fsdp2_native_raw_accelerator.py` (10 cases) and `test_unsharded_context_without_reshard_setter` fail on main and pass here, on torch 2.10, 2.13 and 2.14. The FSDP2 suites keep the same failing test ids as main on every venv (one pre-existing failure on 2.14). In a 2-rank check on one GPU, the raw loop now prepares `FSDPSequential` with DTensor weights where main prepared `DistributedDataParallel`, and a native Trainer run is identical to main (native sharding, same loss). Not run: a real 2-GPU NCCL job, torch 2.6 / 2.7 installs, native Windows, and the memory difference itself.
…U / other non-CUDA installs (unslothai#14760) ## Problem Before unslothai#14273, `UNSLOTH_FSDP2=1` under `torchrun` always exported accelerate's FSDP2 launch env, so it worked wherever accelerate's FSDP2 does, Intel XPU included. unslothai#14273 made the native backend the default for `UNSLOTH_FSDP2=1` and refuses every non-CUDA accelerator (`NATIVE_BACKEND_TABLE` device rows: XPU, NPU, HPU, MLU, MUSA, SDAA, Neuron) at Trainer setup. The same launch command that trained on XPU before now raises `RuntimeError: ... cannot run under Intel XPU`. The only way back is knowing to set `UNSLOTH_FSDP2_BACKEND=accelerate`. ## Change - `fsdp2_launch.non_cuda_install()` returns the non-CUDA accelerator accelerate would pick on this install, from the torch build (`torch.version.cuda / hip / xpu`, read from `torch/version.py` when torch is not imported yet) and the installed vendor packages. It never reports one on a CUDA or ROCm torch build, or for a CPU launch (`ACCELERATE_USE_CPU`). - `unsloth_fsdp2_native_requested()` returns False in that case when no backend is set explicitly, so the launch step exports accelerate's FSDP2 env exactly as before unslothai#14273 (and before the process group exists, so accelerate still picks its `xpu:xccl,cpu:gloo` backend for FULL_STATE_DICT saves). Since the answer does not depend on importing torch, the launch step and Trainer setup agree. - Rank 0 prints one line saying accelerate's FSDP2 shards the model. - An explicit `UNSLOTH_FSDP2_BACKEND=native` still selects native and is still refused on those devices. CUDA and ROCm launches do not change. ## Tests - New `tests/test_fsdp2_non_cuda_accelerate_route.py` (7 cases): XPU build routes to accelerate (`ACCELERATE_USE_FSDP=true`, `FSDP_VERSION=2`), a vendor package on a non-CUDA build routes to accelerate, CUDA / ROCm builds stay native, explicit native and CPU launches stay native, and the torch build is read from `version.py` without importing torch. On main 3 of them fail (the routing cases); on this branch all 7 pass. - `tests/test_fsdp2_native_backend_table.py` and `tests/test_fsdp2_detection.py` pass on this branch. When both files run in one pytest process, `test_loader_utils_versions` and `test_a_built_accelerator_is_authoritative` fail the same way on main, because module state leaks from the backend table file. Run on their own, they pass. ## Not covered - No XPU, NPU or HPU hardware here, so end-to-end accelerate FSDP2 training on those devices was not run. This PR only puts back the routing those launches had before unslothai#14273. - The non-device refuse rows (DeepSpeed, Megatron-LM, XLA, SageMaker, ParallelismConfig) are unchanged. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Summary
Adds Unsloth's own FSDP2 wrapper for multi-GPU training, opt-in with
UNSLOTH_FSDP2=1undertorchrun. Unsloth callsfully_sharditself, per decoder block and then the root, withMixedPrecisionPolicy(parameters gathered in the compute dtype, gradients reduced in fp32). It works with every model Unsloth loads (dense, MoE, VLM), with LoRA, QLoRA (load_in_4bit = True) and full finetuning, and keeps Unsloth's fused LoRA kernels, block compile and gradient checkpointing on.Supported entry points: the Hugging Face / TRL / Unsloth
Trainer, or a plain PyTorch loop usingshard_modelwith the native helpers (native_clip_grad_norm_,native_full_state_dict,native_save_optimizer,native_load_*). Preparing a natively sharded model or optimizer with anAcceleratorbuilt outside the Trainer is refused with a clear error. CUDA (including ROCm) and CPU only; XPU and other accelerators are refused.With the flag off, nothing changes:
fsdp2_nativeis not imported, and single GPU, DDP andaccelerate launchFSDP configs take exactly the current path.UNSLOTH_FSDP2_BACKEND=accelerate, or anaccelerateFSDP config without an explicit backend, keeps accelerate's wrap.Layout
ignored_params, never gathered, like DDP). Only the trainable parameters are sharded, withreshard_after_forward = Falseand one-ahead prefetch. A small trainable set (LoRA) is one root unit: 1 all-gather and 1 reduce-scatter per step. Full finetuning keeps per-block units.UNSLOTH_FSDP2_LAYOUT=sharded, or when the model does not fit): every block is sharded, for the lowest memory.check_shard_units).Model coverage
Int8Paramsare always kept replicated, since theirCB/SCBstate does not survive sharding; they are refused where replication is unavailable (torch 2.6).(N, 1)buffer as uint8. The route is chosen from the weight itself, not a process-global flag.Training state
native_clip_grad_norm_.UNSLOTH_FSDP2_RECOMPUTE_CAST=0turns it off).load_best_model_at_enduses the native loader.Refused or switched
optim = 'galore_*'/'apollo_*', layerwise or not) and Q-GaLore project whole 2-D weights and are refused before sharding.use_cpu = Truewith bitsandbytes quantized weights already on the GPU is refused, since the CPU mesh would move them away from their quantization state.TrainingArguments(fsdp=...)with the native backend,model_init/hyperparameter_search, Unsloth block swap, multi-nodesave_on_each_nodeand CPU / disk offloadeddevice_maps are refused before the model is changed.use_cpu=Truekeeps a CPU mesh.split_param_groups(...)builds groups that work.ignored_params) falls back to sharding frozen weights.Qwen3-VL and Qwen3.5 under FSDP2 also need unslothai/unsloth-zoo#1881 (gradient checkpointing hooks keep
with_kwargs), which is merged.Results
Parity, Kaggle T4 x2, fp16, torch 2.10.0, 2.12.1 and 2.14.1
Real Unsloth
SFTTrainer, 10 steps, sequential sampler. In fp16 the 2-GPU runs skip different overflow steps than 1 GPU, so DDP and native drift from 1 GPU by the same amount. The comparison that isolates FSDP2 is native against DDP: they skip the same steps and agree to within the 1-GPU A/A spread.bf16, 2 GPUs, torch 2.13
Native and DDP are both measured against 1 GPU, so each column shows how far it drifts from the single-GPU run.
Speed, Kaggle T4 x2, fp16
One kernel to itself, 3 reps per arm. Ratio = DDP step time / native step time (above 1.00x is faster than DDP).
Torch 2.10:
Torch 2.14:
UNSLOTH_FSDP2_REDUCE_DTYPE=float16(orbfloat16) reduces gradients in the compute dtype instead of fp32; on torch 2.10 it measured 1.259x of DDP for this config, at the cost of the fp32 reduction.fully_shardon the same LoRA configs ran at 0.36x to 0.77x of DDP and crashed on 4-bit.Compile, Kaggle T4 x2, torch 2.10
Gemma3, Qwen3-MoE and Qwen2.5-VL, each run on 1 GPU and under FSDP2 at GA 1 and GA 2:
On real torch 2.10, a checkpoint recompute probe raises
CheckpointError(saved fp16, recomputed in a different dtype) without the cast backport, and passes with it.Tests
tests/test_fsdp2*.pysuite: 266 passed, 8 skipped. These spawn 2 to 4 gloo ranks per test, so Backend CI runs them in their ownRepo tests (CPU, fsdp2)shard instead of the catch-all, which they pushed to its step cap.tests/test_bnb_nf4_override.py49 passed, 1 skipped.tests/test_block_compile.pypasses.Not covered here
tests/test_grpo_fsdp2_scoring_head.py(2 cases) fails identically on main and is not addressed here.