Skip to content

[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

@Qubitium

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 every TorchLinear.dequantize_weight call. 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 the optimize()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:

  1. 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.
  2. 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.0

Suggested 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 the set_default_dtype window, 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

  1. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    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: 11f9cb369 reached 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

  2. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim: agent-4e3a0639ecaf is 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

  3. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

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

    PR: #5291 — base main, head dcfb15e9f (branch fix/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 — the RLock a 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_dtype construction window saves/sets/restores torch.set_default_dtype, and a trace that overlaps it can restore the wrong dtype.

    _MODEL_GLOBAL_STATE_LOCK is now a process-global reader/writer lock:

    • Compiled proxies take the shared reader side, so they run concurrently.
    • Each construction site (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.
    • Writer is re-entrant per thread and writer-preferred (a waiting load does not starve); a reader→writer upgrade and a load started inside a compiled call raise a clear RuntimeError instead of deadlocking. torch._dynamo.reset() stays removed.

    Evidence (measured on this host)

    probe main 0aa2d4b48 this PR
    two threads × one 200 ms compiled call, wall 0.401 s 0.201 s
    per-thread wall 0.200 + 0.400 s 0.200 + 0.200 s
    warm call behind a held _MODEL_LOAD_LOCK 300.3 ms (blocked) 0.18 ms
    warm call behind the writer (dtype window) 300.9 ms 300.2 ms (blocked, intended)
    per-call, 50k warm calls 9.95 / 10.83 µs 10.00 / 10.07 / 10.91 µs
    • New tests/test_compile_lock_scope_5268.py: 2 intended assertion failures + 2 ImportErrors on pristine main → 4 passed (3 consecutive runs).
    • tests/test_compile_load_race_5209.py 5 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 plus test_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.md and docs/torch-compile-fallback.md describe 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); _ModelGlobalStateLock on 3.14t is reasoned from threading.Condition/threading.local; _call_with_dynamo_suppression still writes the process-global torch._dynamo.config.suppress_errors per call (a race that predates #5251, left as a follow-up).

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