Repository navigation
[PERF] Regression from #5251 (fix of #5209): every compiled call holds the process-wide model-load RLock - concurrent optimize()d/TorchLinear decode serialized (GIL=0 2-thread agg 141 -> 92 tok/s, below 1 thread) and every compiled forward stalls for the whole duration of any concurrent load/save #5268
Description
Found on main @ c1807f8, RTX 4090 (sm_89), torch 2.15 + CUDA 13.2, CPython 3.14t (PYTHON_GIL=0) and 3.14 (GIL).
What is wrong
#5251 (fix of #5209) wraps every compiled call in model_global_state_lock(), which is the process-wide _MODEL_LOAD_LOCK RLock:
gptqmodel/utils/torch.py:558:_install_callable_compile_fallback.call. This covers everyTorchLinear.dequantize_weightcall.TorchLinear.post_init()compiles it by default, so the lock is taken on every forward of every TorchLinear layer.gptqmodel/utils/torch.py:622:_install_module_compile_fallback.forward, and theoptimize()d model forward. The lock is held for the entire model forward.
The same lock is held by from_pretrained / from_quantized for the whole load (_serialized_model_load, models/loader.py:1568), by the save-side shell rebuild (writer.py:2741), and by the dequant and TT paths.
That has two consequences:
- Concurrent inference is serialized process-wide. Two threads serving two different models (or the same model) can no longer run compiled forwards at the same time. Under free-threaded Python, two decode threads now get less total throughput than one thread alone.
- Every compiled forward stalls for the full duration of any load or save in another thread. A server that loads or saves a second model blocks every in-flight
optimize()d / TorchLinear request until that load returns, which can take minutes for a large checkpoint.
docs/concurrency.md:242 and docs/torch-compile-fallback.md say "the steady-state cost is one uncontended re-entrant acquire". That holds only for a single-threaded process. With a second thread the lock is contended on every call.
Measurements
Setup: Qwen2.5-0.5B-Instruct-gptq-4bit, backend=BACKEND.TORCH, device cuda:0, greedy KV-cache decode of 200 steps per thread with a cuda.synchronize() per step. Old = 11f9cb369 (the parent of #5251). The GPU was shared with another light job, so the old/new runs were interleaved.
Two threads, each decoding its own model (aggregate tokens/s):
| build | path | old alone | old 2 threads (agg) | new alone | new 2 threads (agg) |
|---|---|---|---|---|---|
| 3.14t GIL=0 | TorchLinear (default compiled dequantize_weight) |
28.0 / 26.9 | 30.2 / 28.1 | 24.0 / 27.1 | 20.1 / 20.6 |
| 3.14t GIL=0 | model.optimize() |
120.1 | 141.0 (86.5 per thread) | 148.0 | 91.7 (51.7 per thread) |
With optimize(), adding a second serving thread on main cuts total throughput to 0.62x of one thread. Before #5251 the second thread added throughput (1.17x).
Decode thread running while another thread does GPTQModel.load(<same ckpt>, backend=MARLIN) (warm kernel cache), max per-step latency:
| build | old | new |
|---|---|---|
| 3.14t GIL=0 | 1.37 s (load 3.7 s) | 4.07 s / 5.06 s = the whole load (4.0 s / 5.0 s) |
| 3.14 GIL | 1.4-3.0 s | 3.3 s (load 3.2 s) |
On a cold extension cache the load took 92-114 s, and the decode thread stalled for exactly that long (max_ms 92181 / 113856). Default dtype stayed fp32 in every run, so the #5209 correctness fix itself holds. No deadlock was seen: nested same-thread entries are fine because the lock is re-entrant.
Repro (condensed)
import os, sys, time, threading, torch
from gptqmodel import GPTQModel, BACKEND
CK = "Qwen2.5-0.5B-Instruct-gptq-4bit"
def decode(m, steps, out, tag):
ids = torch.tensor([[151644, 872, 198, 9707]], device="cuda:0")
with torch.inference_mode():
o = m(ids, use_cache=True); pkv, nxt = o.past_key_values, o.logits[:, -1:].argmax(-1)
t = time.perf_counter()
for _ in range(steps):
o = m(nxt, past_key_values=pkv, use_cache=True); pkv, nxt = o.past_key_values, o.logits[:, -1:].argmax(-1)
torch.cuda.synchronize()
out[tag] = steps / (time.perf_counter() - t)
a = GPTQModel.load(CK, backend=BACKEND.TORCH, device="cuda:0"); a.optimize()
b = GPTQModel.load(CK, backend=BACKEND.TORCH, device="cuda:0"); b.optimize()
decode(a, 20, {}, "w"); decode(b, 20, {}, "w")
r = {}; decode(a, 200, r, "alone")
ts = [threading.Thread(target=decode, args=(m, 200, r, t)) for m, t in ((a, "t1"), (b, "t2"))]
t0 = time.perf_counter(); [t.start() for t in ts]; [t.join() for t in ts]
print(r, "agg", 400 / (time.perf_counter() - t0))
# PYTHON_GIL=0, main: alone 148.0, t1 51.7, t2 51.8, agg 91.7
# PYTHON_GIL=0, 11f9cb369: alone 120.1, t1 86.5, t2 86.4, agg 141.0Suggested fix
The compiled calls do not need mutual exclusion among themselves. They only need exclusion against the window in which a load changes the process default dtype. Options:
- Use a reader/writer lock. Compiled calls take it shared. Model construction (
from_pretrained/from_quantized/ shell rebuild /_from_config) takes it exclusive, and only around theset_default_dtypewindow, not around the whole load (weight I/O, kernel post_init, repacking). Concurrent forwards then run in parallel, and a forward waits at most for the short dtype window. - Or keep compiled calls lock-free and make the loads stop toggling the process-global default dtype at all: construct with an explicit
dtype=, or under a thread-local default-dtype context.
Also correct the docs' "uncontended acquire" claim.
Test that should have caught it
tests/test_compile_load_race_5209.py checks only that the lock is taken (test_every_compiled_call_takes_the_model_global_lock) and that the dtype stays fp32. A test that runs two compiled forwards on two threads and asserts they overlap would have caught this. For example: with a forward that sleeps 100 ms under the wrapper, two threads should finish in about 100 ms, not 200 ms, and a forward should not wait for a concurrent load's weight I/O.
Severity
High for multi-model or threaded serving (the free-threaded deployment the project targets). Throughput of concurrent compiled inference drops 30-38%, and every compiled request blocks for the full duration of any concurrent load or save. Single-threaded use is unaffected.
🤖 Generated with Claude Code
Activity
Qubitium commentedon Nov 18, 2026
Data point for the GIL build (CPython 3.14, same
optimize()two-thread repro, same hardware). With the GIL the lock does not cost throughput:11f9cb369reached 74.2 tok/s aggregate (52 per thread), main 95.4 (71 per thread). The GIL already serializes the Python side, and the extra lock seems to cut GIL hand-off thrash. So the throughput regression is specific to free-threaded builds (agg 141 -> 92). The load/save stall (a compiled forward blocks for the whole concurrent load) applies to both builds.🤖 Generated with Claude Code
Qubitium commentedon Nov 18, 2026
Agent claim:
agent-4e3a0639ecafis working on this issue now.Started 2026-11-18T16:25:51Z. 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 my #5251 regression: stop serializing every compiled call on the process-wide model lock - hold it only while a call can actually (re)trace or while a load is mutating global state, with a contention benchmark
Qubitium commentedon Nov 18, 2026
Agent claim released:
agent-4e3a0639ecaffinished this issue.PR: #5291 — base
main, headdcfb15e9f(branchfix/5268-compile-lock-scope), 14 files, +635/−130.Fix
#5251 wrapped every compiled call in
model_global_state_lock(), which resolved to_MODEL_LOAD_LOCK— theRLocka load holds for its whole body — so warm compiled forwards serialized against each other and stalled behind unrelated weight I/O. The hazard #5209 fixed is narrower: transformers'local_torch_dtypeconstruction window saves/sets/restorestorch.set_default_dtype, and a trace that overlaps it can restore the wrong dtype._MODEL_GLOBAL_STATE_LOCKis now a process-global reader/writer lock:from_pretrained,from_config+ retry,build_shell_model, save-side shell rebuild, dequant, TT block-float, norm teacher, DeepSeek-V4 MTP shell,TorchLinear.optimize) takes the writer side for the construction call only, not for the rest of a load.RuntimeErrorinstead of deadlocking.torch._dynamo.reset()stays removed.Evidence (measured on this host)
main0aa2d4b48_MODEL_LOAD_LOCKtests/test_compile_lock_scope_5268.py: 2 intended assertion failures + 2 ImportErrors on pristinemain→ 4 passed (3 consecutive runs).tests/test_compile_load_race_5209.py5 passed (3 runs); the agent's 15-file compile/optimize/loader/concurrency/docs set 102 passed, 8 skipped; DeepSeek-V4 43 passed; the parent re-ran the two lock test files plustest_model_load_lock_4204.py,test_optimize_dynamo_release_5020.py,test_compile_nested_suppression_5224.py→ 21 passed, 4 skipped; ruff clean.docs/concurrency.mdanddocs/torch-compile-fallback.mddescribe the reader/writer contract.Not verified: real decode throughput on GPU and on a free-threaded interpreter (host is GIL-enabled 3.14.4, no real quantized checkpoint in the offline cache);
_ModelGlobalStateLockon 3.14t is reasoned fromthreading.Condition/threading.local;_call_with_dynamo_suppressionstill writes the process-globaltorch._dynamo.config.suppress_errorsper call (a race that predates #5251, left as a follow-up).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…