Skip to content

feat(model): add native GPTQModel load bridge for Transformers/Optimum - #3503

Merged
Qubitium merged 4 commits into
mainfrom
feat/hf-native-load-bridge
Nov 3, 2026
Merged

Qubitium merged 4 commits into
mainfrom
feat/hf-native-load-bridge

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

Summary

Transformers hands GPTQ loading to Optimum, which replaces every linear layer with a single homogeneous kernel derived from the global quantization config. That loses per-module dynamic settings and cannot rebuild structural rewrites such as fused blocks or expanded MoE experts, so native GPTQModel checkpoints load with the wrong kernels (or fail outright).

This adds a small stable bridge that GPTQModel checkpoints can use through Transformers/Optimum.

New API — gptqmodel/utils/hf_load.py

Re-exported from gptqmodel.utils.model, so existing import paths keep working.

Symbol Purpose
HFGPTQModelLoadContext Carries state between the pre- and post-weight-load hooks.
hf_gptqmodel_prepare_model_for_load Resolves the checkpoint manifest, applies fused/MoE rewrites on the meta device, and installs one supported kernel per serialized module while honoring the full dynamic config.
hf_gptqmodel_post_init_for_load Runs the v1→v2 conversion and backend post-init once the caller assigned the checkpoint tensors.
is_native_gptqmodel_checkpoint Let a caller decide up front whether a checkpoint needs this path.

Also exposes find_checkpoint_dir for manifest resolution.

Provenance gating

Optimum's own saved checkpoints also record a gptqmodel:<version> entry, because Optimum delegates the quantization math to GPTQModel. Treating any gptqmodel entry as native would hijack Optimum's own loading path and silently swap its selected kernel.

So a checkpoint is only native when its provenance names GPTQModel without naming Optimum:

["gptqmodel:7.8.0"]                  -> native
["gptq-model:7.8.0"]                 -> native
["optimum:2.3.0", "gptqmodel:..."]   -> Optimum keeps its existing path
["optimum:2.3.0"]                    -> Optimum keeps its existing path
unresolvable Hub repo id             -> Optimum keeps its existing path

Supporting change

create_quant_module now accepts {CPU, meta} instead of CPU only. Transformers builds a quantized model shell on the meta device, so the meta path is required for the bridge to work; the replacement layer still lands on whichever device the original layer occupied.

Tests

tests/test_hf_gptqmodel_load_bridge.py (new):

  • manifest-driven kernel selection, with a dense module preserved even though a dynamic rule names it
  • provenance matrix above, including the Optimum-owned and unresolvable-path cases
  • missing-module error after structural conversion
  • Laguna MoE (dense attention + sparse experts) expansion on meta
  • post-init restoration of dynamic / lm_head / method / pack_dtype

tests/test_integration.py: end-to-end AutoModelForCausalLM.from_pretrained over a saved checkpoint, asserting kernel class, per-module group size, preserved dense layer, and no residual meta tensors.

Validation

tests/test_hf_gptqmodel_load_bridge.py            10 passed
tests/test_integration.py (bridge test)            1 passed
both suites together                      17 passed, 1 skipped
ruff check                                  All checks passed

The skip needs a machine-local /monster/data checkpoint path.

Cross-checked against the Optimum-side integration from huggingface/optimum#2469: the 5 Optimum bridge tests pass against this implementation.

Notes

  • Draft: this pairs with fix(gptq): delegate native GPTQModel loads huggingface/optimum#2469. The Optimum side needs a corresponding API-release bump before its CI can exercise the delegate.
  • tests/test_laguna_support.py::test_laguna_module_tree_expands_dense_attention_and_sparse_moe_paths fails on unmodified main too; unrelated to this change.

Transformers hands GPTQ loading to Optimum, which replaces every linear layer
with one homogeneous kernel derived from the global quantization config. That
loses per-module `dynamic` settings and cannot rebuild structural rewrites such
as fused blocks or expanded MoE experts, so native GPTQModel checkpoints load
with the wrong kernels.

Add a stable bridge in `gptqmodel.utils.hf_load`, re-exported from
`gptqmodel.utils.model`:

- `HFGPTQModelLoadContext` carries state between the two hooks.
- `hf_gptqmodel_prepare_model_for_load` resolves the checkpoint manifest,
  applies fused/MoE rewrites on the meta device, and installs one supported
  kernel per serialized module while honoring the full `dynamic` config.
- `hf_gptqmodel_post_init_for_load` runs the v1->v2 conversion and backend
  post-init once the caller has assigned the checkpoint tensors.

Checkpoints that Optimum saved also record a `gptqmodel:<version>` entry,
because Optimum uses GPTQModel for the quantization math. Only checkpoints
whose provenance names GPTQModel without naming Optimum are treated as native,
so Optimum keeps its existing loading path.

Relax the `create_quant_module` device guard to accept the meta device, which
Transformers uses while building a quantized model shell.

Tests cover manifest-driven kernel selection, dense-module preservation, the
Optimum-owned and unresolvable-path cases, missing-module errors, Laguna MoE
expansion on meta, post-init config restoration, and an end-to-end
Transformers load.
Comment thread gptqmodel/utils/model.py Dismissed
@ZX-ModelCloud
ZX-ModelCloud marked this pull request as ready for review November 3, 2026 09:06
github-code-quality flags the bridge re-export in utils/model.py as an unused
import and the test-local imports as import-style noise. Both are deliberate:

- The re-export exists so transformers/optimum can keep importing the bridge
  from the stable `gptqmodel.utils.model` entry point. Dropping it raises
  ImportError there, so keep it and spell out why next to the noqa.
- `test_hf_load_post_init_restores_gptqmodel_config_fields` needs the module
  object for monkeypatch.setattr, matching the local-import convention already
  used by other tests in this repo.

Hoist only GPTQConfig, which transformers already exports at module scope.

Verified: ruff 0.14.2 (CI gate) clean, PLC0415 and F401 clean, bridge tests
10 passed on CUDA and ROCm.
Comment thread tests/test_hf_gptqmodel_load_bridge.py Dismissed

Qubitium commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

Reviewed commit 1b64ef7012c28908ce9a3f1ff992aa7e0fda0760. I found two correctness issues in the native loading path.

1. [P1] Restore the online Hadamard transform for rotated checkpoints — hf_load.py:324–329

The bridge accepts manifests with rotation="hadamard" or "random", but finishing with gptqmodel_post_init() does not restore rotation state. The normal loader separately calls _setup_rotation_online_had(model, qcfg.rotation) and restricts kernel selection to rotation-compatible backends. Neither step is present here. Consequently, mlp.down_proj.online_full_had remains false and the checkpoint's rotated weights consume untransformed activations, silently changing inference results.

I reproduced this with a one-layer Llama shell, a native manifest containing rotation="hadamard", and the real prepare/post-init hooks using GPTQ_TORCH on CPU. Post-init returned successfully with online_full_had=False. For K=128, centered weight codes all -8, unit scales, and input e₀, the projection returned -8; the independent normalized-Hadamard reference is -8 * sqrt(128) ≈ -90.5097.

Please share the normal loader's rotation backend validation and online-transform setup with this bridge. Add a rotated-checkpoint load-and-forward regression, rather than checking only restored metadata.

2. [P2] Apply the saved activation policy before selecting kernels — hf_load.py:277–285

The bridge passes the caller's backend directly to make_quant(), omitting the normal loader's backend_for_activation(qcfg.activation_mode, backend) step. W4AFP8/NVFP4 kernels have zero AUTO-selection priority, so an AUTO load of a native W4A checkpoint installs ordinary GPTQ kernels. Post-init nevertheless attempts to install the W4A activation stream and fails because the required W4A projections are absent.

With a native activation={"mode":"w4afp8"} manifest containing all seven projections of a one-layer Llama, I reproduced BACKEND.AUTO selecting TorchAtenLinear, followed by ValueError: No complete W4A decoder layer was found. This was a CPU loader-path reproduction, not a hardware FP8/NVFP4 execution test.

Please normalize the requested backend and apply backend_for_activation before make_quant, preserving the normal loader's rejection of incompatible explicit backends. Add coverage for saved activation policies with AUTO.

Validation

  • New bridge unit suite: 10 passed.
  • TestIntegration::test_transformers_native_gptqmodel_load_bridge: 1 passed, using companion Optimum PR [CI] fix log files were saved with wrong runid #2469 at 391afc7 via an isolated checkout.
  • Both targeted reproductions above completed; compilation was disabled only for the Torch projection probe.
  • git diff --check passed.
  • The separate Optimum bridge unit class could not collect in the integration environment because parameterized is missing.

The native load bridge skipped two post-processing steps the normal loader
performs, so two classes of native checkpoints loaded incorrectly.

Rotation (P1): rotated checkpoints fuse an orthogonal Q and an exact Hadamard H
into the weights, and H has to be re-applied to activations at inference. The
bridge accepted `rotation=hadamard|random` but never called
`_setup_rotation_online_had`, leaving `mlp.down_proj.online_full_had` False.
The module then consumes untransformed activations, so the load succeeds and
inference is silently wrong. Call the shared helper after post-init, and reject
rotation on backends that cannot apply the transform instead of accepting them.

Activation policy (P2): W4AFP8/NVFP4 kernels carry no AUTO-selection priority,
so an AUTO load of a W4A checkpoint installed ordinary GPTQ kernels and
post-init then failed with "No complete W4A decoder layer was found". Resolve
the backend through `backend_for_activation` before `make_quant`, keeping the
normal loader's rejection of incompatible explicit backends.

Both regressions are covered by tests that fail when the fix is removed:
- rotated post-init leaves `online_full_had` armed on `mlp.down_proj`
- AUTO resolves W4AFP8/NVFP4 from the saved activation mode, and still rejects
  a mismatched explicit backend
- AUTO resolves a rotation-aware kernel, and rotation on MARLIN is rejected

Verified: 16 passed on CUDA and ROCm, bridge integration 1 passed, Optimum
bridge tests 4 passed, ruff 0.14.2 clean.
Comment thread tests/test_hf_gptqmodel_load_bridge.py Dismissed
The bridge was the only load path that skipped
`_set_paged_attention_safe_cuda_graphs`, which the normal loader applies on every
quantized load. Paged Flash Attention is not CUDA-graph capture safe, so models
declaring a paged attn implementation kept transformers' continuous-batching
default `use_cuda_graph=True` and captured an unsafe graph.

Apply the same helper after post-init. It is a no-op for models whose attn
implementation does not list `paged`, so non-paged loads are unchanged.

Tests drive the real post-init hook and cover both sides: a paged model gains
`continuous_batching_config.use_cuda_graph == (False, False)`, and a non-paged
model gains no `generation_config` at all.

Verified: 18 passed on CUDA and ROCm, bridge integration 1 passed, Optimum
bridge tests 4 passed, ruff 0.14.2 clean.
Comment thread tests/test_hf_gptqmodel_load_bridge.py Dismissed
Comment thread tests/test_hf_gptqmodel_load_bridge.py Dismissed

ZX-ModelCloud commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator Author

Both issues reproduced and fixed in e96aba646. Also fixed the same class of omission you did not list (paged-attention CUDA graph capture).

P1 — rotation state restored

Confirmed your finding: hf_load.py had zero references to rotation, so mlp.down_proj.online_full_had stayed False. Independent repro before the fix:

BRIDGE  online_full_had = False
NORMAL  online_full_had = True  K = 1

Fix, shared with the normal loader rather than reimplemented:

  • hf_load.py:381 calls _setup_rotation_online_had(model, qcfg.rotation) after post-init.
  • _resolve_backend_for_checkpoint() (hf_load.py:209) now applies the backend policy I had also omitted: format must be GPTQ/GPTQ_V2, AUTO resolves to GPTQ_TORCH, and anything outside {gptq_torch, gptq_triton, gptq_w4afp8, gptq_w4a_nvfp4} raises NotImplementedError.

P2 — saved activation policy applied before kernel selection

Confirmed: backend_for_activation was not called, so AUTO + w4afp8 stayed BACKEND.AUTO. Repro before the fix matched yours at the path-selection layer (no FP8 hardware execution, same as your note):

AUTO + w4afp8    -> BACKEND.GPTQ_W4AFP8     (was AUTO)
AUTO + w4a_nvfp4 -> BACKEND.GPTQ_W4A_NVFP4  (was AUTO)
TRITON + w4afp8  -> ValueError: Activation policy `w4afp8` requires backend `gptq_w4afp8` (preserved)

Applied at hf_load.py:320 before make_quant(), and the explicit-backend rejection of the normal loader is preserved.

Additional fix — paged attention

_set_paged_attention_safe_cuda_graphs() is called on every normal-loader path (4 sites) and was also missing here. Paged Flash Attention is not CUDA-graph capture safe, so a paged model kept transformers' continuous-batching default use_cuda_graph=True. Now called at hf_load.py:386; no-op for non-paged implementations.

On the test gap you called out

You were right that metadata-only assertions let P1 through. I wrote the regression against the real hf_gptqmodel_post_init_for_load, not the helper, and verified it actually catches the defect by reverting the fix:

Variant Result
Fix reverted (P1 + P2 + paged) 4 failed — all three regressions fire
Fix present 18 passed

Coverage added (tests/test_hf_gptqmodel_load_bridge.py):

  • test_hf_load_post_init_restores_online_hadamard_state (line 312) — drives post-init, asserts online_full_had is True and K is set
  • test_hf_load_bridge_auto_backend_picks_rotation_kernel (283) — AUTO + rotation resolves to a rotation-aware kernel
  • test_hf_load_bridge_rejects_rotation_on_incompatible_backend (299) — rotation + MARLIN raises
  • test_hf_load_bridge_auto_backend_applies_saved_activation_policy (373) — W4AFP8/NVFP4 from saved policy under AUTO
  • test_hf_load_bridge_still_rejects_incompatible_activation_backend (389)
  • test_hf_load_post_init_opts_paged_attention_out_of_cuda_graphs (398)
  • test_hf_load_post_init_leaves_non_paged_attention_untouched

Validation

Suite CUDA (RTX 4090) ROCm (RDNA, 2 GPUs)
tests/test_hf_gptqmodel_load_bridge.py 18 passed 18 passed
test_transformers_native_gptqmodel_load_bridge 1 passed —
Optimum #2469 bridge tests (391afc7) — 4 passed
ruff 0.14.2 (format/check.sh) All checks passed —

One limitation I did not resolve

The rotation and paged-attention tests are structural, not numerical: they assert the transform is armed and graph capture is disabled, but do not run a forward pass against a normalized-Hadamard reference like your -8 vs -90.5097 probe. A real rotated-checkpoint forward regression needs a shippable rotated checkpoint fixture, which we do not have. If you want that before merge, say so and I will build the fixture — otherwise the current fail-on-revert coverage is what I can guarantee.

@Qubitium Requesting another review.

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.

2 participants