Repository navigation
[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
Description
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:
from_quantizedcallstorch._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 alreadyoptimize()d and the user's owntorch.compilefunctions. 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.- 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'spreserve_global_staterestores 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()fromfrom_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._dynamoframe 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 explicitdtype=and noset_default_dtypewindow.
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
Qubitium commentedon Nov 18, 2026
Additional data: the free-threaded build is affected too. With Python 3.14t,
PYTHON_GIL=0, the same repro (warmoptimize()dBACKEND.TORCHmodel forwarding in one thread whileGPTQModel.load(..., dtype=torch.bfloat16)loops in another) ends withFatal Python error: Segmentation fault, rc=139, on the first run.🤖 Generated with Claude Code
Qubitium commentedon Nov 18, 2026
Agent claim:
agent-4e3a0639ecafis 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
Qubitium commentedon Nov 18, 2026
Agent claim released:
agent-4e3a0639ecaffinished this issue.PR: #5251 — base
main, head117bdaaa7(branchfix/5209-compile-load-race), 5 files, +502/−75.Fix
state["compiled"]is gone from both the callable and module fallback proxies, because any call can re-trace when its guards change. The lock is re-entrant, so nested calls stay cheap.from_quantizedno longer callstorch._dynamo.reset(): a load must not wipe every compiled frame in the process (including other models still serving). Dropped models' trace cycles are reclaimed byrelease_compile_trace_garbage([MEM] #4986 (fix of #4937) incomplete: after optimize() + generate(), GPTQ_TRITON/GPTQ_TORCH models still keep 0.96/0.47 GiB VRAM until gc.collect() (dynamo graph-break trace state cycles); PR test is an 8x8 CPU Linear #5020), and the bf16 default-dtype window is serialized through the same lock.Evidence
mainmainmodel load left a corrupted state: torch.get_default_dtype() changed from torch.float32 to torch.bfloat16errors=[] dtype=torch.float32, repeated ×4New
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.mdanddocs/concurrency.mdupdated.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).
fix(compile): serialize every compiled call with model loads (#5209) (#…
fix(compile): hold the model-global lock only for the dtype window (#…
fix(load): hold the global-state writer only for the default-dtype wi…
fix(load): hold the global-state writer only for the default-dtype wi…