Repository navigation
fix(hf): derive missing g_idx for bridge loads (#6339) - #6344
Merged
Merged
Conversation
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
marked this pull request as ready for review
November 29, 2026 09:39
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.
5 tasks done
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>
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.
Summary
Some
desc_act=FalseGPTQ checkpoints store onlyqweight/qzeros/scales(/bias)and nog_idx(for example the AutoRoundauto_gptqexportfbaldassarri/HuggingFaceTB_SmolLM2-1.7B-Instruct-auto_gptq-int4-gs128-sym).GPTQModel.loadis correct because the packed-layer constructor registers the canonicalarange(in_features) // group_sizeplaceholder and a missing checkpoint key leaves it in place. The Transformers/Optimum bridge has no such fallback: it builds the layer onmeta, andPreTrainedModel._move_missing_keys_from_meta_to_devicematerializes the missing buffer withtorch.empty_like— all zeros on CUDA (every row reads group 0) or randomint32on CPU (out-of-range crash). Marlin ignoresg_idxwhendesc_act=False, so it was unaffected; every other kernel silently decoded garbage. Since #6327 this is the defaultfrom_pretrainedpath on CUDA.This PR repairs the buffer in
hf_gptqmodel_post_initbefore any kernel reads it, using the same derivation as theGPTQModel.loadpath.Mechanism
gptqmodel/nn_modules/qlinear/_g_idx.py:13—canonical_g_idx(in_features, group_size)is now the single owner of thearange(in_features) // group_sizederivation (group_size=-1is per-channel, i.e. all zeros).gptqmodel/nn_modules/qlinear/__init__.py:2026—_register_gptq_buffers(theGPTQModel.loadplaceholder) calls the helper instead of its inline list comprehension.gptqmodel/utils/model.py:2239—_repair_bridge_missing_g_idxruns at the top ofhf_gptqmodel_post_init(:2314), beforegptqmodel_post_init/kernelpost_init.has_group_layout(_g_idx.py:32) accepts any permutation of the canonical mapping, so a third-party block permutation that still declaresdesc_act=Falsekeeps its counts and stays authoritative (the Marlin contract is preserved). No Marlin special case.int32fails the range/count test.desc_act=Truecannot rebuild the activation-order permutation, so an invalid index raises an actionableValueErrornaming the layer and telling the user to reload a checkpoint withg_idxor usedesc_act=False. It does not fall back to canonical.metaplaceholders (disk offload) are skipped.g_idxregistered as a parameter (Machete) is replaced with a parameter.Regression test
tests/test_hf_bridge_missing_g_idx_6339.pybuilds aTorchLinearonmeta, assigns the packed checkpoint tensors, and materializes the missingg_idxwith deterministic uninitialized-memory poisons (all zeros = CUDA, randomint32= CPU). It then calls the realhf_gptqmodel_post_init.desc_act=False+ nog_idx→ canonical mapping derived, and the forward matches an independent FP64 decode of the checkpoint (both poison variants).desc_act=False+ a real (non-canonical)g_idx→ left untouched and decodes correctly.desc_act=True+ nog_idx→ raisesValueErrormentioningdesc_act=Trueandg_idx(both poison variants).Red → green
Red at
origin/main(42827b67), same test file:Green on this branch:
End-to-end on the real AutoRound checkpoint (offline, from the local HF cache, CPU):
Affected suites
The two failures are pre-existing at
origin/mainand unrelated:test_hf_packing_api.py::test_hf_bridge_forwards_in_features_to_kernel_validation[v1/v2]still expects the shape-blind bridge to raiseValueError, but #6149/#6326 changed it to fall back to the auto-padding Torch kernel. The same two tests fail in a pristineorigin/mainworktree.Skipped (CPU-only run): CUDA Marlin/ExLlamaV2/Machete runtime tests, disk-offload paths that need an accelerator, and GPU-only packing/feasibility checks.
ruff:Unverified
g_idxpath is CUDA-only here; the repair preserves any valid permutation by construction (unit-checked byhas_group_layout).Fixes #6339