Skip to content

Finish a 16bit load of a static per-tensor fp8 checkpoint (Mistral-Small-4) - #11531

Merged
danielhanchen merged 19 commits into
mainfrom
fp8-static-checkpoint-16bit-load
Sep 25, 2026
Merged

danielhanchen merged 19 commits into
mainfrom
fp8-static-checkpoint-16bit-load

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

What

load_in_16bit = True on a static per-tensor fp8 checkpoint now finishes the dequantization transformers leaves half done, so Mistral-Small-4-119B-2603 (which Mistral only ships in fp8) trains in 16bit instead of stopping at the first forward.

How

With load_in_16bit the loader passes dequantize = True to transformers' fp8 quantizer. transformers folds weight_scale_inv into every nn.Linear weight it has a converter for, but the MoE stacks of a static checkpoint are stored as experts.gate_up_proj with a sibling experts.gate_up_proj_scale_inv: no .weight suffix, so no converter matches, the raw fp8 values land in the plain Mistral4Experts parameter and the scale is dropped as an unexpected key. The first forward feeds float8 into torch._grouped_mm:

RuntimeError: Expected mat_a to be Float32, BFloat16 or Float16 matrix, got Float8_e4m3fn

_dequantize_leftover_fp8_params in loader_utils.py runs after the load, next to the existing dropped-scale repair. For every fp8 parameter whose module carries no scale of its own it reads the checkpoint scale back (per-tensor, per-expert or a block grid, with the block implied by the weight shape the way transformers' own dequantize derives it) and replaces the parameter with its 16bit value. A converted FP8Linear or FP8Experts keeps its scale and its fp8 forward and is left alone, so a healthy load is a no-op. The card can be full to its planned 16bit size while its stacks are still fp8, which leaves room for the result but not for the transient; such a stack is parked on the CPU (freeing its fp8 bytes), dequantized there and moved back once the rest of the card is at its final size. The leftover activation_scale parameters of a static checkpoint are dropped with the weights they described.

Measurements

unsloth/Mistral-Small-4-119B-2603, LoRA r=16 on every module including the expert stacks, 10 steps, seq 512, two B200s:

cell main this PR
16bit fails at step 1, 116 GB of fp8 left in plain modules 10 steps, loss 0.726 to 1.099, 4.23 s per step, 72 stacks dequantized, peak 169 + 187 GB
fp8 (as published) 10 steps, loss 0.721 to 1.091 unchanged

The 16bit and fp8 curves agree step for step (0.7263 / 0.7213, 0.9757 / 0.9792, ... 1.0994 / 1.0908). The plain HF + TRL baseline cannot run this cell at all: FineGrainedFP8Config(dequantize = True) leaves the same fp8 stacks behind and stops on the same error, and the published fp8 form is refused by TRL as untrainable.

Tests

tests/test_fp8_leftover_dequant_16bit.py, 14 offline tests: expert stacks dequantized bit-exactly from the checkpoint scale while an already-dequantized dense weight is untouched, a module with a live scale is left in fp8, no fp8 parameters means the checkpoint is not read, the language_model.model.* VLM key remap resolves, every scale layout against an expanded reference, a grid that does not tile is refused, and the out-of-memory deferral round-trips through the CPU. The module-level test fails on main (ImportError); the 16bit cell above is the GPU differential.

Compatibility

Pure PyTorch over the loaded module tree and the safetensors index, no Triton, no CUDA-only calls, and the same shard resolution as _restore_dropped_fp8_scales. Only reached with load_in_16bit = True and only when fp8 parameters survive the load, so 4bit, 8bit, fp8 and full-precision loads are untouched. transformers 4.57.6 (no dequantize on the fp8 config, so the quantizer keeps FP8Linear modules with their scales and the pass skips them) and 5.x, PEFT 0.18 to 0.21, torch 2.6 and later, Linux, macOS, Windows and WSL.

Companion: unslothai/unsloth-zoo#1321 handles the coarse per-expert scale in the fp8 expert dequant kernel, which is what the same checkpoint hit in its fp8 form.

With load_in_16bit = True on an fp8 checkpoint the loader asks transformers to
dequantize on load, but transformers only folds weight_scale_inv into weights
it has a converter for. A static per-tensor checkpoint such as
Mistral-Small-4-119B ships its MoE stacks as experts.gate_up_proj with a
sibling experts.gate_up_proj_scale_inv (no .weight suffix), so no converter
matches, the raw fp8 values land in the plain Mistral4Experts module and the
scale is dropped as an unexpected key. The first forward then feeds float8
into torch._grouped_mm and training stops before step 1.

After the load, every fp8 parameter whose module carries no scale of its own
is dequantized from the checkpoint scale (per-tensor, per-expert or block
grid) and replaced with its 16bit value. A converted FP8Linear or FP8Experts
keeps its scale and its fp8 forward and is left alone. A card that is already
at its planned 16bit size while its stacks are still fp8 has no room for the
dequant transient; such a stack is parked on the CPU, dequantized there and
moved back once the rest of the card is at its final size.

Mistral-Small-4-119B-2603 in 16bit on two B200s trains 10 steps, loss 0.73 to
1.10 tracking the fp8 cell step for step, where main stops at the first
forward. Fourteen offline tests cover the scale layouts, the VLM key remap,
the converted-module skip and the out-of-memory deferral.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 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 ⚠️ Failed 2026-09-25T19:28:14.318511Z e76c32f New commits
ℹ️ 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[bot]

This comment was marked as resolved.

danielhanchen and others added 3 commits September 22, 2026 06:35
…fp8 Parameter past the first pass

Two problems in the leftover fp8 dequant pass. A checkpoint key such as
layer.weight_scale_inv had its whole suffix stripped, leaving layer, which
the target lookup read as a parameter of the parent module, so a raw fp8
.weight under the standard scale name was never dequantized and hit the same
first-forward failure the pass exists to prevent. And the OOM fallback that
parks a stack on the CPU to free its device bytes could not free them: the
original Parameter stayed referenced from two bookkeeping lists until the
function returned, so the move back onto the card could OOM a second time.

The scale suffix that starts with .weight now maps to the .weight key, and
the bookkeeping keeps parameter names only.

Tests: a standard weight plus weight_scale_inv pair is dequantized, and a
weakref to the original Parameter is dead by the time the CPU pass runs;
both fail on the branch before this commit.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…y on converted modules

A leftover fp8 tensor on the meta device is disk-offloaded: its hook would
restore the raw fp8 bytes at forward time and the checkpoint scale is gone, so
the pass silently skipping it reproduced the torch._grouped_mm dtype failure
one step later. It now raises FP8LeftoverOffloadedError naming the tensor and
the two ways out (keep the model resident, or load_in_4bit = True).

The stale activation-scale cleanup visited every module the checkpoint named,
including an FP8Linear that kept its own weight and scale, and deleted the
activation scale its fp8 forward reads. Cleanup is now limited to modules whose
weights this pass converted.

Tests: the offloaded case raises with the instruction; a module that kept its
fp8 weight keeps its activation scale while the converted one loses it.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… that could not be finished to its device

A uint8 scale is an MXFP8 E8M0 exponent, 2 ** (byte - 127), not a multiplier;
casting the byte applied a scale up to 2 ** 128 too large.

The per-tensor fast path materialised a whole 3-D expert stack in fp32, eight
times its fp8 bytes at once, before the chunk budget could apply, which is
what drove the OOM fallback on the checkpoints this pass exists for. A 3-D
stack with a per-tensor scale now takes the chunked branch.

A stack parked on the CPU by pass 1 whose pass 2 also failed was left there,
turning the dtype error into a device mismatch on the first forward; it goes
back to its planned device.

Tests: a per-tensor 3-D stack is chunked; fails on the previous commit.
test_accelerator_skip_guards flagged this file: the new OOM test gated on
torch.cuda.is_available(), which tests/_zoo_aggressive_cuda_spoof.py
patches to True process-wide. Sharing a pytest session with
tests/version_compat or tests/vllm_compat would un-skip it on a CPU-only
box, and it needs a real card.

has_real_cuda() from tests/_shared is the probe that survives the spoof,
and is what the rest of the suite gates on.

Reverting to the torch probe fails the guard again.
…er attribute

A full fine-tune loads its parameters trainable; the 16bit replacement froze
them, so the experts silently sat out the run. An expert block whose
gate_up_proj was converted while down_proj kept its own scale lost
down_proj's activation scale too; the cleanup now follows the converted
attribute, and a module-level scale goes only once nothing in the module is
fp8.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ape failure too

A variant load names its files model.<variant>.safetensors, so the leftover
pass now reads that index instead of skipping the repair and handing back a
model with fp8 experts. A stack parked on the CPU by pass 1 is restored to
its planned device when pass 2 finds the scale does not tile it, the same as
when pass 2 raises.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…d treat any out of memory error as one

When both orientations of a block grid tile the weight, the shape alone
cannot tell them apart; the checkpoint's weight_block_size decides. A plain
RuntimeError whose text says out of memory (HIP, XPU, WSL, wrapped CUDA) now
defers to the CPU pass like torch.OutOfMemoryError does.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 2 commits September 22, 2026 17:48
transformers puts the variant before the last suffix, so the index is
model.safetensors.index.<variant>.json.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 27082ca232

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

Copy link
Copy Markdown
Member Author

Confirmed that loader_utils.py currently leaves the fp8 expert stacks undequantized under load_in_16bit, so the first forward fails in grouped_mm. Will get this reviewed.

@danielhanchen danielhanchen self-assigned this Sep 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 25, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: dde86b973a

ℹ️ 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/models/loader_utils.py
@danielhanchen
danielhanchen merged commit bda4023 into main Sep 25, 2026
32 of 35 checks passed
@danielhanchen
danielhanchen deleted the fp8-static-checkpoint-16bit-load branch September 25, 2026 19:28
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…all-4) (unslothai#11531)

* Finish a 16bit load of a static per-tensor fp8 checkpoint

With load_in_16bit = True on an fp8 checkpoint the loader asks transformers to
dequantize on load, but transformers only folds weight_scale_inv into weights
it has a converter for. A static per-tensor checkpoint such as
Mistral-Small-4-119B ships its MoE stacks as experts.gate_up_proj with a
sibling experts.gate_up_proj_scale_inv (no .weight suffix), so no converter
matches, the raw fp8 values land in the plain Mistral4Experts module and the
scale is dropped as an unexpected key. The first forward then feeds float8
into torch._grouped_mm and training stops before step 1.

After the load, every fp8 parameter whose module carries no scale of its own
is dequantized from the checkpoint scale (per-tensor, per-expert or block
grid) and replaced with its 16bit value. A converted FP8Linear or FP8Experts
keeps its scale and its fp8 forward and is left alone. A card that is already
at its planned 16bit size while its stacks are still fp8 has no room for the
dequant transient; such a stack is parked on the CPU, dequantized there and
moved back once the rest of the card is at its final size.

Mistral-Small-4-119B-2603 in 16bit on two B200s trains 10 steps, loss 0.73 to
1.10 tracking the fp8 cell step for step, where main stops at the first
forward. Fourteen offline tests cover the scale layouts, the VLM key remap,
the converted-module skip and the out-of-memory deferral.

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

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

* Map weight_scale_inv back to its weight, and keep no reference to an fp8 Parameter past the first pass

Two problems in the leftover fp8 dequant pass. A checkpoint key such as
layer.weight_scale_inv had its whole suffix stripped, leaving layer, which
the target lookup read as a parameter of the parent module, so a raw fp8
.weight under the standard scale name was never dequantized and hit the same
first-forward failure the pass exists to prevent. And the OOM fallback that
parks a stack on the CPU to free its device bytes could not free them: the
original Parameter stayed referenced from two bookkeeping lists until the
function returned, so the move back onto the card could OOM a second time.

The scale suffix that starts with .weight now maps to the .weight key, and
the bookkeeping keeps parameter names only.

Tests: a standard weight plus weight_scale_inv pair is dequantized, and a
weakref to the original Parameter is dead by the time the CPU pass runs;
both fail on the branch before this commit.

* Refuse a disk-offloaded fp8 leftover, and clean activation scales only on converted modules

A leftover fp8 tensor on the meta device is disk-offloaded: its hook would
restore the raw fp8 bytes at forward time and the checkpoint scale is gone, so
the pass silently skipping it reproduced the torch._grouped_mm dtype failure
one step later. It now raises FP8LeftoverOffloadedError naming the tensor and
the two ways out (keep the model resident, or load_in_4bit = True).

The stale activation-scale cleanup visited every module the checkpoint named,
including an FP8Linear that kept its own weight and scale, and deleted the
activation scale its fp8 forward reads. Cleanup is now limited to modules whose
weights this pass converted.

Tests: the offloaded case raises with the instruction; a module that kept its
fp8 weight keeps its activation scale while the converted one loses it.

* Unpack E8M0 scales, chunk the per-tensor 3-D path, and return a stack that could not be finished to its device

A uint8 scale is an MXFP8 E8M0 exponent, 2 ** (byte - 127), not a multiplier;
casting the byte applied a scale up to 2 ** 128 too large.

The per-tensor fast path materialised a whole 3-D expert stack in fp32, eight
times its fp8 bytes at once, before the chunk budget could apply, which is
what drove the OOM fallback on the checkpoints this pass exists for. A 3-D
stack with a per-tensor scale now takes the chunked branch.

A stack parked on the CPU by pass 1 whose pass 2 also failed was left there,
turning the dtype error into a device mismatch on the first forward; it goes
back to its planned device.

Tests: a per-tensor 3-D stack is chunked; fails on the previous commit.

* Skip the device OOM test on the probe the spoof cannot reach

test_accelerator_skip_guards flagged this file: the new OOM test gated on
torch.cuda.is_available(), which tests/_zoo_aggressive_cuda_spoof.py
patches to True process-wide. Sharing a pytest session with
tests/version_compat or tests/vllm_compat would un-skip it on a CPU-only
box, and it needs a real card.

has_real_cuda() from tests/_shared is the probe that survives the spoof,
and is what the rest of the suite gates on.

Reverting to the torch probe fails the guard again.

* Keep a dequantized parameter trainable, and clean activation scales per attribute

A full fine-tune loads its parameters trainable; the 16bit replacement froze
them, so the experts silently sat out the run. An expert block whose
gate_up_proj was converted while down_proj kept its own scale lost
down_proj's activation scale too; the cleanup now follows the converted
attribute, and a module-level scale goes only once nothing in the module is
fp8.

* Read a variant's own shard index, and put a parked stack back on a shape failure too

A variant load names its files model.<variant>.safetensors, so the leftover
pass now reads that index instead of skipping the repair and handing back a
model with fp8 experts. A stack parked on the CPU by pass 1 is restored to
its planned device when pass 2 finds the scale does not tile it, the same as
when pass 2 raises.

* Orient a transposed block-scale grid by the configured block size, and treat any out of memory error as one

When both orientations of a block grid tile the weight, the shape alone
cannot tell them apart; the checkpoint's weight_block_size decides. A plain
RuntimeError whose text says out of memory (HIP, XPU, WSL, wrapped CUDA) now
defers to the CPU pass like torch.OutOfMemoryError does.

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

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

* Name a variant's shard index the way transformers does

transformers puts the variant before the last suffix, so the index is
model.safetensors.index.<variant>.json.

* Apply the repo formatter

* Trim comments

* Trim comments in fp8 leftover dequant pass

* Use the AGPL-3.0 header on the fp8 leftover dequant test

* Format the fp8 leftover dequant test

* Drop two restating docstrings in the fp8 leftover pass

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Oct 21, 2026
…geModel, and save them as 16bit (unslothai#14516)

`load_in_16bit = True` on a fine-grained fp8 checkpoint is meant to load
16-bit weights. Since unslothai#11531, `FastModel` passes `dequantize = True` to
transformers' fp8 quantizer for this. The `FastLanguageModel` fast text
path (Llama, Qwen, Mistral, ... through
`dispatch_model.from_pretrained`) never does. On GPUs with native FP8
(sm89+: L4, H100, B200), transformers then keeps every projection as an
`FP8Linear` with fp8 weights, even though 16-bit was asked for.

Reproduced on B200 with transformers 5.17.0, a tiny block-fp8 Llama (128
x 128 scales), `load_in_16bit = True`:

| loader | main | this PR |
|---|---|---|
| `FastModel` | 0 fp8 params | 0 fp8 params |
| `FastLanguageModel` | 14 fp8 params (`FP8Linear`) | 0 fp8 params |

Saving such a model was also broken, on both loaders. With `dequantize =
True`, transformers 5.x keeps the `Fp8Dequantize` load conversions on
the model (`model._weight_conversions`), and `save_pretrained` reverses
them into `Fp8Quantize`. On B200, transformers 5.17.0, after a 16-bit
load followed by `save_pretrained` and a plain reload:

| checkpoint | loader | main | this PR |
|---|---|---|---|
| block-fp8 Llama | `FastModel` | saves 16 fp8 + 16 scale tensors with
no `quantization_config`; reload changes all 14 projection weights | 21
bf16 tensors; reload bit-identical |
| block-fp8 Llama | `FastLanguageModel` | stays fp8 (above), saved as
fp8 with its config | 21 bf16 tensors; reload bit-identical |
| block-fp8 Qwen3-MoE | both | `save_pretrained` raises `ValueError:
Undefined Operation encountered!` | 45 bf16 tensors; reload
bit-identical |

## Change
- New `_fp8_dequantize_quantization_config(model_config)` in
`loader_utils.py`. It returns the checkpoint's own
`FineGrainedFP8Config` with `dequantize = True`, or None for anything
other than `quant_method: fp8` or when transformers has no `dequantize`
flag.
- `FastLanguageModel.from_pretrained` sets it as the
`quantization_config`, only when:
  - `load_in_16bit` is explicit;
  - no 4-bit / 8-bit is requested;
  - `fast_inference` is off;
  - the user passed no `quantization_config`.
- New `_drop_fp8_dequantize_conversions(model)`, called after a 16-bit
load in both loaders:
- drops the generic `weight + weight_scale_inv -> weight` converter,
whose only op is `Fp8Dequantize`;
- a model converter that had `Fp8Dequantize` prepended (expert merges)
is replaced by its quantizer-free form from
`get_model_conversion_mapping(model)`, so the experts still save per
expert;
  - if no such form exists, it keeps the converter and says so;
  - it does nothing when no `Fp8Dequantize` conversion is present.
- Unchanged:
  - loads without the flag;
  - ModelOpt / compressed-tensors checkpoints;
  - what `FastModel` loads (only what it saves);
  - transformers versions without the `dequantize` flag.

## Validation
New `tests/test_fp8_16bit_text_loader_dequant.py`:
- the helper returns `dequantize = True` for a block-fp8 config (dict or
object), and None for no config, bitsandbytes or ModelOpt;
- an enum `quant_method` is read by its value;
- in a subprocess, `FastLanguageModel` on a tiny block-fp8 Llama: with
`load_in_16bit = True` the model has 0 fp8 params and the quantizer got
`dequantize = True`; without the flag the config is not touched;
- a dequantizing load of a tiny block-fp8 Llama and Qwen3-MoE, then
`_drop_fp8_dequantize_conversions`, `save_pretrained` and a reload: only
bf16 tensors are written, no `quantization_config`, and every weight
reloads bit-identical.

With `tests/test_fp8_leftover_dequant_16bit.py` and
`tests/test_modelopt_fp8_loading.py` on B200:
- transformers 5.17.0: 77 passed, 1 skipped.
- transformers 4.57.6: the new tests skip (no `dequantize` flag); 47
passed, 4 failed, the same 4 `test_modelopt_fp8_loading` plan tests that
fail on main.

Not covered:
- **transformers 4.57.x:** `FineGrainedFP8Config` there has no
`dequantize` parameter, so both loaders still keep `FP8Linear` on an
FP8-capable GPU, and there are no `Fp8Dequantize` conversions to drop.
This PR does not change that.
- **Merged saves:** `save_pretrained_merged` and GGUF export were not
run on a dequantized fp8 model; only `save_pretrained`.
- **GPUs without native FP8 (T4, A100):** transformers already
dequantizes there, so they were never affected.

---------

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.

1 participant