Skip to content

FSDP2: shard QLoRA 4-bit weights with fused LoRA kernels kept on - #13880

Merged
danielhanchen merged 38 commits into
mainfrom
dh/fsdp2-qlora
Oct 16, 2026
Merged

danielhanchen merged 38 commits into
mainfrom
dh/fsdp2-qlora

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Stacked on #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.

@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 ✅ Completed 2026-10-16T07:58:06.097432Z 86d4a20 Manual request
🔒 Security Review ⚠️ Failed 2026-10-15T16:11:35.929337Z 73d7771 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 73d7771352

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

…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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 16, 2026
@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: e0f25ffa5c

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

Base automatically changed from dh/fsdp2-core to main October 16, 2026 06:21
get_lora_parameters(_bias) and fast_lora_forward read W.quant_state inline again, and only consult the
Linear4bit's own copy once prepare_fsdp2_qlora has run (the only way a 4-bit weight loses it). Default
LoRA forwards pay no _base_quant_state call.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 86d4a20a12

ℹ️ 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 086db55 into main Oct 16, 2026
@danielhanchen
danielhanchen deleted the dh/fsdp2-qlora branch October 16, 2026 10:48
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>
iam-knoit pushed a commit to SynhalaAI/unsloth that referenced this pull request Oct 19, 2026
unslothai#14231)

## Summary

Follow-up to the unslothai#13880 review.

1. **Process-global QLoRA flag.** `prepare_fsdp2_qlora` set
`unsloth.kernels.utils._FSDP2_QLORA_PREPARED = True`, and the LoRA
getters and `fast_lora_forward` read it before falling back to the
`Linear4bit`'s own `quant_state`. Dynamo guards on a global it reads.
Once one FSDP2 QLoRA model had been prepared, every compiled dense LoRA
forward in the process compiled a second graph. The fallback is now
gated on the weight itself: only an FSDP2 all-gathered 4-bit weight
loses `quant_state`, and its packed bytes are `(N, 1)`. The flag and its
setter are removed.
2. **Block compile and non-reentrant checkpointing.** A non-reentrant
checkpoint ends a recompute by raising `_StopRecomputationError` through
the forward. The block compile wrapper treated that as a compile failure
and put the stock forward back in every block. It now re-raises it.

Without FSDP2 the getters take the same path as before: `getattr(W,
"quant_state")` first, and the shape check only runs when that is
`None`.

## Tests

`tests/python/test_get_lora_parameters_fsdp2_quant_state.py`:

| Case | main | this PR |
|---|---|---|
| a compiled dense LoRA forward, before and after an FSDP2 QLoRA model
is prepared | 2 graphs | 1 graph |
| the getters read no process-global flag | fails | passes |

With the existing fp8 getter tests, `tests/test_block_compile.py`,
`tests/test_fsdp2_qlora.py` and
`tests/test_fsdp2_qlora_prepare_order.py`: 59 passed.

Under a 2-rank launch with Unsloth's block compile, Llama, Qwen3,
Qwen3-MoE, Gemma3, Gemma4 and Qwen2.5-VL show 0 graph breaks and nothing
compiling from step 2 on, LoRA and QLoRA.

## Not covered here

- torch 2.13 only so far; torch 2.10 and 2.14 runs on T4 x2 are in
progress.
- The GatedDeltaNet self-check under a distributed checkpoint is fixed
separately in unslothai#14195.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 19, 2026
…x merged_4bit save (unslothai#14165)

## Summary

Two fixes for opt-in FSDP2 QLoRA (unslothai#13880, unslothai#13895). The default
single-GPU path is unchanged: both only act under FSDP2.

1. **Silent corruption of 4-bit weights in the loader's dtype pass.**
Under FSDP2, the 4-bit weights are stored as packed bytes in float16 /
bfloat16 so they can be sharded, and that happens before
`patch_model_and_tokenizer`. Its dtype passes
(`module.to(module._pre_set_compute_dtype)`, forced float32) cast every
floating parameter of a module, so the packed bytes were converted as if
they were weights. Modules with `_pre_set_compute_dtype` (for example
gpt-oss bnb-4bit experts loaded in float16) ended up with wrong weights
and no error. On a toy layer through the real loader functions, the
weight error was 0.25 before and 0 after.

The vision loader now runs that step inside `packed_4bit_as_uint8`,
which shows the packed bytes as uint8 (what bitsandbytes stores without
FSDP2, and which the dtype passes skip) and restores the float view
afterwards.
2. **`save_pretrained_merged(..., "merged_4bit")` crashed under FSDP2.**
The collective save gathers the shards to rank 0 with `offload_to_cpu =
True`, so the LoRA weights moved to the CPU while the packed 4-bit base
weights stayed on the GPU, and PEFT's merge raised a device mismatch.
For the merged 4-bit methods the gather now keeps only the merge
operands on the GPU: the LoRA weights of layers whose base weight is
packed 4-bit (`offload_all_but_4bit_merge_operands`). Embeddings,
unquantized towers and LoRA on unquantized layers still go to the CPU,
so rank 0 does not hold full unsharded tensors on its GPU. Every other
save method still offloads everything to the CPU.

## Tests

- New `tests/test_fsdp2_qlora_dtype_pass.py`: packed bytes survive the
`_pre_set_compute_dtype` pass in float16 and bfloat16 storage; disabled
and uint8 storage are untouched; without the context the pass does cast
them; the vision loader wraps `patch_model_and_tokenizer`.
- `tests/test_fsdp2_save_args.py`: new
`test_merged_4bit_keeps_gathered_weights_on_their_device` and
`test_merged_4bit_keeps_only_merge_operands_on_the_gpu`.
- 6 of these fail on main; with them and the existing FSDP2 save tests,
45 pass here (GPU). The existing 2-rank gloo save tests pass.

Not run here: real 2-GPU NCCL, a real gpt-oss load, T4 / ROCm,
transformers 4.57.6. Not fixed here: the 4-bit MoE forward under FSDP2
still crashes loudly because the all-gathered weight is a plain
Parameter (follow-up).

---------

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