Skip to content

FSDP2 NF4 saves: stage packed bytes on the CPU, restore QuantState on full DCP load - #14739

Merged
danielhanchen merged 3 commits into
mainfrom
dh/s3-fsdp2-nf4-save-cpu
Oct 22, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
dh/s3-fsdp2-nf4-save-cpu

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Two fixes for FSDP2 saves of bitsandbytes 4-bit models (follow-up to #13895, #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.

… 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.
@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-22T21:17:37.814694Z b7f123c 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.

@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: 166d0495d3

ℹ️ 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
Comment on lines +499 to +502
has = torch.tensor([int(any(
k.startswith(prefix + "weight.") for prefix, _ in entries for k in state_dict
))])
dist.broadcast(has, src = 0)

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 Put the presence flag on an NCCL-compatible device

When broadcast_from_rank0=True is used with the normal GPU/NCCL FSDP2 process group, torch.tensor(...) creates this flag on the CPU, but NCCL cannot broadcast CPU tensors. The load therefore fails at this collective before any saved QuantState is restored; the added coverage uses only gloo and does not exercise the production NCCL path. Create the flag on the active accelerator or use a backend-compatible object broadcast.

Useful? React with 👍 / 👎.

Comment on lines +519 to +520
if not saved:
continue

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 Reject loaded 4-bit weights that have no quantization state

When a checkpoint contains this module's packed weight but omits all of its QuantState entries, as can happen with an incomplete or filtered full DCP state dict, this branch silently continues. DCP then loads the packed bytes while retaining the live model's old scales and can report that all expected model keys matched, recreating the silent weight corruption this change is intended to prevent. Missing state should only be ignored when the corresponding packed weight is not being loaded; otherwise the load should fail.

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 the latest commits. When a module's packed weight is loaded without any of its QuantState entries, the load now compares the loaded packed bytes with the live packed weight once:

  • different bytes: raises a ValueError naming the module (the silent corruption case you describe);
  • identical bytes: keeps the live QuantState and loads. This is what every full DCP checkpoint written before this PR looks like (frozen QLoRA base, no QuantState saved), so those keep resuming instead of being refused.

Under broadcast_from_rank0 rank 0 decides and broadcasts the verdict, so all ranks raise or load together. Tests cover both cases on gloo with and without broadcast, and a 2-GPU NCCL run gave the same results.

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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: b7f123c0a6

ℹ️ 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 59cd08b into main Oct 22, 2026
@danielhanchen
danielhanchen deleted the dh/s3-fsdp2-nf4-save-cpu branch October 22, 2026 23:08
danielhanchen added a commit that referenced this pull request Oct 22, 2026
pre-commit.ci fails `ruff-format-with-kwargs` on every open PR (#14806,
#14805, #14803, #14790, #14785, #14781, #14780, #14777, #14776, #14775,
#14774, #14773, #14772, #14770, #14769, #14768, and others): "files were
modified by this hook". pre-commit.ci runs the hooks on all files, and
20 files on main (26 by the time this lands) are not in the formatter's
output, so every PR is reformatted outside its own diff. Where
pre-commit.ci can push, its autofix commit drags those unrelated files
into the PR (for example #14790's touches `tests/test_block_compile.py`,
`tests/test_bnb_integration_compile.py` and `unsloth/models/_utils.py`).

The drift came in with PRs merged today, among them #14702, #14751,
#14759, #14784, #14786, #14787, #14788, #14791 and the FP8 block decode,
GRPO routing replay, 4-bit decode, compiled blocks and MoE LoRA target
changes.

### Change

`python scripts/run_ruff_format.py` (the hook's own entry point,
`ruff==0.6.9` as pinned in `.pre-commit-config.yaml`) applied to those
20 files, plus 6 more from #14739, #14779 and #14806, which merged while
this was open. Formatting only.

### Verification

- Every changed file parses to an identical AST before and after.
- A second run of the hook over the same files changes nothing (fixed
point), and over all tracked Python files on this branch it changes
nothing.
- `ruff check` passes on the changed files;
`tests/test_formatter_fixed_point.py` passes (16).

Open PRs pick this up on their next pre-commit.ci run after merging
main.
danielhanchen added a commit that referenced this pull request Oct 23, 2026
main landed #14739, which restores the checkpoint's 4-bit QuantState on a
full DCP load with its own design (_restore_quant_state runs before DCP
loads, broadcasts the entries as objects so NCCL never sees a CPU tensor,
and accepts a legacy checkpoint without QuantState entries only when its
packed bytes equal the live ones). That overlaps this branch, so the
resolution keeps main's implementation and layers on what is unique here.

unsloth/models/fsdp2_save.py:
- Took main's install_dcp_bnb_state_dict wrapper, _restore_quant_state and
  _without_quant_state_entries. Dropped this branch's post-load
  _restore_quant_state_entries / _checkpoint_quant_state and its status
  tensor broadcast: main covers the same restore, and every rank already
  raises identically because the entries reach all ranks by object
  broadcast.
- Kept from this branch: QuantState entries that arrive without their
  packed weight (a partial state dict) are not applied, since DCP keeps the
  live bytes. strict (the default) raises; strict=False warns and keeps the
  live QuantState. main copied those scales onto the live bytes.
- Kept from this branch: a nested checkpoint into a non-nested model (or
  the reverse) raises a message naming the nesting and
  bnb_4bit_use_double_quant, ahead of main's generic key set check.
- Kept from this branch: every key bitsandbytes can write for a QuantState
  (_QUANT_STATE_KEYS) is dropped before DCP, whatever the live layout.

tests/test_fsdp2_save_gloo.py:
- Kept both sides: this branch's dcp_restore and dcp_restore_guard cases
  and tests, and main's _nf4_model, gather_4bit_offload, dcp_quant_state,
  dcp_quant_state_missing and nccl_quant_state cases and tests; both worker
  dispatch blocks.
- dcp_restore's mismatch check now matches main's wording ("4-bit
  quantization state") instead of "quantization metadata".

[skip ci]
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 23, 2026
…merge one layer at a time (unslothai#14823)

Follow up to unslothai#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 unslothai#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 unslothai#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.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 25, 2026
…nslothai#14747)

## Problem

unslothai#14739 restores the checkpoint's 4-bit QuantState on a full DCP load.
One case it still gets wrong: a partial state dict that holds a layer's
QuantState entries (`weight.absmax`, `weight.quant_map`,
`weight.quant_state.bitsandbytes__nf4`, ...) but not its packed
`weight`, loaded with `strict=False`. DCP keeps the model's own packed
bytes for that layer, but `_restore_quant_state` still copied the
checkpoint's scales into the live QuantState, so the layer dequantizes
the old bytes with the new scales and nothing reports it.

Repro on main (2 CPU gloo ranks, source quantized from `0.1*W`,
destination from `0.05*W`, `0.weight` removed from the state dict):
`scales False` on both ranks, for both the `broadcast_from_rank0` full
state dict and the sharded state dict.

A nested (double quant) checkpoint loaded into a non-nested model
already raised on main, but with an entry list that does not say what is
wrong.

## Change

- `_restore_quant_state` skips QuantState entries whose packed weight is
not in the state dict. With `strict=True` (the default) it raises a
ValueError on every rank. With `strict=False` it keeps the live weight
and QuantState and warns once (rank 0 only under
`broadcast_from_rank0`).
- A nested vs non-nested mismatch raises a ValueError that names
`bnb_4bit_use_double_quant`.
- `_without_quant_state_entries` drops every QuantState key bitsandbytes
can write (nested or not, nf4 or fp4), so a `strict=False` load whose
metadata was skipped never passes DCP a key it cannot resolve.
- Full loads that carry both the weight and its QuantState, adapter-only
loads, legacy checkpoints without QuantState entries and optimizer loads
take the same path as before.

## Tests

`tests/test_fsdp2_save_gloo.py` (2 gloo ranks, CPU):
- New `test_full_dcp_load_skips_or_rejects_quant_state_it_cannot_apply`:
QuantState without its packed weight (broadcast and sharded) leaves the
live scales alone and rank 0's dequantized weight unchanged, and a
nested checkpoint into a non-nested model raises the same error on every
rank. Fails on main, passes here.
- New `test_full_dcp_load_restores_the_checkpoint_quant_state`:
regression coverage for the unslothai#14739 restore through the sharded state
dict as well as the full broadcast one, nested and not, plus a
block-size mismatch. Passes on main and here.
- `_run` terminates leftover worker processes if a rank never reports.
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