Repository navigation
fix(torch): serialize TorchLinear's first compile with model loads (#5127) - #5159
Merged
Merged
Conversation
…5127) Dynamo's preserve_global_state saves and restores the process-global torch.set_default_dtype around every trace, exactly like transformers' from_pretrained/from_config. The lazy first TorchLinear.dequantize_weight compile did not take _MODEL_LOAD_LOCK, so it could capture a load's bf16 window and restore bf16 after the load restored fp32 (leaving the process default dtype wrong), or restore bf16 while assert_loaded_model_state was checking the load (failing a valid load). With PYTHON_GIL=0 the same race also raised a dynamo-internal KeyError from get_guard_fail_reason. Hold model_load_lock() for the first (compiling) invocation of the callable and module compile proxies and around TorchLinear.optimize(); later calls short-circuit on state['compiled'] so steady-state forwards stay lock-free. The lock is the loader's RLock, and optimize() is re-entrant when reached from post_init() during construction. Classify a LookupError whose innermost frame is under torch/_dynamo/ as a compiler failure so the eager fallback handles the guard-bookkeeping KeyError. RuntimeError and the dynamo guard AssertionError keep their existing behavior; user-code exceptions still propagate. Tests: a deterministic free-threaded thread test overlaps a real GPTQModel.load() bf16 window with another model's first TorchLinear forward and asserts the default dtype is unchanged; a unit test pins the dynamo-frame KeyError fallback. Both fail on e2f9676.
Qubitium
marked this pull request as ready for review
November 18, 2026 06:56
This was referenced Nov 18, 2026
Qubitium
added a commit
that referenced
this pull request
Nov 18, 2026
…5251) #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).
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.
Summary
Fixes #5127.
Dynamo's
preserve_global_statesaves and restores the process-globaltorch.set_default_dtype()around every trace, exactly like transformers'from_pretrained/from_config. The lazy firstTorchLinear.dequantize_weightcompile did not take
_MODEL_LOAD_LOCK, so the two windows interleaved:the load restored fp32, leaving the process default dtype wrong for the rest
of the process; or
assert_loaded_model_statewas checking theload, failing a valid load with
RuntimeError: model load left a corrupted state.Under
PYTHON_GIL=0the same race also surfaced as a dynamo-internalKeyErrorfromtorch/_dynamo/utils.py:get_guard_fail_reason, which_is_compiler_failuredid not classify.Net diff: 7 files, +418/-36 (code + tests + docs).
New flow
The first (compiling) invocation of the callable/module compile proxy takes the
same re-entrant loader lock;
TorchLinear.optimize()takes it while buildingthe dynamo wrapper. After the first successful compiled call,
state["compiled"]short-circuits the lock, so steady-state forwards stayconcurrent.
flowchart TD A["thread A: GPTQModel.load"] --> B["acquire _MODEL_LOAD_LOCK"] B --> C["transformers sets default dtype bf16"] C --> D["construct model and TorchLinear kernels"] D --> E["restore fp32; assert_loaded_model_state"] E --> F["release lock; load returns"] G["thread B: first TorchLinear forward"] --> H["_install_callable_compile_fallback.call"] H --> I{"state.compiled?"} I -- yes --> J["compiled call, lock-free steady state"] I -- no --> K["acquire _MODEL_LOAD_LOCK"] K --> L{"state.compiled? (re-check)"} L -- yes --> J L -- no --> M["compiled call: dynamo preserve_global_state saves/restores dtype"] M --> N{"first call succeeded?"} N -- yes --> O["state.compiled = true; return result"] N -- compiler failure --> P["state.fallback = true; warn once; eager result"] N -- user error --> Q["re-raise; no retry"] B -. "thread B waits here" .-> K style Q fill:#f8d7da,stroke:#b02a37 style P fill:#fff3cd,stroke:#997404Failure path removed by this change
flowchart TD A["thread A: load sets default dtype bf16"] --> B["thread B: compile starts"] B --> C["preserve_global_state captures bf16"] A --> D["load restores fp32"] C --> E["compile restores bf16"] D --> F{"load asserts before or after the restore?"} F -- before --> G["RuntimeError: model load left a corrupted state"] F -- after --> H["process default dtype stays bf16"] H --> I["later torch.ones / nn.Linear silently use bf16"] G --> J["valid load fails"] style G fill:#f8d7da,stroke:#b02a37 style H fill:#f8d7da,stroke:#b02a37 style J fill:#f8d7da,stroke:#b02a37Before / after
TorchLineartrace vs. load_MODEL_LOAD_LOCKmodel_global_state_lock()in_install_callable_compile_fallback.call(gptqmodel/utils/torch.py:448) and_install_module_compile_fallback.forward(gptqmodel/utils/torch.py:495)optimize()wrapper constructiongptqmodel/nn_modules/qlinear/torch.py:435ate2f9676c6)torch_compileand the adapter (gptqmodel/nn_modules/qlinear/torch.py:467)KeyErrorfromget_guard_fail_reasonescaped a plain forwardLookupErrorwhose innermost frame is undertorch/_dynamo/is a compiler failure (gptqmodel/utils/torch.py:338)state["compiled"]short-circuits the lockThe lock is
_MODEL_LOAD_LOCK(gptqmodel/models/loader.py:1449), anRLock;the loader already holds it during
TorchLinear.post_init(), so the nestedoptimize()entry is re-entrant and cannot deadlock. Only the compiling callis serialized.
Evidence
Interpreter
The container's
/root/venvis not free-threaded(
sysconfig.get_config_var("Py_GIL_DISABLED") == 0, CPython 3.14.4, GIL build),so it cannot run
PYTHON_GIL=0. The race was qualified on the availablefree-threaded interpreter:
The GIL-build checks were run with
/root/venv/bin/python(torch 2.15.0+cu132,transformers 5.22.1).
Red: real two-thread load+forward loop (pre-fix
e2f9676c6)Two threads each load a quantized checkpoint (Qwen2.5-0.5B-Instruct GPTQ-Int4
and an RTN-Int4 checkpoint built from Qwen2.5-0.5B-Instruct) and run one
forward, 5 iterations per thread,
PYTHON_GIL=0:This matches the issue body: one corrupted-state load failure and the process
default dtype left at bf16.
Red: regression tests on
e2f9676c6Thread test (deterministic barriers, free-threaded interpreter):
Unit test (dynamo-internal
KeyError):Green: after the fix
Same 20-iteration two-thread loop,
PYTHON_GIL=0, free-threaded interpreter:Single-thread load+forward still works on both interpreters (default dtype
stays float32 after the forward).
Tests
TorchLinearforward; process default dtype must stay fp32tests/test_model_load_lock_4204.py::test_first_compile_cannot_restore_dtype_over_a_concurrent_loade2f9676c6with dynamo'sGlobal default_dtype state changed5 passedfor the file on the free-threaded interpreterKeyErrorraised from atorch/_dynamo/frame is a compiler failure and falls back to eager, stickilytests/test_torch_compile_fallback.py::test_key_error_from_dynamo_frame_falls_back_to_eagere2f9676c6withKeyError: 519005499072018 passedfor the fileExisting coverage re-run:
tests/test_concurrent_load.pyon the free-threaded interpreter:1 passed(both
PYTHON_GIL=0andPYTHON_GIL=1rounds).tests/test_model_load_lock_4204.py tests/test_torch_compile_fallback.py tests/test_load_state_assertions.py tests/test_ci_free_threaded_lane.py tests/test_generation_compile_policy_4669.py tests/test_hf_init_guard.pyon the free-threaded interpreter:
67 passed, 1 failed; the failure istest_ci_free_threaded_lane.py::test_gate_passes_with_gil0, whose child gatescript exits 1 from triton nanobind leak finalization in this container after
printing all
ok:lines. Unrelated to this change./root/venv: the same load-lock/fallback/state-assertion/lane setgives
51 passed, 1 failed, 3 skipped; the failure is the pre-existingtest_concurrency_guards.py::test_cpu_bf16x3_capability_probe_respects_an_active_scope(
'function' object has no attribute 'cache_clear'), reproduced one2f9676c6without this change. The thread regression is skipped there bydesign (
Py_GIL_DISABLED != 1).tests/test_docs_contract_refs.py:23 passed.tests/test_optimize_no_reference_cycle_4937.py tests/test_optimize_dynamo_release_5020.py tests/test_optimize_generate_4669.py tests/test_cpu_kernel_optimize.py:9 passed, 3 setup errors becausetest_optimize_dynamo_release_5020.pyneeds an HF download while this container is offline.
Lint:
format/check.shcannot run here because itspip installis blocked byPEP 668 (
externally-managed-environment). The gate's actual command,ruff check gptqmodel docs/eora tests setup.py, passes with the installedruff 0.17.4 (the script pins 0.14.2).
git diff --checkis clean.Docs
docs/torch-compile-fallback.md: new first-use lock flow, failure path,before/after table with
file:lineevidence, and updated exception table.docs/concurrency.md: section 4 now documents that the first compile shares_MODEL_LOAD_LOCK, plus the failure-contract row.README.md: linksdocs/torch-compile-fallback.mdfrom the Inference bullet.Limitations / unverified
serialized; the issue and this fix target the lazy first compile. Steady-state
forwards must stay lock-free, so the lock is released after the first
successful compiled call.
/root/venvbecause it is a GIL build; thefree-threaded evidence above uses the available 3.14t interpreter with
torch 2.16.0.dev rather than the issue's torch 2.15.