Repository navigation
fix(compile): serialize every compiled call with model loads (#5209) - #5251
Merged
Merged
Conversation
#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
marked this pull request as ready for review
November 18, 2026 14:22
This was referenced Nov 18, 2026
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #5209.
Problem
Fixes #5209. An
optimize()d model crashed the process while another model wasbeing loaded, and repeated loads left
torch.get_default_dtype()atbf16.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, runGPTQModel.load(..., dtype=torch.bfloat16)in another.upstream/main(cc7a10e3f)eval_frametorch._dynamo.resetneuteredmodel load left a corrupted state: torch.get_default_dtype() changed from torch.float32 to torch.bfloat16,default_dtype=torch.bfloat16Root cause
#5159 put
_MODEL_LOAD_LOCKaround the first compiled call only(
state["compiled"]short-circuited every later call), andfrom_quantizedcalled
torch._dynamo.reset()on every load.torch._dynamo.reset()is process-wide: it discards every compiled frame,including another model's
optimize()d forward and the caller's owntorch.compilefunctions, while their threads may be running them. On a GILbuild that segfaults inside dynamo's frame evaluation.
load's bf16
set_default_dtypewindow is exactly such a change. Dynamo'spreserve_global_statecaptures bf16 during the trace and restores it afterthe 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
gptqmodel/utils/torch.py: removestate["compiled"]. Both compile proxies(
_install_callable_compile_fallback.call,_install_module_compile_fallback.forward) now takemodel_global_state_lock()around every call, not just the first. Thelock is the loader's
RLock, so nested entries are cheap; thedynamo_is_compiling()short-circuit for an outertorch.compile([BUG] Regression from #5171 (fix of #5102) + #5163: VPTQ static-cache generate() crashes ('accessing tensor output of CUDAGraphs that has been overwritten') - #5163's suppress_errors ContextVar write inside the nested dequantize torch_compile graph-breaks every VPTQ layer #5224)stays lock-free.
gptqmodel/models/loader.py:from_quantizedno longer callstorch._dynamo.reset(). A load must not discard other models' frames; thetrace cycles that keep a dropped model alive are already reclaimed by
release_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).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" .-> Kfrom_quantizeddynamo resettorch._dynamo.reset()wiped every model's frames and crashed a concurrent forwardRLockacquire (~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— spiesdynamo.reset; a load must not reset, and a caller-compiled frame must notre-trace.
test_every_compiled_call_takes_the_model_global_lockandtest_every_compiled_module_forward_takes_the_model_global_lock— asignalling
RLockproves the call waits while a load holds the lock.test_optimized_forward_does_not_trace_through_a_loads_bf16_window— thetest 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— subprocesschild, 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 loaderfamily
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.pypasses.
Not verified / caveats
(
test_concurrent_dense_loads_are_serialized,test_first_compile_cannot_restore_dtype_over_a_concurrent_load).lock is held for the whole construction (existing [BUG] Concurrency: concurrent GPTQModel.load() of dense models races transformers' global default dtype / meta-init (mixed fp16/fp32, meta lm_head, untied weights, default dtype stuck fp16) -> concurrent quantize() crashes or differs #4129/[BUG] Re-saving a loaded quantized model builds the shell with
from_configoutside_MODEL_LOAD_LOCK, reopening the #4129 default-dtype race #4204 behaviour, nota regression). The repro therefore bounds the loader loop and sleeps between
loads.