Repository navigation
fix(checkpoint): one qzeros layout invariant across load, save and pack (#4166, #4167, #4171) - #4235
Merged
Merged
Conversation
…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.
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.
Fixes #4166, #4167, #4171
TL;DR
One invariant, three symptoms. The live
qzerosbuffer always holds thekernel's runtime (logical/v2) zero points;
_qzeros_formatrecords only thatlive layout;
_checkpoint_format_on_diskrecords only what the next checkpointwrite 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, branchhead
a351a056bafter mergingorigin/main).1. The problem
Three defects, one missing contract:
get_model_with_quantizecalledload_checkpoint_in_model_then_tie_weightswith nodevice_map; accelerate 1.15 then runsset_model_state_dictonce per shard and refills missing keys from the module's own buffers, including the defaultqzeros_format=1markermodels/writer.py:2526,:2531_incoming_qzeros_formatfell back to the module's on-disk/constructor format, and_restore_qzeros_formatconverted again even when the incoming words were already the live buffernn_modules/qlinear/__init__.py:1608,:1637FORMAT.GPTQ_V2quantize -> save writes zeros +1pack_modulesetqzero_format(2)only when the target format wasFORMAT.GPTQ, so a v2 export kept the constructor's_qzeros_format = 1while the packer wrote logical words;checkpoint_layout_qzeros()then "converted" logical -> v1+1utils/model.py:1390,nn_modules/qlinear/__init__.py:1345pack()labels logical words v1pack_original/pack_block/pack_gpunever setqzero_format(2); onlyhf_pack_layerdidnn_modules/qlinear/__init__.pypackersexpected = set(model.state_dict())included the persistent marker, which every checkpoint writer stripsmodels/writer.py:897_is_runtime_layout()only looked at_marlin_repacked/_native_shuffled/_awq_repacked; Machete and Swordfish set none of themnn_modules/qlinear/__init__.py:1117Old 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:#b02a372. 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:#b8860bEmission stays a pure copy:
checkpoint_layout_qzeros()returns a convertedcopy for the target
checkpoint_formatand never mutates the live buffer.The export shell used by
save()now declares the source layout before loadingand passes
device_map={"": "cpu"}, so each tensor is loaded exactly once evenif a future accelerate build changes the
device_map=Nonepath.3. Per-issue evidence
#4166 — load -> save corrupts qzeros
Repro: synthetic 1-layer Llama, CPU
TorchLinear(REQUIRES_FORMAT_V2), shardedv1 built by splitting the safetensors into two files (one holds q/k/v, the other
the rest).
load().save()2004318071(0x77777777)20043180712004318071(0x77777777)-2004318072(0x88888888)-1717986919(0x99999999)-1431655766(0xAAAAAAAA)-1717986919(0x99999999)-1145324613(0xBBBBBBBB)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:9dad24974:6 failed, 1 passed— the one pass is the single-file v1case, which the issue also reports as unaffected.
7 passed.#4167 —
FORMAT.GPTQ_V2writes zeros +1Synthetic 1-layer Llama, CPU
TorchLinear,sym=False,group_size=32,QuantizeConfig(..., format=...), quantize -> save -> reload.gptqgptq_v2In-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 leavesqzero_format() == 1for logical words and fails with "the packer wrotelogical 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_formatinsave_pretrained()Already fixed by #4155; verified, not re-fixed. On base
9dad24974,GPTQModel.load(...).model.save_pretrained(out)wrote 33 tensors with zero*.qzeros_formatkeys, and the existingtests/test_checkpoint_interop_4053.py::test_save_pretrained_key_set_matches_savepasses. The invariant keeps that behavior:
_write_state_dict_layout_markerstill pops the key inside
checkpoint_serialization().#4171 item 2 — W4A re-save always raised
Parent:
_load_native_w4a_for_savenow excludes the non-persisted marker fromexpected. 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_tensorswas already red onparent for this same reason (
4 failed), and the whole file is green here(
21 passed, 4 skipped; the skips are NVFP4 hardware). New testtest_native_writer_accepts_checkpoint_without_layout_markercoversw4afp8and
w4a_nvfp4, single-file and sharded: parent4 failedwith the exactValueErrorfrom the issue, this PR4 passed.#4171 item 3 — runtime-layout refusal missed Machete/Swordfish
MacheteLinear.post_initand both Swordfishpost_initpaths now set_native_shuffled = Trueafter prepackingqweightand rewritingqzerosinto float offsets.
BitblasLinear.repack_from_gptqandAWQBitBlasKernel.repack_from_awqsetthe same flag after
_load_bitblas_quant_statereplaces the payload.PackedGroupedQuantLinear._save_to_state_dictnow refuses any_is_runtime_layout()module insidecheckpoint_serialization(), so a kernelonly has to raise the flag, not re-implement the guard.
source of truth and derives non-persistent
*_packedbuffers, so it isdocumented as safe rather than refused.
test_any_runtime_layout_flag_refuses_checkpoint_write(CPU): parentFailed: DID NOT RAISE RuntimeError; this PR passes, and the read-onlystate_dict()still labels the payloadqzeros_format=0.tests/test_checkpoint_state_invariant.py::_no_inverse_casesgainsmachete,swordfishandbitblasentries.4. Change inventory
gptqmodel/nn_modules/qlinear/__init__.pyqzero_format(2)gptqmodel/models/writer.pydevice_map={"": "cpu"}, exclude the marker from the W4A expected setgptqmodel/utils/model.pymachete.py,swordfish.py,bitblas.py,bitblas_awq.pydocs/checkpoint-interop.mdtests/test_qzeros_format_invariant.py(new),tests/models/test_w4a_native_writer.py,tests/test_checkpoint_state_invariant.py,tests/test_checkpoint_interop_4053.py5. Tests
test_load_then_save_preserves_qzeros_bytes(v1/v2, single/sharded)load().save()test_gptq_v2_quantize_save_reload_matches_v1test_direct_pack_labels_logical_zero_pointstest_load_state_dict_is_idempotent_with_refilled_shardtest_native_writer_accepts_checkpoint_without_layout_marker,test_public_load_save_preserves_native_w4a_tensorstest_any_runtime_layout_flag_refuses_checkpoint_writetest_no_inverse_kernel_state_dict_contract(machete, swordfish, bitblas)All new tests fail on parent
9dad24974except the single-file v1 case, whichthe issue itself documents as unaffected.
6. Validation (CPU,
OMP_NUM_THREADS=4,CUDA_VISIBLE_DEVICES=GPU-1892...)All runs are capped (
OMP_NUM_THREADS=4,MKL_NUM_THREADS=4) and pinned to oneRTX 4090 (
CUDA_VISIBLE_DEVICES=GPU-1892...) orHIP_VISIBLE_DEVICES=0.ruff-checkis green on the PR.Machete/Swordfish/BitBLAS parametrizations skip on this host (
sm894090:"Machete runtime unavailable", "Swordfish runtime unavailable";
bitblasnotinstalled). The refusal they share is executed by the CPU flag test above.
7. Reviewer notes / residual risk
sym=Falseoverflow case from [BUG] Quant accuracy: AWQ dense layers scale-search on only the last calibration sample (+ down_proj silently RTN) so AWQ == RTN; EXL3 still crashes under default auto_nf12 (#4006 bypass); in-memory model after quantize uses v1 qzeros as v2 (garbage generate) #4063 is unaffected._incoming_qzeros_is_live()is a storage-identity check (data_ptr). Acaller who hands a module a
qzerostensor that literally aliases the livebuffer with no marker cannot be distinguished from accelerate's refill; that
is intentional — such a load is a no-op.
state_dict()transports(required by [BUG] Follow-up on #4103/#4110: HF save_pretrained on ExLlamaV2/Marlin no longer refuses and writes runtime layout (reload = garbage, regression), AWQ CPU kernels still serialize int4pack, v1<->v2 copy lost via safetensors, per-document mask never built #4125 item 3); only checkpoint writes strip it. A third-party
loader that consumes raw
state_dict()output will still see it, which isthe pre-existing contract.
format=FORMAT.GPTQ_V2saves zero points +1 (model accuracy destroyed) #4167's 0.5B NLL numbers were not reproduced offline; the byte-level andtoy-NLL evidence above is what this host can measure.