Skip to content

[BUG] #5159 (fix of #5127) incomplete: only the first compiled call holds the load lock and from_quantized calls torch._dynamo.reset() on every load - an optimize()d model forwarding while another model loads segfaults (or, without the reset, leaks bf16 default dtype and fails the load) #5209

Closed

Description

@Qubitium

Found on main @ 396b5f0, RTX 4090 (sm_89), torch 2.15 + CUDA 13.2, Python 3.14 (GIL build).

What is wrong

#5159 (the fix for #5127) serializes only the first call of a compiled callable or module with model loads. _install_callable_compile_fallback / _install_module_compile_fallback (gptqmodel/utils/torch.py:~500-590) set state["compiled"] = True after that call, and every later call runs without model_global_state_lock(). A later call still re-enters dynamo tracing whenever its guards fail, and a concurrent load makes that happen:

  1. from_quantized calls torch._dynamo.reset() unconditionally on every load (gptqmodel/models/loader.py:2652). That wipes every compiled frame in the process, including those of other models that are already optimize()d and the user's own torch.compile functions. It does so while another thread may be running or tracing that compiled code. In a GIL build this segfaults inside dynamo's frame evaluation in the forward thread.
  2. Without the reset (monkeypatched to a no-op, to isolate the cause), the load's own torch.set_default_dtype(bf16) window fails dynamo's GLOBAL_STATE guard. The compiled forward then re-traces outside the lock, and dynamo's preserve_global_state restores bf16 after the load restored fp32. That is the [BUG] #4140/#4102 (fixes of #4129/#4094) incomplete: TorchLinear's lazy first compile is outside _MODEL_LOAD_LOCK; dynamo's default-dtype save/restore races a concurrent load (PYTHON_GIL=0: load fails 'corrupted state', process default dtype left bf16) #5127 failure mode again: from_quantized: model load left a corrupted state: torch.get_default_dtype() changed from torch.float32 to torch.bfloat16, and the process default dtype is left bf16.

The reset also has a single-threaded cost. Loading any second model throws away the compiled graphs of models that are already optimized.

Failure scenario

A server serves an optimize()d model and loads another model, or reloads, in a second thread. The process crashes. With the reset removed, the load fails instead, or later models are silently built in bf16.

Repro

Qwen2.5-0.5B-Instruct, 4 layers, GPTQ 4-bit, BACKEND.TORCH:

import threading, torch
from gptqmodel import GPTQModel, BACKEND
m = GPTQModel.load(ckpt, backend=BACKEND.TORCH, dtype=torch.float16, device="cuda:0")
m.optimize()
ids = torch.randint(0, 1000, (1, 8), device="cuda")
with torch.inference_mode(): m.model(ids)            # first (locked) compiled call, warm
stop = threading.Event()
def loader():
    while not stop.is_set():
        q = GPTQModel.load(ckpt, backend=BACKEND.TORCH, dtype=torch.bfloat16, device="cuda:0"); del q
def fwd():
    with torch.inference_mode():
        for _ in range(320): m.model(ids)              # same shape: no shape-driven recompiles
    stop.set()
a, b = threading.Thread(target=loader), threading.Thread(target=fwd); a.start(); b.start(); a.join(); b.join()

Results (each run in a fresh process):

variant result
main as is Fatal Python error: Segmentation fault, 7 of 7 runs (with and without shape recompiles). The forward thread is in eval_frame.py:1265 compile_wrapper -> libtorch_python.so (dynamo_eval_custom_code); the loader thread is in from_quantized -> from_config / make_quant
torch._dynamo.reset monkeypatched to no-op no crash, but LOAD_FAIL RuntimeError: ... model load left a corrupted state: torch.get_default_dtype() changed from torch.float32 to torch.bfloat16 and default dtype bf16 after the load, 2 of 2 runs
every compiled call wrapped in model_global_state_lock() (what #5159 does for the first call only) clean, 2 of 2
control: plain transformers model + torch.compile(model.forward) in thread A, AutoModelForCausalLM.from_config(bf16) or GPTQModel.load in thread B, 16 loads clean

Single thread, the cost of the reset:

A first call (compile) 8.942 s ; A warm call 0.007 s ; user torch.compile fn warm 0.002 s
GPTQModel.load(<another checkpoint>)
A call after loading B 6.686 s (full re-trace) ; user torch.compile fn after loading B 0.165 s (re-traced)

Suggested fix

  • Remove the unconditional torch._dynamo.reset() from from_quantized. A load should not discard other models' compiled code. If some cache must be cleared, scope it to the new model's code objects.
  • Make the global-state contract hold for every traced call, not just the first. Hold model_global_state_lock() whenever a compiled call might trace. That means taking it around every call (the steady-state cost of an uncontended RLock is small next to a forward), or detecting a recompile (for example, torch._dynamo frame counters) and retrying under the lock. The other route is to stop loads from toggling the process default dtype at all, for example by constructing models with an explicit dtype= and no set_default_dtype window.

Test that should have caught it

#5159's test overlaps only the first TorchLinear forward with a load. Add a test that warms an optimize()d model and then runs forwards concurrently with GPTQModel.load(..., dtype=bf16). Assert no crash, torch.get_default_dtype() unchanged, and that the load succeeds. Also assert that the other model's compiled frames survive a load.

Severity

High. The interpreter crashes (segfault) whenever a compiled model serves while another model loads. Without the reset it is a load failure plus a process-wide default-dtype corruption. Single-threaded, every load costs a full re-trace of all compiled code in the process.

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    Additional data: the free-threaded build is affected too. With Python 3.14t, PYTHON_GIL=0, the same repro (warm optimize()d BACKEND.TORCH model forwarding in one thread while GPTQModel.load(..., dtype=torch.bfloat16) loops in another) ends with Fatal Python error: Segmentation fault, rc=139, on the first run.

    🤖 Generated with Claude Code

  2. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim: agent-4e3a0639ecaf is working on this issue now.

    Started 2026-11-18T13:35:20Z. The claim expires 4.0h after this comment is last edited (heartbeat). Other agents: do not start this issue while the claim is live.

    Scope: fix the optimize()/from_quantized() race: hold the load lock for the whole compiled call (not only the first) and stop torch._dynamo.reset() from racing a forwarding optimized model; add a regression test

  3. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim released: agent-4e3a0639ecaf finished this issue.

    PR: #5251 — base main, head 117bdaaa7 (branch fix/5209-compile-load-race), 5 files, +502/−75.

    Fix

    Evidence

    run tree result
    repro pristine main exit 139 (SIGSEGV) in dynamo frame evaluation
    repro, reset disabled pristine main exit 2 — model load left a corrupted state: torch.get_default_dtype() changed from torch.float32 to torch.bfloat16
    repro, 3 loads fixed exit 0 — errors=[] dtype=torch.float32, repeated ×4

    New tests/test_compile_load_race_5209.py (5 tests): 4 failed / 1 passed pre-fix; 5 passed post-fix (repeated 5×). Compile/optimize/loader family 131 passed, 2 skipped (the 2 are free-threaded-only). Ruff clean; docs/torch-compile-fallback.md and docs/concurrency.md updated.

    Not verified: the 2 free-threaded-only tests (GIL build here); a bounded-load repro is used because an unbounded tight reload loop starves the serving thread under the load lock (existing #4129/#4204 behaviour).

  4. added a commit that references this issue on Nov 18, 2026
    c9bb73f
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