Repository navigation
fix(models): gate model rotation on explicit per-model-type opt-in (#4169) - #4208
Merged
Merged
Conversation
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 #4169
Root cause
gptqmodel/models/base.py:2127onmainadmitted model-wide rotation withisinstance(self, (LlamaQModel, Qwen2QModel)), while its error text claimed"llama/qwen2 only".
Gemma2QModel,Gemma3QModeland every other Llama-shapeddefinition subclass
LlamaQModel, so they passed the check.On Gemma the fold is wrong three ways:
post_attention_layernormsits on the attention output, not the MLPinput (the real MLP input norm is
pre_feedforward_layernorm).x * (1 + w);reset_lnsetsw = 1, so theeffective gain becomes 2 instead of 1.
Result: silent corruption of Gemma2/Gemma3 checkpoints.
The fix
quantize()now callsvalidate_rotation_model_support(self)(
gptqmodel/models/base.py:2169) beforevalidate_rotation_dimensions, beforeuntying the head, and before
fuse_layer_norms/rotate_model. The gate readsthe declaration from the exact class:
and accepts only a
frozensetof verifiedmodel_typevalues. Absence or anyother value fails closed.
Why a non-inheriting lookup
If
supports_rotation = Truelived onLlamaQModel, all 19 direct subclasseswould inherit it and nothing would be fixed. The own-
__dict__lookup means anew subclass must opt in itself; a synthetic
LlamaQModelsubclass without theattribute is rejected.
Why the opt-in is a per-model-type frozenset, not a bool
LlamaQModelis also the definition formistral,gemma(Gemma 1),cohere,stablelm,olmo,yi,longllama,helium,seed_oss,graniteand
smollm3. A bool on the class would keep admittinggemma(RMSNormx * (1 + w)) andcohere/stablelm(LayerNorm bias), which were neververified. The declaration therefore names the model types it covers:
LlamaQModel.supports_rotation = frozenset({"llama"})(
gptqmodel/models/definitions/llama.py:20)Qwen2QModel.supports_rotation = frozenset({"qwen2"})(
gptqmodel/models/definitions/qwen2.py:17)ROTATION_SUPPORTED_MODEL_TYPES = frozenset({"llama", "qwen2"})is what theerror message prints; a test pins it to the declarations so the message cannot
lie again.
New gate flow
flowchart TD A["quantize(rotation=...)"] --> B{"resolve_model_rotation(qcfg)"} B -->|"None"| Z["no rotation"] B -->|"hadamard / random"| C["validate_rotation_model_support(self)"] C --> D{"rotation_supported(self)"} D -->|"no"| E["ValueError: model class, model_type,<br/>supported model types<br/>no weights modified"] D -->|"yes"| F["validate_rotation_dimensions"] F -->|"unsupported width"| G["ValueError: names the dimension<br/>no weights modified"] F -->|"ok"| H["fuse_layer_norms"] H --> I["rotate_model"] I --> J["rotation backend check"] style E fill:#fde2e1,stroke:#dc2626 style G fill:#fde2e1,stroke:#dc2626flowchart TD A["rotation_supported(model_def)"] --> B["declared = type(model_def).__dict__.get('supports_rotation', False)"] B --> C{"isinstance(declared, frozenset)"} C -->|"no: absent or False"| N["not supported<br/>fail closed"] C -->|"yes"| E["model_type = model_def.model.config.model_type"] E --> F{"model_type in declared"} F -->|"yes"| Y["supported"] F -->|"no"| N style N fill:#fde2e1,stroke:#dc2626Before / after logits
Tiny random CPU models (float64, one decoder layer, all norm gains
normal_(0, 1)), fused with the definition module tree, rotated withhadamard, online Hadamard applied tomlp.down_proj.9.999e-081.0008.144e-081.0001.1260.000ValueErrorbefore any mutationValueErrorbefore any mutationThe Gemma2 row reproduces the issue's
~1.10 / 0.00table.LlamaQModelsubclass auditThe brief says 18 subclasses; current
main(a91d129) has 19 directsubclasses plus 3 indirect (
Qwen3_5TextQModel,QwenDriveQModel,ZDTaichu5QModel) = 22. All 22 were audited; anything not proven by aneutral-rotation test is
False.LlamaQModel(base)llamax * wRMSNorm; post-attention norm feeds the MLP; neutral error9.999e-08Qwen2QModelqwen28.144e-08DeciLMQModeldeci,nemotron-nasDreamQModeldreamErnie4_5QModelernie4_5Gemma2QModelgemma2pre_feedforward_layernorm; RMSNormx * (1 + w); post-norms not rotation-invariantGemma3QModelgemma3_textq_norm/k_normGemma3nTextQModelgemma3n_textx * (1 + w)Gemma4TextQModelgemma4_textq_norm/k_norm/v_norm, per-layer input adaptersGraniteSWAQModelgranite_swaHunYuanDenseV1QModelhunyuan_v1_densequery_layernorm/key_layernormInstellaQModelinstellaInternLMQModelinternlmtransformers<=4.44.2); not verifiedMimoQModelmimoMobileLLMQModelmobilellmNanbeigeQModelnanbeigeOlmo2QModelolmo2q_norm/k_norm;post_attention_layernormis a post-norm on attention output; extrapost_feedforward_layernormQwen3QModelqwen3q_norm/k_normare not rotation-invariantQwen3_5QModelqwen3_5q_norm/k_norm; linear-attention branchXverseQModelxverseQwen3_5TextQModel(indirect)qwen3_5_textq_norm/k_normQwenDriveQModel(indirect)qwen_driveZDTaichu5QModel(indirect)zdtaichu5Enabling any
norow requires adding its model type to that definition'ssupports_rotationtogether with its own neutral-rotation test.Tests
New
tests/test_rotation_opt_in.py:test_rotation_is_neutral_for_every_opted_in_definition— fuses, rotatesand applies the online Hadamard for
llamaandqwen2; asserts relativelogits error
< 1e-3and reports the measured number.test_rotation_raises_for_definition_that_did_not_opt_in— Gemma2, Gemma3,Gemma4, HunYuan, Olmo2 and Qwen3 raise; asserts the message names the class,
the
model_type,llama, qwen2, and "No weights were modified".test_rotation_opt_in_is_not_inherited_by_a_subclass— a syntheticLlamaQModelsubclass without the attribute is rejected.test_rotation_opt_in_can_be_declared_by_a_subclass— positive control.test_supported_model_types_constant_matches_the_declarations— the errormessage cannot drift from the opt-in declarations.
Exact commands and results (CPU only; no GPU taken):
CUDA_VISIBLE_DEVICES= PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest tests/test_rotation_opt_in.py -q10 passedCUDA_VISIBLE_DEVICES= PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest tests/test_rotation_opt_in.py tests/test_rotation_persistence.py tests/module_tree/test_gemma_olmo_family_plan_coverage.py -q47 passed, 4 skipped/opt/venvs/rocm101t/bin/pythonandHIP_VISIBLE_DEVICES=47 passed, 4 skippedCUDA_VISIBLE_DEVICES= PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest tests/module_tree/test_registered_module_plans.py tests/module_tree/test_definition_subset_ordering.py -q426 passedruff check gptqmodel docs/eora tests setup.pyAll checks passed!Pre-existing failures (verified identical on clean
origin/maina91d129, notcaused by this PR):
tests/test_gemma2_backend_guard.py::test_quantized_vllm_engine_still_admittedand
::test_quantized_sglang_engine_still_admittedfail inrestore_init_owned_rotary_buffers(gptqmodel/utils/structure.py:942) withAttributeError: '_FakeEngine' object has no attribute 'modules'.Docs
docs/rotation-model-support.md: the flow diagrams above, the exactsupported model list, the full audit table, the failure contract and the
measured before/after numbers.
docs/quantization-features.mdsection 4 now shows the model-support gatebefore the width check and links the new page.
README.mdanddocs/README.md.Risk / limitation
gptqmodel/models/loader.pyis outof scope for this change (owned by another worker). Existing checkpoints
that already declare rotation on an unsupported layout still load; this PR
prevents new ones from being produced.
mistral,yi,smollm3and the other Llama-shaped aliases now fail closedfor rotation. They were silently admitted before but never verified; enabling
them needs their own neutral-rotation test.
Gemma3is rejected structurally (same layout as Gemma2 plus q/k norms); Idid not run a separate Gemma3 neutral-rotation number because the gate
rejects it before any weight is touched.