Repository navigation
FSDP2: save_pretrained, merged saves and 4-bit checkpoints for sharded models - #13895
Conversation
…cked bytes intact
… only via Trainer [skip ci]
…sdp_plugin=...) loops get them
# 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
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| ''' | ||
| exec(push_to_hub_text, globals()) | ||
|
|
||
| @_fsdp2_collective_save(lambda self, args, kwargs: isinstance(self, PeftModel)) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| if dist is not None: | ||
| # The other ranks wait for rank 0's write, so no later collective overtakes it. | ||
| dist.barrier() |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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).
| if ( | ||
| kwargs.get("state_dict") is not None | ||
| or fsdp2_gather_active() | ||
| or not fsdp2_units(self) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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).
…block-only fused LoRA owners, accelerate >= 1.7 for UNSLOTH_FSDP2, PEFT full state dict backport for accelerate < 1.15
… wrap, keep uint8 out of units on torch < 2.8, size-based wrap counts packed bytes
# Conflicts: # unsloth/models/fsdp2.py
# Conflicts: # tests/test_fsdp2_config.py # unsloth/models/fsdp2_qlora.py
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
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]
…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>
… 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.
…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).
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").trainer.save_model()and every Trainer checkpoint fail with'DTensor' object has no attribute 'absmax': torch.distributed.checkpoint resolves bitsandbytes'weight.absmaxkeys as attributes of the sharded weight. Training withsave_stepsdies 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 asParams4bitwith their QuantState, so a dequantizing merge still works. Adapter saves gather only the trainable weights.save_pretrainedandsave_pretrained_mergeduse it when the model is FSDP2-sharded and nostate_dictwas passed: every rank calls the save, rank 0 writes. Models that are not sharded are untouched.Linear4bitreports only weight and bias, which fixes QLoRA checkpoints,trainer.save_modeland resume.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):
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.