Skip to content

fix(hf): run native MoE bridge, remap legacy VL keys, retune AWQ groups (#4073) - #4084

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4073-moevl
Nov 15, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4073-moevl

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4073

TL;DR

Four HF-interop defects are fixed in one change:

  1. The native GPT-QModel loading bridge now actually runs inside Optimum's GPTQ loader, so MoE checkpoints keep their per-expert weights instead of silently random-initializing them.
  2. The quantized loader applies the model's Transformers checkpoint conversion map, so legacy Transformers-4.x VL checkpoints (model.layers.*, visual.*) load.
  3. AWQ resolves a supported group size that divides in_features before calibration instead of raising after the whole pass.
  4. A native save drops the source auto_map when the .py files are not copied.

New reference page: docs/hf-interop.md, linked from README.md.

1. MoE checkpoints loaded by plain Transformers

Root cause

hf_gptqmodel_prepare_model_for_load (gptqmodel/utils/hf_load.py:242) and hf_gptqmodel_post_init_for_load (:361) were exported but never called by Optimum. Optimum's GPTQQuantizer.convert_model only replaces nn.Linear (optimum/gptq/quantizer.py), while Transformers 5 builds fused 3-D experts. Every experts.<n>.*.qweight was therefore UNEXPECTED and every fused expert MISSING, with no error.

Fix

_patch_optimum_gptqmodel_load_bridge (gptqmodel/__init__.py:228, installed at the end of package import) wraps GPTQQuantizer.convert_model / post_init_model. Native GPT-QModel checkpoints go through the bridge; Optimum-owned checkpoints keep Optimum's path because the bridge returns None for them. hf_compat_warnings (gptqmodel/models/writer.py:232) now also emits a loud save-time warning for per-expert checkpoints.

flowchart TD
    A["AutoModelForCausalLM.from_pretrained"] --> B["GptqHfQuantizer"]
    B --> C["patched GPTQQuantizer.convert_model"]
    C --> D{"hf_gptqmodel_prepare_model_for_load"}
    D -->|"Optimum-owned checkpoint"| E["original Optimum convert_model"]
    D -->|"native GPT-QModel checkpoint"| F["defuser expands fused blocks and MoE experts"]
    F --> G["make_quant per serialized module with dynamic config"]
    G --> H["Transformers assigns checkpoint tensors"]
    H --> I["patched post_init_model"]
    I --> J["hf_gptqmodel_post_init_for_load"]
    style E fill:#fff3cd,stroke:#997404
Loading

Before / after (real OLMoE-1B-7B checkpoint)

Path Result
Before (issue audit) 64 MarlinLinear attention only, experts.gate_up_proj MISSING, PPL 39570, "domest domest domest..."
After, CUDA 4090 (CPU device map) 3136 GPT-QModel quant linears, model.layers.0.mlp.experts.0 present, "The capital of France is Paris."
After, ROCm R9700 3136 quant linears, logits (1, 5, 50304), "The capital of France is Paris."

Save-time warning reproduced on the same real checkpoint:

WARN Model: This checkpoint stores per-expert quantized weights (`experts.<n>.*.qweight`). ...

2. Legacy-layout quantized VL checkpoints

Root cause

models/loader.py:2561 (validation) and :2850 / :2958 (load) read checkpoint keys verbatim. The HF conversion map was only applied on the LazyTurtle quantization path (loader.py:1786), so Qwen2-VL-2B-Instruct-GPTQ-Int8 (keys model.layers.*, visual.*) failed validation.

Fix

_checkpoint_key_converter (gptqmodel/models/loader.py:133) resolves the model's checkpoint conversion map from the live model unless a definition declares an explicit checkpoint_key_for_load / checkpoint_key_for_save. It is used for validation (runtime -> checkpoint) and both load calls (checkpoint -> runtime). The map is idempotent for runtime-layout checkpoints.

flowchart LR
    A["checkpoint: model.layers.0.mlp.down_proj.qweight"] --> B["HF conversion map"]
    B --> C["runtime: model.language_model.layers.0.mlp.down_proj.qweight"]
    D["checkpoint: visual.blocks.0.attn.qkv.weight"] --> B
    B --> E["runtime: model.visual.blocks.0.attn.qkv.weight"]
    F["already-runtime key"] --> B
    B --> G["unchanged"]
    style G fill:#d1e7dd,stroke:#146c43
Loading

Before / after

Path Result
Before ValueError: Missing required quantized weights ... model.language_model.layers.0.mlp.down_proj.qweight
After, CUDA 4090 196 quant linears, forward logits (1, 5, 151936), mean abs 7.31
After, ROCm R9700 196 quant linears, forward logits (1, 5, 151936), mean abs 7.36

3. AWQ with in_features % group_size != 0

Root cause

_accumulate_awq_weight_mean (gptqmodel/looper/awq_processor.py:93) reshapes the input axis into fixed groups and raised for intermediate_size=448 with group_size=128 only after calibration completed.

Fix

AWQProcessor._ensure_group_size_divisibility (awq_processor.py:540) runs in __init__, before any calibration forward. For each non-excluded linear it picks the largest kernel-supported group size that divides in_features (else -1 per-channel), preserves the module's other resolved overrides, and prepends an exact dynamic rule so staging, packing, save, and reload all resolve the same value. A warning names every retuned module.

flowchart TD
    A["AWQProcessor.__init__"] --> B["_ensure_group_size_divisibility"]
    B --> C{"in_features divisible by group_size"}
    C -->|"yes"| D["keep configured value"]
    C -->|"no"| E["largest supported divisor, else -1"]
    E --> F["prepend exact dynamic override"]
    F --> G["calibration, packing, save and reload agree"]
    style F fill:#cfe2ff,stroke:#084298
Loading

Before / after

Path Result
Before ValueError: Expected in_features (448) to be divisible by group_size (128).
After, CUDA 4090 (CPU quantize) Quantizes; down_proj.group_size == 64, override +:^model.layers.0.mlp.down_proj$ -> {"group_size": 64}
After, ROCm R9700 Quantizes; down_proj.group_size == 64, in_features == 448

4. Dangling auto_map after the native trust_remote_code override

Root cause

resolve_trust_remote_code (gptqmodel/utils/hf.py:749) turns remote code off for natively supported types, and the writer skips copying .py files. _save_model_configs_without_weights then merged the source auto_map back into the saved config.json, pointing at files that were not exported.

Fix

_save_model_configs_without_weights (writer.py:290) and save_quantized_embeddings drop auto_map whenever trust_remote_code is false, i.e. exactly when .py files are not copied.

Before / after (real Phi-tiny-MoE source config)

Path Result
Before Saved config.json keeps auto_map -> configuration_slimmoe.PhiMoEConfig; AutoConfig.from_pretrained(out, trust_remote_code=True) raises OSError: ... configuration_slimmoe.py
After, CUDA + ROCm Saved auto_map is None; AutoConfig.from_pretrained(out, trust_remote_code=True) returns PhimoeConfig (model_type=phimoe)

Tests

Exact commands and results:

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

CUDA_VISIBLE_DEVICES=GPU-1892aea4-cc09-827c-b9a5-93d4eef7f5ae \
python -m pytest -q tests/test_hf_gptqmodel_load_bridge.py \
  tests/test_checkpoint_compat.py tests/test_legacy_vl_checkpoint_load.py \
  tests/test_awq_dynamic_group_size.py tests/test_awq_moe_router_scaling.py \
  tests/test_checkpoint_interop_4053.py -k "not selects_compatible"
-> 55 passed, 1 deselected

HIP_VISIBLE_DEVICES=3 python -m pytest -q \
  tests/test_hf_gptqmodel_load_bridge.py tests/test_awq_dynamic_group_size.py \
  -k "not selects_compatible"
-> 23 passed, 1 deselected

HIP_VISIBLE_DEVICES=3 python -m pytest -q tests/test_checkpoint_compat.py \
  tests/test_legacy_vl_checkpoint_load.py -k "not loads_legacy_layout"
-> 18 passed, 1 deselected

Real-model runs (not committed tests) are the before/after tables above. The real VL checkpoint test is committed and skips when /monster/data/model/Qwen2-VL-2B-Instruct-GPTQ-Int8 is absent.

Pre-existing failure

tests/test_awq_dynamic_group_size.py::test_dynamic_group_size_selects_compatible_kernel_and_packs fails identically on clean origin/main (AttributeError: 'Stub' object has no attribute '_module_format'). It is deselected above and is not caused by this PR.

Hardware

  • NVIDIA RTX 4090 GPU-1892aea4-cc09-827c-b9a5-93d4eef7f5ae (CUDA venv, torch 2.16.0.dev+cu130)
  • AMD Radeon R9700 HIP_VISIBLE_DEVICES=3 (ROCm venv, torch 2.16.0.dev+rocm10.1)
  • The RTX 5090 was never used.

Notes / limitations

  • The Optimum bridge is installed by importing gptqmodel. A process that loads a native GPT-QModel checkpoint through Transformers without importing gptqmodel cannot be intercepted; the save-time warning now tells users to import it or use GPTQModel.load.
  • modules_to_not_convert was not added for GPTQ: Optimum's GPTQ loader does not read it. The bridge keeps unquantized gates such as Qwen's shared_expert_gate as nn.Linear, which removes the Marlin K=2048, N=1 crash structurally.
  • AWQ retunes the group size; it does not add partial trailing-group support to the AWQ kernels.

@Qubitium
Qubitium merged commit a247cce into main Nov 15, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-4073-moevl branch November 15, 2026 00:49
Qubitium pushed a commit that referenced this pull request Nov 17, 2026
#4692)

Transformers loads `quant_method: "awq"` through its own AwqQuantizer,
not Optimum. That path only replaces `nn.Linear` modules, so a GPT-QModel
AWQ checkpoint storing per-expert `experts.<n>.*.qweight` tensors against
fused 3-D expert parameters loaded with every routed expert randomly
initialized and no error. #4084 patched the Optimum GPTQ path only.

Wrap AwqQuantizer._process_model_before_weight_loading and
_process_model_after_weight_loading with the same contract as the Optimum
wrapper: a native GPT-QModel checkpoint is rebuilt from the manifest by
hf_gptqmodel_prepare_model_for_load, and any other checkpoint keeps
Transformers' own AWQ path because the bridge returns None.

The save-time warning no longer claims Optimum's GPTQ loader is the only
gap, and it now points at a remedy that applies to both methods.

Refs #4661
Qubitium added a commit that referenced this pull request Nov 17, 2026
…ges (#4680) (#4702)

Both HF load bridges called `hf_gptqmodel_prepare_model_for_load` without the
caller's backend, so `_resolve_backend_for_checkpoint` always saw `None` and
resolved AUTO. `docs/peft.md` tells users to set
`quantization_config["backend"] = "gptq_torch"` to get a trainable kernel; for a
GPT-QModel-made checkpoint that setting was silently dropped and AUTO picked a
different kernel (Marlin on CUDA, which does not support training). An
impossible choice such as `marlin` on a CPU-only host was accepted without a
word. Optimum-owned checkpoints kept honoring it, so behavior depended on who
made the checkpoint.

Forward `getattr(self, "backend", None)` from both bridges — the GPTQ one
(`GPTQQuantizer.convert_model`, #4084) and the AWQ one
(`AwqQuantizer._process_model_before_weight_loading`), which had the identical
defect. A quantizer without the attribute still forwards `None`.

Closes #4680.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant