Repository navigation
Finish a 16bit load of a static per-tensor fp8 checkpoint (Mistral-Small-4) - #11531
Conversation
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.
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. |
…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.
|
@codex security review |
…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.
… 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.
…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.
…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.
transformers puts the variant before the last suffix, so the index is model.safetensors.index.<variant>.json.
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
|
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. |
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. 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". |
# Conflicts: # unsloth/models/loader_utils.py
…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>
…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>
What
load_in_16bit = Trueon 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_16bitthe loader passesdequantize = Trueto transformers' fp8 quantizer. transformers foldsweight_scale_invinto everynn.Linearweight it has a converter for, but the MoE stacks of a static checkpoint are stored asexperts.gate_up_projwith a siblingexperts.gate_up_proj_scale_inv: no.weightsuffix, so no converter matches, the raw fp8 values land in the plainMistral4Expertsparameter and the scale is dropped as an unexpected key. The first forward feeds float8 intotorch._grouped_mm:_dequantize_leftover_fp8_paramsinloader_utils.pyruns 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 convertedFP8LinearorFP8Expertskeeps 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 leftoveractivation_scaleparameters 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:
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, thelanguage_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 withload_in_16bit = Trueand only when fp8 parameters survive the load, so 4bit, 8bit, fp8 and full-precision loads are untouched. transformers 4.57.6 (nodequantizeon the fp8 config, so the quantizer keepsFP8Linearmodules 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.