Skip to content

FSDP2: restore the checkpoint's 4-bit QuantState on a full DCP load - #14747

Merged
danielhanchen merged 5 commits into
mainfrom
fsdp2-dcp-restore-quant-state
Oct 25, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
fsdp2-dcp-restore-quant-state

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Problem

#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 FSDP2 NF4 saves: stage packed bytes on the CPU, restore QuantState on full DCP load #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.

A full DCP state dict of a sharded 4-bit model carries bitsandbytes' absmax / quant_map /
nested entries next to the packed bytes, but loading dropped them and kept the live QuantState,
so a checkpoint loaded into a model quantized from other values reported all keys matched and
dequantized every weight with the wrong scales. Copy the saved values into the live QuantState in
place after the load (broadcast from rank 0 with broadcast_from_rank0), and raise when the saved
layout cannot describe the loaded bytes.
@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-25T06:19:35.984494Z 58a1175 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: 685617866f

ℹ️ 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 +490 to +492
if k in keys:
prefix, key = keys[k]
saved.setdefault(prefix, {})[key] = v

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 metadata only when its packed weight was loaded

With strict=False, a partial state dict may contain foo.weight.absmax and the other quantization entries while omitting foo.weight itself, for example after filtering out frozen base parameters by their exact names. These lines still save the metadata, so DCP leaves the destination's packed bytes untouched and _restore_quant_state_entries subsequently overwrites their scales with values from the checkpoint, silently corrupting dequantization. Only restore a prefix when the corresponding packed weight is present, or reject such an incomplete layer.

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.

Good catch, fixed in b11784e36e. When the quantization entries are stripped, the code now checks that <prefix>weight is in the same state dict. If it is missing, that prefix's metadata is set aside and never restored. Under strict=False it is skipped with a warning, so the model keeps its own bytes and scales. Under strict=True the load is rejected. With broadcast_from_rank0 the decision is made on rank 0 and goes out with the existing status broadcast, so all ranks agree. The new 2-rank gloo test, test_full_dcp_load_skips_or_rejects_quant_state_it_cannot_apply, drops 0.weight but keeps its metadata, in both broadcast and sharded mode, and checks that the destination scales and the dequantized weight are unchanged.

Comment thread unsloth/models/fsdp2_save.py Outdated
Comment on lines +478 to +480
for prefix, module in _linear4bit_entries(model):
drop.update(
prefix + "weight." + key for key in module.weight.quant_state.as_dict(packed = True)
)
if not drop:
return args, kwargs
for key in module.weight.quant_state.as_dict(packed = True):
keys[prefix + "weight." + key] = (prefix, key)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Strip metadata keys based on the checkpoint layout

When a nested checkpoint is loaded into a non-nested destination, the live as_dict() used here does not list nested_absmax or nested_quant_map, so those checkpoint-only entries are neither stripped nor included in saved. With strict=False, DCP can ignore the leaked keys, after which QuantState.from_dict receives a metadata blob declaring nesting but no nested tensors and can raise KeyError; because the broadcast path catches only ValueError, rank 0 exits before broadcasting its status while the other ranks block indefinitely. Collect all recognized checkpoint quantization keys independently of the live layout so the mismatch can be reported collectively.

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 b11784e36e. The recognised key suffixes (absmax, quant_map, nested_absmax, nested_quant_map, and the packed nf4 / fp4 entry) are now collected independently of the live QuantState. Checkpoint-only nested keys are therefore taken out and checked, not left behind. Before calling from_dict, a nested vs non-nested mismatch raises a clear ValueError, and any other from_dict failure is converted to one too. On rank 0, the whole check runs under a broad except Exception, so the status is always broadcast. On a mismatch, rank 0 also broadcasts its error message, and every rank raises the same ValueError instead of hanging. The new test loads a nested checkpoint into a non-nested model, both broadcast and sharded, under a 60 s process group timeout. It asserts that both ranks raise the identical error.

… layout mismatch on every rank

A partial state dict under strict=False could carry absmax / quant_map for a
Linear4bit whose packed weight it omits: DCP keeps the live bytes while their
scales were overwritten. Such metadata is now skipped with a warning (rejected
under strict=True).

Quantization keys are recognised independently of the live layout, so a nested
checkpoint loaded into a non-nested model (or the reverse) raises a clear
ValueError instead of half loading. With broadcast_from_rank0, rank 0 catches
any failure before sending its status and every rank raises the same message,
so no rank waits on a collective that never comes.

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

Reviewed commit: b11784eb2c

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

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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: da3b8562e3

ℹ️ 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 self-assigned this Oct 25, 2026
# Conflicts:
#	tests/test_fsdp2_save_gloo.py

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 58a1175b6e

ℹ️ 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 c066804 into main Oct 25, 2026
28 of 37 checks passed
@danielhanchen
danielhanchen deleted the fsdp2-dcp-restore-quant-state branch October 25, 2026 09:31
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