Repository navigation
feat: compare the tensors of saved and uploaded models with the source checkpoint - #37
Merged
Merged
Conversation
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
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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, savingtiny-random/qwen3.5-moe: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 inreproduce.jsonand verify them when reproducing, are left out (see the decisions below).Review follow-up (a separate commit):
A_log, in bfloat16, which a comparison of shapes reports as a match.model_commitif set), instead of inModel.__init__.model.pyis 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.preflight_check = false), see the first decision below. It now passesmax_shard_sizelike the export (Transformers' own default is 50GB shards), runs inmain.pyafter the model is loaded, and says when it is skipped for a quantized model. It is a property of the invocation (exclude=True), likeprint_debug_information, so it isn't stored in checkpoints or inreproduce.json.repo_idnormalization (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:
A_login bfloat16, and Qwen3-0.6B loses thelm_head.weightthat 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.reproduce.json. Reproduction already compares the output files byte for byte with hashes, which catches any difference in the saved tensors.reproduce.jsonis a public format, and p-e-w questioned uploading the differences as if nothing had happened.report.pydescribes 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):tiny-random/qwen2.5, gemma-3, gemma-4e, gpt-oss, minicpm5, mistral-3, seed-osstiny-random/qwen3.5-moeA_log)tiny-random/qwen3-next-moetiny-random/nemotron-htiny-random/hy3model.layers.4.*)Qwen/Qwen3-0.6Blm_head.weightmissing (tied to the embeddings)tiny-random/deepseek-v4ValueError: Undefined Operation encountered!inrevert_weight_conversionThe last row is what the preflight is for. (
tests/deepseek-v4exports 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 intests/test_tensor_check.py) anduv buildpass locally (Windows, Python 3.12).Reproducibility tests (
tests/run_tests.py) on this branch and onmaster(b50e6f0), same Windows machine: all 69 output files of the 11 tests are byte-identical on both, except theadapter_config.jsonof the 3 adapter tests, whosetarget_modulesPEFT 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, andqwen3.5-moeprints the differences shown above.Preflight, end to end:
tests/qwen3.5-moe/config.tomlwith--preflight-checkprints 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.tomlwith--export-strategy=merge --preflight-checkprintsSaving 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-moewithget_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
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