Skip to content

[BUG] GGUFCudaKernel (GGUF_CPP_CUDA) forward is not thread-safe: concurrent calls on one layer return wrong outputs; distinct layers on one GPU abort the process #4314

Closed

Description

@Qubitium

Severity: high. Status: confirmed by repro on an RTX 4090, with PYTHON_GIL=0 and with PYTHON_GIL=1 (ctypes releases the GIL during the call).

Where

gptqmodel/nn_modules/qlinear/gguf_cpp.py:

  • :1331-1360: GGUFCudaKernel.forward.
  • :801-835: run_quantized_matmul_cuda_plan writes plan.input_tensor, computes, then reads plan.output_tensor.
  • :479: _get_cuda_backend, one ggml CUDA backend per device, shared by every layer.
  • :1274-1296: _cuda_weight (fe09ce2).
  • :1316: _remember_cuda_plan LRU eviction.

Description

  • Each layer caches one ggml plan per batch size, with fixed input and output buffers. Every layer on a device shares one ggml CUDA backend.
  • The CUDA path takes no lock; the CPU path has _cpu_backend_lock.
  • Same layer from two threads: the threads overwrite each other's plan input and output.
  • Different layers on one GPU: the threads drive the shared backend's stream, CUDA-graph capture and memory pool at the same time, and ggml aborts.
  • Also unsynchronized, from static reading (not separately reproduced): _cuda_weight() (fe09ce2) closes every plan and frees the shared weight when the key changes, possibly while another thread is computing with it.

Repro

import sys, threading, torch
from gptqmodel.nn_modules.qlinear.gguf_cpp import GGUFCudaKernel
def make_layer(K=1024, N=512, seed=0):
    m = GGUFCudaKernel(bits="q4_k_m", group_size=-1, sym=True, desc_act=False, in_features=K, out_features=N, bias=False)
    g = torch.Generator().manual_seed(seed)
    raw = torch.randint(0, 256, m.qweight.shape, generator=g, dtype=torch.uint8)
    raw.view(N, -1, 144)[..., 0:4] = torch.tensor([1e-3, 1e-3], dtype=torch.float16).view(torch.uint8)  # d, dmin
    m.qweight.copy_(raw); return m.cuda().eval()
mode = sys.argv[1]                       # "shared" | "distinct"
layers = [make_layer(seed=i) for i in range(4)]
if mode == "shared": layers = [layers[0]] * 4
xs = [torch.randn(5, 1024, device="cuda", dtype=torch.float16) for _ in range(4)]
with torch.inference_mode(): refs = [l(x).clone() for l, x in zip(layers, xs)]
bad = []
def worker(i):
    for _ in range(200):
        with torch.inference_mode(): out = layers[i](xs[i])
        if not torch.equal(out, refs[i]): bad.append(float((out.float() - refs[i].float()).abs().max()))
ts = [threading.Thread(target=worker, args=(i,)) for i in range(4)]; [t.start() for t in ts]; [t.join() for t in ts]
print(mode, "mismatching outputs:", len(bad), "max abs diff:", max(bad) if bad else 0.0)

Actual:

  • shared: 188 of 800 outputs differ from the serial result (max abs diff 61.8). With the GIL on, 292 differ (max 56.1).
  • distinct: the process aborts with CUDA error: the operation cannot be performed in the present state in cudaStreamBeginCapture / cudaGraphLaunch. Another run aborted on GGML_ASSERT(ptr == pool_addr + pool_used) (ggml-cuda.cu:674).

Expected: concurrent forwards are bitwise identical to the serial result. That needs a per-device lock around plan build, run and weight swap, or per-thread plans and contexts.

The test used llama-cpp-python 0.3.36 with the ggml-cuda build.


Found during an AI-assisted review (Claude Code, round 11) of 842d666; repros were run at that commit on RTX 4090/5090 (CUDA 13) and/or Radeon AI PRO R9700 (ROCm) unless marked static/suspected.

Activity

  1. added
    bug
    on Nov 16, 2026
  2. Qubitium commented on Nov 16, 2026

    @Qubitium
    CollaboratorAuthor

    Taking this. I'll investigate against current main, add a targeted regression test, and open a PR. Will report back here if the claim turns out to be invalid or already fixed.

  3. self-assigned this
    on Nov 16, 2026
  4. Qubitium commented on Nov 16, 2026

    @Qubitium
    CollaboratorAuthor

    Fix PR: #4336

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

Metadata

Metadata

Assignees

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions