Skip to content

fix(checkpoint): one qzeros layout invariant across load, save and pack (#4166, #4167, #4171) - #4235

Merged
Qubitium merged 2 commits into
mainfrom
fix/qzeros-format-invariant
Nov 16, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/qzeros-format-invariant

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #4166, #4167, #4171

TL;DR

One invariant, three symptoms. The live qzeros buffer always holds the
kernel's runtime (logical/v2) zero points; _qzeros_format records only that
live layout; _checkpoint_format_on_disk records only what the next checkpoint
write emits; the v1/v2 conversion runs only at the two serialization
boundaries (incoming state dict -> live, live -> emitted), is idempotent,
and follows the layout marker carried by that same incoming state dict —
never the module's default buffer or its current attribute. The marker is never
persisted into a checkpoint. 12 files, +687/-24 (fix commit 980108fdb, branch
head a351a056b after merging origin/main).

1. The problem

Three defects, one missing contract:

Symptom Mechanism that was wrong Base commit
load -> save shifts every zero point (v2 +1, sharded v1 +1/shard) get_model_with_quantize called load_checkpoint_in_model_then_tie_weights with no device_map; accelerate 1.15 then runs set_model_state_dict once per shard and refills missing keys from the module's own buffers, including the default qzeros_format=1 marker models/writer.py:2526, :2531
...and the load hook trusted that refilled marker _incoming_qzeros_format fell back to the module's on-disk/constructor format, and _restore_qzeros_format converted again even when the incoming words were already the live buffer nn_modules/qlinear/__init__.py:1608, :1637
FORMAT.GPTQ_V2 quantize -> save writes zeros +1 pack_module set qzero_format(2) only when the target format was FORMAT.GPTQ, so a v2 export kept the constructor's _qzeros_format = 1 while the packer wrote logical words; checkpoint_layout_qzeros() then "converted" logical -> v1+1 utils/model.py:1390, nn_modules/qlinear/__init__.py:1345
direct pack() labels logical words v1 pack_original/pack_block/pack_gpu never set qzero_format(2); only hf_pack_layer did nn_modules/qlinear/__init__.py packers
W4A re-save always raises expected = set(model.state_dict()) included the persistent marker, which every checkpoint writer strips models/writer.py:897
Machete/Swordfish runtime layouts are not refused _is_runtime_layout() only looked at _marlin_repacked / _native_shuffled / _awq_repacked; Machete and Swordfish set none of them nn_modules/qlinear/__init__.py:1117

Old flow:

flowchart TD
    A["save_quantized"] --> B["get_model_with_quantize"]
    B --> C["load_checkpoint_in_model_then_tie_weights<br/>device_map = None"]
    C --> D["accelerate: set_model_state_dict<br/>once PER SHARD"]
    D --> E["missing keys refilled from live buffers<br/>marker = default 1"]
    E --> F["_load_from_state_dict -> _restore_qzeros_format<br/>marker 1 -> convert v1 to v2"]
    F --> G["next shard repeats the conversion"]
    G --> H["writer converts v2 to v1 once"]
    H --> I["checkpoint: zeros +1 per shard"]
    style F fill:#f8d7da,stroke:#b02a37
    style G fill:#f8d7da,stroke:#b02a37
    style I fill:#f8d7da,stroke:#b02a37
Loading

2. The new flow

flowchart TD
    A["state_dict shard"] --> B{"prefix + qzeros present?"}
    B -- no --> Z["live buffers untouched"]
    B -- yes --> C{"marker / metadata in THIS state dict?"}
    C -- yes --> D{"marker == live _qzeros_format?"}
    D -- yes --> Z
    D -- no --> E["_restore_qzeros_format(marker)"]
    C -- no --> F{"incoming tensor is the live buffer?"}
    F -- yes --> Z
    F -- no --> G["_incoming_qzeros_format()"]
    G --> H["_restore_qzeros_format(incoming)"]
    E --> I["clear runtime weight cache"]
    H --> I
    Z --> I
    style Z fill:#d9f2d9,stroke:#2e7d32
    style E fill:#fff4cc,stroke:#b8860b
    style H fill:#fff4cc,stroke:#b8860b
Loading

Emission stays a pure copy: checkpoint_layout_qzeros() returns a converted
copy for the target checkpoint_format and never mutates the live buffer.
The export shell used by save() now declares the source layout before loading
and passes device_map={"": "cpu"}, so each tensor is loaded exactly once even
if a future accelerate build changes the device_map=None path.

3. Per-issue evidence

#4166 — load -> save corrupts qzeros

Repro: synthetic 1-layer Llama, CPU TorchLinear (REQUIRES_FORMAT_V2), sharded
v1 built by splitting the safetensors into two files (one holds q/k/v, the other
the rest).

Case Source qzeros word Parent load().save() Parent byte-equal This PR byte-equal
v1 single-file 2004318071 (0x77777777) 2004318071 yes (unaffected, as reported) yes
v1 sharded 2004318071 (0x77777777) -2004318072 (0x88888888) no yes
v2 single-file -1717986919 (0x99999999) -1431655766 (0xAAAAAAAA) no yes
v2 sharded -1717986919 (0x99999999) -1145324613 (0xBBBBBBBB) no yes

The sharded cases drift by one step per shard that refills the module, which is
exactly the "+1 per shard" chain in the issue (the issue's sharded 1.1B
fixture drifted by +5/+6 because its shards repeat the refill more often).

Regression test tests/test_qzeros_format_invariant.py::test_load_then_save_preserves_qzeros_bytes:

  • parent 9dad24974: 6 failed, 1 passed — the one pass is the single-file v1
    case, which the issue also reports as unaffected.
  • this PR: 7 passed.

#4167 — FORMAT.GPTQ_V2 writes zeros +1

Synthetic 1-layer Llama, CPU TorchLinear, sym=False, group_size=32,
QuantizeConfig(..., format=...), quantize -> save -> reload.

Format live marker (parent) live marker (PR) saved == live (parent) saved == live (PR) reloaded NLL (parent) reloaded NLL (PR)
gptq 2 2 no (v1 layout by design) no (v1 layout by design) 4.217766 4.217766
gptq_v2 1 2 no yes 4.222926 4.217766

In-memory NLL is 4.217766 for both formats before and after; on the parent the
reloaded v2 model is 4.222926 and every reloaded zero point is one step high.
The issue's Qwen2.5-0.5B numbers (16.679 vs 1.488) need a network download that
this CPU host does not have, so this fixture is synthetic; the corruption is
still exact and byte-level.

Direct pack() (test_direct_pack_labels_logical_zero_points): parent leaves
qzero_format() == 1 for logical words and fails with "the packer wrote
logical zero points but left the v1 label"
; this PR reports 2 and
state_dict()["qzeros"] is byte-identical to the live buffer.

#4171 item 1 — *.qzeros_format in save_pretrained()

Already fixed by #4155; verified, not re-fixed. On base 9dad24974,
GPTQModel.load(...).model.save_pretrained(out) wrote 33 tensors with zero
*.qzeros_format keys, and the existing
tests/test_checkpoint_interop_4053.py::test_save_pretrained_key_set_matches_save
passes. The invariant keeps that behavior: _write_state_dict_layout_marker
still pops the key inside checkpoint_serialization().

#4171 item 2 — W4A re-save always raised

Parent:

ValueError: Missing native W4A checkpoint tensors: ['model.layers.0.mlp.down_proj.qzeros_format', ... 7 total]

_load_native_w4a_for_save now excludes the non-persisted marker from
expected. The W4A fixtures were also corrected to model a real checkpoint
(no marker key): the public round-trip
test_public_load_save_preserves_native_w4a_tensors was already red on
parent
for this same reason (4 failed), and the whole file is green here
(21 passed, 4 skipped; the skips are NVFP4 hardware). New test
test_native_writer_accepts_checkpoint_without_layout_marker covers w4afp8
and w4a_nvfp4, single-file and sharded: parent 4 failed with the exact
ValueError from the issue, this PR 4 passed.

#4171 item 3 — runtime-layout refusal missed Machete/Swordfish

  • MacheteLinear.post_init and both Swordfish post_init paths now set
    _native_shuffled = True after prepacking qweight and rewriting qzeros
    into float offsets.
  • BitblasLinear.repack_from_gptq and AWQBitBlasKernel.repack_from_awq set
    the same flag after _load_bitblas_quant_state replaces the payload.
  • PackedGroupedQuantLinear._save_to_state_dict now refuses any
    _is_runtime_layout() module inside checkpoint_serialization(), so a kernel
    only has to raise the flag, not re-implement the guard.
  • AllSpark is not a runtime layout: it keeps the checkpoint tensors as the
    source of truth and derives non-persistent *_packed buffers, so it is
    documented as safe rather than refused.

test_any_runtime_layout_flag_refuses_checkpoint_write (CPU): parent
Failed: DID NOT RAISE RuntimeError; this PR passes, and the read-only
state_dict() still labels the payload qzeros_format=0.
tests/test_checkpoint_state_invariant.py::_no_inverse_cases gains
machete, swordfish and bitblas entries.

4. Change inventory

Area File Purpose
load boundary gptqmodel/nn_modules/qlinear/__init__.py idempotent conversion, same-state-dict marker, live-buffer detection, runtime-layout refusal, packers set qzero_format(2)
save shell gptqmodel/models/writer.py declare source layout before load, device_map={"": "cpu"}, exclude the marker from the W4A expected set
packing gptqmodel/utils/model.py mark logical zeros for every GPTQ target format, record the target on-disk format
kernels machete.py, swordfish.py, bitblas.py, bitblas_awq.py set the runtime-layout flag when packed tensors are rewritten
docs docs/checkpoint-interop.md invariant, new load-flow diagram, kernel table
tests tests/test_qzeros_format_invariant.py (new), tests/models/test_w4a_native_writer.py, tests/test_checkpoint_state_invariant.py, tests/test_checkpoint_interop_4053.py regressions below

5. Tests

Test Pins
test_load_then_save_preserves_qzeros_bytes (v1/v2, single/sharded) #4166 byte identity through load().save()
test_gptq_v2_quantize_save_reload_matches_v1 #4167 saved == live, reloaded NLL == in-memory NLL
test_direct_pack_labels_logical_zero_points raw packers label logical words 2 and round-trip
test_load_state_dict_is_idempotent_with_refilled_shard two refilled loads do not shift zeros again
test_native_writer_accepts_checkpoint_without_layout_marker, test_public_load_save_preserves_native_w4a_tensors #4171 item 2, public W4A save round-trip
test_any_runtime_layout_flag_refuses_checkpoint_write #4171 item 3 shared refusal
test_no_inverse_kernel_state_dict_contract (machete, swordfish, bitblas) #4171 item 3 inventory

All new tests fail on parent 9dad24974 except the single-file v1 case, which
the issue itself documents as unaffected.

6. Validation (CPU, OMP_NUM_THREADS=4, CUDA_VISIBLE_DEVICES=GPU-1892...)

ruff check gptqmodel docs/eora tests setup.py                       -> All checks passed!
pytest <the six related files> -k "not triton"                      -> 136 passed, 10 skipped (post-merge)
pytest tests/test_qzeros_format_invariant.py                        -> 7 passed
pytest tests/models/test_w4a_native_writer.py                       -> 21 passed, 4 skipped (NVFP4 hardware)
pytest tests/test_checkpoint_state_invariant.py                     -> 24 passed, 3 skipped
pytest tests/test_checkpoint_interop_4053.py -k "not triton"        -> 26 passed
pytest tests/test_format_conversion_flow.py tests/test_hf_packing_api.py -> 60 passed, 1 skipped
ROCm (rocm101t): the four CPU files minus the public W4A case        -> 51 passed, 6 skipped

All runs are capped (OMP_NUM_THREADS=4, MKL_NUM_THREADS=4) and pinned to one
RTX 4090 (CUDA_VISIBLE_DEVICES=GPU-1892...) or HIP_VISIBLE_DEVICES=0.
ruff-check is green on the PR.

Machete/Swordfish/BitBLAS parametrizations skip on this host (sm89 4090:
"Machete runtime unavailable", "Swordfish runtime unavailable"; bitblas not
installed). The refusal they share is executed by the CPU flag test above.

7. Reviewer notes / residual risk

…ck (#4166, #4167, #4171)

The live qzeros buffer always holds the kernel's runtime (logical/v2) zero
points, _qzeros_format records that live layout, and
_checkpoint_format_on_disk records only what a checkpoint write emits. The
v1/v2 conversion runs at the two serialization boundaries, is idempotent, and
follows the marker carried by the same incoming state dict.

#4166: accelerate with device_map=None loads a sharded checkpoint by calling
set_model_state_dict once per shard and refilling missing keys from the
module's own buffers, so the default marker made every refill convert the live
words again (+1 per shard). The load hook now converts only when the incoming
marker differs from the live layout, ignores a qzeros tensor that aliases the
live buffer when no marker travels with it, and the export shell declares its
source layout before loading with device_map={"": "cpu"}.

#4167: pack_module marked logical zeros only for FORMAT.GPTQ, so a GPTQ_V2
export kept the constructor's v1 label and the writer added one to every zero
point. Every GPTQ target format now records logical zeros, and the raw
pack()/pack_block()/pack_gpu() packers do the same.

#4171 item 1 (save_pretrained marker leak) was already fixed by #4155 and is
verified, not re-fixed. Item 2: _load_native_w4a_for_save no longer requires
the non-persisted marker in a native W4A checkpoint. Item 3: Machete, Swordfish
and BitBLAS now flag their runtime layout, and the base packed-module write
path refuses any runtime layout inside checkpoint_serialization().

Tests: load->save byte-compare for v1 single/sharded and v2, GPTQ_V2
quantize->save->reload NLL, direct pack() labelling, refilled-load
idempotency, W4A save round-trip, and the Machete/Swordfish/BitBLAS inventory
entries.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant