Repository navigation
FSDP2: shard QLoRA 4-bit weights with fused LoRA kernels kept on - #13880
Conversation
…cked bytes intact
… only via Trainer [skip ci]
…sdp_plugin=...) loops get them
# Conflicts: # unsloth/models/fsdp2.py
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. |
|
Codex Review: Didn't find any major issues. Nice work! 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". |
…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.
…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: # tests/test_fsdp2_config.py # unsloth/models/fsdp2_qlora.py
# Conflicts: # tests/test_fsdp2_config.py
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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]
|
@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". |
…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>
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.
…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>
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.
bnb_4bit_quant_storageset 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).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.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.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:
Tests:
tests/test_fsdp2_qlora.py(CPU, gloo, real bitsandbytes layers) andtests/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.