Skip to content

FSDP2 QLoRA merged saves: stage the packed 4-bit base on the CPU and merge one layer at a time - #14823

Merged
danielhanchen merged 9 commits into
mainfrom
dh/s3-fsdp2-merged-save-offload
Oct 23, 2026
Merged

danielhanchen merged 9 commits into
mainfrom
dh/s3-fsdp2-merged-save-offload

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

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:

  • merged_16bit merges into the 16-bit checkpoint it reads from disk and only takes the LoRA weights from the model.
  • merged_4bit runs PEFT's merge, which dequantizes, adds the delta and requantizes one layer at a time.

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 own merge, and the requantized weight is staged on the CPU again. PEFT's merge_and_unload then 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.
  • save.py: _fsdp2_collective_save takes an optional gather_options callback. 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

  • New gloo test: a real PEFT LoRA over bitsandbytes NF4 layers, sharded on two CPU ranks. The old and new placements both write the same bytes as an unsharded merge. With the new options, every packed weight leaves the device as it is gathered, and only one layer is ever back on it (restage, merge, restage per layer).
  • New CUDA test: 64 NF4 layers of 2048x2048, one rank with CPU-offloaded shards so every gather allocates on the GPU. Peak writer GPU memory above the shards:
    • merged_16bit: 134.3 MB (the whole packed base) before, 2.1 MB (one layer) after.
    • merged_4bit: 382.4 MB before, 84.7 MB after (one layer's merge temporaries plus the adapters, independent of depth).
    • Written bytes are identical in both cases. Same results on torch 2.10.
  • End to end through save_pretrained_merged on a tiny 4-bit Llama under FSDP2: merged_4bit_forced and merged_16bit write the same model.safetensors (same sha256) with the old and new placement, and the streamed merge ran for all 14 LoRA layers.
  • The new tests and the updated coverage test fail on FSDP2 NF4 saves: stage packed bytes on the CPU, restore QuantState on full DCP load #14739's head and pass here. The FSDP2 save, checkpoint, context parallel save and QLoRA suites pass on torch 2.13 and 2.10.

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.

… 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
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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-23T04:48:19.084486Z 7bb036a Manual request
ℹ️ 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: 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".

Comment on lines +387 to +391
try:
module.merge()
except BaseException:
base_layer._parameters["weight"] = weight
raise

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 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 👍 / 👎.

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

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 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".

Comment thread unsloth/models/fsdp2_save.py Outdated
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")

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 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 👍 / 👎.

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

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 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".

Comment thread unsloth/models/fsdp2_save.py Outdated
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)

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 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 👍 / 👎.

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

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 96d49637cb

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

# Conflicts:
#	unsloth/save.py
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 7bb036aecb

ℹ️ 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 bb166e3 into main Oct 23, 2026
3 of 29 checks passed
@danielhanchen
danielhanchen deleted the dh/s3-fsdp2-merged-save-offload branch October 23, 2026 05:46
danielhanchen added a commit that referenced this pull request Oct 23, 2026
 (#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.
danielhanchen added a commit that referenced this pull request Oct 23, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant