Skip to content

fix(exllamav3): synchronize the EXL3 native dispatch caches (#3951) - #3966

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

Qubitium merged 1 commit into
mainfrom
fix/issue-3951

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #3951

TL;DR

select_exl3_gemm_kernel_tuned and exl3_gemm fill two process-wide host containers on first use with no synchronization, so PYTHON_GIL=0 callers can race them. This adds a shared/exclusive lock pair (parallel reads, exclusive publish) to both, makes the forced-shape record thread-local, and publishes the kernel-attribute entry only after the setup call succeeds. Net diff: 4 files, +222/-13.

1. The problem

Old flow, with the unsynchronized accesses marked:

flowchart TD
    A["exl3_gemm: A, B, C"] --> B["select_exl3_gemm_kernel_tuned"]
    B --> C{"force_shape_idx is positive?"}
    C -->|yes| D["write process-wide forced_result"]
    D --> E["return pointer to the shared record"]
    C -->|no| F["tuning_cache.find key, no lock"]
    F --> G{"found?"}
    G -->|no| H["sample packed table, then tuning_cache[key] assignment, no lock"]
    H --> I["tuning_cache.find key again, no lock"]
    G -->|yes| I
    I --> J["kernel_attr_set device find, no lock"]
    J --> K{"attribute already set?"}
    K -->|no| L["cudaFuncSetAttribute, then insert into the set, no lock"]
    K -->|yes| M["launch kernel"]
    L --> M
    classDef race fill:#fdd,stroke:#b00,color:#700
    class D,F,H,I,J,L race
Loading
Mechanism Where the old logic lived
Tuned-kernel cache gptqmodel_ext/exllamav3/quant/exl3_kernel_map.cu:29 declared, :173 read, :193 written, :201 re-read
Forced-shape record gptqmodel_ext/exllamav3/quant/exl3_kernel_map.cu:30, written per call at :157-161
Kernel attribute set gptqmodel_ext/exllamav3/quant/exl3_gemm.cu:29, read and inserted at :119-127

Two first-use GEMMs on different Python threads can therefore execute a find and an insert on the same std::map concurrently — undefined behaviour that can corrupt the container or return the wrong dispatch result. The forced-shape branch additionally rewrites one shared TResult that another thread may still be reading through the returned pointer.

2. The new flow

flowchart TD
    A["exl3_gemm: A, B, C"] --> B["select_exl3_gemm_kernel_tuned"]
    B --> C{"force_shape_idx is positive?"}
    C -->|yes| D["write thread-local forced_result"]
    D --> E["return this thread's record"]
    C -->|no| F["shared_lock: tuning_cache.find key"]
    F --> G{"found?"}
    G -->|yes| H["return the stable map node pointer"]
    G -->|no| I["unique_lock: re-check, sample table, emplace the record"]
    I --> H
    H --> J["exl3_gemm: shared_lock: kernel_attr_set device lookup"]
    J --> K{"attribute already set?"}
    K -->|yes| M["launch kernel"]
    K -->|no| L["unique_lock: re-check, cudaFuncSetAttribute, insert"]
    L --> M
    style I fill:#dfd,stroke:#060
    style L fill:#dfd,stroke:#060
Loading

std::map and std::set nodes are stable and nothing erases from either container, so a pointer returned under the lock stays valid after it is released. The steady state is a shared lock, so cached dispatches still run in parallel — the exclusive lock is entered only to publish a new entry, which is the one-time initialization the issue asks for.

std::map<uint64_t, TResult> tuning_cache = {};
std::shared_mutex tuning_cache_mutex;
thread_local TResult forced_result;
...
{
    std::shared_lock<std::shared_mutex> guard(tuning_cache_mutex);
    auto lookup = tuning_cache.find(key);
    if (lookup != tuning_cache.end()) return &(lookup->second);
}
std::unique_lock<std::shared_mutex> guard(tuning_cache_mutex);
auto lookup = tuning_cache.find(key);          // re-check
if (lookup == tuning_cache.end()) {
    lookup = tuning_cache.emplace(key, TResult{...}).first;
}
return &(lookup->second);

exl3_gemm uses the same shape for kernel_attr_set[device], with one extra ordering fix: the entry is inserted only after cudaFuncSetAttribute and its cuda_check succeed, so a failed setup is retried by the next launch instead of being remembered as done.

3. Failure and ambiguity contract

Situation Before After
Two threads dispatch different shapes for the first time concurrent find and insert on one std::map one writer under unique_lock, readers under shared_lock
Two threads dispatch the same shape for the first time both may insert; the trailing find decides the loser re-checks and reuses the published entry
Two threads force a shape at once one caller's forced_result overwrites the other's each caller has its own thread_local record
First launch of a kernel variant on two devices concurrent insert into two sets without a lock shared probe, then one exclusive publish per (device, kernel)
cudaFuncSetAttribute fails the variant was marked done before the error was raised the error propagates and the variant stays unmarked

4. Change inventory

File +/- Purpose
gptqmodel_ext/exllamav3/quant/exl3_kernel_map.cu +45/-15 shared_mutex around tuning_cache; thread_local forced_result; emplace iterator replaces the second find
gptqmodel_ext/exllamav3/quant/exl3_gemm.cu +29/-14 shared_mutex around kernel_attr_set[device]; publish only after a successful attribute call
tests/test_exl3_dispatch_concurrency.py +187 concurrent cold-start test
docs/exl3-native-dispatch-caches.md +112 reference page with the same diagrams

5. Tests

Test Invariant
`tests/test_exl3_dispatch_concurrency.py::test_concurrent_first_use_of_the_exl3_dispatch_caches[first second]`

6. Validation

Hardware: RTX 4090 (GPU-50a20676-a7a4-8bb3-eb3d-f191fdc9fa42), torch 2.16.0.dev20261102+cu130, nvcc 13.4, Python 3.14.10t. The EXL3 extension builds and loads on this host, so the native path is exercised rather than mocked.

Command Result
pytest tests/test_exl3_dispatch_concurrency.py -q 2 passed
pytest over the 14 importable tests/test_exl3_*.py plus tests/test_exllamav3.py, tests/test_exllamav3_cpu.py, tests/test_exllamav3_jit.py 197 passed, 4 skipped
ad-hoc probe: PYTHON_GIL=0, 16 threads on a barrier, 16 shapes, 6 fresh processes 6/6 OK
ruff check gptqmodel docs/eora tests setup.py All checks passed

Extension rebuilds were confirmed by a new cache key under ~/.cache/gptqmodel/torch_extensions/exllamav3/ for each source revision tested.

Six other tests/test_exl3_*.py files cannot be collected on this host because the CUDA venv lacks xxhash; that gap predates this change.

7. Reviewer notes — measured before/after

Honest limitation, also recorded in docs/exl3-native-dispatch-caches.md: the pre-fix race is undefined behaviour and does not reproduce deterministically here. The new test passes against the unfixed sources as well, so it is a regression guard on the observable contract (no crash, correct results under a cold concurrent burst), not a reproduction of a captured corruption. The fix is justified by the C++ memory model: both containers were read and written without synchronization from threads that PYTHON_GIL=0 allows to run concurrently.

The native tensor-core GEMM is NVIDIA-only. On ROCm the kernel tables are null and exl3_gemm fails closed with an actionable message, so the test skips there.

`select_exl3_gemm_kernel_tuned` fills a process-wide `std::map` and
`exl3_gemm` a per-device `std::set` on first use. Neither was synchronized,
so two threads under `PYTHON_GIL=0` could read and write the same container
at once: a C++ data race that can corrupt the container or pick the wrong
dispatch result. The per-device `OptionalCUDAGuard` only selects the context.

- `tuning_cache` is guarded by a `std::shared_mutex`. The steady state is a
  shared lookup, so concurrent dispatches still run in parallel; the
  exclusive lock is taken only on a miss, to build and publish the entry.
  `emplace` returns the node iterator, so the second `find` is gone.
- `forced_result` is now `thread_local`: it is rewritten per call, so two
  callers forcing a shape would otherwise overwrite each other's record.
- `kernel_attr_set[device]` is guarded the same way, and the variant is
  published only after `cudaFuncSetAttribute` and its error check pass, so a
  failed setup is retried instead of being recorded as done.

`std::map`/`std::set` nodes are stable and nothing erases, so pointers
returned from under the lock stay valid.

Adds `tests/test_exl3_dispatch_concurrency.py` (8 threads, barrier, fresh
process, `PYTHON_GIL=0`, four shapes, reconstruct + hgemm oracle) and
`docs/exl3-native-dispatch-caches.md` with the before/after flow.
@Qubitium
Qubitium merged commit 1fd770e into main Nov 14, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-3951 branch November 14, 2026 10: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.

EXL3 native dispatch caches race on concurrent GIL=0 first use

1 participant