Repository navigation
fix(compile): let compiled calls share the model-global-state lock (#5268) - #5291
Merged
Merged
Conversation
…5268) #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.
Qubitium
marked this pull request as ready for review
November 18, 2026 17:06
This was referenced Nov 19, 2026
12 tasks done
ZX-ModelCloud
added a commit
that referenced
this pull request
Nov 19, 2026
…ndow (#5304) #5291 took the model-global-state writer around whole transformers `from_pretrained`/`from_config` calls, and #5301 moved it into `_hf_loader_from_pretrained_with_dynamic_module_retry` so no call site could miss it. Only the `local_torch_dtype` window inside those calls is process-global state; the rest of a dense `from_pretrained` is weight I/O, dtype casts, device placement, packing and kernel post-init. A warm `optimize()`d decode step therefore stalled for the entire load: 23-36 s for a 7B model on the reporting host. The writer now belongs to the window. `install_model_global_state_dtype_guard()` wraps transformers' `local_torch_dtype` once at package import and takes the writer while the window is open, so every construction path (and any new one) is covered without wrapping the call. The per-call-site writer is removed from the loader helper, `from_config` sites, `build_shell_model`, the save-side shell rebuild, the compressed-tensors dequant path, the TT block-float path, the norm-tuning teacher and the DeepSeek-V4 MTP shell. Measured on a 1B GPTQ 4-bit checkpoint with a warm compiled decode loop and a concurrent dense `GPTQModel.load` of a 1.5B checkpoint: writer hold 1.50 s -> 21 ms, worst decode step 1516 ms -> 164 ms with only one 21 ms reader wait; the load itself is unchanged. The dtype window still excludes compiled forwards (#5127/#5209), verified by the existing race suites. `tests/test_compile_load_scope_5304.py` fails on the previous head for the load body (writer held during weight I/O) and passes here; the #5301 suite is rewritten from "the helper holds the writer" to "only the window does", and the #5268/#5209/#4204 suites pass unchanged. Fixes #5304
Qubitium
pushed a commit
that referenced
this pull request
Nov 19, 2026
…ndow (#5304) (#5329) #5291 took the model-global-state writer around whole transformers `from_pretrained`/`from_config` calls, and #5301 moved it into `_hf_loader_from_pretrained_with_dynamic_module_retry` so no call site could miss it. Only the `local_torch_dtype` window inside those calls is process-global state; the rest of a dense `from_pretrained` is weight I/O, dtype casts, device placement, packing and kernel post-init. A warm `optimize()`d decode step therefore stalled for the entire load: 23-36 s for a 7B model on the reporting host. The writer now belongs to the window. `install_model_global_state_dtype_guard()` wraps transformers' `local_torch_dtype` once at package import and takes the writer while the window is open, so every construction path (and any new one) is covered without wrapping the call. The per-call-site writer is removed from the loader helper, `from_config` sites, `build_shell_model`, the save-side shell rebuild, the compressed-tensors dequant path, the TT block-float path, the norm-tuning teacher and the DeepSeek-V4 MTP shell. Measured on a 1B GPTQ 4-bit checkpoint with a warm compiled decode loop and a concurrent dense `GPTQModel.load` of a 1.5B checkpoint: writer hold 1.50 s -> 21 ms, worst decode step 1516 ms -> 164 ms with only one 21 ms reader wait; the load itself is unchanged. The dtype window still excludes compiled forwards (#5127/#5209), verified by the existing race suites. `tests/test_compile_load_scope_5304.py` fails on the previous head for the load body (writer held during weight I/O) and passes here; the #5301 suite is rewritten from "the helper holds the writer" to "only the window does", and the #5268/#5209/#4204 suites pass unchanged. Fixes #5304
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.
fix(compile): scope the model-global lock to the dtype window (#5268)
Fixes #5268. Regression from #5251 (fix of #5209).
Problem
#5251 made every compiled call hold
model_global_state_lock(), which isthe process-wide
_MODEL_LOAD_LOCKRLocka load holds for its wholebody. Two consequences:
load or save (weight I/O, packing, kernel post-init), which can be minutes.
The dtype hazard #5251 closed only exists while transformers'
local_torch_dtypesaves/sets/restorestorch.set_default_dtypeduring modelconstruction; the rest of a load does not touch it.
Before
flowchart TD A["thread A: GPTQModel.load"] --> B["_MODEL_LOAD_LOCK held for whole load"] B --> C["from_config / from_pretrained sets default dtype bf16"] C --> D["weight I/O, packing, kernel post-init"] D --> E["assert_loaded_model_state"] F["thread B: warm compiled call"] --> G["model_global_state_lock() = _MODEL_LOAD_LOCK"] G --> H["compiled forward"] B -. "serializes every compiled call" .-> G style G fill:#f8d7da,stroke:#b02a37After
flowchart TD A["thread A: GPTQModel.load"] --> B["_MODEL_LOAD_LOCK held for whole load"] B --> C["global-state writer around construction only"] C --> D["weight I/O, packing, kernel post-init (no writer)"] D --> E["assert_loaded_model_state"] F["thread B: warm compiled call"] --> G["global-state reader"] G --> H["compiled forward"] I["thread C: warm compiled call"] --> J["global-state reader"] J --> K["compiled forward"] C -. "excludes only the dtype window" .-> G D -. "does not exclude" .-> G G --> L["readers run concurrently"] J --> L style G fill:#d1e7dd,stroke:#146c43 style J fill:#d1e7dd,stroke:#146c43Change
_MODEL_GLOBAL_STATE_LOCK(gptqmodel/models/loader.py) is a process-globalreader/writer lock;
model_global_state_lock()(gptqmodel/utils/torch.py)resolves it.
(
_install_callable_compile_fallback.call,_install_module_compile_fallback.forward).from_pretrained,from_quantized'sfrom_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.nests. Reader->writer upgrade raises, and a load started from inside a
compiled call raises instead of risking a lock-order deadlock.
from_quantizedstill does not calltorch._dynamo.reset().Docs:
docs/concurrency.mdsection 4 anddocs/torch-compile-fallback.mddescribe the new flow; the "one uncontended acquire per call" claim is replaced
with the reader/writer contract.
Evidence
Red (worktree at 0aa2d4b with the new test file):
Green: the same file is 4 passed, and
tests/test_compile_load_race_5209.pyis 5 passed (the #5209 contract is unchanged).
Timing (CPU, warm compiled callable, 3 interleaved runs):
_MODEL_LOAD_LOCKValidation:
uvx [email protected] check gptqmodel docs/eora tests setup.pypytestcompile + optimize families + loader/concurrency/docs (15 files)pytest tests/test_compile_load_race_5209.py tests/test_compile_lock_scope_5268.py tests/test_lazy_turtle_conversion_cache.py tests/test_loader_tokenizer_flag_4941.pypytest tests/test_deepseek_v4_support.pyReviewer notes
window transformers mutates
torch.get_default_dtype()in; weight I/O andpost-init no longer exclude forwards.
load's I/O. It still waits for the dtype window, which is the [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 fix.
_call_with_dynamo_suppressionstill writes the process-globaltorch._dynamo.config.suppress_errorsper call; concurrent calls caninterleave that save/restore. The race predates fix(compile): serialize every compiled call with model loads (#5209) #5251 (steady state was
lock-free then); a refcounted guard is a separate change.
interpreter. The host venv is GIL-enabled and the offline cache has no real
quantized checkpoint (Qwen snapshots are stubs).