Repository navigation
Dequantize FP8 weights left raw by text_only and offloaded loads - #11841
Conversation
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.
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. |
|
@codex review |
|
@codex security review |
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
There was a problem hiding this comment.
💡 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): |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| state_dict = getattr(store, "state_dict", None) | ||
| if isinstance(state_dict, dict): | ||
| state_dict[key] = value |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! 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". |
…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>
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:text_only=Trueload. transformers' unanchoredmodules_to_not_convertmatch (mlp.gateagainstgate_proj, [Quantization] Anchor should_convert_module regex to stop prefix-matching siblings huggingface/transformers#47990) leavesgate_projas a plainnn.Linearstoring float8_e4m3fn with itsweight_scale_invdropped. The first forward fails:Fix
Before / after (tiny qwen3_5 built like Qwen3.8-27B-FP8, transformers 5.17)
BFloat16 != Float8_e4m3fn; gate_proj rel err vs bf16 reference 5320Real model, B200:
unsloth/Qwen3.8-27B-FP8text_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).