Skip to content

fix(models): gate model rotation on explicit per-model-type opt-in (#4169) - #4208

Merged
Qubitium merged 1 commit into
mainfrom
fix/issue-4169-rotation-optin
Nov 16, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/issue-4169-rotation-optin

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4169

Root cause

gptqmodel/models/base.py:2127 on main admitted model-wide rotation with
isinstance(self, (LlamaQModel, Qwen2QModel)), while its error text claimed
"llama/qwen2 only". Gemma2QModel, Gemma3QModel and every other Llama-shaped
definition subclass LlamaQModel, so they passed the check.

On Gemma the fold is wrong three ways:

  1. post_attention_layernorm sits on the attention output, not the MLP
    input (the real MLP input norm is pre_feedforward_layernorm).
  2. Gemma RMSNorm computes x * (1 + w); reset_ln sets w = 1, so the
    effective gain becomes 2 instead of 1.
  3. The post-norms are not rotation-invariant.

Result: silent corruption of Gemma2/Gemma3 checkpoints.

The fix

quantize() now calls validate_rotation_model_support(self)
(gptqmodel/models/base.py:2169) before validate_rotation_dimensions, before
untying the head, and before fuse_layer_norms/rotate_model. The gate reads
the declaration from the exact class:

declared = type(model_def).__dict__.get("supports_rotation", False)

and accepts only a frozenset of verified model_type values. Absence or any
other value fails closed.

Why a non-inheriting lookup

If supports_rotation = True lived on LlamaQModel, all 19 direct subclasses
would inherit it and nothing would be fixed. The own-__dict__ lookup means a
new subclass must opt in itself; a synthetic LlamaQModel subclass without the
attribute is rejected.

Why the opt-in is a per-model-type frozenset, not a bool

LlamaQModel is also the definition for mistral, gemma (Gemma 1),
cohere, stablelm, olmo, yi, longllama, helium, seed_oss, granite
and smollm3. A bool on the class would keep admitting gemma (RMSNorm
x * (1 + w)) and cohere/stablelm (LayerNorm bias), which were never
verified. 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 the
error 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:#dc2626
Loading
flowchart 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:#dc2626
Loading

Before / after logits

Tiny random CPU models (float64, one decoder layer, all norm gains
normal_(0, 1)), fused with the definition module tree, rotated with
hadamard, online Hadamard applied to mlp.down_proj.

Model Relative logits error (before gate) Argmax agreement (before) After gate
Llama 9.999e-08 1.000 unchanged
Qwen2 8.144e-08 1.000 unchanged
Gemma2 1.126 0.000 ValueError before any mutation
Gemma3 not measured (same layout + q/k norms) n/a ValueError before any mutation

The Gemma2 row reproduces the issue's ~1.10 / 0.00 table.

LlamaQModel subclass audit

The brief says 18 subclasses; current main (a91d129) has 19 direct
subclasses plus 3 indirect (Qwen3_5TextQModel, QwenDriveQModel,
ZDTaichu5QModel) = 22. All 22 were audited; anything not proven by a
neutral-rotation test is False.

Definition model_type Rotate? Reason
LlamaQModel (base) llama YES x * w RMSNorm; post-attention norm feeds the MLP; neutral error 9.999e-08
Qwen2QModel qwen2 YES Llama decoder layout; neutral error 8.144e-08
DeciLMQModel deci, nemotron-nas no variable-depth/NAS layer selection; not verified
DreamQModel dream no diffusion language model, not a causal decoder forward
Ernie4_5QModel ernie4_5 no Llama-shaped tree but the forward was not verified
Gemma2QModel gemma2 no post-attention norm is on attention output; MLP input is pre_feedforward_layernorm; RMSNorm x * (1 + w); post-norms not rotation-invariant
Gemma3QModel gemma3_text no Gemma 2 layout plus per-head q_norm/k_norm
Gemma3nTextQModel gemma3n_text no Gemma 3n norms and per-layer adapters; x * (1 + w)
Gemma4TextQModel gemma4_text no post-norms, per-head q_norm/k_norm/v_norm, per-layer input adapters
GraniteSWAQModel granite_swa no attention-sink parameters and sliding-window layout; not verified
HunYuanDenseV1QModel hunyuan_v1_dense no per-head query_layernorm/key_layernorm
InstellaQModel instella no Llama-shaped norm positions but no neutral-rotation test
InternLMQModel internlm no pinned remote code (transformers<=4.44.2); not verified
MimoQModel mimo no Qwen2-based remote code; not verified
MobileLLMQModel mobilellm no remote code; not verified
NanbeigeQModel nanbeige no looped physical layers; not verified
Olmo2QModel olmo2 no per-head q_norm/k_norm; post_attention_layernorm is a post-norm on attention output; extra post_feedforward_layernorm
Qwen3QModel qwen3 no per-head q_norm/k_norm are not rotation-invariant
Qwen3_5QModel qwen3_5 no per-head q_norm/k_norm; linear-attention branch
XverseQModel xverse no pinned remote code; not verified
Qwen3_5TextQModel (indirect) qwen3_5_text no Qwen3.5 text layout with q_norm/k_norm
QwenDriveQModel (indirect) qwen_drive no Qwen3.5 layout with a vision tower
ZDTaichu5QModel (indirect) zdtaichu5 no Qwen3.5 text layout

Enabling any no row requires adding its model type to that definition's
supports_rotation together with its own neutral-rotation test.

Tests

New tests/test_rotation_opt_in.py:

  1. test_rotation_is_neutral_for_every_opted_in_definition — fuses, rotates
    and applies the online Hadamard for llama and qwen2; asserts relative
    logits error < 1e-3 and reports the measured number.
  2. 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".
  3. test_rotation_opt_in_is_not_inherited_by_a_subclass — a synthetic
    LlamaQModel subclass without the attribute is rejected.
  4. test_rotation_opt_in_can_be_declared_by_a_subclass — positive control.
  5. test_supported_model_types_constant_matches_the_declarations — the error
    message cannot drift from the opt-in declarations.

Exact commands and results (CPU only; no GPU taken):

Command Result
CUDA_VISIBLE_DEVICES= PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest tests/test_rotation_opt_in.py -q 10 passed
CUDA_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 -q 47 passed, 4 skipped
Same command with /opt/venvs/rocm101t/bin/python and HIP_VISIBLE_DEVICES= 47 passed, 4 skipped
CUDA_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 -q 426 passed
ruff check gptqmodel docs/eora tests setup.py All checks passed!

Pre-existing failures (verified identical on clean origin/main a91d129, not
caused by this PR): tests/test_gemma2_backend_guard.py::test_quantized_vllm_engine_still_admitted
and ::test_quantized_sglang_engine_still_admitted fail in
restore_init_owned_rotary_buffers (gptqmodel/utils/structure.py:942) with
AttributeError: '_FakeEngine' object has no attribute 'modules'.

Docs

  • New docs/rotation-model-support.md: the flow diagrams above, the exact
    supported model list, the full audit table, the failure contract and the
    measured before/after numbers.
  • docs/quantization-features.md section 4 now shows the model-support gate
    before the width check and links the new page.
  • Linked from README.md and docs/README.md.

Risk / limitation

  • The loader-side online-Hadamard setup in gptqmodel/models/loader.py is out
    of 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, smollm3 and the other Llama-shaped aliases now fail closed
    for rotation. They were silently admitted before but never verified; enabling
    them needs their own neutral-rotation test.
  • Gemma3 is rejected structurally (same layout as Gemma2 plus q/k norms); I
    did not run a separate Gemma3 neutral-rotation number because the gate
    rejects it before any weight is touched.

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.

[BUG] rotation is accepted on Gemma2/Gemma3 (and other LlamaQModel subclasses) and silently breaks the model

1 participant