Skip to content

Stamp no bitsandbytes config on a dequantized fp8 load, and read a quantization_config object before stamping - #14803

Merged
danielhanchen merged 5 commits into
mainfrom
fp8-sub-sm89-save-cleanup
Oct 25, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
fp8-sub-sm89-save-cleanup

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #14531 and #14678. Since #14531, fp8 checkpoints (quant_method: fp8) load on GPUs below sm89 (T4, A100), where transformers dequantizes them to 16bit by itself. #14678 drops the leftover Fp8Dequantize conversions after every load, so full finetunes and 16bit loads now save correct 16bit weights. One gap is left on the default load path, and a related one on sm89+.

  1. Default load below sm89. transformers deletes the fp8 quantization_config after dequantizing, so the loaded config looks unquantized. The load_in_4bit default then stamps a bitsandbytes 4bit quantization_config onto a model that holds 16bit weights. save_pretrained writes 16bit tensors under that bnb config. A plain reload builds Linear4bit layers that do not hold the saved weights (max relative error 1.0 against the dequantized reference, on GPU and on CPU).
  2. Default load on sm89+. The load keeps FP8Linear and its FineGrainedFP8Config. get_quant_type reads only dict configs, so the stamp overwrites the fp8 config with a bitsandbytes one too. save_pretrained then writes fp8 weights and scales under a bnb config, and a reload is wrong (relative error 3165).

Colab A100 (sm80), torch 2.11.0, transformers 5.17.0, on a tiny block-fp8 Llama (128 x 128 scales). Each arm loads, runs save_pretrained, then does a plain AutoModelForCausalLM reload on CPU, compared with the dequantized reference:

loader arm main (after #14678) this PR
FastLanguageModel default bf16 weights under a bitsandbytes config, rel err 1.0 bf16, no quantization_config, bit-identical
FastModel default bf16 weights under a bitsandbytes config, rel err 1.0 bf16, no quantization_config, bit-identical
FastLanguageModel / FastModel full_finetuning = True bf16, bit-identical same
FastLanguageModel load_in_16bit = True bf16, bit-identical same

The saved tensors are byte-identical between main and this PR in every arm; only the config changes.

B200 (sm100), default load (FastLanguageModel and FastModel): main saves fp8 + scales under a bitsandbytes config and reloads with relative error 3165. This PR saves the same bytes under the checkpoint's fp8 config, and the reload dequantizes to the reference bit for bit. 16bit and full-finetune saves are unchanged.

Change

  • _drop_fp8_dequantize_conversions marks the model _unsloth_fp8_dequantized when it finds an Fp8Dequantize conversion and the loaded config no longer has a quantization_config (transformers removed it, so the weights are 16bit). A load that kept fp8 weights keeps its config and is not marked.
  • Both bitsandbytes stamps after a load_in_4bit load (FastLanguageModel and FastModel):
    • skip a model marked as dequantized;
    • also read a quantization_config given as a config object, through the new _loaded_quant_method. A kept FineGrainedFP8Config is no longer overwritten.
  • Unchanged: FP8: keep every scoped converter and clean up every dequantizing load before save #14678's converter cleanup, the weights any load puts in memory, and real bitsandbytes loads, which are still stamped as before.

Tests

New cases in tests/test_fp8_16bit_text_loader_dequant.py:

  • a CPU load where transformers dequantizes by itself (the branch it takes below sm89) is marked, and saves bf16 only;
  • both bitsandbytes stamps skip a dequantized model and read config objects;
  • _loaded_quant_method reads dict, object and missing configs;
  • only a load without an fp8 config is marked.

On current main: 4 failed. This PR: 4 passed. tests/test_fp8_dequant_save_policy.py passes with the GPU hidden. Together with test_fp8_device_gate.py, test_fp8_leftover_dequant_16bit.py and test_modelopt_fp8_loading.py on B200: 118 passed, 1 skipped, 1 failed. The failure is test_explicit_and_automatic_dequantize_reload[False], which also fails on main whenever a GPU is visible: it expects a CPU load to dequantize, but transformers checks the visible GPU's capability, and a B200 keeps fp8.

Kaggle T4 (sm75, fp16) and Colab L4 (sm89), merge base vs head, both loaders, default load, then a fresh-process reload:

GPU arm saved config reload max rel err
T4 main bitsandbytes over fp16 weights Linear4bit 1.0
T4 this PR none Linear 2.4e-4 (fp16 rounding)
L4 main bitsandbytes over fp8 weights Linear4bit 7394
L4 this PR fp8 FP8Linear 0.0

Not covered

  • Merged saves (save_pretrained_merged, GGUF) after a sub-sm89 fp8 load.
  • Full finetuning on sm89+ saves bf16 weights under the fp8 config (reload relative error 0.006 here), the same on main and with this PR. Not changed here.

@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-25T09:11:19.661215Z 02cbcb0 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 09962ec2e4

ℹ️ 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 added a commit that referenced this pull request Oct 22, 2026
pre-commit.ci fails `ruff-format-with-kwargs` on every open PR (#14806,
#14805, #14803, #14790, #14785, #14781, #14780, #14777, #14776, #14775,
#14774, #14773, #14772, #14770, #14769, #14768, and others): "files were
modified by this hook". pre-commit.ci runs the hooks on all files, and
20 files on main (26 by the time this lands) are not in the formatter's
output, so every PR is reformatted outside its own diff. Where
pre-commit.ci can push, its autofix commit drags those unrelated files
into the PR (for example #14790's touches `tests/test_block_compile.py`,
`tests/test_bnb_integration_compile.py` and `unsloth/models/_utils.py`).

The drift came in with PRs merged today, among them #14702, #14751,
#14759, #14784, #14786, #14787, #14788, #14791 and the FP8 block decode,
GRPO routing replay, 4-bit decode, compiled blocks and MoE LoRA target
changes.

### Change

`python scripts/run_ruff_format.py` (the hook's own entry point,
`ruff==0.6.9` as pinned in `.pre-commit-config.yaml`) applied to those
20 files, plus 6 more from #14739, #14779 and #14806, which merged while
this was open. Formatting only.

### Verification

- Every changed file parses to an identical AST before and after.
- A second run of the hook over the same files changes nothing (fixed
point), and over all tracked Python files on this branch it changes
nothing.
- `ruff check` passes on the changed files;
`tests/test_formatter_fixed_point.py` passes (16).

Open PRs pick this up on their next pre-commit.ci run after merging
main.
@danielhanchen danielhanchen self-assigned this Oct 25, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

3 similar comments
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 02cbcb0b26

ℹ️ 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 f0c87b1 into main Oct 25, 2026
3 of 29 checks passed
@danielhanchen
danielhanchen deleted the fp8-sub-sm89-save-cleanup branch October 25, 2026 09:26
danielhanchen added a commit that referenced this pull request Oct 26, 2026
…ights (#15364)

## Problem

Loading a block FP8 checkpoint with `quantization_config =
FineGrainedFP8Config(dequantize = True)` and leaving `load_in_4bit` at
its default goes through this sequence in both
`FastLanguageModel.from_pretrained` and `FastModel.from_pretrained`:

1. transformers dequantizes the weights to 16bit and removes
`quantization_config` from the model config.
2. `_drop_fp8_dequantize_conversions` forgets the save time conversions
and marks the model `_unsloth_fp8_dequantized`.
3. The `load_in_4bit` block then writes the caller's config back with
`model.config.update({"quantization_config":
quantization_config.to_dict()})`.

`save_pretrained` therefore writes only bf16 tensors, with no
`weight_scale_inv`, under `quant_method: fp8`. transformers 4.57.6
ignores `dequantize`, builds FP8 layers that expect scales, and the
reload fails with `NotImplementedError: Cannot copy out of meta tensor;
no data!`. A default config load is not affected, since #14803 already
skips the bitsandbytes stamp for a dequantized load.

## Fix

Skip the explicit config restore when the model was marked
`_unsloth_fp8_dequantized`, in both loaders. The flag is only set when
transformers dropped the fp8 config, so a kept FP8 load (sm89+ without
`dequantize`) and every other user config are restored as before.

## Tests

-
`tests/test_fp8_dequant_save_policy.py::test_caller_fp8_config_is_not_restored_over_dequantized_weights`
(CPU, both loaders): every `model.config.update({"quantization_config":
quantization_config...})` in `from_pretrained` sits behind the
dequantized guard. Fails on main, passes here.
-
`tests/test_fp8_16bit_text_loader_dequant.py::test_explicit_dequantize_config_saves_without_fp8_config`
(CUDA, both loaders): loads a tiny block FP8 Llama with
`FineGrainedFP8Config(dequantize = True)`, saves, and checks the saved
config has no `quantization_config`, every tensor is 16bit (float16 on a
T4, which has no bf16) with no scales, and a reload gives identical
weights. On a Kaggle T4 (torch 2.11, transformers 5.17.0) it fails on
main for both loaders, with the saved config still `quant_method: fp8`,
and passes here.
- transformers 4.57.6 reload: the bf16 checkpoint saved by main's
loaders, with only the `quantization_config` entry removed (the one
difference this change makes), reloads bit identical under 4.57.6.

The rest of both test files passes locally on transformers 5.17.0.

## Not covered

The 4.57.6 reload was checked on CPU from a saved checkpoint, not by
running the full Unsloth loader under 4.57.6 (whose
`FineGrainedFP8Config` has no `dequantize`, so the explicit path does
not arise there). The vision loader (`FastBaseModel`) does not restore a
caller config at this point and is unchanged.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Oct 27, 2026
## Problem

```python
FastModel.from_pretrained(fp8_checkpoint, full_finetuning = True, load_in_4bit = False, dtype = torch.bfloat16)
```

FastModel only passes `dequantize = True` to transformers'
`FineGrainedFP8Config` for an explicit `load_in_16bit = True` load. Full
finetuning does not set `load_in_16bit`, so transformers keeps
`FP8Linear` layers. Training preparation then casts the fp8 weight
storage to bf16 without applying `weight_scale_inv`, and three things go
wrong:

- the trained weights are the raw fp8 values, not the dequantized ones;
- `FP8Linear.forward` treats a two-byte weight as a plain `F.linear`
weight, so outputs are off by the block scales;
- `save_pretrained` writes bf16 tensors under a `quant_method: fp8,
dequantize: false` config, so a reload changes every projection again.

This predates #14803. The same load with `load_in_16bit = True` was
already correct.

## Fix

In `FastBaseModel.from_pretrained`, full finetuning of a `quant_method:
fp8` checkpoint now requests `dequantize = True`, as the explicit 16bit
path does. It also runs `_dequantize_leftover_fp8_params` after load,
again as the 16bit path does. A caller's own `quantization_config` still
wins.

If the installed transformers has no `dequantize` flag on
`FineGrainedFP8Config`, the load is refused with a clear message instead
of training unscaled weights. LoRA loads and every other quant method
are unchanged.

## Tests

`tests/test_fp8_full_finetune_dequant.py`:

- Routing (no GPU needed; a subprocess records the config FastModel
hands transformers and stops before any weight is read):
- `full_finetuning = True` with `load_in_4bit = False`, and with the
default `load_in_4bit`, requests `dequantize = True`. Both fail on main.
- `full_finetuning` with `load_in_16bit = True` passes on main and here.
  - A LoRA load keeps `dequantize = False`.
- A transformers whose config has no `dequantize` flag refuses full
finetuning (fails on main, which loads) and still allows a LoRA load.
- GPU (skipped without CUDA): loaded projection weights match the
dequantized checkpoint, no fp8 parameters remain, the saved config has
no `quantization_config`, and a reload changes nothing.

On main: 3 failed, 3 passed, 1 skipped (no GPU). With this change: 6
passed, 1 skipped. The existing FP8 loader suites
(`test_fp8_16bit_text_loader_dequant`, `test_fp8_dequant_save_policy`,
`test_fp8_leftover_dequant_16bit`, `test_fp8_moe_fast_inference_gate`,
`test_fp8_to_nf4_load`, `test_modelopt_fp8_loading`) pass: 92 passed, 21
skipped.

## GPU check

L4 (sm_89), torch 2.14.1, transformers 5.17.0. The model is a locally
generated two-layer block-FP8 Llama with 14 projections, loaded with
`full_finetuning = True, load_in_4bit = False, dtype = torch.bfloat16`:

| Check | main | this PR | main, `load_in_16bit = True` |
|---|---:|---:|---:|
| Projection module | FP8Linear | Linear | Linear |
| Weights equal to the unscaled fp8 cast | 14 / 14 | 0 / 14 | 0 / 14 |
| Max weight rel. L2 error vs dequantized checkpoint | 5672.6 | 0 | 0 |
| Projection forward rel. L2 error vs dequantized checkpoint | 5261.8 |
1.7e-3 | 1.7e-3 |
| Saved `quantization_config` | fp8, `dequantize: false` | none | none |
| Projections changed by save and reload | 14 / 14 | 0 / 14 | 0 / 14 |

The 1.7e-3 forward error is bf16 matmul rounding against an fp32
reference, and it is the same with `load_in_16bit = True`.

## Not covered

- The refusal path was only exercised with a simulated
`FineGrainedFP8Config` that has no `dequantize` flag, not on a real
transformers 4.57.x install.
- Not tested: MoE FP8 checkpoints under full finetuning, multi-GPU
device maps, and an actual training run after the load.

---------

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