Skip to content

fix(hf): derive missing g_idx for bridge loads (#6339) - #6344

Merged
Qubitium merged 2 commits into
mainfrom
fix/6339-gidx
Nov 29, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/6339-gidx

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Some desc_act=False GPTQ checkpoints store only qweight/qzeros/scales(/bias) and no g_idx (for example the AutoRound auto_gptq export fbaldassarri/HuggingFaceTB_SmolLM2-1.7B-Instruct-auto_gptq-int4-gs128-sym). GPTQModel.load is correct because the packed-layer constructor registers the canonical arange(in_features) // group_size placeholder and a missing checkpoint key leaves it in place. The Transformers/Optimum bridge has no such fallback: it builds the layer on meta, and PreTrainedModel._move_missing_keys_from_meta_to_device materializes the missing buffer with torch.empty_like — all zeros on CUDA (every row reads group 0) or random int32 on CPU (out-of-range crash). Marlin ignores g_idx when desc_act=False, so it was unaffected; every other kernel silently decoded garbage. Since #6327 this is the default from_pretrained path on CUDA.

This PR repairs the buffer in hf_gptqmodel_post_init before any kernel reads it, using the same derivation as the GPTQModel.load path.

Mechanism

  • gptqmodel/nn_modules/qlinear/_g_idx.py:13 — canonical_g_idx(in_features, group_size) is now the single owner of the arange(in_features) // group_size derivation (group_size=-1 is per-channel, i.e. all zeros).
  • gptqmodel/nn_modules/qlinear/__init__.py:2026 — _register_gptq_buffers (the GPTQModel.load placeholder) calls the helper instead of its inline list comprehension.
  • gptqmodel/utils/model.py:2239 — _repair_bridge_missing_g_idx runs at the top of hf_gptqmodel_post_init (:2314), before gptqmodel_post_init/kernel post_init.
    • A checkpoint-supplied index is left untouched. has_group_layout (_g_idx.py:32) accepts any permutation of the canonical mapping, so a third-party block permutation that still declares desc_act=False keeps its counts and stays authoritative (the Marlin contract is preserved). No Marlin special case.
    • An all-zero buffer for a multi-group layer is not a permutation of the canonical mapping (all rows in group 0), so it is rejected and replaced. Random int32 fails the range/count test.
    • desc_act=True cannot rebuild the activation-order permutation, so an invalid index raises an actionable ValueError naming the layer and telling the user to reload a checkpoint with g_idx or use desc_act=False. It does not fall back to canonical.
    • Empty placeholders (a kernel already consumed the index) and meta placeholders (disk offload) are skipped. g_idx registered as a parameter (Machete) is replaced with a parameter.

Regression test

tests/test_hf_bridge_missing_g_idx_6339.py builds a TorchLinear on meta, assigns the packed checkpoint tensors, and materializes the missing g_idx with deterministic uninitialized-memory poisons (all zeros = CUDA, random int32 = CPU). It then calls the real hf_gptqmodel_post_init.

  • (a) desc_act=False + no g_idx → canonical mapping derived, and the forward matches an independent FP64 decode of the checkpoint (both poison variants).
  • (b) desc_act=False + a real (non-canonical) g_idx → left untouched and decodes correctly.
  • (c) desc_act=True + no g_idx → raises ValueError mentioning desc_act=True and g_idx (both poison variants).

Red → green

Red at origin/main (42827b67), same test file:

cd /root/openai-audit/i-6339-red/tests
PYTHONPATH=/root/openai-audit/i-6339-red:/root/openai-audit/i-6339-red/tests CUDA_VISIBLE_DEVICES="" \
  /root/venv/bin/python -m pytest test_hf_bridge_missing_g_idx_6339.py -q -rs -p no:cacheprovider
# 4 failed, 1 passed
#   (a) g_idx stays [0,0,...] / random int32
#   (c) cuda-zeros: DID NOT RAISE; cpu-random: out-of-range message, not the desc_act one
#   (b) passes, as expected

Green on this branch:

cd /root/openai-audit/i-6339/tests
PYTHONPATH=/root/openai-audit/i-6339:/root/openai-audit/i-6339/tests CUDA_VISIBLE_DEVICES="" \
  /root/venv/bin/python -m pytest test_hf_bridge_missing_g_idx_6339.py -q -rs -p no:cacheprovider
# 5 passed

End-to-end on the real AutoRound checkpoint (offline, from the local HF cache, CPU):

origin/main: g_idx tail [0, 0, 0, 0] (another run: random int32), canonical=False,
             next token after "The capital of France is" = garbage
this branch: 168 layers repaired, g_idx tail [15, 15, 15, 15], canonical=True,
             logits finite (absmax 21.86), next token = " Paris"

Affected suites

cd /root/openai-audit/i-6339/tests
PYTHONPATH=/root/openai-audit/i-6339:/root/openai-audit/i-6339/tests CUDA_VISIBLE_DEVICES="" \
  /root/venv/bin/python -m pytest \
    test_hf_bridge_missing_g_idx_6339.py test_exllamav2_g_idx_bounds.py \
    test_hf_bridge_cpu_offload_5022.py test_hf_bridge_missing_shape_6149.py \
    test_hf_bridge_mixed_capability_5084.py test_hf_post_init_unpack_shift_5843.py \
    test_marlin_cpu_offload_post_init.py test_marlin_g_idx.py \
    test_marlin_g_idx_placeholder.py test_post_init_payload_5261.py \
    test_triton_g_idx_bounds.py test_hf_packing_api.py \
    test_checkpoint_interop_4053.py -q -rs -p no:cacheprovider
# 2 failed, 141 passed, 24 skipped

The two failures are pre-existing at origin/main and unrelated:
test_hf_packing_api.py::test_hf_bridge_forwards_in_features_to_kernel_validation[v1/v2] still expects the shape-blind bridge to raise ValueError, but #6149/#6326 changed it to fall back to the auto-padding Torch kernel. The same two tests fail in a pristine origin/main worktree.

Skipped (CPU-only run): CUDA Marlin/ExLlamaV2/Machete runtime tests, disk-offload paths that need an accelerator, and GPU-only packing/feasibility checks.

ruff:

/root/venv/bin/ruff check gptqmodel/nn_modules/qlinear/_g_idx.py \
  gptqmodel/nn_modules/qlinear/__init__.py gptqmodel/utils/model.py \
  tests/test_hf_bridge_missing_g_idx_6339.py
# All checks passed!

Unverified

  • CUDA kernel forwards (TorchLinear/Triton) were not run on a GPU; the repair happens before kernel selection/post-init and the constructed CPU test exercises the same buffer path.
  • The Marlin non-contiguous g_idx path is CUDA-only here; the repair preserves any valid permutation by construction (unit-checked by has_group_layout).

Fixes #6339

Transformers builds a quantized model on meta and materializes every
buffer the checkpoint does not contain with torch.empty_like
(_move_missing_keys_from_meta_to_device). A desc_act=False checkpoint may
legitimately omit g_idx (AutoRound's auto_gptq export does), so the packed
layer ends up with uninitialized storage: all zeros on CUDA (every row
reads group 0) and random int32 on CPU (out-of-range crash). GPTQModel.load
is unaffected because its constructor registers the canonical placeholder
and a missing key leaves it in place; the HF bridge had no equivalent.

Move the canonical arange(in_features) // group_size derivation into
qlinear._g_idx.canonical_g_idx and use it from both the packed-layer
constructor and the bridge. hf_gptqmodel_post_init now repairs a GPTQ
layer whose g_idx is not a valid permutation of that canonical mapping,
and leaves a checkpoint-supplied permutation untouched (Marlin treats a
non-contiguous index as authoritative even with desc_act=False). With
desc_act=True the index cannot be rebuilt, so an invalid one raises an
actionable ValueError instead of decoding garbage.

Verified end-to-end on the real fbaldassarri/SmolLM2-1.7B auto_gptq
checkpoint: 168 layers repaired, g_idx ends in [15, 15, 15, 15], logits
finite and the prompt "The capital of France is" continues with " Paris".
At origin/main the same load leaves g_idx as [0, 0, 0, 0] (or random
int32) and the next token is garbage.

Fixes #6339
@Qubitium
Qubitium marked this pull request as ready for review November 29, 2026 09:39
@Qubitium
Qubitium merged commit 0a5b67a into main Nov 29, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/6339-gidx branch November 29, 2026 09:39
Qubitium pushed a commit that referenced this pull request Nov 29, 2026
…he HF bridge (#6191, #6178)

Rebased onto be14824; keeps both the #6344
g_idx repair and the deferred symmetric qzeros materialization in
hf_gptqmodel_post_init, and keeps main's #6327 shape-blind fallback
contract in test_hf_packing_api.
Qubitium added a commit that referenced this pull request Nov 29, 2026
Rebased onto main after #6344 landed. Both post-init steps are preserved:

* `_reselect_offloaded_marlin_kernels` (this PR) reinterprets layers that
  AUTO put on Marlin from the unresolved `device_map` keyword but that
  Accelerate then offloads, so they are re-selected before the shared
  post-init loop initializes them.
* `_repair_bridge_missing_g_idx` (#6344) rebuilds a canonical `g_idx` for
  checkpoints that ship none.

The reselect runs first so the repair reads the `desc_act` of the module the
layer was actually rebuilt as.
Qubitium added a commit that referenced this pull request Nov 29, 2026
) (#6353)

* fix(hf): align portable GPTQ kernel positional order with Optimum

Optimum builds the bridge-selected class positionally as
(bits, group_size, desc_act, sym, ...). The portable GPTQ kernels declared
(bits, group_size, sym, desc_act, ...), so Optimum-built layers got the two
flags swapped. Since #6327 the bridge selects these kernels for shape-blind
HF loads, and #6344 then rejected the swapped desc_act=True instead of
repairing the missing g_idx.

Reorder TorchLinear, TorchAtenLinear (and TorchCpuAvx512Linear via
inheritance), TorchFusedLinear and TorchInt8Linear to match GPTQQuantLinear
and the other GPTQ kernels. No positional callers existed in the repo; all
internal construction is keyword-based.

Fixes #6346

* fix(hf): align W4A GPTQ kernel positional order with Optimum

`hf_select_quant_linear_v2` returns `W4AFP8Linear` (and its
`W4ANVFP4Linear` subclass) when a checkpoint names the saved
`gptq_w4afp8`/`gptq_w4a_nvfp4` backend, and Optimum builds every
returned class positionally as `(bits, group_size, desc_act, sym,
in_features, out_features, bias, ...)`. Both kernels declared
`(bits, group_size, sym, desc_act, ...)`, so a W4A load through
Optimum swapped the two flags. They only support `sym=True,
desc_act=False`, so the swap produced `sym=False` and the constructor
rejected the layer with `NotImplementedError: only supports symmetric
[True] quantization`.

Reorder both (the subclass forwards `*args`) and cover them in the
#6346 positional-order test. All in-repo call sites already pass
keywords, so the reorder is source-compatible.

---------

Co-authored-by: agent <agent@local>
Qubitium added a commit that referenced this pull request Nov 29, 2026
…os in the HF bridge (#6191, #6178, #6336) (#6274)

* fix(hf): packable kernel selection and legacy floor-width qzeros in the HF bridge (#6191, #6178)

Rebased onto be14824; keeps both the #6344
g_idx repair and the deferred symmetric qzeros materialization in
hf_gptqmodel_post_init, and keeps main's #6327 shape-blind fallback
contract in test_hf_packing_api.

* fix(hf): consolidate packable selection, per-layer shape dispatch and legacy qzeros (#6191, #6178, #6336)

Bring #6345's ShapeAware<AutoKernel> dispatcher into #6274's HF bridge
selection path:

- _shape_safe_gptq_selection() now takes the pack flag and selects the
  auto-padding fallback with the same pack gate, so a pack=True call still
  resolves to a packable kernel.
- _hf_pack_backend() runs first and resolves the packing backend; the
  shape-aware decision is layered on the resolved backend.
- the legacy floor-width qzeros wrapper is applied to both concrete kernels
  of the dispatcher (aligned AUTO and partial-group fallback), so #6178's
  deferral survives the per-layer split.
- the plain-HF pack=False AUTO path keeps its constant two selections.

Merged test_hf_packing_api.py keeps #6345's per-layer assertions and
#6274's pack/inference assertions.

* fix(hf): dispatch layer shapes the AUTO kernel cannot build

The #6336 per-layer dispatcher only checked the partial-group rule, so an
AUTO kernel that passed model-wide validation (in_features/out_features
unknown) could still reject the real layer shape. The CPU AVX512 kernel
requires out_features % 32 == 0, so a plain-HF load of a model with a
1744-wide intermediate crashed during layer replacement; route those
layers to the pre-selected TorchLinear fallback.

TorchAtenLinear also advertised SUPPORTS_AUTO_PADDING=True although its
CPU int4pack validation rejects a partial last group. That made the
shape-blind bridge skip the dispatcher for group_size=32 checkpoints and
crash on a 48-wide layer. Declare the contract the op actually enforces.

Update the #6169 dtype tests for the dispatcher's second (padding)
selection and add regression tests for both paths.

* fix(hf): materialize legacy qzeros only for kernels that own the buffer

`_materialize_hf_sym_qzeros` rebuilt every deferred symmetric `qzeros` with
`register_buffer`, but Marlin keeps its zero point in a packed `Parameter`
and never reads the words. An AUTO load of a legacy floor-width checkpoint on
CUDA therefore raised `KeyError: attribute 'qzeros' already exists` before
`gptqmodel_post_init` could run; the portable Torch kernel was unaffected,
which is why the CPU-only coverage missed it.

The deferral only hides the legacy width from the core loader, so a kernel
that does not own a `qzeros` buffer has nothing left to repair. Skip it, and
replace the constructor's meta placeholder with the empty parameter the
kernel's own runtime state installs, so a resident layer is not mistaken for
an offloaded one.

`tests/test_hf_bridge_legacy_qzeros_marlin_6274.py` covers the Marlin load on
CUDA, the portable path on CPU, and both branches of the skip directly.

---------

Co-authored-by: pr-keeper <pr-keeper@localhost>
Co-authored-by: agent <agent@local>
Qubitium added a commit that referenced this pull request Nov 29, 2026
#6253)

* fix(hf): reselect offload-safe kernels for Marlin at post-init (#6152)

Rebased onto main after #6344 landed. Both post-init steps are preserved:

* `_reselect_offloaded_marlin_kernels` (this PR) reinterprets layers that
  AUTO put on Marlin from the unresolved `device_map` keyword but that
  Accelerate then offloads, so they are re-selected before the shared
  post-init loop initializes them.
* `_repair_bridge_missing_g_idx` (#6344) rebuilds a canonical `g_idx` for
  checkpoints that ship none.

The reselect runs first so the repair reads the `desc_act` of the module the
layer was actually rebuilt as.

* fix(hf): keep legacy qzeros markers across kernel reselect (#6152)

`_switch_quant_linear_class()` reassigns `__class__`, which drops the
checkpoint-format markers the HF bridge's #6178 compatibility wrapper keeps
on the generated subclass. A reselected offloaded Marlin layer then loses
`_HF_DEFER_SYM_QZEROS`, so the post-load bridge skips the deferred symmetric
`qzeros` materialization and decodes an unmaterialized buffer.

Carry the truthy markers onto the instance across the swap and cover the
reselect path with a regression test.

* fix(hf): refresh materialized Marlin offload snapshots (#6152)

`_post_init_cpu_offloaded_marlin` decided whether an Accelerate snapshot exists from `checkpoint_payload_is_meta()`. A loader can materialize an offloaded layer's payload before the bridge runs, so the probe is false while the layer-level hook still owns a writable map. The early return then called `post_init()` on the resident tensors: on CPU Marlin raised `ValueError: GPTQ Marlin requires CUDA tensors, got cpu`, and on CUDA the map kept the pre-repack layout.

Decide from `_layer_offload_hook()` instead. When the hook exists, always materialize from the map on its execution device, repack, return to meta and publish every persistent tensor the map replays. Derive those names from the module's parameters/buffers rather than only the meta ones, so a stale snapshot is refreshed and the #5022 invariant holds.

Tests: v1 grouped GPTQ `device_map="auto"` + `max_memory` offload fixture, the stale-snapshot regression (CPU stub and CUDA), and a CPU-only structural check of the reselect decision.

---------

Co-authored-by: agent <agent@local>
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