Repository navigation
fix(checkpoint): make state_dict() a real checkpoint for every kernel (#4091) - #4103
Merged
Merged
Conversation
…format alignment (#4095) In _copy_packed_state(), copy live named buffers and parameters directly instead of calling source.state_dict(). state_dict() produces checkpoint-converted v1 zero points, which previously caused repacked modules that decode v2 zero points to decode every zero point one step low. Propagate _checkpoint_format_on_disk from source to target during _copy_packed_state() so targets preserve their serialization layout. In _restore_gptq_runtime_qzeros(), set _checkpoint_format_on_disk = FORMAT.GPTQ when converting v1 checkpoint words to v2, ensuring save_pretrained() and state_dict() emit proper v1 words instead of v2 words under a v1 label. In hf_pack_layer(), record _checkpoint_format_on_disk for GPTQ formats. Add regression test test_hf_repack_layer_preserves_gptq_v1_zero_points and assertions to test_hf_pack_layer_post_init_restores_v2_runtime_layout and test_hf_post_init_restores_gptq_v2_runtime_layout. Signed-off-by: Prajwal7-2002 <[email protected]>
…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
…#4091) Three paths in the checkpoint/state_dict family still disagreed with what the live kernel holds: * CPU int4pack kernels (TorchAtenLinear, TorchFusedLinear) replace `qweight` and `qzeros` in place with int4pack words and float affine offsets, then `state_dict()` serialized those runtime buffers. `checkpoint_layout_qzeros` applied the integer v1 conversion to the float offsets, producing `inf` or `65536`, so a reload produced `inf`/`NaN` logits. `_save_to_state_dict` now emits the `_fused_train_state` checkpoint snapshot, and a modified runtime state raises instead of writing garbage. * `_load_from_state_dict` assumed incoming qzeros used the *target's* `_checkpoint_format_on_disk`, so copying a state dict between a v1-loaded and a v2-loaded model shifted every zero point. The emitted layout is now recorded in the state dict's per-module metadata (`qzeros_format`) and the load converts from it. Metadata adds no tensor keys, so `strict=True` loading of a plain HF checkpoint is unchanged. * Marlin/ExLlamaV2 raised from `_save_to_state_dict` unconditionally, but PEFT calls `model.state_dict()` to load an adapter, so merely loading an adapter on a Marlin base failed. The raise is now gated on an explicit `checkpoint_serialization()` scope, which GPT-QModel's checkpoint writers enter; read-only collection returns the runtime tensors. Adds `tests/test_checkpoint_state_invariant.py`, a data-driven inventory that holds every kernel to "state_dict() rebuilds the layer in a fresh module" and "load_state_dict(state_dict()) is an identity" for both on-disk formats.
…eckpoint Both branches are slices of #4091 and collided in tests/test_checkpoint_interop_4053.py. Resolution: * kept both new test sets: pr4101's test_hf_from_pretrained_refuses_every_refused_method (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 pr4101 inherited byte-identical from main and never edited. It asserts an unconditional raise from Marlin/ExLlamaV2 `_save_to_state_dict`, which is the exact behaviour item 4 changes. Its two assertions (marlin + 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. gptqmodel/nn_modules/qlinear/__init__.py auto-merged: pr4101's BaseQuantLinear.__getstate__ and this branch's _save_to_state_dict / _load_from_state_dict / qzero-layout metadata changes are disjoint.
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
Qubitium
added a commit
that referenced
this pull request
Nov 15, 2026
…carry layout in a tensor (#4125) (#4134) Three defects in the #4103 checkpoint work, found by the follow-up audit. 1. Regression: HF `save_pretrained()` no longer refused. `checkpoint_serialization()` was only entered by `models/writer.py`, but `PreTrainedModel.save_pretrained()` collects `state_dict()` itself. Marlin, AWQ-Marlin, ExLlamaV2 and AWQ-ExLlamaV2 therefore published their private runtime layout under an ordinary GPTQ/AWQ config with no error; AUTO selects those kernels by default on CUDA. The ExLlamaV2 directory reloaded as garbage ("flags flags flags ..."), Marlin raised a shape error only at load time. `gptqmodel.__init__` now wraps `PreTrainedModel.save_pretrained()` so the HF writer runs inside `checkpoint_serialization()`, next to the existing `_patch_transformers_*` guards. PEFT's read-only `state_dict()` call stays outside the scope and keeps working. 2. `AWQuantLinear` had no save hook. Only `GPTQQuantLinear._save_to_state_dict` emitted the fused-train snapshot, so the CPU AWQ kernels (`TorchAtenAwqLinear`, `TorchFusedAwqLinear`, `TorchCpuAvx512AwqLinear` -- the CPU AUTO default for AWQ) captured a snapshot that nothing wrote out. An eval forward replaced `qweight` with the int4pack operand and `state_dict()` emitted that shape under the checkpoint key: (896, 448) instead of (896, 112), which reloaded with a shape mismatch. `_write_fused_train_state_snapshot` and `_save_to_state_dict` moved up to `PackedGroupedQuantLinear`, the shared GPTQ/AWQ base. 3. The v1/v2 copy depended on `state_dict._metadata`. The layout record was not a tensor, so a safetensors round trip (Trainer/accelerate) or a plain `{k: v for k, v in sd.items()}` copy dropped it and the receiving module read v2 words as v1. It now travels in a persistent `qzeros_format` int64 buffer: 1 = v1, 2 = v2, 0 = kernel-private runtime layout. The buffer is optional on load (a pre-existing checkpoint has no such key, so it is stripped from `missing_keys`), and the metadata entry is kept as the fallback for state dicts written by earlier releases. `GPTQModel.save()` does not emit the buffer: the writer resolves the convention from `config.json`, so a second label there could only disagree with the words it writes. `_checkpoint_qzeros_format()` now answers the effective on-disk convention for both `checkpoint_layout_qzeros` and the emitted code, so the words and their label cannot drift apart for a freshly quantized module. Tests: `test_checkpoint_state_invariant.py` gains a `save_pretrained()` guard test, a runtime-layout model test, an AWQ transform test that actually reaches the int4pack path (eval + per-kernel activation dtype) and a safetensors/dict-copy transport test. The AWQ inventory also asserts the checkpoint shape after the transform.
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 2-4)
Fixes the checkpoint/
state_dictfamily for three paths that still disagreed with what the live kernel holds, and adds the invariant test that was missing:state_dict()must rebuild the layer in a fresh module, andload_state_dict(m.state_dict())must be an identity, for every kernel and both on-disk formats.Root cause
Item 2 — CPU AUTO kernels serialize a runtime layout (
inf/NaN)TorchAtenLinear(CPU AUTO for FP16) andTorchFusedLinear(BF16) rewriteqweightandqzerosin place on the first eval forward (qlinear/torch_fused.py:394transform_cpu,qlinear/torch_aten_kernel.py:298):qweightbecomes an int4pack operand andqzerosbecomes float affine offsets. The checkpoint tensors survive only in the_fused_train_statesnapshot._save_to_state_dictserialized the live buffers, andcheckpoint_layout_qzeros(qlinear/__init__.py:1275before this PR) applied the integer v1 conversion to those float offsets.Item 3 — a state dict does not record its own qzero layout
_load_from_state_dict(qlinear/__init__.py:1454) converted the incoming words using the target's_checkpoint_format_on_disk. Nothing in the state dict said which layout the source had, so copying between a model loaded fromgptq(v1) and one loaded fromgptq_v2shifted every zero point whilestrict=Truereported success.Item 4 — Marlin/ExLlamaV2 raise for read-only callers
_save_to_state_dictraised unconditionally inmarlin.py:484,marlin_awq.py:363,exllamav2.py:193,exllamav2_awq.py:157. PEFT 0.21set_peft_model_state_dictcallsmodel.state_dict(), so merely loading an adapter on a Marlin base failed.The fix
flowchart TD A["state_dict()"] --> B["GPTQQuantLinear._save_to_state_dict"] B --> C{"_fused_train_state snapshot?"} C -- yes --> D["emit snapshot qweight/qzeros<br/>(checkpoint tensors)"] C -- "no (not transformed)" --> E["emit live buffers"] D --> F["checkpoint_layout_qzeros<br/>v2 to v1 copy"] E --> F F --> G["record qzeros_format in<br/>state-dict metadata"] G --> H["checkpoint / read-only caller"] style D fill:#d9f2d9,stroke:#2e7d32 style G fill:#d9f2d9,stroke:#2e7d32flowchart TD A["load_state_dict(state)"] --> B["copy words"] B --> C{"prefix + qzeros present?"} C -- no --> E["keep runtime layout<br/>(partial load, PEFT)"] C -- yes --> D{"metadata qzeros_format"} D -- "1" --> F["v1 to v2 if REQUIRES_FORMAT_V2<br/>else _qzeros_format = 1"] D -- "2" --> G["v2 to v1 if not REQUIRES_FORMAT_V2<br/>else _qzeros_format = 2"] D -- "absent (HF checkpoint)" --> H["fall back to<br/>_checkpoint_format_on_disk"] F --> I["_clear_runtime_weight_cache"] G --> I H --> I E --> I style F fill:#d9f2d9,stroke:#2e7d32 style G fill:#d9f2d9,stroke:#2e7d32_write_fused_train_state_snapshot(qlinear/__init__.py:1287) emits the captured checkpoint tensors under their checkpoint names before the qzero conversion. A runtime state that no longer matches the snapshot has no inverse, so export raises instead of writinginf._write_state_dict_layout_metadata(:1316) records the emitted layout per module asqzeros_formatin the state dict's_metadata;_incoming_qzeros_format(:1390) and_restore_qzeros_format(:1419) convert from it. No tensor key is added, sostrict=Trueloading of a plain HF checkpoint is unaffected — a checkpoint read from disk has no such entry and falls back to_checkpoint_format_on_disk, then to the module's constructedformat.gptqmodel/utils/checkpoint_state.pyadds aContextVarscope,checkpoint_serialization(). The raise is gated on it; GPT-QModel's checkpoint writers enter it (models/writer.py:732). Read-onlystate_dict()returns the runtime tensors.The invariant test (main deliverable)
tests/test_checkpoint_state_invariant.pyis data-driven so the next kernel added cannot silently break it:TorchLinear,TorchAtenLinear,TorchFusedLinear,TorchCpuAvx512LinearAwqTorchLinear+ repackedTorchAtenAwqLinear,TorchFusedAwqLinear,TorchCpuAvx512AwqLinearMarlinLinear,AwqMarlinLinearTwo assertions per case:
load_state_dict(state_dict())is an identity — emitted tensors and layer output unchanged.state_dict()is a checkpoint — a fresh module that never ran a forward, loaded from it, reproduces the logits.Assertion 2 is what catches item 2. A self round-trip alone cannot: copying the transformed buffers back into the same transformed module is trivially an identity.
Fail-before / pass-after
tests/test_checkpoint_state_invariant.pyonorigin/main(718256fd7) vs this branch:torch_atenv1 + v2Tensor-likes are not close! Mismatched elements: 191 / 192 (99.5%)torch_fusedv1 + v2size mismatch for qweight: shape [64, 64] vs [16, 64];qzeros [4, 64] vs [4, 8]Before:
4 failed, 8 passed. After:14 passed.Item 3, same 1-layer fixture (
Aloaded fromgptq,Bfromgptq_v2):A.load_state_dict(B.state_dict())0.25090.0B.load_state_dict(A.state_dict())0.12980.0Item 2,
qzeros[0]and logits on the CPU AUTO kernels:GPTQ_TORCH_ATENqzerosfloat16[inf, inf, inf], logitsNaN[2004318071, ...], maxdiff0.0GPTQ_TORCH_FUSEDqzerosfloat16[inf, inf, inf], logitsNaN[2004318071, ...], maxdiff0.0Item 4: on
origin/main,marlin.state_dict()after repack raisesRuntimeError: Marlin rewrites qweight ...; here it returns the runtime tensors and onlycheckpoint_serialization()raises.Validation
CUDA venv (
/opt/venvs/cu130t/bin/python),CUDA_VISIBLE_DEVICES=GPU-d458708b-c760-bbf1-08fb-8b8803a2157d:ROCm venv (
/opt/venvs/rocm101t/bin/python),HIP_VISIBLE_DEVICES=2only (noROCR_VISIBLE_DEVICES):test_hf_packing_api.py::test_gpu_feasibility_and_best_formatfails on ROCm identically onorigin/main(1 failed, 53 deselectedon718256fd7) because it asserts Marlin repack feasibility, which is CUDA-only. Pre-existing, unrelated to this PR.CPU-only matrix: the four CPU kernels run in the invariant test on both venvs without a device.
Lint:
Hardware: 1x RTX 4090 (
GPU-d458708b-c760-bbf1-08fb-8b8803a2157d), 1x AMD R9700 (HIP_VISIBLE_DEVICES=2). The RTX 5090 was not used.Docs
docs/checkpoint-interop.md— §3 (read-only vs checkpoint-write contract), §9 (state-dict metadata and cross-format copies), new §12 (CPU int4pack snapshot), and the failure-contract tables. The page is already linked fromREADME.md:117. All 12 Mermaid blocks validated (balanced fences,flowchart TD, no raw-HTML wrapping).Scope
Items 2-4 of #4091 only. Item 1 (AWQ
batch_size>1), item 5 (HF refusing quantizers) and items 6-10 are owned by other workers. The#4095items 1-2 are handled by #4096, which this branch is based on (ba0a651d) so the_checkpoint_format_on_diskplumbing layers on top instead of colliding.Known limitation
A raw
PreTrainedModel.save_pretrained()call that bypassesGPTQModel(i.e. calling it directly onmodel.modelrather than on theGPTQModelwrapper) is not wrapped incheckpoint_serialization(), so it will serialize Marlin's runtime tensors rather than raising.GPTQModel.save(),save_quantized()andsave_pretrained()all route through the export shell and remain fail-closed.