Skip to content

[BUG] HF bridge: AutoModelForCausalLM.from_pretrained of a GPT-QModel GPTQ checkpoint crashes when any in_features is not a multiple of group_size (SmolLM2 hidden=576, g128): bridge returns MarlinLinear without shape info #6149

Done

Description

@Qubitium

Summary

A default GPTQ quantization (GPTQConfig(bits=4, group_size=128)) of HuggingFaceTB/SmolLM2-135M (hidden size 576 = 4.5 x 128) saves fine and reloads fine through GPTQModel.load (which picks MarlinLinear for the divisible modules and TritonV2Linear for the 576-input ones). Loading the same checkpoint with plain Transformers on CUDA crashes before any weight is read:

NotImplementedError: <class 'gptqmodel.nn_modules.qlinear.marlin.MarlinLinear'>: `in_features`: 576 must be divisible by `group_size: 128`.

Transformers/Optimum call hf_select_quant_linear_v2(...) once, without layer shapes, and then construct that single class for every layer (optimum/gptq/quantizer.py::_replace_by_quant_layers). The bridge passes allow_marlin=True and no in_features, so AUTO returns MarlinLinear (priority 90). MarlinLinear has SUPPORTS_AUTO_PADDING = False, so its constructor rejects every 576-input projection (q/k/v/o, gate/up). The same happens for any model whose hidden or intermediate size is not a multiple of the group size (e.g. SmolLM2-360M, hidden 960, g128), with sym=True/False and desc_act=True/False, GPTQ v1 or v2.

docs/hf-interop.md states "A plain GPTQ or AWQ checkpoint without GPT-QModel-only features therefore still loads through AutoModelForCausalLM.from_pretrained exactly as upstream implements it". This checkpoint has no GPT-QModel-only features (no dynamic, no lm_head, dense model), and the save step emits no hf_compat_warnings entry for it.

Introduced by

Pre-existing: allow_marlin=True # TODO: remove this after marlin padding is fixed in the HF bridge dates from c597668 (Dec 2024); the in_features % group_size check in GPTQBaseQuantLinear.validate from 96ff08b (#2456). Still present at HEAD a311c91.

Location

gptqmodel/utils/importer.py:1371-1450 (hf_select_quant_linear_v2, and the same at :1334-1368 for hf_select_quant_linear):

    return select_quant_linear(
        bits=bits, group_size=group_size, desc_act=desc_act, sym=effective_sym,
        backend=backend, device=device, format=fmt, quant_method=method, pack=pack,
        allow_marlin=True,  # TODO: remove this after marlin padding is fixed
        ...

gptqmodel/nn_modules/qlinear/__init__.py:1444-1448:

        if in_features is not None:
            validate = in_features % group_size == 0 or cls.SUPPORTS_AUTO_PADDING
            if not validate:
                err = f"{cls}: `in_features`: {in_features} must be divisible by `group_size: {group_size}`."

Reproduction (ran it, RTX 4090, torch 2.15, transformers 5.23, optimum installed)

import torch
from gptqmodel import GPTQModel, CalibrationConfig
from gptqmodel.quantization import GPTQConfig
from transformers import AutoModelForCausalLM

texts = [...]  # 64 wikitext-2 train paragraphs
m = GPTQModel.load("HuggingFaceTB/SmolLM2-135M", GPTQConfig(bits=4, group_size=128), device="cuda:0", dtype=torch.float16)
m.quantize(CalibrationConfig(dataset=texts, batch_size=1))
m.save("SmolLM2-135M-gptq-4bit")

GPTQModel.load("SmolLM2-135M-gptq-4bit", device="cuda:0")   # OK: kernels {MarlinLinear, TritonV2Linear}, PPL 35.58 (fp16 31.83)
AutoModelForCausalLM.from_pretrained("SmolLM2-135M-gptq-4bit", device_map="cuda:0", dtype=torch.float16)

Output of the last line:

  File ".../transformers/quantizers/quantizer_gptq.py", line 94, in _process_model_before_weight_loading
  File ".../optimum/gptq/quantizer.py", line 318, in _replace_by_quant_layers
  ...
  File "gptqmodel/nn_modules/qlinear/__init__.py", line 630, in __init__
    raise err
NotImplementedError: <class 'gptqmodel.nn_modules.qlinear.marlin.MarlinLinear'>: `in_features`: 576 must be divisible by `group_size: 128`.

Same failure for sym=False, desc_act=True, format=FORMAT.GPTQ_V2, RTNConfig(bits=4, group_size=128) and a dynamic checkpoint on this model (GPTQConfig(bits=8, group_size=32) loads, since 576 is a multiple of 32). The same flow on Qwen/Qwen2.5-0.5B-Instruct (all widths multiples of 128) loads in Transformers.

Expected vs actual

Expected: a plain GPTQ checkpoint written by GPTQModel.save() loads in AutoModelForCausalLM.from_pretrained on CUDA (as it does in GPTQModel.load), or at minimum the save emits an hf_compat_warnings entry naming GPTQModel.load.
Actual: Transformers load raises NotImplementedError in layer replacement for every model with a non-multiple-of-group_size width.

Suggested fix

The bridge cannot see per-layer shapes, so it must not return a kernel that rejects partial groups. Options: drop allow_marlin=True / exclude kernels with SUPPORTS_AUTO_PADDING=False and in-features constraints when the checkpoint group_size != -1 (the TODO already anticipates this), or return a thin dispatching subclass whose constructor falls back to a shape-compatible kernel (e.g. TritonV2Linear/TorchLinear) per layer, as GPTQModel.load does. Add a save-time hf_compat_warnings entry if neither is done.

Activity

  1. Qubitium commented on Nov 29, 2026

    @Qubitium
    CollaboratorAuthor

    Status after #6187 (merged): the bridge side is done, and the remaining gap is exactly the one the maintainer called out — the caller has to hand the width over.

    What landed in #6187:

    • hf_select_quant_linear / hf_select_quant_linear_v2 now accept in_features (and out_features), and forward them into select_quant_linear → validate_candidate → validate_quant_linear for every candidate kernel, in both the AUTO ranking loop and the explicit-backend path (gptqmodel/utils/importer.py).
    • A width-incompatible kernel is therefore rejected at selection time when the width is supplied, instead of being handed back and failing later inside MarlinLinear's shape contract.

    Why the SmolLM2 case can still bite, and why it is not fixable from our side alone:

    • in_features defaults to None. When it is None, validate_quant_linear has nothing to check the group_size divisibility against, so a width-blind selection is still possible. That is the "missing information" case — the bridge cannot invent a width it was never told, and guessing it from config.hidden_size would be wrong for the many layers whose in_features is not the hidden size (q/k/v/gate/up/down all differ).
    • Transformers' GptqQuantizer (transformers/quantizers/quantizer_gptq.py) calls gptqmodel's bridge without a width, so on a plain AutoModelForCausalLM.from_pretrained the information is simply absent. The fix belongs upstream in the caller.

    Practical options for a user hitting the SmolLM2 shape today (any one of them supplies or removes the missing information):

    1. Quantize/load through GPTQModel.load(...), which builds each layer with its real in_features.
    2. Pass an explicit backend= (e.g. BACKEND.TORCH) so the width-blind AUTO ranking never picks a width-constrained kernel.
    3. Pass in_features to the bridge directly when calling it from custom code.

    I have not closed this: the crash is real for the upstream call path, but the only remaining change would be in Transformers. Suggest either tracking it as an upstream issue or documenting option 2 in docs/hf-interop.md; I did not add that doc note because it is the maintainer's call whether to bless the explicit-backend workaround.

  2. Qubitium commented on Nov 29, 2026

    @Qubitium
    CollaboratorAuthor

    Implemented the GPT-QModel half in #6323 (merged as 339036d).

    New behaviour: hf_select_quant_linear{,_v2} now refuses to return a grouped kernel whose in_features % group_size == 0 contract cannot be checked when the caller omits in_features (and group_size != -1). It raises an actionable ValueError that names the missing in_features/out_features, the selected kernel (e.g. MarlinLinear), the group size, and the upstream caller, and points callers that cannot supply the width at GPTQModel.load(). Callers that pass in_features keep the existing selection; group_size=-1 and auto-padding kernels are unchanged.

    Remaining upstream gap: Transformers' GptqQuantizer (via Optimum's GPTQQuantizer.select_quant_linear) and Transformers' AWQ layer replacement still do not forward the layer width. Optimum already reads layer.in_features in _replace_by_quant_layers, so the load fix is a pass-through upstream. Until then, plain AutoModelForCausalLM.from_pretrained fails fast with the actionable error instead of crashing inside the kernel; GPTQModel.load is unaffected.

    Evidence: the new CPU-only tests/test_hf_bridge_missing_shape_6149.py fails 4/10 on the pre-fix bridge (DID NOT RAISE ValueError) and passes 10/10 after; the affected suites report 480 passed, 129 skipped.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions