Skip to content

fix(threadx): acquire each distinct lock once per lock scope (#3878) - #3915

Merged
Qubitium merged 1 commit into
mainfrom
fix/issue-3878
Nov 14, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/issue-3878

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #3878

TL;DR

A lock scope is a list of (device_key, _RWLock) pairs, but two keys can name the
same lock: a virtual pool key reuses its parent's lock. read_lock("cpu") on the
shipped default pool therefore acquired one lock twice, which deadlocks against a
queued writer. _LockGroup / _ReadLockGroup now deduplicate pairs by lock
identity, so every multi-lock path acquires each lock once. Net diff: +35/−2 in
gptqmodel/utils/threadx.py, one new test module, one new docs page.

1. The problem

DeviceThreadPool gives each device key a writer-preference _RWLock, and a
virtual pool key (alias:parent) reuses the parent's lock object so that two
worker groups on one physical device serialize against each other. The shipped
CPU config uses this for model_loader:cpu.

Scope expansion then produces one pair per key, not per lock:

sequenceDiagram
    participant R as reader thread
    participant L as _RWLock for cpu
    participant W as writer thread
    R->>L: acquire_read() for "cpu"
    W->>L: acquire_write() blocked, writers_waiting = 1
    R->>L: acquire_read() for "model_loader:cpu" same lock
    Note over L: writer-preference loop blocks the new reader
    Note over R,W: reader waits for the writer, writer waits for the reader
    Note over R,W: permanent deadlock
Loading

_RWLock.acquire_read (gptqmodel/utils/threadx.py:220-234) blocks new readers
while any writer waits. It recognizes a writer re-entering as a reader, but a
reader re-entering behind a queued writer is treated as a brand-new reader.

Mechanism Where it lived on origin/main (66d27f9) Consequence
Virtual key sharing one lock gptqmodel/utils/threadx.py:822 self._locks[v_key] = self._locks[parent_key] Two keys, one lock object
Family map listing both keys _rebuild_family_keys, gptqmodel/utils/threadx.py:882-897 read_lock("cpu") expands to both keys
Scope pairs built per key :1296, :1311 pairs = [(k, self._locks[k]) for k in fam_keys] Duplicate lock in the group
Group acquired every pair :256 and :278 self._pairs = ordered_pairs Same lock acquired twice
Writer preference :229 while self._writer is not None or self._writers_waiting > 0 Second acquisition waits behind the queued writer

The same duplicate existed in read_lock("all") (_ordered_keys contains the
alias key) and in wait(lock=True); the writer path lock() tolerated it only
because acquire_write is re-entrant.

2. The new flow

flowchart TD
    A["read_lock(scope) / lock() / wait(lock=True)"] --> B["expand scope to key pairs"]
    B --> C["_dedupe_lock_pairs: keep first pair per lock identity"]
    C --> D{"more pairs?"}
    D -- Yes --> E["acquire this lock once"]
    E --> D
    D -- No --> F["body runs"]
    F --> G["release in reverse order"]
    G --> H["queued writer proceeds"]
    style C fill:#dfd,stroke:#060
    style H fill:#dfd,stroke:#060
Loading

_dedupe_lock_pairs keys on id(lock) and keeps first-seen order, so
acquisition order stays deterministic and release order remains the exact
reverse. Because _LockGroup, _ReadLockGroup, and _WaitAndLock all construct
through it, one rule covers every multi-lock path.

3. Failure and ambiguity contract

Situation Before After
Family read scope over an aliased key with a queued writer Deadlock Reader acquires once, completes, writer proceeds
read_lock("all") with an aliased key Same lock acquired twice Each distinct lock acquired once
wait(lock=True) over an aliased scope Same double acquisition Each distinct lock acquired once
Genuine multi-lock scope (two distinct devices) Both acquired in canonical order Unchanged
Writer queued behind an in-flight reader Reader that has not yet acquired blocks Unchanged (writer preference preserved)
Two names for one device in _family_keys Both present Unchanged; dedup happens at acquisition

Deduplication is deliberately at acquisition time, not at pool construction: the
alias must keep sharing the parent lock, and wait() inflight bookkeeping is
keyed by name.

4. Change inventory

Area File ± Purpose
Lock scopes gptqmodel/utils/threadx.py +31/−2 _dedupe_lock_pairs, used by both group constructors; docstring contracts
Tests tests/test_threadx_cpu_locks.py +178 CPU-only, time-bounded interleaving regression plus scope guards
Docs docs/cpu-pool-lock-scopes.md +106 Mechanism page with flow, failure sequence, contracts
Docs link README.md +2 Link from the operational notes near multi-GPU scheduling

5. Tests / guarantees

Test Invariant
test_virtual_alias_shares_its_parent_lock Alias still shares the parent lock; both keys stay in the family map
test_family_read_lock_acquires_the_shared_lock_once read_lock("cpu") acquires one distinct lock
test_all_read_lock_acquires_each_lock_once read_lock("all") acquires every distinct pool lock once
test_wait_lock_true_acquires_each_lock_once wait(lock=True) uses the deduplicated group
test_family_read_lock_does_not_deadlock_against_a_waiting_writer The issue interleaving finishes: both threads exit
test_lock_group_still_acquires_every_distinct_lock A two-lock scope acquires both in order and releases in reverse

Every wait in the new module is bounded (Event.wait, Thread.join timeouts), so
a regression fails rather than hanging the suite. The module is CPU-only and does
not inherit the CUDA skip mark in tests/test_threadx.py.

6. Validation

Hardware: RTX 4090 (SM 8.9), torch 2.16.0.dev20261102+cu130; R9700 (gfx1201),
torch 2.16.0.dev20261025+rocm10.1.

Command Result
pytest tests/test_threadx_cpu_locks.py -q (CUDA venv) 6 passed
same, with the threadx.py change stashed (unmodified origin/main) 4 failed, 2 passed
pytest tests/test_threadx.py tests/test_threadx_cpu_locks.py tests/test_calibration_data_device.py -q (CUDA venv, one 4090) 40 passed, 28 skipped in 201 s
pytest tests/test_threadx_cpu_locks.py tests/test_calibration_data_device.py -q (ROCm venv, one R9700) all 6 lock tests passed; one pre-existing integration failure (below)
issue reproducer on both venvs alias shares lock: True, both blocked: False

The 28 skips are the existing require_n_gpus(2) guards on a single visible GPU.

7. Reviewer notes

  • Pre-existing ROCm failure, not a regression.
    tests/test_calibration_data_device.py::TestCalibrationDataDeviceIntegration::test_calibration_data_device_cpu_integration
    fails on this R9700 host with
    ValueError: model.layers.1.mlp.down_proj.scales: 6818 scale value(s) cannot be stored as fp16 ... largest finite source magnitude is 8.242e+36.
    I re-ran that single test with this diff stashed and it fails identically on
    unmodified origin/main, so it is an environment/model issue unrelated to locking.
    It passes in the CUDA run above.
  • Chosen option. The issue offers deduplication or read re-entrancy. I chose
    deduplication because the defect is identity aliasing inside one scope, and
    deduplication fixes read_lock("cpu"), read_lock("all"), lock(), and
    wait(lock=True) in one place without changing _RWLock semantics.
  • Residual scope. A caller that nests two separate read_lock scopes over
    the same device still queues behind a waiting writer on the inner scope. No
    shipped call site nests them (gptqmodel/looper/stage_inputs_capture.py takes
    a single family read lock), so this is not addressed here; it would require
    per-thread read re-entrancy in _RWLock.

A virtual pool key reuses its parent's _RWLock, and the family map lists
both names, so read_lock("cpu") expanded to two pairs naming the same lock
when the default config contains cpu and model_loader:cpu. _ReadLockGroup
acquired that lock twice. _RWLock.acquire_read blocks new readers while a
writer waits, so the second acquisition waited for a writer that was
itself waiting for the reader's first acquisition: a permanent deadlock.

Deduplicate scope pairs by lock identity, keeping first-seen order, in the
shared _LockGroup and _ReadLockGroup constructors. Every multi-lock path
(family read scope, read_lock("all"), lock(), wait(lock=True)) routes
through them, so all of them now acquire each lock once. Distinct locks
keep their canonical order and release order stays the exact reverse, so
two scopes over the same locks still cannot interleave. Writer preference
is unchanged, and the alias still shares the parent lock.

Fixes #3878
@Qubitium
Qubitium merged commit 8ecc295 into main Nov 14, 2026
4 of 6 checks passed
@Qubitium
Qubitium deleted the fix/issue-3878 branch November 14, 2026 08:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CPU family read lock can deadlock against a writer through its shared virtual alias

1 participant