Skip to content

fix(interop): HF quant refusers, optimize() pickling, CPU-only max_memory, MLX masks/export (#4091) - #4101

Merged
Qubitium merged 5 commits into
mainfrom
fix/issue-4091-interop
Nov 15, 2026
Merged

Qubitium merged 5 commits into
mainfrom
fix/issue-4091-interop

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Part of #4091 (items 5-10)

TL;DR

Six independent root causes, six fixes, each with a regression test.

Item Fix Main symbols
5 add exl3 to the shared refusal table and emit a save-time warning for every refused method REFUSED_HF_QUANT_METHODS, hf_compat_warnings
6 drop compiled callables before pickling compiled_module_getstate, BaseQuantLinear.__getstate__, ExllamaV3TorchLinear.__getstate__
7 a CPU-only max_memory selects CPU kernels (or is rejected when it contradicts device) _resolve_max_memory_device
8 strip per-row pad positions using attention_mask / pad_token_id _mlx_strip_padding
9 scope eos_token_id to a per-call tokenizer copy _mlx_tokenizer_with_eos
10 stock-compatible MLX export by default _packed_mlx_weights(stock_compatible=True)

1. Root causes (file:line)

  • Item 5 — gptqmodel/__init__.py registered a refusing quantizer only for gptqmodel_gguf. For every other name transformers does not implement, AutoHfQuantizer.supports_quant_method only logs Unknown quantization type, got <name> ... skip the quantization and from_pretrained random-initializes every linear layer. hf_compat_warnings (gptqmodel/models/writer.py:233) had no entry, and docs/checkpoint-interop.md claimed plain HF raises.
    • After the merge with fix(macaq): int64 row offsets, device-bound Triton launches, sm_120 K tiles (#4090) #4099 (1732d2ae3) the registration is shared: REFUSED_HF_QUANT_METHODS in gptqmodel/_quant_methods.py + gptqmodel/utils/hf_refusing_quantizer.py. That table covered macaq, paroquant, qqq, nf12, tt-blockfloat; exl3 was still missing, and no save-time warning existed for any of them. This PR adds exactly that, on the merged table (no second table, no parallel module).
  • Item 6 — gptqmodel/nn_modules/qlinear/fp8.py:686 and gptqmodel/nn_modules/exllamav3_torch.py:590 store a compiled bound method in _compiled_forward; gptqmodel/nn_modules/qlinear/vptq_torch.py:300 does the same for dequantize. Pickle cannot serialize those wrappers.
  • Item 7 — gptqmodel/models/loader.py:755-776 (_normalize_explicit_placement) left device="cuda:0" as the kernel target while _normalize_max_memory / build_layerwise_device_map (:2626-2635) made the placement CPU-only. The first forward raised ValueError: Expected a cuda device, but got: cpu.
  • Item 8 — gptqmodel/utils/mlx.py:525 (_mlx_prompt_list) and :674 passed the full padded row to mlx_lm.generate, so pad ids became prompt tokens.
  • Item 9 — gptqmodel/utils/mlx.py:562-574 (_mlx_tokenizer_with_eos) mutated the shared functools.partial tokenizer, so one call's EOS ids truncated every later call.
  • Item 10 — gptqmodel/utils/mlx.py:184-185 routed every TorchLinear to gptq_dtype, which produced the *.linear.* key prefix at :229. Stock mlx_lm.load rejects those names.

2. New flow

2.1 HF refusal registration (item 5, consolidated on #4099)

flowchart TD
    A["import gptqmodel"] --> B["_patch_transformers_refusing_quantizers"]
    B --> C["REFUSED_HF_QUANT_METHODS<br/>exl3, macaq, paroquant, qqq, nf12, tt-blockfloat"]
    C --> D["AUTO_QUANTIZATION_CONFIG_MAPPING.setdefault<br/>GPTQModelRefusingQuantizationConfig"]
    C --> E["AUTO_QUANTIZER_MAPPING.setdefault<br/>GPTQModelRefusingHfQuantizer"]
    A --> F["_patch_transformers_gptqmodel_gguf_quantizer_compat"]
    F --> F2["GGUF_EXPORT_QUANT_METHOD registered"]
    G["AutoModelForCausalLM.from_pretrained"] --> H["AutoHfQuantizer.from_config"]
    H --> I{"quant_method registered?"}
    I -- no --> J["warn and skip quantization<br/>random Linear weights"]
    I -- yes --> K["GPTQModelRefusingHfQuantizer.__init__<br/>raise ValueError"]
    style J fill:#f8d7da,stroke:#b02a37
    style K fill:#d9f2d9,stroke:#2e7d32
Loading

setdefault keeps any quantizer transformers already owns (gptq, awq, fp8, bitsandbytes, its own vptq), so the table only covers names transformers does not implement. vptq and bitsandbytes are deliberately not added: transformers implements both, and a refusal there would break legitimate checkpoints.

2.2 MLX export vs runtime (item 10)

flowchart TD
    A["GPTQModel.export(..., 'mlx')"] --> B["convert_gptq_to_mlx_weights<br/>stock_compatible=True"]
    R["GPTQModel.load(backend='mlx')"] --> S["convert_gptq_to_mlx_weights<br/>stock_compatible=False"]
    B --> C["_packed_mlx_weights"]
    S --> C
    C --> D{"custom-runtime layer?"}
    D -- "yes, export" --> E["return None"]
    D -- "no" --> F["exact repack into direct<br/>weight / scales / biases"]
    D -- "yes, runtime load" --> G["custom MLX runtime class"]
    E --> H["quantize_model with dynamic predicate"]
    H --> I{"format requantizable?"}
    I -- no --> J["ValueError naming the format"]
    I -- yes --> K["stock MLX-LM checkpoint"]
    F --> L{"stock_compatible?"}
    L -- yes --> K
    L -- no --> G
    style E fill:#fff3cd,stroke:#997404
    style J fill:#f8d7da,stroke:#b02a37
    style K fill:#d9f2d9,stroke:#2e7d32
Loading

2.3 CPU-only max_memory device resolution (item 7)

flowchart TD
    A["GPTQModel.load(device, max_memory)"] --> B["_normalize_explicit_placement"]
    B --> C["_resolve_max_memory_device"]
    C --> D{"budget has an accelerator entry?"}
    D -- yes --> E["keep the existing device resolution"]
    D -- no --> F{"explicit device is an accelerator?"}
    F -- yes --> G["ValueError: CPU-only budget contradicts device"]
    F -- no --> H["device = DEVICE.CPU<br/>CPU kernels selected"]
    style G fill:#f8d7da,stroke:#b02a37
    style H fill:#d9f2d9,stroke:#2e7d32
Loading

3. Before / after

Item 5 — plain HF no longer loads random weights

Before (origin/main @ 718256fd7, PYTHONPATH=/tmp/before4091):

exl3: LOADED WITHOUT ERROR (random weights)
qqq: LOADED WITHOUT ERROR (random weights)
nf12: LOADED WITHOUT ERROR (random weights)
tt-blockfloat: LOADED WITHOUT ERROR (random weights)

After (merged tree, all six names in the shared table):

table: ['exl3', 'macaq', 'nf12', 'paroquant', 'qqq', 'tt-blockfloat']
exl3: ValueError: GPT-QModel EXL3 checkpoints cannot be loaded by `transformers`; load them with `GPTQModel.load`
macaq: ValueError: GPT-QModel MACaQ MXFP4 checkpoints cannot be loaded by `transformers`; ...
nf12: ValueError: GPT-QModel NF12 checkpoints cannot be loaded by `transformers`; ...
paroquant: ValueError: GPT-QModel ParoQuant checkpoints cannot be loaded by `transformers`; ...
qqq: ValueError: GPT-QModel QQQ checkpoints cannot be loaded by `transformers`; ...
tt-blockfloat: ValueError: GPT-QModel Tenstorrent block-float checkpoints cannot be loaded by `transformers`; ...

exl3 is the entry this PR adds; the other five already refused after #4099 and are asserted here so the merged table cannot lose them.

Item 6 — torch.save/torch.load round trip

Before: pytest -q tests/test_checkpoint_interop_4053.py -k pickle -> 4 failed (PicklingError for FP8/EXL3/VPTQ; TorchLinear restored with optimized=True).
After: 5 passed, including an eager-vs-compiled forward comparison for Torch, FP8, EXL3 Torch and VPTQ.

Item 7 — exact issue snippet on the 4090

Before (RTX 4090 GPU-50a20676-a7a4-8bb3-eb3d-f191fdc9fa42):

LOADED kernel: <class 'gptqmodel.nn_modules.qlinear.tritonv2.TritonV2Linear'>
device: cpu
GENERATE FAIL: ValueError Expected a cuda device, but got: cpu

After, device="cuda:0", max_memory={"cpu": "10GiB"}:

REJECTED: ValueError `max_memory` has no accelerator entry, so it can only place layers on
CPU; that contradicts `device='cuda:0'`. ...

After, max_memory={"cpu": "10GiB"} with no device (previously also crashed):

LOADED kernel: <class 'gptqmodel.nn_modules.qlinear.torch_cpu_avx512.TorchCpuAvx512Linear'>
device: cpu
GENERATE OK

Decision: a budget that names no accelerator honours CPU-only when no device is requested, and rejects device="cuda:0" because silently ignoring an explicit accelerator request is the same class of surprise as silently dropping a memory cap (#4082 item 3).

Items 8-10 — MLX

Before (origin/main @ 718256fd7 with the new tests copied in):

FAILED tests/test_mlx_packing.py::test_mlx_stock_compatible_export_loads_with_stock_mlx_lm
FAILED tests/test_mlx_packing.py::test_mlx_stock_compatible_transfer_refuses_custom_runtime_layers
FAILED tests/test_mlx_packing.py::test_mlx_generate_strips_batched_left_padding
FAILED tests/test_mlx_packing.py::test_mlx_generate_strips_pad_token_id_without_a_mask
FAILED tests/test_mlx_packing.py::test_mlx_eos_override_is_scoped_to_one_call
FAILED tests/test_mlx_packing.py::test_mlx_generate_warns_on_unhonoured_arguments
6 failed

After: 7 passed (the 6 above plus the existing EOS test, updated to the scoped contract). The stock export test saves the checkpoint with mlx_lm.utils.save_model / save_config and reloads it with stock mlx_lm.load; it asserts a stock nn.QuantizedLinear with (group_size, bits) == (32, 8) and bit-identical packed words.

4. Tests run (merged tree)

All commands from the clone root.

Command Result
ruff check gptqmodel docs/eora tests setup.py All checks passed!
PYTHONPATH=$PWD CUDA_VISIBLE_DEVICES="" /opt/venvs/cu130t/bin/python -m pytest -q tests/test_checkpoint_interop_4053.py tests/test_checkpoint_compat.py tests/test_layerwise_device_placement.py 74 passed, 3 skipped
same, plus tests/test_cpu_kernel_optimize.py 75 passed, 3 skipped
PYTHONPATH=$PWD CUDA_VISIBLE_DEVICES=GPU-50a20676-a7a4-8bb3-eb3d-f191fdc9fa42 /opt/venvs/cu130t/bin/python -m pytest -q tests/test_macaq.py 66 passed, 1 skipped (guards #4090)
PYTHONPATH=$PWD CUDA_VISIBLE_DEVICES="" /opt/venvs/cu130t/bin/python -m pytest -q tests/test_exllamav3_cpu.py 59 passed, 4 skipped
PYTHONPATH=$PWD /opt/venvs/mlx/bin/python -m pytest -q tests/test_mlx_packing.py -k "strip or eos_override or unhonoured or stock_compatible or maps_seed" 7 passed
PYTHONPATH=$PWD /opt/venvs/mlx/bin/python -m pytest -q tests/test_mlx_packing tests/test_mlx_macaq.py tests/test_mlx_nf12.py 158 passed, 99 failed, 3 skipped; the 99 failures are the same 82 pre-existing MLX quantized linear requires Apple Silicon failures plus 17 pre-existing MACaQ/NF12 Metal failures measured on origin/main @ 1acb30fe9 (17 failed, 4 passed there)

origin/main was merged twice (1acb30fe9 #4097, then 1732d2ae3 #4099) before opening/updating; git merge-base --is-ancestor origin/main HEAD is true and ruff/tests were re-run afterwards. The stock-compatible guard also returns None for the new MacaqLinear/NF12Linear layers.

5. Merge resolution with #4099

Collision Resolution
gptqmodel/utils/hf_quant_refusal.py (this branch) duplicated gptqmodel/utils/hf_refusing_quantizer.py (#4099) deleted the duplicate; use GPTQModelRefusingHfQuantizer / GPTQModelRefusingQuantizationConfig
gptqmodel/_quant_methods.py: two parallel tables kept REFUSED_HF_QUANT_METHODS (name → label) and added the missing "exl3": "EXL3"; net diff vs main is +2 lines
gptqmodel/__init__.py: two registration functions took main's _patch_transformers_gptqmodel_gguf_quantizer_compat + _patch_transformers_refusing_quantizers unchanged; this PR's __init__.py diff vs main is empty
gptqmodel/models/writer.py still adds the save-time hf_compat_warnings entry, now iterating REFUSED_HF_QUANT_METHODS
docs/macaq.md (#4099's interop table) kept every entry; added the exl3 row so the table stays complete

6. Hardware and environments

  • Items 5, 6, 7 (CPU paths): /opt/venvs/cu130t/bin/python (Py3.14t, Torch 2.16.0.dev+cu130), CUDA_VISIBLE_DEVICES="".
  • Item 7 GPU repro and tests/test_macaq.py: NVIDIA RTX 4090 GPU-50a20676-a7a4-8bb3-eb3d-f191fdc9fa42 via CUDA_VISIBLE_DEVICES. The RTX 5090 was never touched.
  • Items 8-10: /opt/venvs/mlx (mlx 0.32.4, mlx-lm 0.32.2, CPU). Ran on Linux/mlx-cpu: prompt normalization, EOS scoping, stock mlx_lm.load export. Read, not run: Apple Silicon/Metal kernel execution (no Apple hardware here); item 10's Metal dispatch is untouched.

7. Limitations

  • Item 5: a process that never imports gptqmodel still only gets transformers' warning; that is transformers' behaviour and is now documented. vptq and bitsandbytes are deliberately absent from the table because transformers implements them.
  • Item 7: the device="cuda:0" + CPU-only-budget combination is rejected rather than silently run on CPU (rationale above).
  • Item 10: layers that need the custom MLX runtime are requantized on export; formats with no requantization path (FP8, GGUF, EXL3, MACaQ, NF12, ParoQuant, QQQ) fail with the existing clear ValueError instead of writing an unreadable layout.

8. Docs

  • docs/hf-interop.md: new section 5 with the refusal-registration flow (merged names), before/after table, tests.
  • docs/checkpoint-interop.md: corrected the plain-HF claim (it only warns without the import), generalized the pickling section to all kernels, fixed the refusal diagram.
  • docs/mlx-runtime.md: attention-mask/EOS scoping, stock-compatible export flow and contract.
  • docs/macaq.md: added the exl3 row to the shared interop table.
  • README.md: link descriptions updated (both pages were already linked).

…4091)

Plain transformers only warns 'Unknown quantization type ... skip the
quantization' for a quant_method it does not implement, then random-initializes
every linear layer. Register a refusing quantizer for each name in the single
GPTQMODEL_ONLY_QUANT_METHODS table (exl3, qqq, paroquant, macaq, nf12,
tt-blockfloat) and emit the same caveat through hf_compat_warnings at save
time. gptqmodel_gguf keeps its dedicated message.

optimize() may also store a torch.compile wrapper on the module. BaseQuantLinear
and ExllamaV3TorchLinear now share compiled_module_getstate(), which drops
_compiled_forward / dequantize / dequantize_weight and resets optimized, so
torch.save(model) round-trips for Torch, FP8, EXL3 Torch and VPTQ.
max_memory is the authoritative list of devices that may hold weights. A
budget with only a cpu entry placed every layer on CPU but kernel selection
still used the requested cuda device, so the first forward raised
'Expected a cuda device, but got: cpu'. Resolve the kernel device from the
budget: a CPU-only budget selects DEVICE.CPU, while an explicit accelerator
device that contradicts the budget is rejected with a clear ValueError
instead of silently loading on CPU.
…4091)

- Strip pad positions per row from attention_mask (or pad_token_id as a
  fallback) before mlx_lm.generate, and warn about arguments that cannot be
  honored instead of dropping them silently.
- Return a per-call copy of the tokenizer when eos_token_id is passed so one
  call's EOS ids no longer truncate later calls bound to the same tokenizer.
- Export with stock_compatible=True: GPTQ/AWQ layers that map onto
  mlx.nn.QuantizedLinear keep direct weight/scales/biases names, custom-runtime
  layers fall back to requantization, and formats without a fallback fail with
  the existing clear ValueError. GPTQModel.load(backend='mlx') keeps the
  custom runtime path.
# Conflicts:
#	gptqmodel/__init__.py
#	gptqmodel/_quant_methods.py
@Qubitium
Qubitium merged commit d7a41a1 into main Nov 15, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-4091-interop branch November 15, 2026 09:06
Qubitium added a commit that referenced this pull request Nov 15, 2026
main now carries #4101 (d7a41a1) and #4096 (c73793c) in squashed form.
The only conflict is tests/test_checkpoint_interop_4053.py, which both #4101
and this branch extend. Resolution:

* kept both new test sets: main's
  test_hf_from_pretrained_refuses_every_refused_method (#4091 item 5) and this
  branch's test_runtime_layout_state_dict_is_readable_but_checkpoint_writes_refuse
  (item 4) + test_state_dict_copy_between_v1_and_v2_models (item 3).
* dropped only test_runtime_layout_kernels_refuse_state_dict, which #4101
  inherited byte-identical from main and never edited. It asserts an
  unconditional raise from Marlin/ExLlamaV2 `_save_to_state_dict`, which is the
  exact contract item 4 changes. Both of its assertions (marlin and exllamav2
  raise "cannot be reconstructed") are preserved and strengthened by the
  parametrized replacement, which asserts the same raise under
  `checkpoint_serialization()` *and* that a read-only collection succeeds.
* removed one duplicate copy of test_hf_from_pretrained_refuses_every_refused_method:
  this branch already carried it from the earlier pr4101 merge, so taking main's
  copy as well defined it twice (ruff F811). One copy remains, identical to main.

Merged test inventory: 15 test functions / 26 collected cases, none of this
branch's and none of main's new tests lost.
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.

1 participant