Repository navigation
Description
Found on main @ dba142d, CPU (Xeon, AVX512-BF16), CPython 3.12 (GIL) and 3.14t (PYTHON_GIL=0).
What is wrong
The CPU int4pack kernels (TorchAtenLinear, TorchFusedLinear, TorchCpuAvx512Linear and the AWQ variants) restructure the module on its first forward:
capture_fused_train_state()callsmodule.register_buffer(...)for each snapshot tensor (gptqmodel/nn_modules/qlinear/_fused_train_state.py:141).- The transform rebinds
qweight,qzerosandscales_and_zeros(for exampletorch_aten_kernel.py:437). finalize_fused_train_state()pops theqweightclone and then swaps in the rebuild descriptor (_fused_train_state.py:195-196, from fix(cpu-int4): rebuild checkpoint qweight instead of keeping a clone (#4395) #4532).
#4600 (the fix for #4565) wraps all of this in _cpu_transform_lock (torch_aten_kernel.py:457, torch_fused.py:530), so two forwards are serialized. state_dict() does not take that lock:
nn.Module._save_to_state_dictiteratesself._bufferswhile the forward adds to it and pops from it._write_fused_train_state_snapshot(qlinear/__init__.py:1357) reads the snapshot while it is half built.
So a state_dict() / save / get_peft_model_state_dict running on another thread while the model serves its first request either raises or returns wrong checkpoint tensors:
RuntimeError: dictionary changed size during iteration. This happens with the GIL enabled too, in about 25% of first forwards.qweightemitted as the runtime int4packuint8 [896, 448]tensor instead of the checkpointint32 [112, 896], or withqzeros/scales/biasmissing. This needs a window between_buffers.popandsnapshot[name] = descriptor(or before the snapshot is published whileqweightis already rebound). It was seen withPYTHON_GIL=0.
A state dict taken at that moment and saved through safetensors is a corrupt checkpoint. Its qzeros_format marker still says 2, so it is not detected on reload.
Repro (Qwen2.5-0.5B-Instruct truncated to 4 layers, GPTQ 4-bit g128 and AWQ 4-bit g128, loaded on CPU)
import threading, copy, collections, torch
from gptqmodel import GPTQModel, BACKEND
from gptqmodel.nn_modules.qlinear import BaseQuantLinear
q = GPTQModel.load(CKPT, backend=BACKEND.GPTQ_TORCH_ATEN, dtype=torch.bfloat16, device="cpu")
base = next(m for m in q.model.modules() if isinstance(m, BaseQuantLinear)) # q_proj 896x896
ref = {k: v.clone() for k, v in base.state_dict().items()}
x = torch.randn(2, base.in_features, dtype=torch.bfloat16)
errs, bad = collections.Counter(), collections.Counter()
for _ in range(300):
m = copy.deepcopy(base); stop = threading.Event(); go = threading.Barrier(3)
def hammer():
go.wait()
while not stop.is_set():
try: sd = m.state_dict()
except Exception as e: errs[f"{type(e).__name__}: {e}"] += 1; continue
for k, v in ref.items():
w = sd.get(k)
if w is None: bad[f"{k} missing"] += 1
elif w.dtype != v.dtype or w.shape != v.shape: bad[f"{k} {w.dtype}{tuple(w.shape)} != {v.dtype}{tuple(v.shape)}"] += 1
elif not torch.equal(w, v): bad[f"{k} values differ"] += 1
th = [threading.Thread(target=hammer) for _ in range(2)]; [t.start() for t in th]
go.wait()
with torch.inference_mode(): m(x) # first forward -> int4pack transform
stop.set(); [t.join() for t in th]
print("ERRORS", dict(errs)); print("BAD", dict(bad))Output (300 first forwards each):
| kernel | Python | errors | wrong / missing tensors in the returned state dict |
|---|---|---|---|
| TorchAtenLinear (GPTQ) | 3.12, GIL | dictionary changed size during iteration x80 |
0 |
| TorchAtenLinear (GPTQ) | 3.14t, GIL=0 | x77 | qweight torch.uint8(896, 448) != torch.int32(112, 896): 4 |
| TorchFusedAwqLinear | 3.14t, GIL=0 | x42 | qweight torch.uint8(896, 448) != torch.int32(896, 112): 3; qzeros, scales, bias missing: 1 each |
| TorchCpuAvx512Linear (CPU AUTO) | 3.14t, GIL=0 | x74 | 0 |
Every state dict taken after the first forward is correct, as are the forward outputs (bitwise equal to serial). Only the overlap window is affected.
Suggested fix
Make the first-forward transform atomic with respect to readers:
- Take
_cpu_transform_lockinPackedGroupedQuantLinear._save_to_state_dict(and in_load_from_state_dict/restore_fused_train_state). It is already an RLock. - Or build the new
_buffersdict and snapshot off to the side and publish them with a single assignment, so no reader ever sees a partially transformed module.
In finalize_fused_train_state, assign snapshot[name] = descriptor before popping the clone buffer.
Test that should have caught it
tests/test_cpu_lazy_transform_concurrency_4565.py covers forward vs. forward only. Add a case that runs state_dict() in a loop on another thread while each module's first forward runs, and asserts that no exception is raised and that every returned tensor equals the checkpoint tensors.
Severity
Medium. Concurrent state_dict()/save while serving, or while a training callback runs, can crash with the GIL enabled. Under free-threading it can silently produce a corrupt checkpoint (runtime int4pack words written under the checkpoint qweight key, or tensors dropped).
🤖 Generated with Claude Code
Activity
Qubitium commentedon Nov 17, 2026
Claiming. Will take
_cpu_transform_lockin_save_to_state_dict/_load_from_state_dict(and publish the fused snapshot before popping the clone), then add a state_dict-vs-first-forward concurrency regression test totests/test_cpu_lazy_transform_concurrency_4565.py.fix(qlinear): serialize state_dict with the CPU int4pack cold transfo…
fix(paro): keep one packed CPU layout per layer (#4814) (#4832)