Skip to content

feat: compare the tensors of saved and uploaded models with the source checkpoint - #37

Merged
redchupa merged 3 commits into
masterfrom
claude/competent-antonelli-825a4f
Dec 5, 2026
Merged

redchupa merged 3 commits into
masterfrom
claude/competent-antonelli-825a4f

Conversation

@redchupa

@redchupa redchupa commented Dec 5, 2026 •

Copy link
Copy Markdown
Owner

Roadmap, stage 4: "모델 텐서 무결성 검사 (PR #447)". This PR ticks that item.

What and why

Heretic only changes the values of a model's tensors, so a merged model that it saves or uploads should have exactly the tensors of the checkpoint it was loaded from. It often doesn't, and nothing said so: Transformers leaves out layers that it doesn't load, saves tensors that a checkpoint keeps in float32 in the model's dtype, writes tied weights once, and fails to convert some models back to their checkpoint format at all. This ports p-e-w/heretic#447 by hpnyaggerman. After a merged model is saved or uploaded, Heretic reads the safetensors headers (names, dtypes and shapes, not the data) of the source checkpoint and of the result, and prints what differs. For example, saving tiny-random/qwen3.5-moe:

* Differences from the 2034 tensors of the source checkpoint:
  * 401 missing (such as mtp.fc.weight)
  * 6 with another dtype (such as model.language_model.layers.0.linear_attn.A_log: F32 -> BF16)

An opt-in preflight save right after loading (preflight_check = true, --preflight-check) runs the same comparison on an unmodified copy, to find out before an optimization run of hours whether the model can be saved at all.

How it was ported. The first commit of #447 (9995fff) is cherry-picked under its author, with the conflicts resolved for the current code: the dtype fallback loop has moved to _load_model_with_dtype_fallback(), and the save and upload branches have gained the model card code. The two later commits of #447, which record the differences in reproduce.json and verify them when reproducing, are left out (see the decisions below).

Review follow-up (a separate commit):

  1. Dtypes are compared too. #447 compared shapes only. Qwen3.5-MoE and NemotronH save tensors that their checkpoints keep in float32, such as A_log, in bfloat16, which a comparison of shapes reports as a match.
  2. Differences are counted by kind (missing, added, with another shape, with another dtype), each with an example, instead of one total and the first ten differences in alphabetical order. A model that loses hundreds of MTP tensors fills those ten lines with them, so another kind of difference further down the alphabet doesn't show.
  3. The source checkpoint is read when checking, from the model's directory or from the Hugging Face cache that Transformers loaded it from (at model_commit if set), instead of in Model.__init__. model.py is unchanged, and the special case for a "PEFT adapter source" that p-e-w asked about is gone: a source without safetensors model files (such as an adapter repository) gets a warning that the tensors could not be compared.
  4. The preflight save is opt-in (preflight_check = false), see the first decision below. It now passes max_shard_size like the export (Transformers' own default is 50GB shards), runs in main.py after the model is loaded, and says when it is skipped for a quantized model. It is a property of the invocation (exclude=True), like print_debug_information, so it isn't stored in checkpoints or in reproduce.json.
  5. Docstrings for every function, which p-e-w asked for, a comment that answers p-e-w's "What is this for?" on the repo_id normalization (the uploaded files are read back from the Hub, which needs the repository's full name), and 10 unit tests.

Decisions on the questions from #447's review:

  • Preflight off by default, comparison after saving always on. p-e-w called the default a conundrum: on, it wastes time in almost every run; off, what good is it? Splitting the two answers it. The comparison after every merged save and upload reads only file headers, so it is always on and reports problems without anyone asking. The preflight writes a full copy of the model to the current directory before the run, so it is for when a model is suspect, such as a new architecture, before a long run.
  • Warn, don't stop. p-e-w asked whether any tensor difference should be "Game Over" for the export. Here it isn't. In the measurements below, Qwen3.5, Qwen3-Next and Hy3 lose their MTP layers, which Transformers doesn't load, NemotronH and Qwen3.5 save float32 tensors such as A_log in bfloat16, and Qwen3-0.6B loses the lm_head.weight that its checkpoint stores although it is tied to the embeddings. Stopping would make all of them unexportable, though they work for generation. The warning tells the user what the saved model lacks, and the save goes ahead. A save that fails still fails as before.
  • Not recorded in reproduce.json. Reproduction already compares the output files byte for byte with hashes, which catches any difference in the saved tensors. reproduce.json is a public format, and p-e-w questioned uploading the differences as if nothing had happened.
  • Not in the report. The report from report.py describes the optimization and is written when the Pareto front is shown, before anything is saved. The check is about a save.

What Transformers 5.18 does to each model (load with dtype="auto" on CPU, save_pretrained, compare with this code):

Model Tensors in the checkpoint Saved model
tiny-random/ qwen2.5, gemma-3, gemma-4e, gpt-oss, minicpm5, mistral-3, seed-oss 51, 67, 284, 36, 21, 44, 27 the same
tiny-random/qwen3.5-moe 2034 401 missing (MTP), 6 F32 → BF16 (A_log)
tiny-random/qwen3-next-moe 555 113 missing (MTP)
tiny-random/nemotron-h 289 18 F32 → BF16
tiny-random/hy3 2374 593 missing (the MTP layer, model.layers.4.*)
Qwen/Qwen3-0.6B 311 lm_head.weight missing (tied to the embeddings)
tiny-random/deepseek-v4 saving fails: ValueError: Undefined Operation encountered! in revert_weight_conversion

The last row is what the preflight is for. (tests/deepseek-v4 exports only the adapter, so the reproducibility tests don't run into it.)

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.

  • ruff format --check, ruff check --extend-select I, ty check --error-on-warning, unit tests (197, of which 10 new in tests/test_tensor_check.py) and uv build pass locally (Windows, Python 3.12).

  • Reproducibility tests (tests/run_tests.py) on this branch and on master (b50e6f0), same Windows machine: all 69 output files of the 11 tests are byte-identical on both, except the adapter_config.json of the 3 adapter tests, whose target_modules PEFT writes from a set, in a different order on every run. The same 5 tests fail against the committed hashes on both (deepseek-v4, deepseek-v4-ara, gemma-3, gemma-4e, qwen3.5-moe), which is this machine's numerics; CI checks the committed hashes. On the branch, the 8 tests that export a merged model print the check: 7 match their source checkpoint, and qwen3.5-moe prints the differences shown above.

  • Preflight, end to end: tests/qwen3.5-moe/config.toml with --preflight-check prints the same differences right after loading, and the merged model that the run saves is byte-identical to the test run's without the preflight (all 8 files). tests/deepseek-v4/config.toml with --export-strategy=merge --preflight-check prints Saving failed: Undefined Operation encountered! right after loading; the run then fails the same way when it saves the merged model at the end, as it does without this PR. The temporary directory is removed in both cases.

  • Upload: not run against the Hub, since that would publish a repository. The unit tests cover the Hub read with a mock, and reading tiny-random/qwen3.5-moe with get_safetensors_metadata, the call that the check after an upload makes, gives the same 2034 tensors as reading it from the local cache.

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. (Written by Claude Code on behalf of the maintainer; the maintainer reviews before merging.)

Merging: please use a rebase merge (or a merge commit), so that the first commit stays under its author. With a squash merge, keep Co-authored-by: hpnyagman <115356333+hpnyaggerman@users.noreply.github.com> in the message.

🤖 Generated with Claude Code

hpnyaggerman and others added 3 commits December 5, 2026 08:44
Cherry-picked from the first commit of p-e-w/heretic#447 (9995fff),
with the conflicts resolved for the current code: the check runs at the
end of the merged save and upload branches (the model card code and the
later reset_trial_model() call are unchanged), and the preflight save
runs right after the model is loaded and checked to be resident, now
that the dtype loop lives in _load_model_with_dtype_fallback(). The two
later commits of that pull request, which record the differences in
reproduce.json, are not included.
Review changes on top of the port of p-e-w/heretic#447:

- Compare the dtypes of the tensors as well as their shapes. Transformers
  saves some float32 tensors in bfloat16 (A_log in Qwen3.5-MoE and
  NemotronH), which a comparison of shapes alone reports as a match.
- Report the differences by kind (missing, added, with another shape,
  with another dtype), each with a count and an example, instead of the
  first ten names in alphabetical order, which can all be of one kind.
- Read the headers of the source checkpoint when checking, from the
  Hugging Face cache that the model was loaded from, instead of in
  Model.__init__, which leaves model.py unchanged. A source without
  safetensors files (such as a PEFT adapter) now gives a warning that
  the tensors could not be compared.
- Make the preflight save opt-in (preflight_check = false), because it
  writes a full copy of the model to the current directory before every
  run, and save it with max_shard_size, like the export. Do it in
  main.py, and say when it is skipped for a quantized model.
- Add unit tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@redchupa
redchupa merged commit 1973c87 into master Dec 5, 2026
5 checks passed
@redchupa
redchupa deleted the claude/competent-antonelli-825a4f 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.

2 participants