Skip to content

FSDP2: save_pretrained, merged saves and 4-bit checkpoints for sharded models - #13895

Merged
danielhanchen merged 53 commits into
mainfrom
dh/fsdp2-save
Oct 16, 2026
Merged

danielhanchen merged 53 commits into
mainfrom
dh/fsdp2-save

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Stacked on #13880 (FSDP2 QLoRA), which is stacked on #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.

# Conflicts:
#	unsloth/models/fsdp2.py
…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.
…ix 4-bit checkpoints, reduce unsharded trainable grads
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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-16T07:55:16.067341Z 5e9e39a New commits
🔒 Security Review ⚠️ Failed 2026-10-15T17:12:24.965533Z ce34884 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 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: ce348846f1

ℹ️ 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/save.py
'''
exec(push_to_hub_text, globals())

@_fsdp2_collective_save(lambda self, args, kwargs: isinstance(self, PeftModel))

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 Gather frozen adapter state selected by PEFT

For an FSDP2 PeftModel, this always selects trainable_only=True, but PEFT can serialize frozen parameters: save_pretrained() defaults to saving every adapter, including inactive adapters whose parameters have requires_grad=False, and save_embedding_layers=True or its automatic equivalent can include frozen base embeddings. Those selected tensors remain DTensor shards, so safetensors can fail with the same invalid-storage error this wrapper is intended to prevent, or the checkpoint can contain non-gathered values. The gather decision must account for the adapters and embedding layers PEFT will actually save rather than using requires_grad alone.

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 e3bd2c4: PEFT adapter saves now also gather the frozen tensors PEFT will write: every adapter's parameters (inactive adapters included), modules_to_save copies, and the input/output embeddings unless save_embedding_layers=False. Arguments are bound against the original save_pretrained, so the positional form works too, and fsdp2_gathered takes an include(name, param) selector. Tests: test_peft_saves_gather_the_frozen_tensors_peft_writes, plus an include case in the gloo gather test.

Comment on lines +198 to +200
if _DCP_DEPTH[0]:
return torch.nn.Module._save_to_state_dict(self, destination, prefix, keep_vars)
return original_save(self, destination, prefix, keep_vars)

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 Limit the bnb override to adapter-only checkpoints

Whenever any patched DCP helper is active, this bypasses Linear4bit._save_to_state_dict and drops its weight.absmax and quantization metadata. Because install_fsdp2_hooks() installs the override globally on ordinary Unsloth import, a user taking a full DCP checkpoint of a bitsandbytes model—not just the intended ignore_frozen_params=True adapter checkpoint—silently records packed weights without the data required to reconstruct or dequantize them. Scope this behavior to the adapter-only FSDP2 path instead of every DCP state-dict operation.

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 e3bd2c4: the Linear4bit state dict override now applies only to adapter-only DCP calls (accelerate's _get/_set_model_state_dict with adapter_only=True, or an explicit options.ignore_frozen_params=True). Any other DCP state dict keeps weight.absmax and the quant_state entries. test_dcp_state_dict_of_bitsandbytes_4bit now checks that a full get_model_state_dict keeps "0.weight.absmax" and that the adapter-only path still works.

Comment thread unsloth/models/fsdp2_save.py Outdated
Comment on lines +161 to +163
if dist is not None:
# The other ranks wait for rank 0's write, so no later collective overtakes it.
dist.barrier()

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 Avoid holding non-writer ranks in a timed barrier

On every save, nonzero ranks reach this barrier immediately while rank 0 joins only after completing the entire write. For large merged saves—and especially the newly wrapped compressed exports, which run a quantization subprocess and may upload to the Hub—rank 0 can legitimately take longer than the process group's default collective timeout, causing the waiting NCCL ranks to abort before the writer arrives and making an otherwise successful export fail. The writer needs a synchronization mechanism that remains alive during long-running I/O rather than one barrier whose timeout covers the whole save.

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 e3bd2c4: the closing dist.barrier() is replaced by a wait on the default c10d store. Rank 0 sets a per-save key after writing and the other ranks store.wait on it with UNSLOTH_FSDP2_SAVE_TIMEOUT (default 7 days), so no collective is pending during rank 0's I/O and the process group timeout no longer applies. It falls back to a barrier only if no default store exists. Test: test_a_slow_writer_does_not_time_out_the_other_ranks (4 s group timeout, 10 s write).

Comment thread unsloth/save.py Outdated
Comment on lines +5781 to +5784
if (
kwargs.get("state_dict") is not None
or fsdp2_gather_active()
or not fsdp2_units(self)

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 Detect positional state_dict arguments before gathering

This bypass only recognizes a keyword state_dict, although both Transformers' save_pretrained and save_pretrained_merged accept it positionally. A caller that already gathered a full state dict and invokes the supported positional form—often on rank 0 only—therefore unexpectedly enters the collective gather and hangs waiting for ranks that correctly were not needed for that supplied state dict. Bind the wrapped function's arguments, or inspect the appropriate positional slot, before deciding that a collective is required.

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 e3bd2c4: _fsdp2_collective_save binds the call's arguments before deciding to gather (against the wrapped function, or the original save_pretrained when the wrapper only forwards *args), so a positional or keyword state_dict passes straight through with no collective. Test: test_a_positional_state_dict_is_passed_through (positional for save_pretrained_merged and PreTrainedModel.save_pretrained).

@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. Chef's kiss.

Reviewed commit: 1564f9c588

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

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

Reviewed commit: 128c721bfa

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

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]
Base automatically changed from dh/fsdp2-qlora to main October 16, 2026 10:48
@danielhanchen
danielhanchen merged commit 81e51f6 into main Oct 16, 2026
@danielhanchen
danielhanchen deleted the dh/fsdp2-save branch October 16, 2026 10:49
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>
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.
Stanley00 pushed a commit to stanley-fork/unsloth that referenced this pull request Nov 15, 2026
…checks (unslothai#17869)

Without bitsandbytes installed, `from bitsandbytes.nn import Linear4bit`
returns unsloth_zoo's stub, which is an instance rather than a class.
The FSDP2 save helpers' `isinstance(m, Linear4bit)` checks then raised
`TypeError`. That broke every full DCP state dict, including
`Trainer.save_model` under FSDP2 / TP, on such hosts. The bug has been
on main since unslothai#13895.

A small `_linear4bit_class()` helper now returns the class only when it
really is one. The four call sites skip the bitsandbytes handling when
it isn't.

- **Flip test** `tests/test_fsdp2_save_bnb_stub.py`: `TypeError` on
main, passes here.
- **Existing tests:** `test_fsdp2_save_args.py` and
`test_fsdp2_save_coverage.py` pass (33 total with the new test).
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