Skip to content

[BUG] CPU int4pack kernels: state_dict() concurrent with the first forward raises 'dictionary changed size during iteration' (GIL on) or returns the runtime uint8 qweight / drops keys (GIL=0); #4600 lock not taken by state_dict #4788

Closed

Description

@Qubitium

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() calls module.register_buffer(...) for each snapshot tensor (gptqmodel/nn_modules/qlinear/_fused_train_state.py:141).
  • The transform rebinds qweight, qzeros and scales_and_zeros (for example torch_aten_kernel.py:437).
  • finalize_fused_train_state() pops the qweight clone 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_dict iterates self._buffers while 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.
  • qweight emitted as the runtime int4pack uint8 [896, 448] tensor instead of the checkpoint int32 [112, 896], or with qzeros/scales/bias missing. This needs a window between _buffers.pop and snapshot[name] = descriptor (or before the snapshot is published while qweight is already rebound). It was seen with PYTHON_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_lock in PackedGroupedQuantLinear._save_to_state_dict (and in _load_from_state_dict / restore_fused_train_state). It is already an RLock.
  • Or build the new _buffers dict 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

  1. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Claiming. Will take _cpu_transform_lock in _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 to tests/test_cpu_lazy_transform_concurrency_4565.py.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions