Repository navigation
fix(checkpoint): refuse runtime-layout HF saves, emit AWQ snapshots, carry layout in a tensor (#4125) - #4134
Merged
Merged
Conversation
…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.
This was referenced Nov 15, 2026
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]>
This was referenced Nov 17, 2026
This was referenced Nov 27, 2026
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.
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 #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:363andexllamav2_awq.py:157oncheckpoint_serialization(), so that PEFT's read-onlystate_dict()keeps working. Onlymodels/writer.pyentered that scope.PreTrainedModel.save_pretrained()collectsstate_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) —
AWQuantLinearhad no save hook_write_fused_train_state_snapshotlived onGPTQQuantLinearonly.AWQuantLinear(qlinear/__init__.py:2329) had no_save_to_state_dict, sotorch_fused_awq.py:395,torch_aten_kernel_awq.py:282andtorch_cpu_avx512_awq.py:279captured a_fused_train_statesnapshot that nothing wrote out. An eval forward replacedqweightwith the int4pack operand andstate_dict()emitted that shape under the checkpoint key.Item 3 (low-medium) — the v1/v2 copy depended on
state_dict._metadataThe layout record was non-tensor metadata.
torch.savekeeps_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:#2e7d32gptqmodel/__init__.py:190adds_patch_transformers_save_pretrained_runtime_layout_guard()and registers it at:524next to the existing_patch_transformers_*guards. It wrapsPreTrainedModel.save_pretrainedso every HF checkpoint write runs insidecheckpoint_serialization(); PEFT's read-onlystate_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_write_fused_train_state_snapshotand_save_to_state_dictmoved up fromGPTQQuantLineartoPackedGroupedQuantLinear(qlinear/__init__.py:1119,:1148), the shared GPTQ/AWQ base, soAWQuantLinearinherits 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:#b02a37The layout now travels in a persistent
qzeros_formatint64 buffer (_fused_train_state.py:22). It is optional on load — a pre-existing checkpoint has no such key, so_load_from_state_dictstrips it frommissing_keysand falls back to the metadata entry, then_checkpoint_format_on_disk, then the module's constructedformat._checkpoint_qzeros_format()(:1452) answers the effective convention for bothcheckpoint_layout_qzerosand 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 fromconfig.json, so a second label there could only disagree with the words it writes. That also keeps the on-disk schema ofsave_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/main13ee428f2in a scratch worktree.Item 1 —
Llama-3.2-1B GPTQ 4-bit g128, AUTO on CUDA (picksMarlinLinear)model.model.save_pretrained(dir)RuntimeError: Marlin rewrites qweight into its runtime tile layout ...qweight(128, 4096)(tile layout)ValueError: Trying to set a tensor of shape [512, 4096] in "qweight" (which has shape [1024, 2048])state_dict()(PEFT)0Item 1 — same checkpoint forced to
BACKEND.EXLLAMA_V2(the silent case)model.model.save_pretrained(dir)RuntimeError: ExLlamaV2 shuffles qweight in place into its native runtime layout ...' Paris. Which of the following''woke%/orpionishly ])->gü'Item 2 —
Qwen2.5-0.5B-Instruct-AWQ, CPU AUTO (picksTorchCpuAvx512AwqLinear)qweight(896, 112)(896, 112)qweightafter eval forward(896, 448)(896, 448)state_dict()qweight(896, 448)(896, 112)save_pretrained()+ reloadValueError: Trying to set a tensor of shape [2048, 4096] in "qweight" (which has shape [8192, 256])2e-3Item 3 — v1 GPTQ model loading a
gptq_v2state dict (TORCH kernel), max logit difftorch.save0.00.05.89230.0{k: v.clone() for k, v in sd.items()}5.89230.0Tests
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:Lint:
New coverage
test_transformers_save_pretrained_enters_checkpoint_scopecheckpoint_serialization()and the scope does not leaktest_save_pretrained_refuses_runtime_layout_modelsave_pretrained()raises,state_dict()still readable, payload marked0test_awq_cpu_kernels_emit_checkpoint_layout_after_transform_fused_train_statepresent,qweightreshaped),state_dict()emits the checkpoint shape and integer finite qzeros, and a fresh module reloads to matching logitstest_v1_v2_copy_survives_every_state_dict_transport[torch,safetensors,dict]test_no_inverse_kernel_state_dict_contract[marlin,awq_marlin]0, a checkpoint-layout receiver raisesThe AWQ cases in
test_awq_state_dict_round_trip_is_identitynow run ineval()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 withAssertionError: Original native weight allocations were retainedon both this branch andorigin/main13ee428f2(verified in the scratch worktree, same 6 ids). Not claimed as mine.Docs
docs/checkpoint-interop.md:PreTrainedModel.save_pretrained()is wrapped, and howtorch.save(state_dict())is handled by the self-describing payload.save_pretrained()row is accurate again.All 12 Mermaid blocks validated: balanced fences,
flowchart TD, no raw-HTML wrapping, no unquoted braces in labels.