Skip to content

fix: load FP8 checkpoints such as Hy3-FP8 by dequantizing them - #38

Merged
redchupa merged 1 commit into
masterfrom
claude/determined-feistel-fe3950
Dec 5, 2026
Merged

redchupa merged 1 commit into
masterfrom
claude/determined-feistel-fe3950

Conversation

@redchupa

@redchupa redchupa commented Dec 5, 2026

Copy link
Copy Markdown
Owner

What and why

Roadmap stage 3, Hy3 (p-e-w/heretic#436). Transformers 5.18 implements Hy3 (tiny-random/hy3 already worked on master), but the official FP8 checkpoint, tencent/Hy3-FP8, could not be loaded. Its format was never checked because no small FP8 variant exists and the real model is about 300 GB. This PR builds a tiny checkpoint from tiny-random/hy3 in the same format and makes Heretic load, modify and export it correctly.

The format (from the config.json and the safetensors headers of tencent/Hy3-FP8 at commit ecc1d8e):

  • quantization_config: {"activation_scheme": "static", "ignored_layers": ["lm_head", "model.embed_tokens"], "quant_method": "fp8", "kv_cache_scheme": "static"}, with no weight_block_size.
  • Each quantized projection is stored as <module>.weight (F8_E4M3), <module>.weight_scale (BF16, a single value with no dimensions, so weight = fp8 × weight_scale) and <module>.input_scale (F32, shape [1], a static activation scale).
  • Quantized: self_attn.{q,k,v,o}_proj, the dense MLP's mlp.{gate,up,down}_proj, mlp.shared_mlp.* and every expert's mlp.experts.<E>.{gate,up,down}_proj (stored per expert), including in the MTP layer. Not quantized: embeddings, lm_head, norms, the router, expert_bias and the MTP layer's eh_proj. There are no KV cache scales, although kv_cache_scheme is "static".

Problem. Transformers only knows the names that checkpoints with one scale per block use (weight_scale_inv, activation_scale). It dropped the per-tensor scales:

  • On CPU (and GPUs without FP8 support), Transformers dequantizes by default. The scales were dropped and the per-expert weights stayed in FP8, so the first forward pass failed with RuntimeError: Expected mat_a to be Float32, BFloat16 or Float16 matrix, got Float8_e4m3fn.
  • On an RTX 5070 Ti, Transformers keeps FP8 weights, which needs Triton: Failed to load model: No module named 'triton' on Windows. Where Triton is available, the weights would be loaded in FP8 with their scales missing, and Heretic can't modify FP8 weights anyway.

Changes (model.py):

  • Every checkpoint whose quantization_config has quant_method: "fp8" is loaded with FineGrainedFP8Config(dequantize=True), so its weights arrive in the dtype Heretic loads the model with (bfloat16 for Hy3). For checkpoints without weight_block_size, a key_mapping renames weight_scale to weight_scale_inv and input_scale to activation_scale, so Transformers applies the scales.
  • After loading, the weight conversions that Transformers keeps for save_pretrained are dropped. Reversing the FP8 dequantization fails for MoE models (ValueError: Undefined Operation encountered!). For other models it writes FP8 weights and scales again, but without the quantization_config needed to load them. Without the kept conversions, the model is saved like one that wasn't loaded from a checkpoint: unquantized, in the layout of the model's unquantized version (for Hy3, that of tencent/Hy3).
  • FP8 checkpoints with quantization = "bnb_4bit" are refused with a clear message. Transformers can't combine the two and would otherwise fail with a ValueError about mismatched quantization config classes.
  • reset_model() reads the quantization configuration of the model it actually loads. With evaluate_model, it loads a different model than the first one, for example a BF16 export of an FP8 model.
  • README: the footnote on quantization says how FP8 models are handled.

Decisions.

  • Dequantize rather than keep FP8. Heretic reads and changes the weights themselves, and FP8 values only make sense together with their scales. Changing FP8 weights would need LoRA adapters and merging that handle FP8 scales, for linear layers and merged experts alike. The cost is memory: the model takes as much as its BF16 version, about 600 GB for Hy3 instead of 300 GB. Keeping FP8 weights in memory is recorded in the roadmap as what remains.
  • Export unquantized. The modified weights would need new scales, and the result can be used and requantized like tencent/Hy3. Dropping the kept conversions relies on _weight_conversions, a private attribute of Transformers 5. The new save test fails if a Transformers update changes how it works.
  • All quant_method: "fp8" checkpoints, not only Hy3. Checkpoints with block scales (e.g. DeepSeek V3, Qwen3-FP8) had the same problems on FP8-capable GPUs and when saving. I checked tiny dense and MoE checkpoints with block scales: they load exactly and save correctly with this change, and the save fix is needed for both.
  • DeepSeek V4 (tests/deepseek-v4*, block scales) is the only FP8 model in the reproducibility tests. On CPU its parameters are identical to master's (names, dtypes and values compared). Its merged save no longer crashes, but Transformers 5.18 can't reload any saved DeepSeek V4 correctly: a model created from its config, without FP8 or Heretic, fails with a dtype mismatch in its first forward pass after saving and reloading. Its tests therefore keep exporting the adapter.
  • Input scales aren't used once the weights are dequantized. They are renamed only so that Transformers discards them silently. Those of the experts keep their names: Transformers would otherwise rename them after the merged experts' weights and report those as unexpected. So the load report still lists the experts' input_scale tensors as unexpected (3 lines per MoE layer). That is cosmetic.
  • fix: handle FP8 model weights in LoRA adapters and merge p-e-w/heretic#182 (LoRA adapters and merging for FP8 weights) is not ported, because Hy3 doesn't need it: no FP8 weights reach LoRA or merging anymore. It handled FP8 Linear layers with block scales, and was written for Heretic before trials were merged into the weights (fix: score trials with the adapters merged into the weights #26). Its other commits are unrelated to FP8 (evaluator scoring with zero base refusals, NaN KL divergence, log_softmax in float32 with a clamp, the max_weight range, target modules found by identity). The stage 5 roadmap item now lists them for a separate review.
  • Transformers doesn't implement Hy3's MTP layer, so exports don't include it. Exports of tencent/Hy3 have the same limitation.

Testing

  • The checks listed in CLAUDE.md pass locally, or I explain below why not.
  • No tests/*/SHA256SUMS.* file changes, or the description explains why model outputs are meant to change.

Windows 11, Python 3.12.13, torch 2.14.1, Transformers 5.18.0, PEFT 0.22.0.

  • CI commands: ruff format --check, ruff check --extend-select I, ty check --error-on-warning and uv build pass. The unit tests pass: 192 tests, OK with the 2 expected failures as on master.
  • Reproducibility tests: I ran tests/run_tests.py on this branch and on master b50e6f0, on the same machine.
    • The same 5 tests differ from the committed hashes in both runs: deepseek-v4, deepseek-v4-ara, gemma-3, gemma-4e and qwen3.5-moe. They are known to fail on this machine.
    • Of the 69 tests/*/model/* files, 66 are byte-identical between the two runs. They include the adapters of the two DeepSeek V4 tests, which load an FP8 checkpoint. The other 3 are adapter_config.json files with the same target_modules in a different order (PEFT keeps them in a set).
  • Unit tests: tests/test_model_loading.py has 5 new tests. save_hy3_fp8_checkpoints() builds a small random Hy3 model in the tencent/Hy3-FP8 format, together with the exact dequantization of its FP8 weights in the tencent/Hy3 format.
    • Loaded through Heretic, every parameter of the FP8 model is equal to the exact dequantization. The saved model has the same tensors, bit for bit, and no quantization_config.
    • After an FP8 model, reset_model() loads a different model correctly, and the other way round. On the code without the reset_model() fix, this test fails in both directions: the BF16 model gets a FineGrainedFP8Config, and the FP8 model's weights are loaded unscaled.
    • The other tests cover the scale renaming (per-tensor scales only) and the refusal of 4-bit quantization.
  • Tiny checkpoint in the real format: a script (not in the repository) builds it from tiny-random/hy3 at 1ea1658. It quantizes per tensor with the layout above, including the MTP layer, and calibrates the static input scales on 8 prompts.
    • CPU: Heretic's load equals the exact dequantization, and so do the logits. With 2 trials and a merged export, Heretic ran on this checkpoint and on tiny-random/hy3 (BF16), with Abliteration and with ARA. Both exports have the same 1781 tensors with the same shapes and dtypes, and no quantization_config. Abliteration changed the same 5 tensors in both runs (the o_proj and shared-expert down_proj weights of layers 1–3). ARA changed none in either run, because the random model refuses nothing.
    • RTX 5070 Ti (torch 2.14.1+cu130, compute capability 12.0): master fails to load the checkpoint (No module named 'triton'). With this branch, the weights and logits equal the exact dequantization on CUDA, and Heretic runs with Abliteration and ARA to a merged export. Both exports load and generate on cuda:0.
    • The GPU runs used this branch before its last change: reset_model() now reads the configuration of the model it loads, which is the same configuration unless the model changes. Repeated on CPU with the final code, both FP8 runs export byte-identical files.

AI use declaration

  • I wrote this pull request (code and description) entirely by myself.
  • I used AI to write some or all of this pull request, and I have reviewed all of it myself,
    understand it, and can answer questions about it without relying on the AI.

🤖 Generated with Claude Code

tencent/Hy3-FP8 stores each FP8 weight matrix with one scale
(`weight_scale`, plus a static `input_scale`), but Transformers only knows
the names of per-block scales (`weight_scale_inv`), so it dropped the
scales. On CPU the experts' weights stayed in FP8 and the first forward
pass failed; on GPUs with FP8 support the weights were kept in FP8, which
needs Triton (missing on Windows) and can't be modified by Heretic.

Heretic now loads every checkpoint with `quant_method: "fp8"` with its
weights dequantized to the dtype it loads the model with, and renames
per-tensor scales to the names Transformers expects. It drops the weight
conversions that Transformers keeps for saving: reversing them fails for
MoE models and writes FP8 weights without a quantization configuration
for others. Exported models are therefore unquantized, in the layout of
the model's unquantized version. Transformers can't quantize FP8
checkpoints to 4 bits, so that combination is refused with a clear
message. reset_model() reads the quantization configuration of the model
it loads, which differs from the first one with evaluate_model.

Verified with a tiny checkpoint built from tiny-random/hy3 in the format
of tencent/Hy3-FP8, on CPU and on an RTX 5070 Ti.

Roadmap: stage 3, Hy3 (p-e-w/heretic#436). p-e-w/heretic#182 isn't
ported: no FP8 weights reach LoRA or merging anymore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@redchupa
redchupa merged commit 404bcb7 into master Dec 5, 2026
5 checks passed
@redchupa
redchupa deleted the claude/determined-feistel-fe3950 branch December 5, 2026 04:33
redchupa added a commit that referenced this pull request Dec 5, 2026
Since FP8 checkpoints such as tencent/Hy3-FP8 are loaded dequantized and
exported unquantized (#38), the tensor check (#37) reported every FP8
weight "with another dtype" (F8_E4M3 -> BF16) and every scale as missing.
For a tiny Hy3-FP8, that buried the one real difference, the 593 tensors
of the MTP layer that Transformers doesn't load, under 5271 missing and
1756 dtype changes.

When the source checkpoint's config.json says that its weights are stored
in FP8 (read like the model loader does, at the same revision), the check
now leaves out the scale tensors (weight_scale, weight_scale_inv,
input_scale, activation_scale) and the dtype change of F8_* weights, and
prints one line saying that the FP8 weights were compared as dequantized.
Every other difference is still reported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant