Repository navigation
FSDP2 QLoRA merged saves: stage the packed 4-bit base on the CPU and merge one layer at a time - #14823
Conversation
… full DCP load save_pretrained / push_to_hub of a sharded 4-bit model kept every gathered packed weight on rank 0's accelerator, ignoring offload_to_cpu, so the whole quantized base had to fit on one GPU. Saves that only write the packed bytes now stage them, with a CPU copy of their QuantState, on the CPU. Merged saves still dequantize on the device and are unchanged. A full DCP load dropped the saved QuantState entries, so the loaded bytes were silently paired with whatever scales the live model held. They are now copied into the live QuantState in place (broadcast from rank 0 under broadcast_from_rank0), and a mismatching QuantState raises.
…, refuse a packed weight without its QuantState The broadcast_from_rank0 presence flag was a CPU tensor, which an NCCL group cannot broadcast, so the load failed before any QuantState was restored. It now goes through broadcast_object_list. A checkpoint holding a module's packed 4-bit weight but none of its QuantState entries was loaded silently with the live model's scales; it now raises on every rank.
… match the model A full DCP checkpoint written before QuantState entries were saved holds the packed bytes of a frozen QLoRA base, so the live scales are theirs. A packed weight without its QuantState is now compared with the live packed weight (gathered once, uint8): equal bytes keep the live QuantState and load, other bytes still raise. Under broadcast_from_rank0 rank 0 decides and broadcasts the verdict. [skip ci]
…e layer at a time save_pretrained_merged / push_to_hub_merged of a sharded NF4 QLoRA gathered every packed 4-bit weight onto rank 0's GPU and kept it there until the write, so the whole quantized base had to fit on one card above its shards. merged_16bit never reads those bytes (it merges into the 16-bit checkpoint), and merged_4bit only needs one layer at a time. - merged_save_gather_options: both merged saves gather packed weights onto the CPU with a CPU copy of their QuantState; merged_4bit keeps the 4-bit layers' adapters on their device as before. A merged_16bit that folds onto dequant(W4) (falcon_h1) and other export methods keep the old placement. - merge_4bit_lora_layer_by_layer: merged_4bit brings one packed layer back to the device it was gathered on, runs PEFT's own merge there, and stages the requantized weight on the CPU; PEFT's merge_and_unload then only unloads. unmerge_flags undoes the bookkeeping if the export fails. - Written checkpoints are byte for byte the same; non-FSDP2 saves are untouched.
…ve-offload # Conflicts: # tests/test_fsdp2_save_coverage.py # tests/test_fsdp2_save_gloo.py # unsloth/models/fsdp2_save.py # unsloth/save.py
|
@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: e5d5a30521
ℹ️ 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".
| try: | ||
| module.merge() | ||
| except BaseException: | ||
| base_layer._parameters["weight"] = weight | ||
| raise |
There was a problem hiding this comment.
Restore earlier merge flags when a streamed layer fails
If a later layer's module.merge() raises (for example due to GPU OOM), this handler restores only that layer's weight and exits before returning the accumulated merged list, so _unmerge_flags_on_error never sees the layers already merged earlier in the loop. The gather then restores those layers' original unmerged shards, but their merged_adapters lists still claim the adapters are folded into the base; subsequent forwards therefore skip the LoRA contribution and can silently continue with incorrect outputs. Clear the flags for all entries accumulated in merged before re-raising.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 543d150: when a layer's merge raises, the flags of every layer merged earlier in the loop (and that layer's, if PEFT recorded it) are reset before re-raising. New test makes the third of three layers fail and checks none still claims a merge.
…later merge fails [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 543d150fd5
ℹ️ 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".
| raise | ||
| result = base_layer._parameters.get("weight", None) | ||
| if result is not None and getattr(result, "quant_state", None) is not None: | ||
| result = _restage_4bit(result, "cpu") |
There was a problem hiding this comment.
Clear merge flags if the post-merge restage fails
When the post-merge _restage_4bit(result, "cpu") raises—for example, because host memory is exhausted—the adapter has already been added to merged_adapters, but the layer is not appended to merged until later and this exception is outside the cleanup handler. The streamed = merge_4bit_lora_layer_by_layer(model) assignment therefore never completes, so the outer error context cannot clean it either; the gather restores the unmerged FSDP shard while the module still claims it is merged, causing subsequent forwards to omit the LoRA contribution. Include this restage in the per-layer cleanup path and reset the current and previously merged layers before re-raising.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in d720be7: the post-merge restage now sits inside the same per-layer handler, so a failure there resets that layer's and every earlier layer's merge flags before re-raising; new test makes the second restage to CPU fail.
…the merge flags [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d720be78a4
ℹ️ 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".
| home = staged.get(id(weight)) if weight is not None else None | ||
| if home is None: | ||
| continue | ||
| base_layer._parameters["weight"] = _restage_4bit(weight, home) |
There was a problem hiding this comment.
Guard the initial GPU restage with merge cleanup
When _restage_4bit(weight, home) fails for a later layer—for example because that layer cannot be allocated on the GPU—the exception occurs before the try block, so unmerge_flags(merged) is never called for layers merged earlier in the loop. The gather then restores those layers' unmerged shards while their merged_adapters still claim they are merged, causing subsequent forwards to skip their LoRA contributions. Unlike the now-guarded merge and CPU restage, this initial restage must also clear the accumulated flags before propagating the failure.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 96d4963: the GPU restage now runs inside the same try block, so a failure there restores the weight and clears the merge flags of every layer merged earlier in the loop before re-raising. New test test_streamed_merge_gpu_restage_failure_clears_earlier_merge_flags fails on the previous commit and passes now.
… merge flags [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! 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". |
# Conflicts: # unsloth/save.py
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. 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". |
(#14930) Files merged without the repo formatter, so pre-commit.ci's `ruff-format-with-kwargs` hook (which runs on all files) rewrites them on every PR queued after: - `tests/test_fp8_scale_dequant_one_pass.py`: formatted in #14885, then changed again by #14913 (05:27 UTC) - `unsloth/models/fsdp2_save.py`, `tests/test_fsdp2_save_gloo.py`, `tests/test_fsdp2_merged_save_memory_cuda.py`: from #14823 (05:46 UTC), folded in while this was in review Same class as #14817, #14852, #14878, #14885 and #14908. `python scripts/run_ruff_format.py` (the hook's entry point, `ruff==0.6.9`) applied to those four files. Each parses to an identical AST before and after, `ruff check` passes, and a full run of the hook over every tracked Python file on this branch changes nothing else.
…ness (#14961) ## Summary Two save test harnesses fail on main since #14823, 18 tests in `tests/test_merged_hub_destination.py` (Backend CI) and 7 in `tests/saving/test_save_method_lora_routing.py` (every Core matrix cell): ``` E NameError: name '_unmerge_flags_on_error' is not defined ``` Both harnesses rebuild `unsloth_generic_save` and its neighbours from `unsloth/save.py` by AST and runs them against a stub namespace. #14823 wrapped the merge in `with relative, _unmerge_flags_on_error(streamed):` (`save.py:6531`), and the new helper is not in that namespace. Saving itself is unaffected: in `save.py` the helper is defined at module level. ## Change Stub `_unmerge_flags_on_error` as `contextlib.nullcontext()`, next to the existing `lora_relative_to_original_base` stub in each harness, and list it in the routing harness's `_GENERIC_SAVE_STUBBED_HELPERS`, which `test_every_helper_the_generic_save_calls_is_loaded_or_stubbed` checks. The helper only unmerges FSDP2 streamed layers when a save raises, and these fixtures never stream. Pulling in the real function instead does not work here, because the harness strips decorators and it is a `@contextmanager`. Test-only change. ## Testing - `tests/test_merged_hub_destination.py` on main: 18 failed, 38 passed. With this change: 56 passed. - `tests/saving/test_save_method_lora_routing.py` on main: 7 failed. With this change, both files: 114 passed.
Follow up to #14739, which stages the packed NF4 bytes on the CPU for full save_pretrained and push_to_hub but leaves merged saves on the previous placement.
Under FSDP2, save_pretrained_merged and push_to_hub_merged of a sharded NF4 QLoRA gathered every packed 4-bit weight onto rank 0's GPU and kept it there until the write. The whole quantized base therefore had to fit on one card above its shards, so a 70B QLoRA (about 35 GB of packed bytes) could not be merged and saved on a 24 to 48 GB card. Adapter saves were not affected.
Neither merged path needs the whole base on the device at once:
Changes
merged_save_gather_options(fsdp2_save.py): merged_16bit and merged_4bit gather the packed weights onto the CPU with a CPU copy of their QuantState, as FSDP2 NF4 saves: stage packed bytes on the CPU, restore QuantState on full DCP load #14739 does for full saves. merged_4bit still keeps the adapters of 4-bit layers on their device. A merged_16bit that folds the adapter onto dequant(W4) (falcon_h1 in unsloth_zoo) and the other export methods keep the previous placement.merge_4bit_lora_layer_by_layer: for merged_4bit, each packed layer is copied back to the device it was gathered on, merged there with PEFT's ownmerge, and the requantized weight is staged on the CPU again. PEFT'smerge_and_unloadthen finds those layers merged and only unloads them. If the export, a GPU restage, a merge or the CPU restage fails, the merge flags of every layer merged so far are reset, since the gather puts the unmerged sharded weights back._fsdp2_collective_savetakes an optionalgather_optionscallback. Both merged entry points use it. Non-FSDP2 saves are untouched, because the helper only acts inside an FSDP2 gather.The written checkpoints are byte for byte the same as before. The merge runs on the same device with the same operands, only one layer at a time.
Testing
Not covered: a real two-GPU NCCL run and a 30B or larger model. falcon_h1 merged_16bit still dequantizes the live base on the GPU and keeps the previous placement. Covering it needs unsloth_zoo to stage each packed layer to the merge device before that dequantize.