Repository navigation
fix(models): keep declared fp32 modules exempt from the load dtype guard (#4170) - #4209
Merged
Merged
Conversation
… guard (#4170) #4140's assert_loaded_model_state() required every floating parameter to share one dtype. transformers deliberately keeps the modules named by _keep_in_fp32_modules (fp16 loads) and _keep_in_fp32_modules_strict (fp16 and bf16 loads) in float32 via _get_dtype_plan, so valid checkpoints failed with "model load left a corrupted state" (Ernie4.5-MoE gate.weight/moe_statics, GPT-OSS norms, T5/mT5 wo, DeepSeek-V3.2 indexer.weights_proj). Exclude a parameter from both dtype checks only when it is float32 and its full name matches a declaration, collected from the model and its submodules. Matching mirrors transformers 5.22: each entry is compiled as a regex with "*" -> ".*" and searched against the whole parameter name. Undeclared float32 parameters, declared modules left in a half dtype, and pinned parameters on the meta device still raise, so the #4140 protection is intact. Tests cover Ernie4.5-MoE (native and QuantizeConfig(offload_to_disk=False) + bfloat16), a tiny GPT-OSS in fp16, the negative controls (undeclared fp32 leakage and cleared declarations), and the #4140 suites.
This was referenced Nov 17, 2026
sLaffey
pushed a commit
to sLaffey/GPTQModel
that referenced
this pull request
Nov 18, 2026
…ction dtypes (ModelCloud#4888) (ModelCloud#5021) * fix(hymba): materialize root-level bare parameters and honour construction dtypes (ModelCloud#4888) Hymba could not be quantized in half precision, for two independent generic reasons. 1. `get_modules_with_direct_meta_tensors` only returned the modules a definition declares. A decoder root (or any other module-tree prefix node) can own a bare `nn.Parameter`/buffer that is not a child module -- Hymba's `model.memory_tokens` is one. Nothing in the base-module or layer traversal materializes it, so with the default offload shell it stayed on `meta` and the input-capture forward raised `Tensor on device cpu is not on the expected device meta!`. The scan now also walks every module-tree prefix path and returns the nodes that own a direct meta tensor, so no definition has to enumerate them. 2. `assert_loaded_model_state` refused a valid bf16 load of Hymba because its remote constructor allocates `mamba.A_log` in fp32 from an explicit fp32 `A`, and transformers loads the bf16 checkpoint value into that fp32 parameter without changing its dtype (values exact). `ModelCloud#4209` only exempts `_keep_in_fp32_modules`. The dtype each parameter had when the model was constructed is now recorded in `PreTrainedModel.post_init` (dtypes only, never tensors). A parameter that is still fp32 *and* was already fp32 at construction is treated as intentional; one the load changed away from its construction dtype is still reported, so a broken cast is not masked. Fixes ModelCloud#4888 * fix(hf): ignore an uninformative all-fp32 construction record (ModelCloud#4888) A record taken without transformers' dtype context (every parameter fp32) says nothing about which parameters were intentionally fp32, so it must not exempt anything: keep the strict check in that case. Also move the keep-in-fp32 matcher inside the defensive try, since it now runs on every model construction rather than only at the post-load guard.
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.
Fixes #4170
TL;DR
assert_loaded_model_state(require_uniform_dtype=True, expected_dtype=...)treated every float32 parameter inside a half-precision model as corruption. transformers keeps the modules named by_keep_in_fp32_modules/_keep_in_fp32_modules_strictin float32 on purpose, so valid checkpoints (Ernie4.5-MoE, GPT-OSS, T5/mT5, DeepSeek-V3.2, glm_moe_dsa) failed to load. The guard now exempts a parameter from both dtype checks only when it is float32 and its full name matches a declaration. Undeclared fp32 leakage still raises, so #4140's protection is unchanged. Net: +66 lines ingptqmodel/utils/hf.py, +314 in the load-state tests, +47 indocs/concurrency.md.1. Root cause
#4140 (commit
67ebd21) added the post-load safety net ingptqmodel/utils/hf.pyand called it fromgptqmodel/models/loader.py:1880(native load),gptqmodel/models/loader.py:2086(quantize-path load,offload_to_disk=False),gptqmodel/models/loader.py:3284(quantized load; dtype checks off).The old code (
origin/maingptqmodel/utils/hf.py:423-449) counted every non-meta floating parameter into oneCounterand raised when it held more than one dtype, or when any dtype differed fromexpected_dtype. It never consulted the model's declarations.transformers 5.22 does the opposite on purpose:
PreTrainedModel._get_dtype_plan(modeling_utils.py:3764)_keep_in_fp32_modulesentry totorch.float32whendtype is torch.float16, and every_keep_in_fp32_modules_strictentry for fp16 and bf16core_model_loading.py:1697-1739build_glob_alternation(dtype_plan)compiles each entry (*->.*) andre.searches it against the renamed parameter key; a match overrides the load dtype with float32So
Ernie4_5_MoeForCausalLM(modeling_ernie4_5_moe.py:460,_keep_in_fp32_modules_strict = ["gate.weight", "moe_statics"]) legitimately produces{'torch.bfloat16': 22, 'torch.float32': 2}— exactly whatAutoModelForCausalLM.from_pretrainedreturns for the same directory.2. The fix
gptqmodel/utils/hf.py:_iter_keep_in_fp32_declarations(line 390) collects both attributes from the model and every submodule (a composite model may register them on a child), de-duplicated._compile_keep_in_fp32_matcher(line 413) compiles each declaration exactly like transformers 5.22:name.replace("*", ".*")fed tore.compile, thenre.searchagainst the full parameter name. Entries are module substrings (gate.weight,wo,norm), so this is a substring/regex search, not set-equality on module names; wildcard entries keep transformers' glob behaviour.assert_loaded_model_state(line 437) skips such a parameter only whenparameter.dtype is torch.float32(line 495) — the dtype_get_dtype_planpins it to.No call site changed; the signature is untouched.
flowchart TD A["named_parameters()"] --> B{"floating"} B -- no --> Z["ignore"] B -- yes --> C{"is_meta"} C -- yes --> D["meta violation"] C -- no --> E{"dtype is float32"} E -- no --> F["count dtype"] E -- yes --> G{"keep-in-fp32 matcher hits name"} G -- "yes" --> Z G -- "no" --> F F --> H{"expected_dtype set"} H -- yes --> I{"dtype != expected_dtype"} H -- no --> J{"uniform required and more than one dtype"} I -- yes --> K["RuntimeError: corrupted state"] J -- yes --> K67ebd21)_keep_in_fp32_modules+_keep_in_fp32_modules_strict, model and submodulesre.searchon the full parameter name3. Repro: before
main@9dad24974, CUDA venv, CPU device (CUDA_VISIBLE_DEVICES=""), tiny Ernie4.5-MoE written withcfg.dtype = bfloat16and the two pinned tensors kept fp32:4. Repro: after
Same scripts, same machine:
The remaining float32 parameters are exactly the declared pins:
Reference:
AutoModelForCausalLM.from_pretrained(ernie_tiny, dtype=torch.bfloat16)yields the same histogram,{'torch.bfloat16': 22, 'torch.float32': 2}.5. Negative control: #4140 still protects
_Tiny([float16, float32]), no declarations,require_uniform_dtype=TrueRuntimeError: ... mixed dtypesexpected_dtype=float16RuntimeError: ... not all torch.float16model.layers.1.self_attn.q_proj.weightcast to fp32RuntimeError: ... not all torch.bfloat16_keep_in_fp32_*declaration shadowed withNoneRuntimeError: ... mixed dtypeskeep) left in fp16 whileexpected_dtype=float32RuntimeError: ... not all torch.float32RuntimeError: ... stayed on the meta device6. Tests
tests/test_load_state_assertions.py(+314 lines; 6 new cases plus real-model fixtures):test_declared_keep_in_fp32_modules_are_exempt_from_both_dtype_checkstest_keep_in_fp32_declaration_on_a_submodule_is_honoredtest_keep_in_fp32_patterns_follow_transformers_glob_matchingkeep.w*matches,keep.biasdoes nottest_declared_module_left_in_a_half_dtype_is_still_reportedtest_undeclared_mixed_dtypes_still_raise/test_clearing_keep_in_fp32_declaration_restores_the_guard/test_declared_fp32_parameter_on_meta_still_raisestest_ernie4_5_moe_loads_with_declared_keep_in_fp32_strict_modulesQuantizeConfig(offload_to_disk=False)+ bfloat16, prints both histogramstest_gpt_oss_loads_in_fp16_with_declared_keep_in_fp32_normstest_ernie4_5_moe_negative_controls_still_raiseWith
origin/main'sgptqmodel/utils/hf.pyrestored (i.e. before the fix), the same file is 6 failed, 11 passed — the six failures are the behaviour above (test_ernie4_5_moe_negative_controls_still_raisefails because the load itself raises). After the fix: 17 passed.tests/test_concurrent_load.py,tests/test_hf_init_guard.pyandtests/test_concurrency_guards.pyare #4140's own safety net; they pass unchanged.7. Docs
docs/concurrency.mdgains a "Declared float32 pins are exempt" subsection under Safety net: the transformers dtype-plan mechanism, the matching semantics, the flow diagram above, and the failure/ambiguity rows (declared fp32 exempt; undeclared fp32 or declared non-fp32 still raises). The validation section now lists the load-state suites.8. Hardware
CPU only (
CUDA_VISIBLE_DEVICES=""), on the CUDA 2.16.0.dev+cu130 / transformers 5.22.2 venv and the ROCm 10.1 venv (HIP_VISIBLE_DEVICES=2, R9700 gfx1201). No GPU compute was used.9. Risk / limitations
re.searchof the declaration over the full parameter name, exactly like transformers 5.22. A declaration that is a raw regex with metacharacters is compiled as-is (same failure mode as transformers); no escaping is added.GPTQMODEL_*switch was added; no signature or call-site change.