Skip to content

fix(concurrency): refcount global guards and serialize Triton JIT (#4094) - #4102

Merged
Qubitium merged 4 commits into
mainfrom
fix/issue-4094-concurrency
Nov 15, 2026
Merged

Qubitium merged 4 commits into
mainfrom
fix/issue-4094-concurrency

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #4094

TL;DR

Three concurrency defects, one branch, net +732/-45 lines across the guards, the Triton patch, and the compiler-failure classifier. Process-global BLAS/TF32 guards are now reference-counted, Triton JIT compilation is single-flight and globally serialized, and dynamo guard assertions fall back to eager instead of aborting a forward.

1. The problem

Item Old mechanism File:line at 718256fd7
1 quant_blas_backend snapshots/restores the process-global BLAS backend on every entry; no count, no lock gptqmodel/utils/rocm.py:240-283, entered at gptqmodel/models/base.py:2128
1 tf32_high_precision_guard snapshots/restores the process-global TF32 state on every entry gptqmodel/utils/torch.py:1021, entered at gptqmodel/looper/module_looper.py:1777
2 TritonPatch patched only Autotuner; JITFunction._do_compile was unguarded gptqmodel/utils/nogil_patcher.py:57
3 _is_compiler_failure checked frame origin only for RuntimeError; dynamo's guard AssertionError escaped gptqmodel/utils/torch.py:332

Old guard flow (wrong when two quantizes overlap):

flowchart TD
    A["quantize A enters"] --> B["snapshot Cublaslt, set Cublas"]
    B --> C["quantize B enters"]
    C --> D["sees Cublas, skips override"]
    D --> E["A exits, restores Cublaslt"]
    E --> F["B's remaining layers run on Cublaslt"]
    F --> G["checkpoint differs from serial run"]
Loading

Before/after measured on ROCm gfx1201: an outer quantize guard exited while a real 32-sample Qwen2.5-0.5B quantize was still running. 76 of its Hessian inverses ran after that exit.

Metric Before After
Tensors differing from a serial run 268 of 504, 2/2 runs 0 of 504, 3/3 runs
BLAS seen by those 76 post-exit Hessian calls Cublaslt Cublas

The issue measured 177-210 of 794 on its checkpoint layout; the count differs with the model/sample shape, the defect is the same.

2. The new flow

Reference-counted BLAS/TF32 guards

flowchart TD
    A["guard enter"] --> B{"depth == 0"}
    B -- yes --> C["snapshot user setting"]
    C --> D["apply override"]
    D --> E["depth = 1"]
    B -- no --> F["depth += 1, keep override"]
    E --> G["caller runs"]
    F --> G
    G --> H["guard exit: depth -= 1"]
    H --> I{"depth == 0"}
    I -- yes --> J["restore snapshot"]
    I -- no --> K["another caller still inside"]
Loading

_QUANT_BLAS_GUARD_LOCK/_QUANT_BLAS_GUARD_DEPTH/_QUANT_BLAS_GUARD_PREVIOUS (gptqmodel/utils/rocm.py:240-319) and _TF32_GUARD_LOCK/_TF32_GUARD_DEPTH/_TF32_GUARD_PREVIOUS (gptqmodel/utils/torch.py:313-320, guard at :1030-1062) implement this. The first entry owns the snapshot; only the last exit restores it. Concurrent quantize() calls stay concurrent; nothing is serialized.

This composes with #4092's narrower Hessian/linalg placement: the count depends only on entry/exit, not on which phase wraps the context. It also works when the two callers enter from different phases.

Single-flight, globally serialized Triton JIT

flowchart TD
    A["JITFunction.run cache miss"] --> B["patched_do_compile"]
    B --> C["acquire _TRITON_COMPILE_LOCK"]
    C --> D{"kernel cache has key"}
    D -- yes --> E["return cached kernel"]
    D -- no --> F["libtriton compile"]
    F --> G["store kernel"]
    G --> H["release lock"]
    E --> H
Loading

patch_triton_jit_compile (gptqmodel/utils/nogil_patcher.py:97-122) wraps JITFunction._do_compile; _single_flight_triton_compile (:80-94) rechecks the per-device kernel cache under _TRITON_COMPILE_LOCK (:77). Same-key misses collapse into one compile; different keys are serialized because the unsafe nanobind state is process-global inside libtriton. The lock is taken only on a cache miss. The MACaQ Triton kernels launch through the same JITFunction.run path and are covered by the same wrapper.

Dynamo guard assertions are compiler failures

flowchart TD
    A["compiled callable raises"] --> B["_is_compiler_failure"]
    B --> C{"control flow exception"}
    C -- yes --> D["propagate"]
    C -- no --> E{"BackendCompilerFailed or TorchRuntimeError"}
    E -- yes --> F["eager fallback"]
    E -- no --> G{"fullgraph"}
    G -- yes --> H["propagate"]
    G -- no --> I{"cause chain has TorchDynamoException"}
    I -- yes --> F
    I -- no --> J{"innermost frame in torch compiler package"}
    J -- yes --> F
    J -- no --> K["propagate user error"]
Loading

_is_compiler_failure (gptqmodel/utils/torch.py:338-382) now applies the innermost-frame origin check to every non-control-flow exception, not only RuntimeError. A dynamo guard AssertionError originates in torch/_dynamo/guards.py, so the eager path runs. User code raising AssertionError keeps its own frame at the origin and still propagates; fullgraph=True still fails closed.

3. Failure and ambiguity contract

Situation Result
Platform refuses the BLAS switch guard yields without counting; caller keeps its backend
User already selected non-hipBLASLt guard yields without counting
Restore raises swallowed; the quantization result is already computed
Triton compile raises lock released; next miss retries
Triton cache already populated no lock, no compile
Dynamo guard fails on a user frame propagates; no double execution
fullgraph=True capture failure propagates; no silent fallback

4. Change inventory

Area File +/- Purpose
BLAS guard gptqmodel/utils/rocm.py +58/-25 RLock + depth + one snapshot
TF32 guard gptqmodel/utils/torch.py +46/-19 RLock + depth + one snapshot
Compiler failure gptqmodel/utils/torch.py +15/-8 innermost-frame check for all exceptions
Triton JIT gptqmodel/utils/nogil_patcher.py +68/-4 global compile lock + cache recheck
Docs docs/concurrency.md +175 mechanism, diagrams, contracts
Docs link README.md +7/-1 link from the Triton patch section
Ledger pytorch_gil_0_compat.md +27/-1 AWQ cold JIT row and manual finding 10
Tests tests/test_concurrency_guards.py +147 two-thread and nested guard counts
Tests tests/test_awq_triton_cold_jit.py +100 GIL=0 child, empty cache, 24 threads, 2 runs
Tests tests/test_triton_patch_api.py +98 same-key single-flight, cross-key serialization
Tests tests/test_torch_compile_fallback.py +48 dynamo guard fallback, user assertion propagation

5. Tests and guarantees

Test Invariant
test_quant_blas_backend_is_reference_counted first exit does not restore while a second caller is inside
test_quant_blas_backend_nested_entries_restore_once nested entries restore once
test_tf32_high_precision_guard_is_reference_counted user TF32 setting survives two concurrent guards
test_single_flight_triton_compile_compiles_one_key_once 8 same-key misses compile once and share the kernel
test_single_flight_triton_compile_serializes_distinct_keys max concurrent compiles is 1
test_triton_jit_compile_patch_is_installed JITFunction._do_compile is wrapped
test_macaq_triton_kernels_use_the_patched_jit_function MACaQ kernels share the patched JITFunction
test_cold_concurrent_awq_triton_jit_exits_cleanly PYTHON_GIL=0, empty cache, 24 threads, exit 0, repeated twice
test_dynamo_guard_assertion_falls_back_to_eager guard AssertionError from a dynamo frame runs eager
test_user_assertion_is_not_misread_as_a_compiler_failure user assertion propagates, no retry

Fail-before evidence (old 718256fd7 worktree at /tmp/main4094):

  • tests/test_concurrency_guards.py: 3 failed.
  • tests/test_triton_patch_api.py -k "single_flight or jit_compile_patch": 3 failed (no attribute '_single_flight_triton_compile').
  • tests/test_awq_triton_cold_jit.py: 1 failed, child exited -6 (SIGABRT).
  • tests/test_torch_compile_fallback.py -k "dynamo_guard": 1 failed with the guard AssertionError.

6. Validation

Hardware:

  • ROCm 10.1, Radeon AI PRO R9700 gfx1201, HIP_VISIBLE_DEVICES=0 only, torch 2.16.0.dev20261025+rocm10.1, Python 3.14.10t, /opt/venvs/rocm101t/bin/python.
  • CUDA RTX 4090 GPU-50a20676-a7a4-8bb3-eb3d-f191fdc9fa42, torch 2.16.0.dev+cu130, Python 3.14.10t, /opt/venvs/cu130t/bin/python. The RTX 5090 was never touched.

Item 1 (ROCm, two quantizes overlapping; 32-sample Qwen2.5-0.5B, 76 Hessian inverses after the first guard exit):

# before, /tmp/main4094 = 718256fd7
PYTHONPATH=/tmp/main4094 HIP_VISIBLE_DEVICES=0 /opt/venvs/rocm101t/bin/python /tmp/repro_4094_item1.py
# CONCURRENT vs SERIAL: 268/504 tensors differ
# BLAS seen after A returned: 76 ... Cublaslt     (2/2 runs)

# after
PYTHONPATH=$PWD HIP_VISIBLE_DEVICES=0 /opt/venvs/rocm101t/bin/python /tmp/repro_4094_item1.py
# CONCURRENT vs SERIAL: 0/504 tensors differ
# BLAS seen after A returned: 76 ... Cublas       (3/3 runs)

Item 2 (ROCm, PYTHON_GIL=0, empty TRITON_CACHE_DIR, 24 threads generate() on AWQ-Llama-3.2-1B-g128-gemm):

# before
PYTHONPATH=/tmp/main4094 HIP_VISIBLE_DEVICES=0 PYTHON_GIL=0 /opt/venvs/rocm101t/bin/python /tmp/repro_4094_item2.py 24
# rc=134, Critical nanobind error: inst_dealloc("triton._C.libtriton.ir.type")
# 4/4 runs at 24 threads; also 4/4 at 32 threads

# after
PYTHONPATH=$PWD HIP_VISIBLE_DEVICES=0 PYTHON_GIL=0 /opt/venvs/rocm101t/bin/python /tmp/repro_4094_item2.py 24
# rc=0, done in 5.7-7.5s, errors=[] alive=[]   (4/4 runs)

Cold-start cost of the one-time compile, single-threaded on the same model: first generate() 2.60 s, second (warm) 0.33 s. The lock serializes only this cold compile; steady-state launches are unchanged.

Item 3 (CUDA, 40 compile/race iterations per mode):

# before, PYTHON_GIL=0
PYTHONPATH=/tmp/main4094 PYTHON_GIL=0 /opt/venvs/cu130t/bin/python /tmp/probe_dtype.py
# ok=18 fail=22   (GIL=1 initial probe: 2 failures in 40)

# after, PYTHON_GIL=0 and PYTHON_GIL=1
PYTHONPATH=$PWD PYTHON_GIL=0 /opt/venvs/cu130t/bin/python /tmp/probe_dtype.py   # ok=40 fail=0
PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python /tmp/probe_dtype.py                 # ok=40 fail=0

Natural 3-thread GPTQModel.load + generate with TorchLinear on CUDA: ok=3 failed=0 after the fix.

Committed test suites, after merging origin/main:

PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest \
  tests/test_concurrency_guards.py tests/test_rocm_quant_blas.py \
  tests/test_rocm_quant_tuning.py tests/test_triton_patch_api.py \
  tests/test_torch_compile_fallback.py -q
# 64 passed

PYTHONPATH=$PWD /opt/venvs/rocm101t/bin/python -m pytest \
  tests/test_concurrency_guards.py tests/test_rocm_quant_blas.py \
  tests/test_rocm_quant_tuning.py tests/test_triton_patch_api.py \
  tests/test_torch_compile_fallback.py -q
# 64 passed

PYTHONPATH=$PWD HIP_VISIBLE_DEVICES=0 PYTHON_GIL=0 \
  /opt/venvs/rocm101t/bin/python -m pytest tests/test_awq_triton_cold_jit.py -q
# 1 passed (two cold child processes)

CUDA_VISIBLE_DEVICES=GPU-50a20676-a7a4-8bb3-eb3d-f191fdc9fa42 PYTHONPATH=$PWD PYTHON_GIL=0 \
  /opt/venvs/cu130t/bin/python -m pytest tests/test_awq_triton_cold_jit.py -q
# 1 passed

ruff check gptqmodel docs/eora tests setup.py
# All checks passed!

7. Reviewer notes

  • quant_blas_backend remains scoped where callers enter it. [BUG][ROCm] Follow-up on #4072/#4075: CUDA-only JIT loads hipify over tracked tt_blockfloat_hip sources, AWQ Triton split-K nondeterministic (AUTO on RDNA4), forced rocBLAS 8-14x slower fp16/bf16 GEMM, hipblaslt opt-in non-reproducible #4092 can move that scope to the Hessian/linalg phase; the refcount does not depend on the phase.
  • The Triton lock serializes cold compilation of different kernels too. The measured cost is the one-time 2.27 s compile on this model; warm launches do not take the lock. Single-flight per key alone would leave unrelated kernels compiling concurrently, which the libtriton nanobind state does not tolerate.
  • _is_compiler_failure now classifies any exception whose innermost frame is inside torch/_dynamo, torch/_inductor, or torch/_functorch. A user exception keeps its own origin frame and is not retried; fullgraph=True still propagates capture failures.
  • docs/concurrency.md is committed and linked from the README Triton-patch section. pytorch_gil_0_compat.md records the AWQ cold-JIT row and manual finding 10.
  • No GPTQMODEL_* behaviour switch was added. No whole-quantize() serialization. No dense weight cache was introduced.

Comment thread gptqmodel/utils/rocm.py Resolved
Comment thread gptqmodel/utils/torch.py Resolved
Comment thread tests/test_concurrency_guards.py Resolved
@Qubitium
Qubitium merged commit dd67ee7 into main Nov 15, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-4094-concurrency branch November 15, 2026 09:01
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