Skip to content

[BUG] CPU AUTO kernels (TorchAten/TorchFused/TorchCpuAvx512, GPTQ+AWQ) repack weights on first forward without a lock: concurrent first forward crashes and can corrupt the module permanently #4565

Closed

Description

@Qubitium

Found on main @ 4b65923, CPU only (x86-64 with AVX512-BF16, torch 2.15 CPU path, CPython 3.14t). It reproduces with both PYTHON_GIL=0 and PYTHON_GIL=1.

What is wrong

The CPU kernels that AUTO selects for GPTQ and AWQ checkpoints do a one-time, in-place weight repack on the first forward, and nothing guards it against concurrent callers:

  • TorchAtenLinear.forward (nn_modules/qlinear/torch_aten_kernel.py:452-469): it checks self.linear_mode is None, then calls transform() → transform_cpu() (:396-438), which overwrites self.qweight with int4pack words, self.qzeros with float offsets and scales_and_zeros, and only then sets _cpu_transformed = True / linear_mode = "inference".
  • The same check-then-act pattern is in TorchFusedLinear.forward (torch_fused.py:512-529), TorchAtenAwqLinear (torch_aten_kernel_awq.py:346-363), TorchFusedAwqLinear (torch_fused_awq.py:430-450), TorchCpuAvx512AwqLinear (torch_cpu_avx512_awq.py:275-285), and TorchCpuAvx512Linear.

When two threads run the first forward of the same model at once (for example concurrent generate() on one loaded model, which free-threaded builds encourage), thread B reads qweight/qzeros while thread A is replacing them. B then either crashes on the half-converted tensors or repacks the already-packed words a second time. In the second case the module is left permanently corrupted: every later forward fails, even a single-threaded one.

The repo already treats a concurrent post-load first forward as supported for ExLlamaV2 (exllamav2.py:_ensure_q_handle: "A post-load first forward can run from several free-threaded workers. Serialize only this cold rebuild"). The CPU kernels have no equivalent.

Repro

Uses a GPTQ 4-bit g128 checkpoint of Qwen2.5-0.5B-Instruct that I quantized with GPTQModel (an AWQ one shows the same). Run on CPU (CUDA_VISIBLE_DEVICES=):

import sys, threading, torch
from gptqmodel import GPTQModel, BACKEND
ck, backend, dtype = sys.argv[1], sys.argv[2], getattr(torch, sys.argv[3])
T = 8
def load():
    return GPTQModel.load(ck, backend=getattr(BACKEND, backend), device="cpu", dtype=dtype)
ref_m, m = load(), load()
x = torch.randint(100, 5000, (1, 16))
with torch.inference_mode():
    ref = ref_m.model(x).logits            # serial first forward on a separate copy
print("kernel:", type(m.model.model.layers[0].mlp.down_proj).__name__)
errors, barrier = [], threading.Barrier(T)
def run():
    barrier.wait()
    try:
        with torch.inference_mode():
            m.model(x)                       # concurrent first forward of the same model
    except Exception as e:
        errors.append(f"{type(e).__name__}: {e}"[:120])
ts = [threading.Thread(target=run) for _ in range(T)]
[t.start() for t in ts]; [t.join() for t in ts]
print("concurrent first forward errors:", len(errors), "of", T, errors[:2])
try:
    with torch.inference_mode():
        out = m.model(x).logits              # later serial forward
    print("serial forward after: max |diff| vs reference =", (out - ref).abs().max().item(), "equal:", torch.equal(out, ref))
except Exception as e:
    print("serial forward after FAILED:", f"{type(e).__name__}: {e}"[:200])

Output (each line was reproduced in every run, 2/2 for the first case):

== gptq AUTO float16  (PYTHON_GIL=0, and the same with PYTHON_GIL=1)
kernel: TorchAtenLinear
concurrent first forward errors: 7 of 8 ['NotImplementedError: "rshift_cpu" not implemented for \'Half\'', 'RuntimeError: _weight_int4pack_mm_cpu : expect B.size(1) to be K/2, got 512']
serial forward after FAILED: RuntimeError: _weight_int4pack_mm_cpu : expect B.size(1) to be K/2, got 512      <- module permanently broken
== gptq GPTQ_TORCH_FUSED bfloat16
kernel: TorchFusedLinear
concurrent first forward errors: 7 of 8 ['NotImplementedError: "rshift_cpu" not implemented for \'Float\'', ...]
serial forward after FAILED: RuntimeError: _weight_int4pack_mm_cpu: expect qScaleAndZeros to be 3d tensor with sizes [:, 448, 2]   <- permanently broken
== gptq AUTO bfloat16
kernel: TorchCpuAvx512Linear
concurrent first forward errors: 7 of 8 ['RuntimeError: qweight must be int32', ...]
== awq AUTO float16
kernel: TorchAtenAwqLinear
concurrent first forward errors: 7 of 8 ["RuntimeError: shape '[7, 4864]' is invalid for input of size 25088", 'IndexError: index 14592 is out of bounds for dimension 0 with size 896']
== awq AUTO bfloat16
kernel: TorchCpuAvx512AwqLinear
concurrent first forward errors: 7 of 8 ['RuntimeError: qweight must be int32', ...]
== awq AWQ_TORCH_FUSED bfloat16
kernel: TorchFusedAwqLinear
concurrent first forward errors: 7 of 8 ['NotImplementedError: "rshift_cpu" not implemented for \'Float\'', ...]
== control: gptq GPTQ_TORCH bfloat16 (no lazy transform)
kernel: TorchLinear
concurrent first forward errors: 0 of 8 []
serial forward after: max |diff| vs reference = 0.0 equal: True

A kernel-level stress test that calls distinct modules from 8 threads gives the same result: TorchLinear has 0/504 mismatches, while TorchAtenLinear and TorchFusedLinear raise in 6-7 of 8 threads.

Suggested fix

Make the one-time transform single-flight per module. Add a per-instance lock (or one class-level lock, which is cheap because this runs once per module). Under the lock, re-check linear_mode / _cpu_transformed, run transform(), and publish linear_mode = INFERENCE last. Readers that see linear_mode == INFERENCE then always see the finished tensors. This is the same pattern as ExllamaV2Linear._ensure_q_handle. Alternatively, do the transform eagerly in post_init() when the module is on CPU in eval mode, so that the forward never mutates state.

Which test should have caught it

None today: the CPU kernel tests (tests/kernels/test_torch_fused*.py, tests/test_concurrency_guards.py) only exercise single-threaded first forwards. A test that runs the first forward of one module from N threads behind a barrier and compares the result with a serial copy would catch this.

Severity

Medium-high. With the default AUTO kernel on CPU, concurrent inference on a freshly loaded model crashes, and in the GPTQ fp16 and TorchFused bf16 cases it leaves the model permanently unusable until it is reloaded.

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Claimed. This issue is now owned by a dedicated worker; a fix PR referencing it will follow.

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