Skip to content

[BUG] VPTQLinear (VPTQ_TORCH, AUTO on ROCm) under free-threaded Python: concurrent first forwards from several threads return silently wrong outputs (rel err up to 5.7) - per-module compiled dequantize; clean with the GIL or TORCH_COMPILE_DISABLE=1 #5228

Closed

Description

@Qubitium

Found on main @ 396b5f0, AMD Radeon AI PRO R9700 (gfx1201), torch 2.16.0.dev+rocm10.1, CPython 3.14t (free-threaded) with PYTHON_GIL=0, which GPT-QModel advertises ("Python GIL is disabled and GPT-QModel will auto enable ...").

What is wrong

VPTQLinear.post_init() calls optimize(), which replaces each module's bound self.dequantize with a torch_compile() wrapper (gptqmodel/nn_modules/qlinear/vptq_torch.py:301-323). Every VPTQ layer therefore runs its own compiled wrapper of the same code object (VPTQLinear.dequantize), and dynamo traces and guards that code object per module on first use. _install_callable_compile_fallback (gptqmodel/utils/torch.py) serializes only the first call of each wrapper, under model_global_state_lock(). It does not serialize a module's first trace against compiled calls of the other modules that share that code object and run concurrently on other threads.

When several threads, each on its own stream, make the first forwards through a freshly loaded VPTQ model, some layers return finite but completely wrong outputs, with relative error 1-6 against the same module run single-threaded right afterwards. Nothing raises. This is the normal pattern for a multi-threaded server warming up, or for concurrent requests right after a load. VPTQ_TORCH is the AUTO kernel for VPTQ on ROCm, and an explicit BACKEND.VPTQ_TORCH selects it on CUDA.

Repro

QwenL2_vptq is Qwen2.5-0.5B-Instruct (2 layers) quantized with VPTQConfig(). Each run uses fresh Triton and inductor cache dirs.

import threading, sys, torch
from gptqmodel import GPTQModel, BACKEND
T, LOADS = 4, 6
torch.manual_seed(0); xs = None; bad = total = 0
for load in range(LOADS):
    m = GPTQModel.load(ckpt, backend=BACKEND.VPTQ_TORCH, dtype=torch.float16)
    mods = [x for _, x in sorted(m.model.named_modules()) if type(x).__name__ == "VPTQLinear"]
    if xs is None:
        xs = [[torch.randn(1, q.in_features, device="cuda", dtype=torch.float16) for q in mods] for _ in range(T)]
    outs = [[None] * len(mods) for _ in range(T)]
    barrier = threading.Barrier(T)
    def work(t):
        s = torch.cuda.Stream()
        with torch.inference_mode(), torch.cuda.stream(s):
            barrier.wait()
            for i, q in enumerate(mods):          # first forward of every layer, concurrently
                outs[t][i] = q(xs[t][i])
        s.synchronize()
    th = [threading.Thread(target=work, args=(t,)) for t in range(T)]
    [x.start() for x in th]; [x.join() for x in th]
    with torch.inference_mode():                  # same modules, same inputs, single thread
        for t in range(T):
            for i, q in enumerate(mods):
                ref = q(xs[t][i]); total += 1
                rel = ((outs[t][i] - ref).abs().max() / ref.abs().max()).item()
                if rel > 0.05:
                    bad += 1; print(f"load {load} thread {t} VPTQLinear #{i}: rel err {rel:.2f}")
print(f"GIL enabled: {sys._is_gil_enabled()}  wrong outputs: {bad}/{total}")
PYTHON_GIL=0:
load 0 thread 0 VPTQLinear #7: rel err 5.18
load 0 thread 2 VPTQLinear #8: rel err 1.11
GIL enabled: False  wrong outputs: 2/336
PYTHON_GIL=1:
GIL enabled: True  wrong outputs: 0/336

A broader harness covered every quant module at M in {1, 7, 64}, each thread on its own stream, with 3-4 fresh loads per run and the threaded pass first in a cold process:

config runs runs with wrong outputs (rel > 5%) worst rel
PYTHON_GIL=0, 4 threads 4 4 (3-10 wrong outputs each) 5.7
PYTHON_GIL=0, 8 threads 2 2 (11, 13 wrong outputs) -
PYTHON_GIL=1, 4 threads 2 0 1-ulp diffs only
PYTHON_GIL=0 + TORCH_COMPILE_DISABLE=1 1 0 (bitwise) 0

Wrong outputs show up in later fresh loads too, not only the very first trace in the process. The same harness is clean under PYTHON_GIL=0 for every other ROCm kernel: AWQ GEMM/GEMV Triton, GEMV_FAST Torch, BnB Triton, GGUF Triton, GPTQ Torch, MACaQ Triton, QQQ Torch, EXL3 Torch, and Paro Triton (1-ulp plan-autotune differences only). None of those compile per module.

Suggested fix

  • Do not compile a bound method per module. Compile one module-independent function, _vptq_dequantize(indices, centroids, ..., shapes), with the tensors passed as arguments, so one graph serves every layer and no per-module trace/guard happens on the serving path.
  • Alternatively, under free-threading, hold the compile lock for every call of the wrapper until all modules sharing the code object have traced (or skip the lazy compile entirely when has_gil_disabled()).
  • Add a free-threaded concurrent first-forward test for every kernel that compiles in post_init.

Severity

High under free-threaded Python: silent wrong outputs (no error) during concurrent warm-up of any VPTQ model on ROCm. The round-18 ROCm audit saw this intermittently and could not confirm it. It reproduces reliably once the Triton and inductor caches are cold.

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim released: agent-fb5145b84190 finished this issue.

    Pull request: #5244

    Free-threaded Python is the local default here; will reproduce the concurrent first-forward race with VPTQ_TORCH and fix the per-module compiled dequantize path.

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