Skip to content

Native FSDP2: fully_shard per block and root for every model, LoRA, QLoRA and full finetuning (UNSLOTH_FSDP2=1) - #14273

Merged
danielhanchen merged 129 commits into
mainfrom
dh/fsdp2-native-int
Oct 20, 2026
Merged

danielhanchen merged 129 commits into
mainfrom
dh/fsdp2-native-int

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds Unsloth's own FSDP2 wrapper for multi-GPU training, opt-in with UNSLOTH_FSDP2=1 under torchrun. Unsloth calls fully_shard itself, per decoder block and then the root, with MixedPrecisionPolicy (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 using shard_model with the native helpers (native_clip_grad_norm_, native_full_state_dict, native_save_optimizer, native_load_*). Preparing a natively sharded model or optimizer with an Accelerator built 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_native is not imported, and single GPU, DDP and accelerate launch FSDP configs take exactly the current path. UNSLOTH_FSDP2_BACKEND=accelerate, or an accelerate FSDP config without an explicit backend, keeps accelerate's wrap.

Layout

  • Fit layout (auto when the model fits one GPU). Frozen weights stay replicated (ignored_params, never gathered, like DDP). Only the trainable parameters are sharded, with reshard_after_forward = False and 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.
  • Per-block layout (UNSLOTH_FSDP2_LAYOUT=sharded, or when the model does not fit): every block is sharded, for the lowest memory.
  • Ranks agree on the layout with one all-reduce at shard time, so GPUs with different free memory cannot pick different collectives.
  • No FSDP unit is ever placed inside a compiled decoder block (check_shard_units).

Model coverage

  • 8-bit: bitsandbytes Int8Params are always kept replicated, since their CB / SCB state does not survive sharding; they are refused where replication is unavailable (torch 2.6).
  • 4-bit: the NF4 bytes are stored in the compute dtype so FSDP2 can shard them, and the override reads the all-gathered (N, 1) buffer as uint8. The route is chosen from the weight itself, not a process-global flag.
  • VLMs and audio: on multimodal models whose encoders take part in collectives, each forward agrees over ranks, with one small all-reduce, on which inputs (image or video, audio) are present. When only some ranks have an input, the others run a dummy encoder pass, so image and text-only ranks run the same collectives. If no safe dummy can be built (inline vision such as Mllama, a required argument the dummy cannot supply, or audio), every rank raises a clear error instead of hanging. Text-only models pay nothing.
  • MoE: the zoo all-gathered expert tables were fixed in MoE under FSDP2: restore swapped expert weights cleanly, re-key NF4 pointer tables for all-gathered experts unsloth-zoo#1872 (merged).
  • Gemma4 per-layer embedding tables get their own unit.
  • Mixed-dtype norms and float8 weights are replicated.

Training state

  • Gradient clipping goes through native_clip_grad_norm_.
  • On torch < 2.13, a guard covers accumulated gradients, and the forward-input cast is backported for checkpoint recompute (UNSLOTH_FSDP2_RECOMPUTE_CAST=0 turns it off).
  • Trainer checkpoints save the full optimizer state (the other ranks wait for rank 0's write through the store, not a barrier, so a slow write cannot trip the collective timeout), and resume restores it, including persistent buffers.
  • load_best_model_at_end uses the native loader.
  • Adapter checkpoints include the frozen tensors PEFT saves (resized embeddings, inactive adapters).
  • Merged exports select operands by name.

Refused or switched

  • bitsandbytes Lion and AdEMAMix cannot run on DTensors and are refused with a clear error.
  • GaLore and APOLLO optimizers (optim = 'galore_*' / 'apollo_*', layerwise or not) and Q-GaLore project whole 2-D weights and are refused before sharding.
  • use_cpu = True with bitsandbytes quantized weights already on the GPU is refused, since the CPU mesh would move them away from their quantization state.
  • DeepSpeed, TrainingArguments(fsdp=...) with the native backend, model_init / hyperparameter_search, Unsloth block swap, multi-node save_on_each_node and CPU / disk offloaded device_maps are refused before the model is changed. use_cpu=True keeps a CPU mesh.
  • A prebuilt optimizer and scheduler over parameter groups that mix sharded and replicated parameters are refused; split_param_groups(...) builds groups that work.
  • bitsandbytes RMSprop switches to torch's.
  • CUDA bootstrap falls back to gloo when NCCL is not available.
  • torch 2.6 (no 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.

config torch 2.10: native vs DDP max loss diff torch 2.12: native vs DDP torch 2.14: native vs DDP 1-GPU A/A max loss diff peak GiB 1 GPU / DDP / native / per-block
Llama-3.2-1B LoRA, GA 1 0.0029 0.0006 0.0002 0.0000 to 0.0002 3.26 / 3.08 / 2.98 / 2.66
Llama-3.2-1B LoRA 4-bit, GA 2 0.0004 0.0003 0.0016 0.0000 1.97 / 1.71 / 1.69 / 1.87
Qwen3-0.6B LoRA, GA 2 0.0005 0.0008 0.0011 0.0005 2.07 / 1.77 / 1.75 / 1.45
Qwen3-0.6B full finetuning, GA 2 0.0005 0.0004 0.0006 0.0007 to 0.0011 11.94 / 14.32 / 9.79 / 8.10

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.

config native vs 1 GPU max loss diff DDP vs 1 GPU max loss diff peak GiB native (DDP)
Llama LoRA, GA 1 0.0027 0.0013 3.03 (3.10)
Llama LoRA 4-bit, GA 1 0.0028 0.0040 1.70 (1.72)
Llama full finetuning, GA 1 0.0022 0.0396 8.94 (14.90)
Qwen3 LoRA 4-bit, GA 2 0.0035 0.0033 1.18 (1.20)
Qwen3 full finetuning, GA 2 0.0037 0.0063 6.28 (7.22)
Qwen3-MoE 4-bit LoRA (tiny) 0.0003 0.0002 0.55 (0.56)
Qwen2.5-VL 4-bit LoRA (tiny) 0.0034 0.0034 native equals DDP bitwise
  • The fit and per-block layouts are bitwise identical on every config run in both.
  • Fused LoRA kernel call counts equal 1 GPU.

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:

config DDP ms (rep spread) native ms native vs DDP per-block layout vs DDP peak GiB DDP / native / per-block
LoRA 16-bit Llama-1B, seq 512 330.9 (33%) 301.2 1.098x 0.413x 2.87 / 2.76 / 2.46
LoRA 16-bit Llama-1B, seq 2048 1038.6 (2.3%) 1047.9 0.991x 0.789x 3.55 / 3.52 / 3.01
LoRA 4-bit Llama-1B, seq 2048 1063.3 (7.1%) 1073.0 0.991x 0.901x 2.23 / 2.21 / 2.21
Full finetuning Qwen3-0.6B, seq 2048 2247.0 (2.7%) 2171.5 1.035x 1.007x 13.34 / 7.65 / 6.09

Torch 2.14:

config DDP ms (rep spread) native ms native vs DDP per-block layout vs DDP peak GiB DDP / native / per-block
LoRA 16-bit Llama-1B, seq 512 319.1 (21%) 278.7 1.145x 0.395x 2.87 / 2.76 / 2.46
LoRA 16-bit Llama-1B, seq 2048 1135.4 (0.8%) 1142.3 0.994x 0.813x 3.55 / 3.52 / 3.01
LoRA 4-bit Llama-1B, seq 2048 1164.6 (2.6%) 1178.8 0.988x 0.916x 2.23 / 2.21 / 2.21
Full finetuning Qwen3-0.6B, seq 2048 1370.7 (1.5%) 1480.0 0.926x 0.907x 13.34 / 7.57 / 5.99
  • The default layout matches DDP on LoRA on both torch versions, within DDP's own rep spread.
  • Full finetuning uses 43% less memory than DDP on both versions. It is 1.035x of DDP on torch 2.10 and 0.926x on torch 2.14, where DDP itself got much faster (1371 ms vs 2247 ms). Per-block full finetuning adds a weight all-gather per block per step on top of the gradient reduce, which DDP does not need. UNSLOTH_FSDP2_REDUCE_DTYPE=float16 (or bfloat16) 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.
  • Last-step losses agree to 1e-4 across arms.
  • The per-block layout trades speed for memory and is opt-in.
  • For reference, stock fully_shard on 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:

  • 0 graph breaks, and no recompiles after step 1.
  • The same unique graph count as 1 GPU.
  • Losses match 1 GPU to about 1e-5.

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

  • New CPU gloo tests (2-rank spawn), each failing before the matching fix:
    • shard units and gradients across Llama, Qwen3, Mistral, Gemma2, Qwen3-MoE, GPT-OSS, Qwen3-Next, Gemma3 VL, Qwen2.5-VL, Qwen3-VL, Gemma4 and Qwen3.5, LoRA and full;
    • layout agreement across ranks with unequal free memory, and the torch 2.6 fallback;
    • mixed image / text ranks, including Llava with a trainable projector;
    • save and resume, including buffers, best-model loading, frozen PEFT tensors and optimizer refusals.
  • The full tests/test_fsdp2*.py suite: 266 passed, 8 skipped. These spawn 2 to 4 gloo ranks per test, so Backend CI runs them in their own Repo tests (CPU, fsdp2) shard instead of the catch-all, which they pushed to its step cap.
  • GPU: tests/test_bnb_nf4_override.py 49 passed, 1 skipped. tests/test_block_compile.py passes.

Not covered here

  • Windows: the gloo fallback is unit tested only; no Windows multi-GPU run.
  • AMD: not run.
  • Torch versions:
    • Timing was run on torch 2.10 and 2.14.
    • Parity ran on torch 2.10, 2.12, 2.13 and 2.14, but not on 2.11.
    • Torch 2.6 is covered by API checks only.
  • No heterogeneous-GPU run. No meta-device or rank-0-only loading: every rank loads the same checkpoint, as with DDP.
  • Pixtral, Mistral3 and Mllama vision dummies are not exercised. Video on one rank and images on another is not covered.
  • tests/test_grpo_fsdp2_scoring_head.py (2 cases) fails identically on main and is not addressed here.

danielhanchen and others added 30 commits October 18, 2026 22:59
…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.
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.
…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
…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).
pre-commit-ci Bot and others added 3 commits October 20, 2026 04:41
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.
@danielhanchen

Copy link
Copy Markdown
Member Author

The NCCL failure is gone on the latest push, but Repo tests (CPU, rest) now hits the shard's 2100 s timeout:

10186 passed, 1510 skipped ... in 2092.28s (0:34:52)
KeyboardInterrupt
##[error]Process completed with exit code 124.

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 *_gloo.py files, each spawning a process group. Running pytest tests/ -k fsdp2_native --durations=30 locally should show which ones dominate. Keeping the per-case world size and model at the smallest that still proves the claim, sharing one spawned group across cases, or giving the heaviest ones their own shard would keep rest under its budget.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 6c79c5b50f

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member Author

The new shard in studio-backend-ci.yml fixes the timeout, but it trips a guard that counts the parallel runs, so workflow-trigger lint now fails:

tests/studio/test_backend_ci_parallel_isolation.py::test_the_command_scan_sees_the_parallel_run_and_the_serial_steps
  AssertionError: expected six parallel pytest runs, three shards of the backend matrix and three of repo-cpu-tests
  assert 7 == 6

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 tests/test_ci_repo_cpu_shards.py update this push already makes.

repo-cpu-tests now has four parallel shards, so the scan expects seven parallel
pytest runs and four repo-root ones.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +475 to +476
if requested is not None and torch.device(requested).type == "cpu":
return torch.device("cpu")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread unsloth/models/fsdp2_native.py Outdated
Comment on lines +1862 to +1864
if path is not None and should_save:
torch.save(state, path)
return state

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread unsloth/models/fsdp2_native.py Outdated
Comment on lines +2177 to +2179
state_dict = native_full_state_dict(root)
if self.args.should_save:
_save_unwrapped(self, root, output_dir, state_dict = state_dict)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread unsloth/fsdp2_launch.py
Comment on lines +273 to +277
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")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: f2566acef3

ℹ️ 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".

@danielhanchen
danielhanchen merged commit c280b6f into main Oct 20, 2026
@danielhanchen
danielhanchen deleted the dh/fsdp2-native-int branch October 20, 2026 09:30
danielhanchen added a commit that referenced this pull request Oct 20, 2026
…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.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 22, 2026
… 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.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 23, 2026
…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.
danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Oct 25, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant