Skip to content

fix(models): keep declared fp32 modules exempt from the load dtype guard (#4170) - #4209

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4170-keep-fp32
Nov 16, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4170-keep-fp32

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

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_strict in 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 in gptqmodel/utils/hf.py, +314 in the load-state tests, +47 in docs/concurrency.md.

1. Root cause

#4140 (commit 67ebd21) added the post-load safety net in gptqmodel/utils/hf.py and called it from

  • gptqmodel/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/main gptqmodel/utils/hf.py:423-449) counted every non-meta floating parameter into one Counter and raised when it held more than one dtype, or when any dtype differed from expected_dtype. It never consulted the model's declarations.

transformers 5.22 does the opposite on purpose:

transformers symbol Behaviour
PreTrainedModel._get_dtype_plan (modeling_utils.py:3764) maps every _keep_in_fp32_modules entry to torch.float32 when dtype is torch.float16, and every _keep_in_fp32_modules_strict entry for fp16 and bf16
core_model_loading.py:1697-1739 build_glob_alternation(dtype_plan) compiles each entry (* -> .*) and re.searches it against the renamed parameter key; a match overrides the load dtype with float32

So 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 what AutoModelForCausalLM.from_pretrained returns 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 to re.compile, then re.search against 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 when parameter.dtype is torch.float32 (line 495) — the dtype _get_dtype_plan pins 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 --> K
Loading
Mechanism Before (67ebd21) After
Declaration source ignored _keep_in_fp32_modules + _keep_in_fp32_modules_strict, model and submodules
Matching none transformers-5.22 regex/glob re.search on the full parameter name
Exempt dtype none float32 only (the pinned dtype)
Undeclared fp32 parameter raises raises (unchanged)
Declared module left in fp16/bf16 raises raises (not exempt)
Declared parameter on meta raises raises (materialization check runs first)

3. Repro: before

main @ 9dad24974, CUDA venv, CPU device (CUDA_VISIBLE_DEVICES=""), tiny Ernie4.5-MoE written with cfg.dtype = bfloat16 and the two pinned tensors kept fp32:

RuntimeError: Ernie4_5_MoeQModel.from_pretrained: model load left a corrupted state: floating parameters have mixed dtypes: {'torch.bfloat16': 22, 'torch.float32': 2}
  File "/root/stableabi/gptqmodel-fp32/gptqmodel/models/loader.py", line 1880, in from_pretrained
  File "/root/stableabi/gptqmodel-fp32/gptqmodel/utils/hf.py", line 454, in assert_loaded_model_state

RuntimeError: Ernie4_5_MoeQModel.from_pretrained: model load left a corrupted state: floating parameters are not all torch.bfloat16: {'torch.float32': 2}
  File "/root/stableabi/gptqmodel-fp32/gptqmodel/models/loader.py", line 2086, in from_pretrained   # QuantizeConfig(offload_to_disk=False), dtype=bfloat16

RuntimeError: GPTOSSGPTQ.from_pretrained: model load left a corrupted state: floating parameters are not all torch.float16: {'torch.float32': 5}
  File "/root/stableabi/gptqmodel-fp32/gptqmodel/models/loader.py", line 1880, in from_pretrained   # tiny GPT-OSS, dtype=float16

4. Repro: after

Same scripts, same machine:

# GPTQModel.load(ernie_tiny)                          -> LOADED OK {'torch.bfloat16': 22, 'torch.float32': 2}
# GPTQModel.load(ernie_tiny, QuantizeConfig(offload_to_disk=False), dtype=torch.bfloat16)
#                                                     -> LOADED OK {'torch.bfloat16': 32, 'torch.float32': 2}
# GPTQModel.load(gptoss_tiny, dtype=torch.float16)    -> LOADED OK {'torch.float16': 32, 'torch.float32': 5}

The remaining float32 parameters are exactly the declared pins:

ernie:   ['model.layers.1.mlp.gate.moe_statics.e_score_correction_bias', 'model.layers.1.mlp.gate.weight']
gpt_oss: ['model.layers.0.input_layernorm.weight', 'model.layers.0.post_attention_layernorm.weight',
          'model.layers.1.input_layernorm.weight', 'model.layers.1.post_attention_layernorm.weight',
          'model.norm.weight']

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

Control Result
_Tiny([float16, float32]), no declarations, require_uniform_dtype=True RuntimeError: ... mixed dtypes
same, expected_dtype=float16 RuntimeError: ... not all torch.float16
Real Ernie4.5-MoE loaded, then model.layers.1.self_attn.q_proj.weight cast to fp32 RuntimeError: ... not all torch.bfloat16
Real Ernie4.5-MoE loaded, then every _keep_in_fp32_* declaration shadowed with None RuntimeError: ... mixed dtypes
Declared module (keep) left in fp16 while expected_dtype=float32 RuntimeError: ... not all torch.float32
Declared parameter moved to the meta device RuntimeError: ... stayed on the meta device

6. Tests

tests/test_load_state_assertions.py (+314 lines; 6 new cases plus real-model fixtures):

Test Invariant
test_declared_keep_in_fp32_modules_are_exempt_from_both_dtype_checks declared fp32 pin is exempt from uniform + expected dtype checks
test_keep_in_fp32_declaration_on_a_submodule_is_honored declaration on a child module counts
test_keep_in_fp32_patterns_follow_transformers_glob_matching keep.w* matches, keep.bias does not
test_declared_module_left_in_a_half_dtype_is_still_reported exemption is float32-only
test_undeclared_mixed_dtypes_still_raise / test_clearing_keep_in_fp32_declaration_restores_the_guard / test_declared_fp32_parameter_on_meta_still_raises #4140 guard intact
test_ernie4_5_moe_loads_with_declared_keep_in_fp32_strict_modules issue repro: native + QuantizeConfig(offload_to_disk=False) + bfloat16, prints both histograms
test_gpt_oss_loads_in_fp16_with_declared_keep_in_fp32_norms issue repro: fp16 GPT-OSS
test_ernie4_5_moe_negative_controls_still_raise real-model negative controls

With origin/main's gptqmodel/utils/hf.py restored (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_raise fails because the load itself raises). After the fix: 17 passed.

CUDA venv (CPU device):  PYTHONPATH=$PWD CUDA_VISIBLE_DEVICES="" /opt/venvs/cu130t/bin/python -m pytest \
  tests/test_load_state_assertions.py tests/test_concurrent_load.py tests/test_hf_init_guard.py tests/test_concurrency_guards.py -q -p no:randomly
  -> 30 passed, 1 warning in 93.20s      (post-merge; 30 passed in 121.56s pre-merge)

ROCm venv (HIP_VISIBLE_DEVICES=2): PYTHONPATH=$PWD HIP_VISIBLE_DEVICES=2 /opt/venvs/rocm101t/bin/python -m pytest \
  tests/test_load_state_assertions.py tests/test_concurrent_load.py tests/test_hf_init_guard.py tests/test_concurrency_guards.py -q -p no:randomly
  -> 30 passed, 1 warning

ruff check gptqmodel docs/eora tests setup.py  ->  All checks passed!

tests/test_concurrent_load.py, tests/test_hf_init_guard.py and tests/test_concurrency_guards.py are #4140's own safety net; they pass unchanged.

7. Docs

docs/concurrency.md gains 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

  • Matching is a re.search of 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.
  • The exemption is keyed on name + float32 dtype, not on "transformers actually applied the plan". A model that declares a name and leaves it in fp32 while the load dtype is fp32 is unaffected (uniform anyway). A model that declares a name but whose fp32 parameter was not produced by the plan is still accepted — that is the declared contract the issue asks for.
  • Only the two real attribute names are read. A misspelled attribute is equivalent to declaring nothing, so such a model still raises exactly as it did before this change.
  • No GPTQMODEL_* switch was added; no signature or call-site change.

… 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.
@Qubitium
Qubitium merged commit 5b5ea86 into main Nov 16, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-4170-keep-fp32 branch November 16, 2026 04:31
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.
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.

[REGRESSION] #4140: loading models that keep some parameters in fp32 now raises "model load left a corrupted state"

1 participant