Skip to content

fix(compile): serialize every compiled call with model loads (#5209) - #5251

Merged
Qubitium merged 1 commit into
mainfrom
fix/5209-compile-load-race
Nov 18, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/5209-compile-load-race

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #5209.

Problem

Fixes #5209. An optimize()d model crashed the process while another model was
being loaded, and repeated loads left torch.get_default_dtype() at bf16.

Repro (RTX 4090, sm_89, torch 2.15.0+cu132, Python 3.14.4 GIL build, GPTQ
Qwen2.5-0.5B-Instruct-Int4): serve one optimize()d model in one thread, run
GPTQModel.load(..., dtype=torch.bfloat16) in another.

variant result
upstream/main (cc7a10e3f) SIGSEGV, exit 139 in dynamo's eval_frame
main with torch._dynamo.reset neutered exit 2, model load left a corrupted state: torch.get_default_dtype() changed from torch.float32 to torch.bfloat16, default_dtype=torch.bfloat16

Root cause

#5159 put _MODEL_LOAD_LOCK around the first compiled call only
(state["compiled"] short-circuited every later call), and from_quantized
called torch._dynamo.reset() on every load.

  1. torch._dynamo.reset() is process-wide: it discards every compiled frame,
    including another model's optimize()d forward and the caller's own
    torch.compile functions, while their threads may be running them. On a GIL
    build that segfaults inside dynamo's frame evaluation.
  2. Without the reset, a later call re-traces whenever a guard changes — the
    load's bf16 set_default_dtype window is exactly such a change. Dynamo's
    preserve_global_state captures bf16 during the trace and restores it after
    the load restored fp32, so the process default dtype stays bf16 (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 again) or the load trips assert_loaded_model_state.

Fix

flowchart TD
    A["thread A: load takes _MODEL_LOAD_LOCK"] --> B["transformers sets default dtype bf16"]
    B --> C["build model"]
    C --> D["restore fp32; assert_loaded_model_state"]
    D --> E["release lock; load returns"]

    G["thread B: any compiled call"] --> H["_install_callable_compile_fallback.call"]
    H --> I{"outer torch.compile already tracing?"}
    I -- yes --> J["inline eager body; no lock, no config write (#5224)"]
    I -- no --> K["acquire _MODEL_LOAD_LOCK"]
    K --> L["compiled call: dynamo preserve_global_state saves/restores dtype"]
    L --> M{"call succeeded?"}
    M -- yes --> N["release lock; return result"]
    M -- compiler failure --> O["state.fallback = true; warn once; eager result"]
    M -- user error --> P["re-raise; no retry"]
    B -. "thread B waits here" .-> K
Loading
before after
compiled call vs. load lock held for the first call only; later calls could re-trace through a load's dtype window lock held for every call
from_quantized dynamo reset torch._dynamo.reset() wiped every model's frames and crashed a concurrent forward no reset
steady-state forward lock-free one uncontended RLock acquire (~0.08 µs; ~0.8 µs for the accessor lookup)

Tests

New tests/test_compile_load_race_5209.py (5 tests):

  • test_a_load_does_not_reset_another_models_compiled_frames — spies
    dynamo.reset; a load must not reset, and a caller-compiled frame must not
    re-trace.
  • test_every_compiled_call_takes_the_model_global_lock and
    test_every_compiled_module_forward_takes_the_model_global_lock — a
    signalling RLock proves the call waits while a load holds the lock.
  • test_optimized_forward_does_not_trace_through_a_loads_bf16_window — the
    test backend parks the trace inside the load's bf16 window; pre-fix the
    process is left at bf16, post-fix it stays fp32.
  • test_optimized_forward_survives_repeated_concurrent_loads — subprocess
    child, 3 rounds x 2 loads x 40 forwards; asserts exit 0, unchanged logits and
    default_dtype=torch.float32.

Pre-fix these 5 give 4 failed / 1 passed; post-fix 5 passed (repeated
x5). End-to-end GPU repro: exit 139 / exit 2 -> exit 0 x3, errors=[],
dtype=torch.float32, 320 forwards per run.

Suites: test_*compile*.py + test_optimize_*.py (72 passed) and the loader
family test_loader* / test_load_state_assertions / test_concurrent_load /
test_model_load_lock_4204 / test_awq_loader_dtype / test_eval_loader_args
(59 passed, 2 skipped). ruff 0.14.2 check gptqmodel docs/eora tests setup.py
passes.

Not verified / caveats

#5159 held `_MODEL_LOAD_LOCK` around the first compiled call only and set
`state["compiled"]` to skip the lock afterwards, while `from_quantized`
called `torch._dynamo.reset()` on every load. Two failures followed:

* `torch._dynamo.reset()` is process-wide. It discarded every compiled
  frame, including another model's `optimize()`d forward and the caller's
  own `torch.compile` functions, while their threads were running them,
  and segfaulted dynamo's frame evaluation on a GIL build.
* Without the reset, a later call re-traced whenever a guard changed. A
  load's bf16 `set_default_dtype` window is exactly such a change, so
  dynamo's `preserve_global_state` captured bf16 and restored it after the
  load restored fp32: the process default dtype stayed bf16 (#5127 again),
  compiled logits changed, or the load tripped `assert_loaded_model_state`.

Remove `state["compiled"]` and take `model_global_state_lock()` around
every call in both compile proxies. The lock is the loader's `RLock`, so
nested entries are cheap and cannot deadlock, and the
`dynamo_is_compiling()` short-circuit for an outer `torch.compile` (#5224)
stays lock-free. Drop the `torch._dynamo.reset()` from `from_quantized`: a
load must not discard other models' frames, and the trace cycles that keep
a dropped model alive are already reclaimed by
`release_compile_trace_garbage` (#5020).

Verified with a GPTQ Qwen2.5-0.5B checkpoint on an RTX 4090, serving an
`optimize()`d model while another thread loads: `upstream/main` segfaults
(exit 139); with the reset neutered it exits 2 with
`default_dtype=torch.bfloat16` and changed logits. With this change the
same repro exits 0 with `errors=[]` and `dtype=torch.float32` across three
bounded runs. New `tests/test_compile_load_race_5209.py` covers the reset
spy, the per-call lock, the bf16-window capture and a repeated concurrent
load child process; it is 4 failed / 1 passed pre-fix and 5 passed after.
`test_*compile*.py` + `test_optimize_*.py` and the loader family pass
(131 passed, 2 skipped on this GIL build).
@Qubitium
Qubitium marked this pull request as ready for review November 18, 2026 14:22
@Qubitium
Qubitium merged commit 35af39e into main Nov 18, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/5209-compile-load-race branch November 18, 2026 14:25
Qubitium added a commit that referenced this pull request Nov 18, 2026
…5268) (#5291)

#5251 fixed #5209 by taking `model_global_state_lock()` around every compiled
call. That resolved to `_MODEL_LOAD_LOCK`, the `RLock` a load holds for its
whole body, so two warm compiled forwards could never overlap and a warm
forward waited for an unrelated load's weight I/O, packing and kernel
post-init (#5268). The dtype hazard only exists while transformers'
`local_torch_dtype` saves/sets/restores `torch.set_default_dtype` during
construction, not for the rest of a load.

Replace the shared `RLock` with a process-global reader/writer lock
(`_MODEL_GLOBAL_STATE_LOCK`):

* compiled callable/module proxies take the shared reader side for the call;
* every transformers construction site takes the writer for the construction
  call only: from_pretrained, from_quantized's from_config (+ retry),
  build_shell_model, the save-side shell rebuild, compressed-tensors dequant,
  TT block-float, the norm-tuning teacher and the DeepSeek-V4 MTP shell;
  `TorchLinear.optimize()` takes it while installing the dynamo wrapper;
* the writer is re-entrant for its thread, readers nest, a reader->writer
  upgrade raises, and a load started inside a compiled call raises instead of
  risking a lock-order deadlock;
* `from_quantized` still never calls `torch._dynamo.reset()`.

Two warm compiled forwards now overlap (0.401 s -> 0.201 s for two 200 ms
calls) while a warm forward still waits for a construction's dtype window
(300 ms held -> 300 ms) and no longer waits for the load mutex (300 ms held ->
0.2 ms). Per-call overhead is unchanged (~10 us). `tests/test_compile_lock_scope_5268.py`
is 2 behavioral failures on 0aa2d4b and 4 passed after; the #5209 suite
stays 5 passed.

Co-authored-by: agent-4e3a0639ecaf <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant