Skip to content

fix(torch): serialize TorchLinear's first compile with model loads (#5127) - #5159

Merged
Qubitium merged 1 commit into
mainfrom
fix/5127-torchlinear-compile-lock
Nov 18, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/5127-torchlinear-compile-lock

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Fixes #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 the two windows interleaved:

  • a compile that started while a load had bf16 installed restored bf16 after
    the load restored fp32, leaving the process default dtype wrong for the rest
    of the process; or
  • the compile restored bf16 while assert_loaded_model_state was checking the
    load, failing a valid load with RuntimeError: model load left a corrupted state.

Under PYTHON_GIL=0 the same race also surfaced as a dynamo-internal
KeyError from torch/_dynamo/utils.py:get_guard_fail_reason, which
_is_compiler_failure did 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 building
the dynamo wrapper. After the first successful compiled call,
state["compiled"] short-circuits the lock, so steady-state forwards stay
concurrent.

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:#997404
Loading

Failure 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:#b02a37
Loading

Before / after

Mechanism Before After
First TorchLinear trace vs. load no shared lock; the compile ran from the forward thread while a load held _MODEL_LOAD_LOCK model_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 construction unlocked (gptqmodel/nn_modules/qlinear/torch.py:435 at e2f9676c6) lock held around torch_compile and the adapter (gptqmodel/nn_modules/qlinear/torch.py:467)
Dynamo-internal lookup failure KeyError from get_guard_fail_reason escaped a plain forward LookupError whose innermost frame is under torch/_dynamo/ is a compiler failure (gptqmodel/utils/torch.py:338)
Steady-state forwards lock-free still lock-free: state["compiled"] short-circuits the lock

The lock is _MODEL_LOAD_LOCK (gptqmodel/models/loader.py:1449), an RLock;
the loader already holds it during TorchLinear.post_init(), so the nested
optimize() entry is re-entrant and cannot deadlock. Only the compiling call
is serialized.

Evidence

Interpreter

The container's /root/venv is 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 available
free-threaded interpreter:

/opt/venvs/cu130t/bin/python
CPython 3.14.10, Py_GIL_DISABLED=1, sys._is_gil_enabled() == False with PYTHON_GIL=0
torch 2.16.0.dev20261102+cu130, transformers 5.22.2, CPU only

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:

gil_enabled= False start_dtype= torch.float32
ERROR gptq 1: RuntimeError: Qwen2QModel.from_quantized: model load left a corrupted state: torch.get_default_dtype() changed from torch.float32 to torch.bfloat16
ok= {'gptq': 4, 'rtn': 5} alive= [False, False]
end_dtype= torch.bfloat16 ones_dtype= torch.bfloat16
RESULT BAD

This matches the issue body: one corrupted-state load failure and the process
default dtype left at bf16.

Red: regression tests on e2f9676c6

Thread test (deterministic barriers, free-threaded interpreter):

FAILED tests/test_model_load_lock_4204.py::test_first_compile_cannot_restore_dtype_over_a_concurrent_load
E AssertionError: concurrent first forward failed: [AssertionError('Global default_dtype state changed while dynamo tracing, please report a bug\n')]

Unit test (dynamo-internal KeyError):

FAILED tests/test_torch_compile_fallback.py::test_key_error_from_dynamo_frame_falls_back_to_eager
E KeyError: 5190054990720
/site-packages/torch/_dynamo/guards.py:2

Green: after the fix

Same 20-iteration two-thread loop, PYTHON_GIL=0, free-threaded interpreter:

gil_enabled= False start_dtype= torch.float32
ok= {'gptq': 20, 'rtn': 20} alive= [False, False]
errors= []
end_dtype= torch.float32 ones_dtype= torch.float32
RESULT ok

Single-thread load+forward still works on both interpreters (default dtype
stays float32 after the forward).

Tests

Invariant / trigger Test node Red Green
A load held in its bf16 window overlaps another model's first TorchLinear forward; process default dtype must stay fp32 tests/test_model_load_lock_4204.py::test_first_compile_cannot_restore_dtype_over_a_concurrent_load fails on e2f9676c6 with dynamo's Global default_dtype state changed passes; 5 passed for the file on the free-threaded interpreter
A KeyError raised from a torch/_dynamo/ frame is a compiler failure and falls back to eager, stickily tests/test_torch_compile_fallback.py::test_key_error_from_dynamo_frame_falls_back_to_eager fails on e2f9676c6 with KeyError: 5190054990720 passes; 18 passed for the file

Existing coverage re-run:

  • tests/test_concurrent_load.py on the free-threaded interpreter: 1 passed
    (both PYTHON_GIL=0 and PYTHON_GIL=1 rounds).
  • 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.py
    on the free-threaded interpreter: 67 passed, 1 failed; the failure is
    test_ci_free_threaded_lane.py::test_gate_passes_with_gil0, whose child gate
    script exits 1 from triton nanobind leak finalization in this container after
    printing all ok: lines. Unrelated to this change.
  • GIL build /root/venv: the same load-lock/fallback/state-assertion/lane set
    gives 51 passed, 1 failed, 3 skipped; the failure is the pre-existing
    test_concurrency_guards.py::test_cpu_bf16x3_capability_probe_respects_an_active_scope
    ('function' object has no attribute 'cache_clear'), reproduced on
    e2f9676c6 without this change. The thread regression is skipped there by
    design (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 because test_optimize_dynamo_release_5020.py
    needs an HF download while this container is offline.

Lint: format/check.sh cannot run here because its pip install is blocked by
PEP 668 (externally-managed-environment). The gate's actual command,
ruff check gptqmodel docs/eora tests setup.py, passes with the installed
ruff 0.17.4 (the script pins 0.14.2). git diff --check is clean.

Docs

  • docs/torch-compile-fallback.md: new first-use lock flow, failure path,
    before/after table with file:line evidence, 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: links docs/torch-compile-fallback.md from the Inference bullet.

Limitations / unverified

  • Re-traces caused by new input shapes after the first successful call are not
    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.
  • The race was not reproduced on /root/venv because it is a GIL build; the
    free-threaded evidence above uses the available 3.14t interpreter with
    torch 2.16.0.dev rather than the issue's torch 2.15.
  • GPU paths were not exercised (this issue is CPU-only).

…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
Qubitium marked this pull request as ready for review November 18, 2026 06:56
@Qubitium
Qubitium merged commit 986e5ea into main Nov 18, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/5127-torchlinear-compile-lock branch November 18, 2026 06:57
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).
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