Skip to content

FSDP2: first-class LoRA and full finetuning, keep fused LoRA kernels per block - #13865

Merged
danielhanchen merged 17 commits into
mainfrom
dh/fsdp2-core
Oct 16, 2026
Merged

danielhanchen merged 17 commits into
mainfrom
dh/fsdp2-core

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

FSDP2 through accelerate did not work with Unsloth on current accelerate. Since accelerate 1.14 the final norm and lm_head get their own FSDP unit, and Unsloth's forward reads lm_head.weight directly for the fused cross entropy, so every model with an untied lm_head stopped at the first step with "aten.mm.default got mixed torch.Tensor and DTensor". On T4 (float16) the runs that did start skipped their first steps: accelerate's automatic FSDP2 policy casts the loss to float16 before the GradScaler multiplies it by 65536, which overflows. The fused LoRA kernels were also switched off for any FSDP.

This PR:

  • Detects FSDP2 in every launch mode with the same answer on every rank: accelerate launch, TrainingArguments(fsdp, fsdp_config version 2), and a new UNSLOTH_FSDP2=1 for plain torchrun, which exports accelerate's own FSDP2 launch environment before transformers is imported (per block wrapping by default, UNSLOTH_FSDP2_RESHARD_AFTER_FORWARD=0 for a ZeRO-2 style run).
  • Fills in what accelerate leaves at its defaults: gradients reduced in float32, no cast of the model outputs, float16 gathers the stored weights and leaves the casting to autocast like the single GPU run, the last decoder block stays gathered for backward, and bfloat16 full finetuning gets float32 master weights (FSDP2 needs one trainable dtype per unit). A policy the user wrote is never changed.
  • Gathers the FSDP units of lm_head and the final norm before the forward, since Unsloth reads their weights directly.
  • Keeps the fused LoRA kernels when every decoder block is its own FSDP unit (the block's weights are gathered before its forward); FSDP1, a root-only wrap or a finer wrap still decline them, decided once after wrapping and agreed across ranks. UNSLOTH_FORCE_FUSED_LORA=1 and UNSLOTH_FSDP2_FUSED_LORA=0 still work.
  • Maps no_sync to set_requires_gradient_sync on accelerate older than 1.11.

Results on Kaggle T4x2 (float16), 1 GPU vs 2 GPU FSDP2, 5 steps: LoRA loss within 4e-6 and update cosine 0.99997 or better for GA 1 and 2, Llama (untied) and Qwen2 (tied), in all three launch modes, with the fused kernels running and never seeing a shard. Full finetuning peak memory per GPU 3.9 GB vs 8.4 GB for DDP on the same 375M model. Full finetuning gradients match the single GPU run computed with the exact cross entropy (cosine 0.999999); the single GPU float16 fused cross entropy differs from the exact one by itself, which is tracked separately.

Tests: tests/test_fsdp2_detection.py, tests/test_fsdp2_config.py, tests/test_fsdp2_wrap_gloo.py (two gloo ranks through accelerate's real fsdp2_prepare_model, checking that layers which read weights directly see whole tensors inside per-block units and that a finer wrap declines them).

Not covered here: save / merge / resume under FSDP2 (follow-up), torch older than 2.13 on GPU, vision / MoE / Gemma models, multi-node, CPU offload, timing. 2-GPU packing differs from 1 GPU by the same amount under DDP and FSDP2 (pre-existing).

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-15T14:56:30.864899Z ba93771 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-16T02:59:08.546279Z 1f1ea48 New commits
🔒 Security Review ⚠️ Failed 2026-10-15T14:56:35.948542Z ba93771 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@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: 4bb90327bf

ℹ️ 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.py
return
model._unsloth_fsdp2_prepared = True
parents = _parents(model)
blocks = [b for b in _decoder_blocks(model) if isinstance(b, FSDPModule)]

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 Retain the last block when activation checkpointing wraps it

When the FSDP2 plugin enables activation checkpointing, Accelerate replaces each decoder layer with a CheckpointWrapper before calling fsdp2_prepare_model and then applies fully_shard to that wrapper. _decoder_blocks still finds the underlying decoder module, but this filter discards it because the wrapper—not the decoder—is the FSDPModule; blocks is therefore empty and the last-block set_reshard_after_forward(False) optimization never runs. Resolve each decoder block's FSDP owner (or recognize checkpoint wrappers) so checkpointed training does not incur the avoidable last-block re-gather on every backward.

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.

The decoder layer itself is still an FSDPModule under activation checkpointing. In accelerate 1.14+, fsdp2_prepare_model walks modules bottom-up, so the inner decoder layer matches the policy and is sharded before its CheckpointWrapper is visited; in 1.13 and earlier, fsdp2_apply_ac wraps the decoder's children (self_attn, mlp), not the decoder, so the decoder layer stays the unit. _decoder_blocks therefore finds the sharded blocks and keeps the last one gathered. Added a two-rank gloo regression test with fsdp2_apply_ac (passes on accelerate 1.15 and 1.13), and a 2-GPU raw loop with activation_checkpointing=True reports every block and the last block gathered after forward.

…precision masters on accelerate 1.13

Raw Accelerator loops patch the model before any FSDP plugin exists, so the
post-wrap gate now applies the opt-out itself. accelerate 1.13 drops its own
float32 upcast (param = param.to(...)), so mixed trainable dtypes under
mixed precision are upcast here. Adds a gloo test for activation checkpointed
blocks keeping the last block gathered.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 3 commits October 15, 2026 10:50
…block-only fused LoRA owners, accelerate >= 1.7 for UNSLOTH_FSDP2, PEFT full state dict backport for accelerate < 1.15
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: e3f1975f69

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

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 5c007d4599

ℹ️ 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 ee2ce8c into main Oct 16, 2026
@danielhanchen
danielhanchen deleted the dh/fsdp2-core branch October 16, 2026 06:21
bestoffersdirect-fork-sync Bot pushed a commit to BestOffersDirect/unsloth that referenced this pull request Oct 16, 2026
…hai#13910)

Stacked on unslothai#13848 (Ulysses context parallel, which stacks on unslothai#4257).
Depends on unslothai#13865 (FSDP2 core), which is merged into this branch; the
change itself is commit 39d648e.

Context parallelism was DDP only: an FSDP2 launch with
context_parallel_size > 1 was refused. This lets the two compose the way
torchtitan does. The world is laid out as a (dp_shard, cp) mesh, FSDP2
shards parameters over dp_shard x cp flattened (accelerate's
dp_shard_cp), and the sequence split plus the ring or Ulysses
collectives stay on the cp submesh. CP peers hold different tokens of
the same rows, so their gradients are reduced together with the data
parallel ones, and the existing token count normalisation (pre-shard
count divided by the CP size, loss scaled by the world size) stays exact
because FSDP2 averages over the same D x N ranks DDP did.

Usage is unchanged: SFTConfig(context_parallel_size = N) under an FSDP2
launch (UNSLOTH_FSDP2=1 torchrun ..., or an accelerate FSDP2 config);
dp_shard is world size / N.

accelerate's own ParallelismConfig(cp_size = N) is still refused. With
cp_size > 1 accelerate attaches torch's context_parallel SDPA hooks in
prepare(), transformers wraps each step in maybe_context_parallel and
divides num_items_in_batch by the CP size, all of which Unsloth already
does itself. Instead Unsloth installs a ParallelismConfig with
dp_shard_size = D x N and cp_size = 1 next to its own mesh, so
fsdp2_prepare_model shards over mesh["dp_shard_cp"] and the data loader
gives CP peers the same batch (both read the same way since accelerate
1.10, the CP minimum).

FSDP1, DeepSpeed and a ParallelismConfig with dp_replicate, tp or sp
above 1 are refused on every rank before any collective.

Tests
- tests/test_context_parallel.py: FSDP2 accepted, mesh and config
installed and restored by a later trainer, FSDP1 and extra dimensions
refused.
- tests/test_context_parallel_fsdp2_gloo.py: four gloo ranks on CPU,
(dp_shard 2, cp 2). Mesh layout, accelerate's real data loader and
fsdp2_prepare_model, and one patched training step through FSDP2
matching an unsharded model's gradients.
- GPU accuracy on a tiny Llama with LoRA (3 steps, first-step
gradients): (dp_shard, cp) = (1, 2) ring and Ulysses, fp32 and bf16,
gradient accumulation 2, (2, 1) and (2, 2) ring and Ulysses on four GPUs
all match the single GPU run (loss rel err <= 2.5e-5, min grad cosine >=
0.99988). Removing the count division moves loss and gradients by
exactly 0.5, so the check can fail.

Not covered: HSDP or TP with CP, packing / FA3 / FA4 / 4-bit bases under
FSDP2 + CP, multi-node, timing.

---------

Co-authored-by: Dan Saunders <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Stanley00 pushed a commit to stanley-fork/unsloth that referenced this pull request Oct 16, 2026
…lothai#13880)

Stacked on unslothai#13865 (FSDP2 core); review that one first.

QLoRA under FSDP2 currently leaves every 4-bit weight replicated on each
GPU: bitsandbytes stores the packed bytes as uint8, which accelerate
excludes from sharding. This change shards them.

- When FSDP2 is requested, Unsloth quantizes with
`bnb_4bit_quant_storage` set to the compute dtype (float16 on T4,
bfloat16 elsewhere). Pre-quantized uint8 checkpoints are reinterpreted
in place as the same dtype (a view of the same bytes, no copy, same
QuantState).
- FSDP2 rebuilds the gathered weight as a plain Parameter and drops
`quant_state`. FSDPParam is wrapped so the sharded and the gathered
weight keep it, and the fused LoRA kernels fall back to the Linear4bit's
own QuantState if it is still missing.
- Mixed precision never casts packed 4-bit bytes.
- An all-gather holding packed weights always copies bytes. When all
inputs of a unit share one float dtype, FSDP2 copies them with
`torch._foreach_copy_`, which on CUDA rewrites float16 and bfloat16 NaN
bit patterns to the canonical NaN. About 1.7% of packed float16 words
were changed this way, which corrupted every 4-bit weight once LoRA was
gathered in the storage dtype.
- The FSDPParam and collective hooks are method wrappers, checked
against torch 2.6 to 2.14. If an anchor is missing, nothing is patched
and the weights stay uint8 (replicated, as before). The same happens
with accelerate older than 1.13, whose FSDP2 wrap upcasts the whole
model.

Results on 2 GPUs with a 2-rank FSDP2 run against the 1-GPU run at the
same per-forward batch, fused LoRA kernels on:
- tinyllama-bnb-4bit (2 x B200): the 4-bit weights per GPU go from 484
MB to 242 MB, and peak training memory from 1.56 GB (replicated) to 1.25
GB.
- Through the Trainer, the loss stays within 7e-4 of the 1-GPU run over
6 steps and the LoRA update cosine is 0.9999.
- The manual fully_shard run matches a 2-rank replicated run bit for
bit.
- On Kaggle T4x2 (fp16, torch 2.14), the Trainer FSDP2 QLoRA run stays
within 5e-4 of the 1-GPU loss with LoRA update cosine 0.99997, and the
packed weights per GPU are halved.
- On Kaggle T4x2 (fp16, torch 2.14) with tinyllama-bnb-4bit through the
Trainer: loss within 7.1e-4 of the 1-GPU run, LoRA update cosine
0.99989, 4-bit weights per GPU 484 MB to 242 MB and peak training memory
1.33 GB to 1.16 GB per GPU. On torch 2.9.1 a 100M model through the
Trainer stays within 1.4e-4 (cosine 1.0000).

Tests: `tests/test_fsdp2_qlora.py` (CPU, gloo, real bitsandbytes layers)
and `tests/python/test_get_lora_parameters_fsdp2_quant_state.py`.

The all-gather corruption also affects accelerate's documented bf16
FSDP2 QLoRA recipe (all-bf16 units), so it may be worth reporting
upstream separately.

Not covered: torch 2.6 to 2.8 keep uint8 storage (those versions require
one dtype per unit including frozen weights), so 4-bit weights stay
replicated there, as today; torch 2.10 to 2.12 were checked against
source only; accelerate older than 1.13 and transformers 4.57 are unit
tested only; gradient checkpointing under FSDP2 QLoRA, vision models and
8-bit were not run.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Stanley00 pushed a commit to stanley-fork/unsloth that referenced this pull request Oct 16, 2026
…d models (unslothai#13895)

Stacked on unslothai#13880 (FSDP2 QLoRA), which is stacked on unslothai#13865 (FSDP2
core).

Under FSDP2 every parameter is a DTensor shard, so the save paths that
read module weights directly break:

- `model.save_pretrained()` fails in peft/safetensors ("invalid python
storage") for LoRA, QLoRA and full finetuning.
- `model.save_pretrained_merged(..., "merged_16bit")` fails inside the
zoo merge ("Cannot set version_counter for inference tensor").
- QLoRA `trainer.save_model()` and every Trainer checkpoint fail with
`'DTensor' object has no attribute 'absmax'`:
torch.distributed.checkpoint resolves bitsandbytes' `weight.absmax` keys
as attributes of the sharded weight. Training with `save_steps` dies at
the first checkpoint.

Changes:

- `unsloth/models/fsdp2_save.py`: `fsdp2_gathered(model)` reshards every
unit, all-gathers one parameter at a time, and on rank 0 swaps the full
tensors (CPU) into the modules for the duration of the save, then
restores the shards and barriers. 4-bit weights are gathered as raw
bytes and rebuilt as `Params4bit` with their QuantState, so a
dequantizing merge still works. Adapter saves gather only the trainable
weights.
- `save_pretrained` and `save_pretrained_merged` use it when the model
is FSDP2-sharded and no `state_dict` was passed: every rank calls the
save, rank 0 writes. Models that are not sharded are untouched.
- Inside torch's state dict helpers, bitsandbytes `Linear4bit` reports
only weight and bias, which fixes QLoRA checkpoints,
`trainer.save_model` and resume.
- Trainable parameters left out of FSDP2 (`ignored_modules`) now have
their gradients averaged across ranks; before, each rank stepped on its
own gradient and the copies drifted apart.

Evidence (2 GPUs, tiny Llama, bf16):

- Saved adapters and full weights are bit-identical to the gathered
trained parameters for LoRA, LoRA with trained embeddings and lm_head,
QLoRA and full finetuning.
- Merged checkpoints reloaded in plain transformers match the adapter
reload (max logit difference 2e-6 for LoRA and QLoRA) and equal the fp32
merge of the trained weights to 7e-9.
- Resume from a mid-run checkpoint reproduces the continuous run bit for
bit (losses, grad norms, learning rate, final weights) for LoRA, LoRA
with dropout, QLoRA and full finetuning. Zeroing the LoRA B weights or
the Adam moments in the checkpoint changes the resumed losses, so the
state really is loaded.
- New CPU test `tests/test_fsdp2_save_gloo.py` (2 gloo ranks) covers the
gather, the 4-bit byte round trip, the drift of ignored trainable
parameters and the checkpoint state dict of a sharded 4-bit model.

Merged saves hold the full model in rank 0 host RAM (like accelerate's
full state save), and save_pretrained must be called on every rank; a
rank 0 only call waits for the NCCL timeout, with a message saying so.

Not covered: GRPO without fast_inference under FSDP2 still fails in
Unsloth's generation fast path (reads DTensor weights directly), GGUF
and hub-push exports are not wrapped, older torch / accelerate versions
and T4 fp16 were not run.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
yermakoffivan pushed a commit to yermakoffivan/unsloth that referenced this pull request Oct 16, 2026
…unslothai#14023)

Two follow-ups to PRs merged this week, each found by re-checking the
merged code against its parent.

## Changes

**GRPO: the reward locals alias no longer keeps rollout tensors alive**
(follow-up to unslothai#13891)

The reward rewrite (TRL 0.24 and newer) binds `_unsloth_reward_locals =
locals()` in `_generate_and_score_completions`. unslothai#13891 added a later
`locals().get('tool_mask')` call in the same frame. On CPython 3.12 and
older, `locals()` returns the frame's one dict and refreshes it, so the
second call stores that dict inside itself. The cycle keeps every local
of the step, including the concatenated prompt and completion ids and
the reward tensors, alive after the method returns, until the cyclic GC
happens to run. That is GPU memory carried into the training step and
the next rollout. Python 3.13 is not affected (PEP 667). The alias is
now deleted right after the reward call, before anything else calls
`locals()`.

**FSDP2: the automatic mixed precision repair also runs on torch 2.6**
(follow-up to unslothai#13865)

unslothai#13865 switches accelerate's automatic FSDP2 policy to fp32 gradient
reduction when it matches the compute dtype. torch 2.6
`MixedPrecisionPolicy.__post_init__` stores `reduce_dtype = None` when
it equals `param_dtype`, so the `reduce_dtype != compute` check returned
early and torch 2.6 kept reducing fp16 gradients in fp16. `None` means
the same thing there (reduce in the compute dtype), so it now counts as
a match.

## Tests

- `tests/test_grpo_reward_locals_cycle.py`: rewrites the installed TRL
`_generate_and_score_completions` and checks the alias is deleted before
any later `locals()` call (fails on main), plus a frame lifetime check.
A standalone repro of the pattern on CPython 3.12 keeps the object alive
before the change and frees it after; CPython 3.13 frees it either way.
- `test_torch_26_normalized_auto_policy_still_reduces_in_fp32` (fp16 and
bf16): fails on main, passes here.
- `tests/test_grpo_*.py` and `tests/test_fsdp2_*.py`: 380 passed, 25
skipped. `test_fsdp2_default_optim.py` fails the same way on main and on
the pre-week base in this environment, so it is left out here.

---------

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant