Repository navigation
fix(interop): HF quant refusers, optimize() pickling, CPU-only max_memory, MLX masks/export (#4091) - #4101
Merged
Conversation
…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: # README.md
# Conflicts: # gptqmodel/__init__.py # gptqmodel/_quant_methods.py
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.
This was referenced Nov 15, 2026
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.
Part of #4091 (items 5-10)
TL;DR
Six independent root causes, six fixes, each with a regression test.
exl3to the shared refusal table and emit a save-time warning for every refused methodREFUSED_HF_QUANT_METHODS,hf_compat_warningscompiled_module_getstate,BaseQuantLinear.__getstate__,ExllamaV3TorchLinear.__getstate__max_memoryselects CPU kernels (or is rejected when it contradictsdevice)_resolve_max_memory_deviceattention_mask/pad_token_id_mlx_strip_paddingeos_token_idto a per-call tokenizer copy_mlx_tokenizer_with_eos_packed_mlx_weights(stock_compatible=True)1. Root causes (
file:line)gptqmodel/__init__.pyregistered a refusing quantizer only forgptqmodel_gguf. For every other name transformers does not implement,AutoHfQuantizer.supports_quant_methodonly logsUnknown quantization type, got <name> ... skip the quantizationandfrom_pretrainedrandom-initializes every linear layer.hf_compat_warnings(gptqmodel/models/writer.py:233) had no entry, anddocs/checkpoint-interop.mdclaimed plain HF raises.1732d2ae3) the registration is shared:REFUSED_HF_QUANT_METHODSingptqmodel/_quant_methods.py+gptqmodel/utils/hf_refusing_quantizer.py. That table coveredmacaq,paroquant,qqq,nf12,tt-blockfloat;exl3was 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).gptqmodel/nn_modules/qlinear/fp8.py:686andgptqmodel/nn_modules/exllamav3_torch.py:590store a compiled bound method in_compiled_forward;gptqmodel/nn_modules/qlinear/vptq_torch.py:300does the same fordequantize. Pickle cannot serialize those wrappers.gptqmodel/models/loader.py:755-776(_normalize_explicit_placement) leftdevice="cuda:0"as the kernel target while_normalize_max_memory/build_layerwise_device_map(:2626-2635) made the placement CPU-only. The first forward raisedValueError: Expected a cuda device, but got: cpu.gptqmodel/utils/mlx.py:525(_mlx_prompt_list) and:674passed the full padded row tomlx_lm.generate, so pad ids became prompt tokens.gptqmodel/utils/mlx.py:562-574(_mlx_tokenizer_with_eos) mutated the sharedfunctools.partialtokenizer, so one call's EOS ids truncated every later call.gptqmodel/utils/mlx.py:184-185routed everyTorchLineartogptq_dtype, which produced the*.linear.*key prefix at:229. Stockmlx_lm.loadrejects 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:#2e7d32setdefaultkeeps any quantizer transformers already owns (gptq,awq,fp8,bitsandbytes, its ownvptq), so the table only covers names transformers does not implement.vptqandbitsandbytesare 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:#2e7d322.3 CPU-only
max_memorydevice 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:#2e7d323. Before / after
Item 5 — plain HF no longer loads random weights
Before (
origin/main@718256fd7,PYTHONPATH=/tmp/before4091):After (merged tree, all six names in the shared table):
exl3is 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.loadround tripBefore:
pytest -q tests/test_checkpoint_interop_4053.py -k pickle-> 4 failed (PicklingErrorfor FP8/EXL3/VPTQ; TorchLinear restored withoptimized=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):After,
device="cuda:0", max_memory={"cpu": "10GiB"}:After,
max_memory={"cpu": "10GiB"}with nodevice(previously also crashed):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@718256fd7with the new tests copied in):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_configand reloads it with stockmlx_lm.load; it asserts a stocknn.QuantizedLinearwith(group_size, bits) == (32, 8)and bit-identical packed words.4. Tests run (merged tree)
All commands from the clone root.
ruff check gptqmodel docs/eora tests setup.pyAll 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.py74 passed, 3 skippedtests/test_cpu_kernel_optimize.py75 passed, 3 skippedPYTHONPATH=$PWD CUDA_VISIBLE_DEVICES=GPU-50a20676-a7a4-8bb3-eb3d-f191fdc9fa42 /opt/venvs/cu130t/bin/python -m pytest -q tests/test_macaq.py66 passed, 1 skipped(guards #4090)PYTHONPATH=$PWD CUDA_VISIBLE_DEVICES="" /opt/venvs/cu130t/bin/python -m pytest -q tests/test_exllamav3_cpu.py59 passed, 4 skippedPYTHONPATH=$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 passedPYTHONPATH=$PWD /opt/venvs/mlx/bin/python -m pytest -q tests/test_mlx_packing tests/test_mlx_macaq.py tests/test_mlx_nf12.py158 passed, 99 failed, 3 skipped; the 99 failures are the same 82 pre-existingMLX quantized linear requires Apple Siliconfailures plus 17 pre-existing MACaQ/NF12 Metal failures measured onorigin/main@1acb30fe9(17 failed, 4 passedthere)origin/mainwas merged twice (1acb30fe9#4097, then1732d2ae3#4099) before opening/updating;git merge-base --is-ancestor origin/main HEADis true and ruff/tests were re-run afterwards. The stock-compatible guard also returnsNonefor the newMacaqLinear/NF12Linearlayers.5. Merge resolution with #4099
gptqmodel/utils/hf_quant_refusal.py(this branch) duplicatedgptqmodel/utils/hf_refusing_quantizer.py(#4099)GPTQModelRefusingHfQuantizer/GPTQModelRefusingQuantizationConfiggptqmodel/_quant_methods.py: two parallel tablesREFUSED_HF_QUANT_METHODS(name → label) and added the missing"exl3": "EXL3"; net diff vs main is +2 linesgptqmodel/__init__.py: two registration functions_patch_transformers_gptqmodel_gguf_quantizer_compat+_patch_transformers_refusing_quantizersunchanged; this PR's__init__.pydiff vs main is emptygptqmodel/models/writer.pyhf_compat_warningsentry, now iteratingREFUSED_HF_QUANT_METHODSdocs/macaq.md(#4099's interop table)exl3row so the table stays complete6. Hardware and environments
/opt/venvs/cu130t/bin/python(Py3.14t, Torch2.16.0.dev+cu130),CUDA_VISIBLE_DEVICES="".tests/test_macaq.py: NVIDIA RTX 4090GPU-50a20676-a7a4-8bb3-eb3d-f191fdc9fa42viaCUDA_VISIBLE_DEVICES. The RTX 5090 was never touched./opt/venvs/mlx(mlx 0.32.4,mlx-lm 0.32.2, CPU). Ran on Linux/mlx-cpu: prompt normalization, EOS scoping, stockmlx_lm.loadexport. Read, not run: Apple Silicon/Metal kernel execution (no Apple hardware here); item 10's Metal dispatch is untouched.7. Limitations
gptqmodelstill only gets transformers' warning; that is transformers' behaviour and is now documented.vptqandbitsandbytesare deliberately absent from the table because transformers implements them.device="cuda:0"+ CPU-only-budget combination is rejected rather than silently run on CPU (rationale above).ValueErrorinstead 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 theexl3row to the shared interop table.README.md: link descriptions updated (both pages were already linked).