Skip to content

fix(checkpoint): refuse runtime-layout HF saves, emit AWQ snapshots, carry layout in a tensor (#4125) - #4134

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4125-checkpoint-refusal
Nov 15, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4125-checkpoint-refusal

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Part of #4125 (items 1-3)

Follow-up audit of #4103. Item 1 is a silent regression I introduced; items 2 and 3 are gaps the audit found in the same fix. Item 4 (AWQ per-document mask) belongs to another worker.

Root cause

Item 1 (high, regression) — HF save_pretrained() stopped refusing

#4103 gated the runtime-layout refusals in qlinear/exllamav2.py:193, marlin.py:484, marlin_awq.py:363 and exllamav2_awq.py:157 on checkpoint_serialization(), so that PEFT's read-only state_dict() keeps working. Only models/writer.py entered that scope. PreTrainedModel.save_pretrained() collects state_dict() itself, on the read-only side, so Marlin / AWQ-Marlin / ExLlamaV2 / AWQ-ExLlamaV2 published their private tile-permuted or shuffled layout under an ordinary GPTQ/AWQ config with no error — and AUTO picks those kernels by default on CUDA. The ExLlamaV2 directory then reloaded as garbage; Marlin raised a shape error only at load. Both reproduced below.

Item 2 (medium) — AWQuantLinear had no save hook

_write_fused_train_state_snapshot lived on GPTQQuantLinear only. AWQuantLinear (qlinear/__init__.py:2329) had no _save_to_state_dict, so torch_fused_awq.py:395, torch_aten_kernel_awq.py:282 and torch_cpu_avx512_awq.py:279 captured a _fused_train_state snapshot that nothing wrote out. An eval forward replaced qweight with the int4pack operand and state_dict() emitted that shape under the checkpoint key.

Item 3 (low-medium) — the v1/v2 copy depended on state_dict._metadata

The layout record was non-tensor metadata. torch.save keeps _metadata; safetensors (Trainer/accelerate) and a plain {k: v for k, v in sd.items()} copy drop it, so the receiving module read v2 words as v1.

The fix

flowchart TD
    A["PreTrainedModel.save_pretrained"] --> B["wrapper installed at import<br/>enters checkpoint_serialization()"]
    B --> C{"kernel in runtime layout?"}
    C -- yes --> D["raise RuntimeError<br/>checkpoint layout cannot be reconstructed"]
    C -- no --> E["write checkpoint tensors"]
    F["PEFT: model.state_dict()"] --> G["read-only, outside the scope"]
    G --> H["returns runtime tensors"]
    style D fill:#f8d7da,stroke:#b02a37
    style H fill:#d9f2d9,stroke:#2e7d32
Loading

gptqmodel/__init__.py:190 adds _patch_transformers_save_pretrained_runtime_layout_guard() and registers it at :524 next to the existing _patch_transformers_* guards. It wraps PreTrainedModel.save_pretrained so every HF checkpoint write runs inside checkpoint_serialization(); PEFT's read-only state_dict() stays outside.

flowchart TD
    A["first eval forward"] --> B["capture_fused_train_state"]
    B --> C["transform_cpu<br/>in-place int4pack qweight"]
    C --> D["state_dict()"]
    D --> E["PackedGroupedQuantLinear._save_to_state_dict"]
    E --> F["_write_fused_train_state_snapshot<br/>emit checkpoint qweight/qzeros/scales"]
    E --> G["_write_state_dict_layout_marker<br/>qzeros_format tensor"]
    F --> H["checkpoint payload"]
    G --> H
    style F fill:#d9f2d9,stroke:#2e7d32
    style G fill:#d9f2d9,stroke:#2e7d32
Loading

_write_fused_train_state_snapshot and _save_to_state_dict moved up from GPTQQuantLinear to PackedGroupedQuantLinear (qlinear/__init__.py:1119, :1148), the shared GPTQ/AWQ base, so AWQuantLinear inherits them.

flowchart TD
    A["state_dict()"] --> B["qzeros_format tensor<br/>1 = v1, 2 = v2, 0 = runtime layout"]
    B --> C{"transport"}
    C -- "torch.save" --> D["metadata and tensor survive"]
    C -- "safetensors / dict copy" --> E["metadata dropped, tensor survives"]
    D --> F["_load_from_state_dict reads the tensor"]
    E --> F
    F --> G{"0?"}
    G -- "yes, receiver has checkpoint tensors" --> H["raise: not a checkpoint"]
    G -- no --> I["convert from the recorded layout"]
    style E fill:#d9f2d9,stroke:#2e7d32
    style H fill:#f8d7da,stroke:#b02a37
Loading

The layout now travels in a persistent qzeros_format int64 buffer (_fused_train_state.py:22). It is optional on load — a pre-existing checkpoint has no such key, so _load_from_state_dict strips it from missing_keys and falls back to the metadata entry, then _checkpoint_format_on_disk, then the module's constructed format. _checkpoint_qzeros_format() (:1452) answers the effective convention for both checkpoint_layout_qzeros and the emitted code, so the words and their label cannot drift apart.

GPTQModel.save() deliberately does not emit the buffer (utils/model.py:2484, :2605): the writer resolves the convention from config.json, so a second label there could only disagree with the words it writes. That also keeps the on-disk schema of save_quantized() unchanged.

A module that is itself in a runtime layout keeps its own round trip, because that is how ExLlamaV2 rebinds finalized words between matching layers (exllamav2.py:225).

Fail-before / pass-after

All measured on this machine; "before" is origin/main 13ee428f2 in a scratch worktree.

Item 1 — Llama-3.2-1B GPTQ 4-bit g128, AUTO on CUDA (picks MarlinLinear)

Before After
model.model.save_pretrained(dir) OK (no error) RuntimeError: Marlin rewrites qweight into its runtime tile layout ...
saved qweight (128, 4096) (tile layout) refused, nothing written
reload ValueError: Trying to set a tensor of shape [512, 4096] in "qweight" (which has shape [1024, 2048]) —
read-only state_dict() (PEFT) works works, marker 0

Item 1 — same checkpoint forced to BACKEND.EXLLAMA_V2 (the silent case)

Before After
model.model.save_pretrained(dir) OK (no error) RuntimeError: ExLlamaV2 shuffles qweight in place into its native runtime layout ...
prompt generation before ' Paris. Which of the following' —
reloaded directory generates 'woke%/orpionishly ])->gü' not written

Item 2 — Qwen2.5-0.5B-Instruct-AWQ, CPU AUTO (picks TorchCpuAvx512AwqLinear)

Before After
checkpoint qweight (896, 112) (896, 112)
runtime qweight after eval forward (896, 448) (896, 448)
state_dict() qweight (896, 448) (896, 112)
save_pretrained() + reload ValueError: Trying to set a tensor of shape [2048, 4096] in "qweight" (which has shape [8192, 256]) reloads without a shape error; the kernel-level test below asserts the reloaded layer's logits match within 2e-3

Item 3 — v1 GPTQ model loading a gptq_v2 state dict (TORCH kernel), max logit diff

Transport Before After
torch.save 0.0 0.0
safetensors round trip 5.8923 0.0
{k: v.clone() for k, v in sd.items()} 5.8923 0.0

Tests

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

$ pytest -q tests/test_checkpoint_state_invariant.py tests/test_checkpoint_interop_4053.py \
           tests/test_checkpoint_compat.py tests/test_save_state_dict_buffer_collection.py \
           tests/test_hf_packing_api.py
127 passed, 3 skipped, 9 warnings in 49.92s

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

$ pytest -q tests/test_checkpoint_state_invariant.py tests/test_checkpoint_interop_4053.py \
           tests/test_checkpoint_compat.py
64 passed, 5 skipped, 9 warnings in 51.19s

Lint:

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

New coverage

Test Pins
test_transformers_save_pretrained_enters_checkpoint_scope the HF writer enters checkpoint_serialization() and the scope does not leak
test_save_pretrained_refuses_runtime_layout_model a real Marlin model: save_pretrained() raises, state_dict() still readable, payload marked 0
test_awq_cpu_kernels_emit_checkpoint_layout_after_transform the AWQ transform actually ran (_fused_train_state present, qweight reshaped), state_dict() emits the checkpoint shape and integer finite qzeros, and a fresh module reloads to matching logits
test_v1_v2_copy_survives_every_state_dict_transport[torch,safetensors,dict] exactness through all three transports
test_no_inverse_kernel_state_dict_contract[marlin,awq_marlin] read-only collection works, payload marked 0, a checkpoint-layout receiver raises

The AWQ cases in test_awq_state_dict_round_trip_is_identity now run in eval() with the per-kernel activation dtype, so they reach the transform instead of asserting on an untransformed module.

Pre-existing failures (not mine)

tests/module_tree/test_fusion_kernel_backends.py::test_native_fusion_shapes_oracle_ownership_and_invalidation[...ExllamaV2Linear...] — 6 cases fail with AssertionError: Original native weight allocations were retained on both this branch and origin/main 13ee428f2 (verified in the scratch worktree, same 6 ids). Not claimed as mine.

Docs

docs/checkpoint-interop.md:

  • §3 now states that PreTrainedModel.save_pretrained() is wrapped, and how torch.save(state_dict()) is handled by the self-describing payload.
  • §9 documents the tensor marker, its fallback chain, and why the writer does not emit it.
  • §12 covers the AWQ CPU kernels and explains that the hook lives on the shared base.
  • The failure-contract tables gained the AWQ, safetensors/dict-copy rows; the save_pretrained() row is accurate again.

All 12 Mermaid blocks validated: balanced fences, flowchart TD, no raw-HTML wrapping, no unquoted braces in labels.

…carry layout in a tensor (#4125)

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.
@Qubitium
Qubitium merged commit 6f9ad69 into main Nov 15, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-4125-checkpoint-refusal branch November 15, 2026 11:21
Qubitium added a commit that referenced this pull request Nov 16, 2026
…rker (#4360)

Three test-side classes from the R9700 suite triage. Each failing test was
reproduced at HEAD and classified before editing.

1. Missing ROCm gates.
   - `kernels/test_qqq_workspace.py`: `validate()` consults the once-gate,
     which returns `QQQ_ROCM_UNSUPPORTED` before the file's runtime/device
     stubs. The workspace sizing is pure Python, so stub `validate_once`
     instead of skipping the file on ROCm (7 tests now run on both backends).
   - `test_nan_activation_quantizers_4220.py`: the E4M3 skip gate only checked
     compute capability, so it ran on ROCm and hit the CUDA-only `fp8_pack`.
     Gate on `IS_ROCM` too; the QQQ quantizer in the same file does work there.

2. Order-dependent thread cap.
   `test_process_thread_count_does_not_scale_with_cpu_count` counted
   process-wide threads, so a prior `quantize()` (DeviceThreadPool teams plus
   the tokenizer rayon pool) pushed it to 399 against the 80 limit. Measure the
   harness contract in a fresh subprocess instead, the pattern this file
   already uses for its other cap tests.

3. Stale `qzeros_format` expectations.
   The marker is intentional (#4125/#4134): `state_dict()` carries it and
   `get_state_dict_for_save` deliberately drops it. Realign
   `kernels/test_torch_int8.py`, `kernels/test_w4a_cache_lifecycle.py` and
   `module_tree/test_llama_fusion.py` the same way #4241 did for its files.

No assertion was weakened and no test was skipped to make it pass.

Fixes #4351

Co-authored-by: triage-rocm <[email protected]>
Qubitium added a commit that referenced this pull request Nov 27, 2026
#4620 removed the PreTrainedModel.save_pretrained wrapper that entered
checkpoint_serialization(), so an HF-loaded Marlin/ExLlamaV2 model wrote its
irreversible runtime layout (tile/shuffled qweight, empty qzeros/g_idx) plus
qzeros_format markers under an ordinary checkpoint_format: gptq config. The
directory could not be reloaded by GPTQModel.load or Transformers.

Attach the guard to the loaded model instance in hf_gptqmodel_post_init, the
bridge Transformers' GPTQ/AWQ quantizers already call. It is instance-scoped,
so no Transformers class is touched. Bridge saves now refuse on runtime-layout
kernels with the #4134 error and drop qzeros_format for checkpoint-layout
kernels; GPTQModel.load/GPTQModel.save and read-only state_dict() callers are
unchanged.
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