Skip to content

fix(checkpoint): make state_dict() a real checkpoint for every kernel (#4091) - #4103

Merged
Qubitium merged 11 commits into
mainfrom
fix/issue-4091-checkpoint
Nov 15, 2026
Merged

Qubitium merged 11 commits into
mainfrom
fix/issue-4091-checkpoint

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Part of #4091 (items 2-4)

Fixes the checkpoint/state_dict family 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, and load_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) and TorchFusedLinear (BF16) rewrite qweight and qzeros in place on the first eval forward (qlinear/torch_fused.py:394 transform_cpu, qlinear/torch_aten_kernel.py:298): qweight becomes an int4pack operand and qzeros becomes float affine offsets. The checkpoint tensors survive only in the _fused_train_state snapshot.

_save_to_state_dict serialized the live buffers, and checkpoint_layout_qzeros (qlinear/__init__.py:1275 before 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 from gptq (v1) and one loaded from gptq_v2 shifted every zero point while strict=True reported success.

Item 4 — Marlin/ExLlamaV2 raise for read-only callers

_save_to_state_dict raised unconditionally in marlin.py:484, marlin_awq.py:363, exllamav2.py:193, exllamav2_awq.py:157. PEFT 0.21 set_peft_model_state_dict calls model.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:#2e7d32
Loading
flowchart 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
Loading
  • Item 2 — _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 writing inf.
  • Item 3 — _write_state_dict_layout_metadata (:1316) records the emitted layout per module as qzeros_format in the state dict's _metadata; _incoming_qzeros_format (:1390) and _restore_qzeros_format (:1419) convert from it. No tensor key is added, so strict=True loading 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 constructed format.
  • Item 4 — gptqmodel/utils/checkpoint_state.py adds a ContextVar scope, checkpoint_serialization(). The raise is gated on it; GPT-QModel's checkpoint writers enter it (models/writer.py:732). Read-only state_dict() returns the runtime tensors.

The invariant test (main deliverable)

tests/test_checkpoint_state_invariant.py is data-driven so the next kernel added cannot silently break it:

Inventory Kernels
GPTQ, both on-disk formats TorchLinear, TorchAtenLinear, TorchFusedLinear, TorchCpuAvx512Linear
AWQ AwqTorchLinear + repacked TorchAtenAwqLinear, TorchFusedAwqLinear, TorchCpuAvx512AwqLinear
No-inverse runtime layout (CUDA) MarlinLinear, AwqMarlinLinear

Two assertions per case:

  1. load_state_dict(state_dict()) is an identity — emitted tensors and layer output unchanged.
  2. 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.py on origin/main (718256fd7) vs this branch:

Case Before After
torch_aten v1 + v2 Tensor-likes are not close! Mismatched elements: 191 / 192 (99.5%) pass
torch_fused v1 + v2 size mismatch for qweight: shape [64, 64] vs [16, 64]; qzeros [4, 64] vs [4, 8] pass
everything else pass pass

Before: 4 failed, 8 passed. After: 14 passed.

Item 3, same 1-layer fixture (A loaded from gptq, B from gptq_v2):

Copy Before maxdiff After maxdiff
A.load_state_dict(B.state_dict()) 0.2509 0.0
B.load_state_dict(A.state_dict()) 0.1298 0.0

Item 2, qzeros[0] and logits on the CPU AUTO kernels:

Kernel Before After
GPTQ_TORCH_ATEN qzeros float16 [inf, inf, inf], logits NaN int32 [2004318071, ...], maxdiff 0.0
GPTQ_TORCH_FUSED qzeros float16 [inf, inf, inf], logits NaN int32 [2004318071, ...], maxdiff 0.0

Item 4: on origin/main, marlin.state_dict() after repack raises RuntimeError: Marlin rewrites qweight ...; here it returns the runtime tensors and only checkpoint_serialization() raises.

Validation

CUDA venv (/opt/venvs/cu130t/bin/python), CUDA_VISIBLE_DEVICES=GPU-d458708b-c760-bbf1-08fb-8b8803a2157d:

$ pytest tests/test_checkpoint_state_invariant.py tests/test_checkpoint_interop_4053.py \
         tests/test_hf_packing_api.py tests/test_save_state_dict_buffer_collection.py -q
88 passed, 3 skipped, 4 warnings in 31.88s

ROCm venv (/opt/venvs/rocm101t/bin/python), HIP_VISIBLE_DEVICES=2 only (no ROCR_VISIBLE_DEVICES):

$ pytest <same four files> -q -k "not test_gpu_feasibility_and_best_format"
82 passed, 8 skipped, 4 warnings in 27.26s

test_hf_packing_api.py::test_gpu_feasibility_and_best_format fails on ROCm identically on origin/main (1 failed, 53 deselected on 718256fd7) 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:

$ ruff check gptqmodel docs/eora tests setup.py
All checks passed!

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 from README.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 #4095 items 1-2 are handled by #4096, which this branch is based on (ba0a651d) so the _checkpoint_format_on_disk plumbing layers on top instead of colliding.

Known limitation

A raw PreTrainedModel.save_pretrained() call that bypasses GPTQModel (i.e. calling it directly on model.model rather than on the GPTQModel wrapper) is not wrapped in checkpoint_serialization(), so it will serialize Marlin's runtime tensors rather than raising. GPTQModel.save(), save_quantized() and save_pretrained() all route through the export shell and remain fail-closed.

Prajwal7-2002 and others added 11 commits November 15, 2026 13:09
…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:
#	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.
@Qubitium
Qubitium merged commit 0ff46b6 into main Nov 15, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-4091-checkpoint branch November 15, 2026 09:16
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.
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.

2 participants