Skip to content

fix(load): hold the global-state writer only for the default-dtype window (#5304) - #5329

Merged
Qubitium merged 1 commit into
mainfrom
fix/5304-global-state-writer-dtype-window
Nov 19, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/5304-global-state-writer-dtype-window

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

Summary

Fixes #5304.

model_global_state_lock() is a process-global reader/writer lock: compiled calls take the reader side, and the writer excludes them so a re-trace cannot capture and restore a construction's torch.set_default_dtype window (#5127, #5209).

#5291 gave the writer to each transformers construction call, and #5301 moved it into _hf_loader_from_pretrained_with_dynamic_module_retry so a new call site could not miss it. That scope is the bug: for a dense load the call is the entire from_pretrained body — weight I/O, dtype casts, device placement, packing, kernel post-init — while the process-global state only changes inside transformers' local_torch_dtype window. Every optimize()d forward in the process therefore waited for the whole load.

Confirmed on current main (4cf5c383a) before writing the fix: with a warm compiled decode loop (1B GPTQ 4-bit, optimize(backend="eager")) and a concurrent dense GPTQModel.load of a 1.5B checkpoint, the writer was held for 1.50 s of a 1.92 s load and the worst decode step was 1516 ms against a 15 ms p50.

What Changed

The writer now belongs to the dtype window itself, not to any call site.

  • gptqmodel/utils/torch.py: install_model_global_state_dtype_guard() wraps transformers.modeling_utils.local_torch_dtype once per process and takes the writer while the window is open; model_global_state_dtype_guard_installed() reports the state.
  • gptqmodel/__init__.py: installs that guard next to the other transformers patches at import time.
  • Removed the per-call-site writer from _hf_loader_from_pretrained_with_dynamic_module_retry (initial call and retry), from_quantized's two from_config sites, build_shell_model, the save-side shell rebuild (ModelWriter.get_model_with_quantize), the compressed-tensors dequant path, the TT block-float path, the norm-tuning teacher and the DeepSeek-V4 MTP shell. Those paths still serialize through _MODEL_LOAD_LOCK; only the window is exclusive against compiled calls.
  • TorchLinear.optimize() keeps the writer while it installs the dynamo wrapper, unchanged.
  • docs/concurrency.md, docs/torch-compile-fallback.md: new flow, before/after table and measured numbers.

Behaviour is unchanged for correctness: the window is still exclusive against compiled forwards, and nested windows (e.g. from_quantized → from_config) are re-entrant.

Old flow (removed)

flowchart TD
    A["thread 1: GPTQModel.load"] --> B["_MODEL_LOAD_LOCK: whole load"]
    B --> C["global-state writer around the whole from_pretrained / from_config call (#5291, #5301)"]
    C --> D["weight I/O, dtype casts, device placement, local_torch_dtype, packing, kernel post-init"]
    E["thread 2: optimize()d forward"] --> F["global-state reader"]
    F -. "blocked for the entire load" .-> C
    style C fill:#f8d7da,stroke:#b02a37
Loading

New flow (shipped)

flowchart TD
    A["thread 1: GPTQModel.load"] --> B["_MODEL_LOAD_LOCK: whole load"]
    B --> C["weight I/O, dtype casts, device placement: no writer"]
    C --> D["install_model_global_state_dtype_guard wraps local_torch_dtype"]
    D --> E["local_torch_dtype opens: acquire global-state writer"]
    E --> F["transformers sets default dtype; construct model"]
    F --> G["window closes: release writer"]
    G --> H["packing, kernel post-init, assert_loaded_model_state"]
    I["thread 2: optimize()d forward"] --> J["global-state reader"]
    J -. "waits only for the window" .-> E
    C -. "overlaps" .-> J
    H -. "overlaps" .-> J
    style E fill:#d1e7dd,stroke:#146c43
Loading
Mechanism Before After
Writer owner each from_pretrained/from_config call site (gptqmodel/models/loader.py helper, utils/hf.py, models/writer.py, utils/model_dequant.py, utils/tt_blockfloat_quant.py, models/base.py, models/definitions/deepseek_v4.py at 4cf5c383a) transformers' local_torch_dtype window (gptqmodel/utils/torch.py:install_model_global_state_dtype_guard)
Reader exclusion during a dense load whole load dtype window only
New construction site must remember the writer; #5301 was exactly a missed site covered automatically
Writer hold during the measured dense load 1.50 s of 1.92 s 21 ms
Worst decode step in a serving thread 1516 ms 164 ms (one 21 ms reader wait)

Tests

  • Unit tests executed and passed.
  • New targeted regression added.

tests/test_compile_load_scope_5304.py (new): a fake loader whose body stands in for weight I/O and whose construction opens a real local_torch_dtype window. It asserts (1) a reader enters while the load body runs, (2) a reader waits while the window is open, and (3) the helper does not hold the writer during the body.

tests/test_quantize_load_global_state_5301.py (rewritten): the old contract ("the helper holds the writer for every attempt") is inverted to "only the window holds the writer", plus AST checks that no loader.from_pretrained/from_config site re-widens it and that the guard is installed on transformers.modeling_utils.local_torch_dtype.

Red evidence on origin/main at 4cf5c383a (same test file, fix reverted):

tests/test_compile_load_scope_5304.py::test_dense_load_body_does_not_block_compiled_forwards FAILED
tests/test_compile_load_scope_5304.py::test_dtype_window_guard_is_the_only_writer FAILED
2 failed, 1 passed

Green:

python -m pytest tests/test_compile_load_scope_5304.py tests/test_quantize_load_global_state_5301.py -q
# 10 passed (3 consecutive runs)

python -m pytest tests/test_compile_load_scope_5304.py tests/test_quantize_load_global_state_5301.py \
    tests/test_compile_lock_scope_5268.py tests/test_concurrency_guards.py -q
# 22 passed, 1 failed

python -m pytest tests/test_load_state_assertions.py tests/test_hf_init_guard.py \
    tests/test_model_load_lock_4204.py -q \
    --deselect tests/test_model_load_lock_4204.py::test_first_compile_cannot_restore_dtype_over_a_concurrent_load
# 26 passed

python -m pytest tests/test_compile_load_race_5209.py -q \
    --deselect tests/test_compile_load_race_5209.py::test_optimized_forward_survives_repeated_concurrent_loads
# 5 passed

bash format/check.sh
# All checks passed!

Skips and failures that are not from this change (both reproduce on unmodified origin/main with the same commands):

  • tests/test_concurrency_guards.py::test_cpu_bf16x3_capability_probe_respects_an_active_scope — fails identically before the change (1 failed, 8 passed on base).
  • tests/test_model_load_lock_4204.py::test_first_compile_cannot_restore_dtype_over_a_concurrent_load and tests/test_compile_load_race_5209.py::test_optimized_forward_survives_repeated_concurrent_loads — segfault (exit 139 / -11) inside dynamo's compiled-code evaluation on the base commit too; the crash is in the interpreter/dynamo combination, not in the lock scope. Both are free-threaded-only suites.

Measurement (same host, same checkpoint, three runs; optimize(backend="eager") so the numbers reflect the lock and not inductor):

run load writer hold decode p50 decode max
before 1.92 s 1.50 s 15 ms 1516 ms
after 1 1.24 s 21 ms 15 ms 190 ms
after 2 1.20 s 21 ms 15 ms 164 ms
after 3 1.55 s 20 ms 16 ms 431 ms

The remaining spikes (100-400 ms) are the load's host work on a free-threaded interpreter; a control run with the same CPU burn and no load still shows them, and the reader-wait instrumentation records exactly one 21 ms wait (the window) in the whole load.

Not verified: no ROCm or multi-GPU run was needed for a CPU-host-side lock scope change; kernel numerics are untouched and the numeric suites are unaffected.

Model Support / Module Plan

Not applicable: no model type, alias, definition, module plan or fusion change. The DeepSeek-V4 MTP edit only removes an outer lock.

AWQ onboarding safety

Not applicable: no AWQ grouping, search, replay or folding change.

Logic Flow Documentation

  • This change alters a control flow, and the diagrams and docs page are included.
  • New-flow Mermaid diagram(s) use shipped symbol names.
  • The removed mechanism is tabulated with file:line evidence.
  • Failure paths are marked and visually distinct.
  • docs/concurrency.md and docs/torch-compile-fallback.md repeat the diagrams; both are already linked from README.md.

Diagram summary: above (old flow, new flow, before/after table); the same diagrams are in docs/concurrency.md §4 and docs/torch-compile-fallback.md.

Review Requirements

Kernel Accuracy Requirements

Not applicable: no kernel, dispatch or fusion change.

Notes

  • The writer is per-thread for the window, so an unusual lazy construction triggered from inside a compiled call would attempt a reader→writer upgrade and still fail loudly, as before.
  • Follow-up (out of scope): the remaining 100-400 ms decode spikes while a dense load runs are the load's own host work on this interpreter, unrelated to the lock. They existed before the fix inside the writer and are not excluded by it.

…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants