Skip to content

fix(hf): keep the AUTO kernel for group-aligned layers on plain-HF loads (#6336, #6332, #6334) - #6345

Closed
Qubitium wants to merge 1 commit into
mainfrom
fix/6336-perf
Closed

Qubitium wants to merge 1 commit into
mainfrom
fix/6336-perf

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #6336. Rebased onto #6340 (which merged #6332 and #6334); this PR now carries only the product fix and the per-layer test contract that supersedes #6340's whole-checkpoint assertions.

Problem

_needs_shape_safe_gptq_kernel() is true for the shape-blind AUTO GPTQ call because TorchCpuAvx512Linear.SUPPORTS_AUTO_PADDING = False (torch_cpu_avx512.py:172) and MarlinLinear.SUPPORTS_AUTO_PADDING = False (marlin.py:104). #6327's _shape_safe_gptq_selection then replaced the AUTO class with TorchLinear for the whole checkpoint.

On CPU, TorchLinear.post_init → optimize() → an eager torch_compile(...) per layer, and the first call imports dynamo/inductor. TorchCpuAvx512Linear inherits the base no-op optimize(), so it never pays that cost. On CUDA the cost is Marlin→Torch decode/prefill.

Measured (CPU, tiny 1-layer MPT GPTQ, aligned group_size, plain AutoModelForCausalLM.from_pretrained, 3 processes, warm = median of 5):

checkout cold warm median kernel
42827b67 1.52 s 0.440 s TorchLinear
pre-wave 89dbcf91 0.87 s 0.365 s TorchCpuAvx512Linear
this PR 0.88 s 0.374 s TorchCpuAvx512Linear

CUDA end-to-end (RTX 4090, aligned g128, fp16): 42827b67 → TorchLinear, pre-wave → MarlinLinear, this PR → MarlinLinear; finite forward in all three.

Fix

gptqmodel/utils/importer.py:

  • _shape_aware_gptq_kernel() returns ShapeAware<AutoKernel> — a subclass of the already-selected AUTO kernel whose __new__ reads in_features and dispatches; kernel_for_width() is one modulo test.
  • A metaclass __instancecheck__ keeps Optimum's isinstance / get_layers working.
  • _shape_safe_gptq_selection() selects the padding kernel once per checkpoint (2 select_quant_linear calls total, independent of module count).

Per-layer outcome:

layer width kernel
in_features % group_size == 0 the AUTO kernel (MarlinLinear on CUDA, TorchCpuAvx512Linear on CPU)
partial group (e.g. SmolLM2 hidden 576, g128) TorchLinear (auto-padding)
width unknown TorchLinear (stays safe)

Explicit backend / explicit in_features / group_size=-1 / non-GPTQ paths are unchanged.

Tests

tests/test_hf_bridge_grouped_load_cost_6336.py (7 nodes, CPU-only, structural rather than wall-clock):

7/7 fail on 42827b67, 7/7 pass here. Asserts per-layer dispatch (aligned→AUTO, partial→TorchLinear, unknown→TorchLinear), exactly 2 select_quant_linear calls per checkpoint with 36 width decisions adding zero calls, isinstance covering both kernels, and an end-to-end plain-HF aligned load keeping the host AUTO kernel.

tests/test_hf_packing_api.py — test_hf_bridge_forwards_in_features_to_kernel_validation[v1,v2] now asserts the per-layer contract instead of #6340's whole-checkpoint TorchLinear fallback, and still proves in_features/out_features reach validate_quant_linear.

Verification

cd tests && CUDA_VISIBLE_DEVICES="" PYTHONPATH=<clone>:<clone>/tests \
  /root/venv/bin/python -m pytest test_hf_packing_api.py test_docs_contract_refs.py \
  test_hf_bridge_grouped_load_cost_6336.py test_hf_bridge_missing_shape_6149.py \
  -q -rs -p no:cacheprovider

→ 307 passed, 5 skipped (all five skips are pre-existing CUDA device-count gates)

Broader affected set: 272 passed, 89 skipped across test_hf_bridge_missing_shape_6149, test_hf_packing_api, kernels/test_selection, test_checkpoint_interop_4053, test_checkpoint_compat, test_hf_bridge_cpu_offload_5022, test_hf_bridge_mixed_capability_5084.

/root/venv/bin/ruff check on every changed file → All checks passed.

Not measured

Absolute CUDA decode/prefill tok/s were not re-benchmarked (the GPUs are shared). The mechanism is verified end-to-end — aligned CUDA layers are MarlinLinear again — but the throughput delta itself is unquantified here.

@Qubitium Qubitium changed the title fix(hf): keep the AUTO kernel for group-aligned layers on plain-HF loads (#6336) fix(hf): keep the AUTO kernel for group-aligned layers on plain-HF loads (#6336, #6332, #6334) Nov 29, 2026
#6327's `_shape_safe_gptq_selection` replaced the AUTO kernel with
`TorchLinear` for the whole checkpoint, because
`TorchCpuAvx512Linear.SUPPORTS_AUTO_PADDING` and
`MarlinLinear.SUPPORTS_AUTO_PADDING` are both False. Group-aligned layers
therefore lost their real kernel, and on CPU `TorchLinear.post_init` runs an
eager `torch_compile` per layer: cold 0.87 s -> 1.52 s, warm 0.365 s -> 0.440 s.

`_shape_aware_gptq_kernel()` now returns `ShapeAware<AutoKernel>`, a subclass
of the already-selected AUTO kernel whose `__new__` dispatches on
`in_features`: aligned widths keep the AUTO kernel, partial groups get the
auto-padding `TorchLinear`. A metaclass `__instancecheck__` keeps Optimum's
`isinstance`/`get_layers` working, and the padding kernel is selected once per
checkpoint rather than per module.

Rebased onto #6340, whose whole-checkpoint fallback assertions this replaces
with the per-layer contract.

Fixes #6336
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Cross-PR note: #6353 (fix for #6346) is a prerequisite for this PR's positional path.

_ShapeAwareKernel.__new__ already reads the width from args[4] with the comment (bits, group_size, desc_act, sym, in_features, ...) — i.e. it assumes Optimum's order, which is what MarlinLinear and every other GPTQ kernel already declare.

But on current main the portable kernels (TorchLinear, TorchAtenLinear/TorchCpuAvx512Linear, TorchFusedLinear, TorchInt8Linear) declare (bits, group_size, sym, desc_act, ...) — the opposite order. So _ShapeAwareKernel(*args) forwards the same positional args to two classes that interpret slots 2 and 3 differently: an aligned layer built as MarlinLinear and a partial-group layer built as TorchLinear would disagree about sym/desc_act.

#6353 fixes that at the source by aligning the four portable kernels with GPTQQuantLinear.__init__ (qlinear/__init__.py:1353-1356, which already declares bits, group_size, desc_act, sym). It touches one signature line per kernel and no file this PR touches, so the two are independent — but merging #6353 first makes this PR's positional path correct by construction.

Verified no internal caller is affected: an AST/rg audit over gptqmodel/, tests/ and scripts/ found zero positional constructions of those four classes.

@Qubitium

Copy link
Copy Markdown
Collaborator Author

Honest scoping of the perf claim, from an independent end-to-end smoke pass on real checkpoints (pre-wave 89dbcf91 vs post-wave):

check pre-wave post-wave
static GPTQ 1B, TORCH, CPU, warm load 2.32–2.58 s 2.32–2.58 s (identical output digest + NLL)
AWQ 1B, TORCH_AWQ, CPU, warm 1.71/1.77 s 1.61/1.77 s
dynamic OLMoE 1B, CPU, warm 17.7–22.8 s 18.3–35.2 s
Marlin 1B, cuda:0 2.68 s 2.36 s

No reproducible slowdown was found at 1B scale on a shared host — the cold/warm deltas are within noise there. The regression this PR fixes is real and reproducible on a tiny checkpoint (cold 0.87 s → 1.52 s, warm 0.365 s → 0.440 s) because the per-layer torch_compile dominates when there is little else to do; on a 1B model the Inductor cost amortizes into load time that is already seconds.

So treat this PR as restoring the pre-wave kernel for group-aligned layers (a correctness/parity fix — aligned layers keep MarlinLinear/TorchCpuAvx512Linear instead of being silently downgraded to TorchLinear), not as a headline speedup. The per-layer dispatch also removes a real behavioural wart: partial-group layers get the padding kernel while aligned layers keep the fast one, instead of the whole checkpoint being downgraded.

Output parity is unaffected either way — all six smoke cells produced identical digests and NLL pre- and post-wave.

Qubitium added a commit that referenced this pull request Nov 29, 2026
… 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.
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Consolidated into #6274 (new head 9c647ac7) and closing this draft so the two HF-bridge rewrites land as one change.

What moved

The constant-selection-count property is preserved: the plain-HF pack=False AUTO path still makes exactly 2 select_quant_linear calls per checkpoint, and the 36-width loop adds none. The assertion was not relaxed. (pack=True with an inference-only backend adds one required contract-probe call, which is not this test's path.)

Verification on the consolidated branch

  • test_hf_packing_api.py test_hf_bridge_grouped_load_cost_6336.py test_hf_bridge_missing_shape_6149.py test_checkpoint_interop_4053.py kernels/test_qlinear_hierarchy.py test_hf_bridge_missing_g_idx_6339.py → 118 passed, 11 skipped
  • test_hf_bridge_cpu_offload_5022.py test_hf_bridge_mixed_capability_5084.py kernels/test_selection.py test_docs_contract_refs.py test_hf_bridge_missing_g_idx_6339.py → 395 passed, 75 skipped
  • ruff check on all changed files → clean

No commit from fix/6336-perf was dropped; the branch tip (7b96fd8f) is fully represented in #6274's new head 9c647ac7e777bbb54cb4bf2afb7d7a94e500c986. Thanks for the fix and the structural tests — #6336 is now fixed in #6274.

@Qubitium Qubitium closed this Nov 29, 2026
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>
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