Skip to content

Dequantize FP8 weights left raw by text_only and offloaded loads - #11841

Merged
danielhanchen merged 8 commits into
mainfrom
qwen35-eval-forward
Sep 25, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
qwen35-eval-forward

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

Two ways a block-FP8 checkpoint (for example unsloth/Qwen3.8-27B-FP8) ends up with a projection that holds raw fp8 values and no scale:

  1. text_only=True load. transformers' unanchored modules_to_not_convert match (mlp.gate against gate_proj, [Quantization] Anchor should_convert_module regex to stop prefix-matching siblings huggingface/transformers#47990) leaves gate_proj as a plain nn.Linear storing float8_e4m3fn with its weight_scale_inv dropped. The first forward fails:
    RuntimeError: expected mat1 and mat2 to have the same dtype, but got: c10::BFloat16 != c10::Float8_e4m3fn
    
  2. Offloaded layers. When accelerate offloads a layer to CPU or disk, the existing dropped-scale restore skipped it ("25 dropped FP8 weight_scale_inv tensor(s) skipped because the layer is disk-offloaded"), so that layer ran unscaled.

Fix

  • A plain Linear holding fp8 values with an orphaned scale is dequantized to the compute dtype with the checkpoint's block scale.
  • Offloaded layers are restored through accelerate's weights map, so the offloaded copy is scaled too. Healthy offloaded FP8Linear layers are no longer counted as skipped.
  • A 16/32-bit weight is scaled only while it still holds raw fp8 values (every element on the e4m3 / e5m2 grid). A weight that was already dequantized upstream (for example by unsloth-zoo#1339) is left alone, so it is never scaled twice.

Before / after (tiny qwen3_5 built like Qwen3.8-27B-FP8, transformers 5.17)

Case main this PR
text_only FP8 load, eval BFloat16 != Float8_e4m3fn; gate_proj rel err vs bf16 reference 5320 runs; gate_proj rel err 0.0267 (fp8 floor), logits bit-identical to the full load
Full load, 200MB offload logits max-abs 2.25 off the non-offloaded load bit-identical
With unsloth-zoo#1339 merged (it dequantizes first) gate_proj rel err 0.9998 (scaled twice) 0.0265, bit-identical
Dense bf16 and NF4 loads same code path runs, logits bit-identical
Restore-helper enumeration (84 cells) 36 identical; the 48 that move all crashed, ran unscaled, or only had a warning / count fixed

Real model, B200: unsloth/Qwen3.8-27B-FP8 text_only, 10 step LoRA SFT with unsloth-zoo#1380: wikitext-2 PPL 6.717 (bf16 checkpoint 6.708), loss 1.06 to 0.45. On main the first eval forward fails as above.

Tests

tests/test_fp8_restore_dropped_scale.py: 23 passed on transformers 5.17 and 5.4. Includes an fp8 weight and a raw bf16 weight each scaled once, an already-dequantized weight skipped, and the offloaded path on CPU and disk. Nine existing fixtures now build their raw weights on the fp8 grid, as a real load does; their assertions are unchanged.

Pairs with unsloth-zoo#1380 (no-autocast LoRA forward on FP8 weights).

unsloth/Qwen3.8-27B-FP8 lists `model.language_model.layers.N.mlp.gate` in
modules_to_not_convert. transformers' should_convert_module prefix-matches that
entry against `mlp.gate_proj`, so gate_proj stays a plain nn.Linear and its
weight_scale_inv is dropped as an unexpected key.

On a full load the raw fp8 values are cast to bf16 and
_restore_dropped_fp8_scales rescales them (#6200). With text_only=True the key is
renamed (`model.language_model.*` -> `model.*`), and transformers 5 keeps the
checkpoint dtype for renamed keys on pre-quantized loads, so gate_proj keeps a
raw fp8 weight. The restore helper took any fp8 weight for a converted FP8Linear
and skipped it, so the eval forward failed with
`expected mat1 and mat2 to have the same dtype, but got: BFloat16 != Float8_e4m3fn`.

A module holding an fp8 weight without its own weight_scale_inv / weight_scale
is now dequantized into the load dtype (passed from the three loader call sites,
falling back to config dtype, the embedding dtype, then bfloat16). The result is
bit-identical to the unrenamed load. Real FP8Linear / FbgemmFp8Linear modules
still carry their scale and are skipped as before.
…eights map

When a device map offloads part of an FP8 checkpoint (a text_only
Qwen3.8-27B-FP8 load on a GPU that is partly in use already), the orphaned
gate_proj weights of the offloaded layers are meta placeholders, and the restore
helper skipped them with a warning. The text_only forward then still hit a raw
fp8 weight on those layers (`BFloat16 != Float8_e4m3fn`), and an unrenamed load
ran them unscaled.

For a meta weight, find the store accelerate materializes it from (the
OffloadedWeightsLoader behind the hooks' PrefixedDataset), dequantize a copy of
the stored tensor and write it into the loader's in-memory state_dict, which it
reads before the disk index, then recast the placeholder so accelerate's cast on
materialize keeps the dequantized dtype. Converted fp8 modules that carry their
own scale are now skipped before the offload check, so they no longer inflate
the "offloaded" warning. The in-place scaling is moved into
_apply_fp8_block_scale unchanged.
_restore_dropped_fp8_scales treated every 16/32-bit weight that has a checkpoint
weight_scale_inv as raw values transformers cast without their scale. That is
true on a plain load, but not once a load-time dequantize has already folded
the scale in: with unslothai/unsloth-zoo#1339 (dequantize fp8 weights that have
no FP8 container) the orphaned mlp.gate_proj of Qwen3.8-27B-FP8 was scaled a
second time, leaving it at a relative error of 1.0 against the bf16 weights,
on device and, since the offload restore, on offloaded layers too.

A 16/32-bit weight is now scaled only while every element lies exactly on the
e4m3 or e5m2 grid, which raw widened fp8 values always do and scale-multiplied
values practically never do. The offload path decides from the stored tensor
accelerate materializes. Checking the dtype alone is not enough: an unrenamed
load hands the raw values over as bf16, and that is the case the helper exists
for (#6200).

Tiny qwen3_5 FP8 on transformers 5.17: with #1339, gate_proj goes from 0.9998
back to 0.0267 relative error and the logits match the reference exactly, on
full, text_only and offloaded loads; without it every cell is unchanged. The
fixtures that stood in for raw weights with arbitrary bf16 values now use
fp8-grid values, as a real load produces.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 24, 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-09-25T15:57:31.884133Z 461fff4 Manual request
🔒 Security Review ✅ Completed 2026-09-25T14:56:57.269484Z 0a2ac91 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

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 0a2ac916c4

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@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: 0a2ac916c4

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

for fp8 in _FP8_DTYPES:
for start in range(0, flat.numel(), chunk_elements):
chunk = flat[start : start + chunk_elements]
if not torch.equal(chunk.to(fp8).to(chunk.dtype), chunk):

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 Track dequantization instead of guessing from the FP8 grid

When an already-dequantized weight still lies on the FP8 grid, this equality returns true and the checkpoint scale is applied again. For example, raw values of 1 with a valid block scale of 0.5 produce dequantized values of 0.5, which round-trip through FP8 exactly; the helper therefore changes them to 0.25. The same case also makes a second invocation non-idempotent, silently corrupting model outputs, so restoration state cannot be inferred solely from representable values.

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.

Not reachable on real checkpoints: a folded weight only stays on the fp8 grid if every element does, which needs block scales near 1. Measured 0 of 100 misreads on realistic weights (std 0.006 to 1.0, 20 seeds) with power-of-two ue8m0 scales, and 0 across bf16/fp16 with arbitrary scales; the restore also runs once per load, so there is no second invocation to make idempotent.

Comment on lines +1374 to +1376
state_dict = getattr(store, "state_dict", None)
if isinstance(state_dict, dict):
state_dict[key] = value

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 Keep restored disk-offloaded tensors on disk

When the affected layer was assigned to "disk", this inserts its dequantized tensor into OffloadedWeightsLoader.state_dict, which is an in-memory override and remains resident for the model's lifetime. Thus every restored FP8 tensor bypasses disk offloading and also expands from FP8 to 16/32-bit storage; on the large models that require disk offload, the affected projections can consume several additional GiB and exhaust host RAM during loading. The restored value needs to remain disk-backed or be transformed lazily rather than retained in this dictionary.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in 461fff4: a disk-offloaded orphan is now written to a new .dat in the offload folder through accelerate's offload_weight (index entry replaced, checkpoint untouched), so nothing is held in RAM; covered by test_disk_offloaded_orphan_stays_on_disk.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 461fff455d

ℹ️ 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 a20dcb2 into main Sep 25, 2026
4 of 35 checks passed
@danielhanchen
danielhanchen deleted the qwen35-eval-forward branch September 25, 2026 17:32
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…lothai#11841)

* Dequantize fp8 weights left in plain Linears by a text_only FP8 load

unsloth/Qwen3.8-27B-FP8 lists `model.language_model.layers.N.mlp.gate` in
modules_to_not_convert. transformers' should_convert_module prefix-matches that
entry against `mlp.gate_proj`, so gate_proj stays a plain nn.Linear and its
weight_scale_inv is dropped as an unexpected key.

On a full load the raw fp8 values are cast to bf16 and
_restore_dropped_fp8_scales rescales them (unslothai#6200). With text_only=True the key is
renamed (`model.language_model.*` -> `model.*`), and transformers 5 keeps the
checkpoint dtype for renamed keys on pre-quantized loads, so gate_proj keeps a
raw fp8 weight. The restore helper took any fp8 weight for a converted FP8Linear
and skipped it, so the eval forward failed with
`expected mat1 and mat2 to have the same dtype, but got: BFloat16 != Float8_e4m3fn`.

A module holding an fp8 weight without its own weight_scale_inv / weight_scale
is now dequantized into the load dtype (passed from the three loader call sites,
falling back to config dtype, the embedding dtype, then bfloat16). The result is
bit-identical to the unrenamed load. Real FP8Linear / FbgemmFp8Linear modules
still carry their scale and are skipped as before.

* Restore dropped FP8 scales on offloaded layers through accelerate's weights map

When a device map offloads part of an FP8 checkpoint (a text_only
Qwen3.8-27B-FP8 load on a GPU that is partly in use already), the orphaned
gate_proj weights of the offloaded layers are meta placeholders, and the restore
helper skipped them with a warning. The text_only forward then still hit a raw
fp8 weight on those layers (`BFloat16 != Float8_e4m3fn`), and an unrenamed load
ran them unscaled.

For a meta weight, find the store accelerate materializes it from (the
OffloadedWeightsLoader behind the hooks' PrefixedDataset), dequantize a copy of
the stored tensor and write it into the loader's in-memory state_dict, which it
reads before the disk index, then recast the placeholder so accelerate's cast on
materialize keeps the dequantized dtype. Converted fp8 modules that carry their
own scale are now skipped before the offload check, so they no longer inflate
the "offloaded" warning. The in-place scaling is moved into
_apply_fp8_block_scale unchanged.

* Only scale an orphaned FP8 weight that still holds raw fp8 values

_restore_dropped_fp8_scales treated every 16/32-bit weight that has a checkpoint
weight_scale_inv as raw values transformers cast without their scale. That is
true on a plain load, but not once a load-time dequantize has already folded
the scale in: with unslothai/unsloth-zoo#1339 (dequantize fp8 weights that have
no FP8 container) the orphaned mlp.gate_proj of Qwen3.8-27B-FP8 was scaled a
second time, leaving it at a relative error of 1.0 against the bf16 weights,
on device and, since the offload restore, on offloaded layers too.

A 16/32-bit weight is now scaled only while every element lies exactly on the
e4m3 or e5m2 grid, which raw widened fp8 values always do and scale-multiplied
values practically never do. The offload path decides from the stored tensor
accelerate materializes. Checking the dtype alone is not enough: an unrenamed
load hands the raw values over as bf16, and that is the case the helper exists
for (unslothai#6200).

Tiny qwen3_5 FP8 on transformers 5.17: with unslothai#1339, gate_proj goes from 0.9998
back to 0.0267 relative error and the logits match the reference exactly, on
full, text_only and offloaded loads; without it every cell is unchanged. The
fixtures that stood in for raw weights with arbitrary bf16 values now use
fp8-grid values, as a real load produces.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim comments in FP8 restore helpers

* Drop narration comments in FP8 restore

* Keep restored disk-offloaded FP8 tensors on disk instead of in RAM

* Tighten disk-offload test docstring

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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.

2 participants