Skip to content

fix(gil0): propagate thread-pool errors and isolate Triton autotuner state (#3972) - #3986

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-3972
Nov 14, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-3972

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #3972

TL;DR

DeviceThreadPool no longer calls os._exit(1) from a worker: task and warmup failures resolve their future with the exception, so the caller unwinds normally. The GIL=0 Triton autotuner scratch state (nargs, best_config) is per-thread instead of a shared attribute, the GPTQ Hessian workspace pool is releasable, and JIT builds no longer mutate process-wide os.environ. Net tracked diff: +400/−176 across 11 files, plus 4 new files (457 lines). The architectural consequence is that a failed quantization task is now an ordinary catchable exception, not a process kill.

1. The problem

Old task path: _DeviceWorker._run set the future exception and then killed the interpreter.

flowchart TD
    A["_DeviceWorker._run"] --> B["_run_warmup"]
    B -- "exception" --> D["_abort_process"]
    B -- "ok" --> C["fn(*args, **kwargs)"]
    C -- "exception" --> E["_on_task_finished, fut.set_exception"]
    E --> D
    C -- "result" --> R["_on_task_finished, fut.set_result"]
    D --> F["traceback.print_exception"]
    F --> G["os._exit(1)"]
    G --> X["finally / atexit / checkpoint restore skipped, caller cannot catch"]
    classDef failure fill:#ffe8e8,stroke:#b30000,color:#111;
    class D,G,X failure;
Loading

Mechanisms removed (line numbers from base origin/main at 00163850):

Area Before After
Task exception _abort_process after fut.set_exception (gptqmodel/utils/threadx.py:556-562, 570-581) exception stays on the future; _DeviceWorker._run keeps the worker alive
Warmup failure _abort_process then return (gptqmodel/utils/threadx.py:531-535) _on_task_finished; fut.set_exception; continue; _WorkerWarmupState caches the error
Sync worker already only set the exception (_SyncWorker.submit) unchanged; both worker kinds agree
Triton patch nargs shared self.nargs set/reset (gptqmodel/utils/nogil_patcher.py:257, 291) Autotuner.nargs/best_config are thread-local data descriptors
GGUF autotuner shared self.nargs, unlocked self.cache (gptqmodel/nn_modules/triton_utils/custom_autotune.py:93-123) explicit nargs argument plus thread-local property and _cache_lock
Hessian workspace module-level pool survives the run (gptqmodel/quantization/gptq.py:110-111, 231-289) release_workspace_cache(); called from LoopProcessor.finalize
JIT arch override _temporary_merged_cuda_arch_override mutates TORCH_CUDA_ARCH_LIST (gptqmodel/utils/cpp.py:951-969, 1911-1914) _merged_cuda_arch_flags passes explicit -gencode flags via extra_cuda_cflags
JIT verbosity set/pop GPTQMODEL_EXT_VERBOSE (gptqmodel/utils/cpp.py:2193-2203, 2229-2237) explicit verbose= through extension.load and TorchOpsJitExtension.load

2. The new flow

flowchart TD
    A["_DeviceWorker._run"] --> B["_run_warmup"]
    B -- "exception" --> W["_on_task_finished,<br/>fut.set_exception, continue"]
    B -- "ok" --> C["fn under ctx(read lock, _device_ctx)"]
    C -- "exception" --> E["_on_task_finished,<br/>fut.set_exception"]
    C -- "result" --> R["_on_task_finished,<br/>fut.set_result"]
    W --> Q["caller future.result raises"]
    E --> Q
    R --> S["caller receives result"]
    Q --> U["normal unwind: finally, atexit, checkpoint signal restore"]
    classDef failure fill:#ffe8e8,stroke:#b30000,color:#111;
    class W,E,Q failure;
Loading

LoopProcessor.log_save_async is fire-and-forget, so it attaches _on_async_log_failure to log a failed write instead of dropping it. stage_subset._collect_worker_results, stage_layer._drain_finalize_futures, forward_executor's fut.result(), stream_sync's future.result(), and the linalg/weight-only submits already consume their futures; they now receive the error instead of racing a dying process.

3. Triton autotuner state

flowchart LR
    A["Thread A: patched_run"] -- "self.nargs = nargs (TLS)" --> T1["threading.local A"]
    B["Thread B: patched_run"] -- "self.nargs = nargs (TLS)" --> T2["threading.local B"]
    T1 --> C["_get_config_for_key key A"]
    T2 --> D["_get_config_for_key key B"]
    C --> E["_bench / prune_configs / pre_hook read A nargs"]
    D --> F["_bench / prune_configs / pre_hook read B nargs"]
    C --> G["_cache_lock guards shared _cache and _cache_futures"]
    D --> G
    classDef failure fill:#ffe8e8,stroke:#b30000,color:#111;
Loading

CustomizedTritonAutoTuner additionally passes nargs explicitly to _bench and prune_configs; its _nargs_state uses atomic dict.setdefault so two threads cannot create competing threading.local objects.

4. Failure and ambiguity contract

Situation Before After
Submitted task raises future exception set, then os._exit(1) future.result() raises; pool stays usable
Warmup raises os._exit(1) first task's future raises; later tasks raise the cached _WorkerWarmupState error
Async log write raises process died done-callback logs it
Two threads run one autotuned kernel B's nargs could replace A's during _bench/prune_configs/pre_hook each thread reads its own nargs; shared cache stays locked
release_workspace_cache() races an active lease pool repopulated lease observes _WORKSPACE_GENERATION change and drops its slot
TORCH_CUDA_ARCH_LIST set during a build process-wide env rewritten for minutes environment unchanged; flags travel in extra_cuda_cflags

5. Change inventory

Area File ± lines Purpose
Thread pool gptqmodel/utils/threadx.py +10/−18 remove _abort_process from task and warmup paths
Async log gptqmodel/looper/loop_processor.py +17/−1 log failed fire-and-forget writes; release workspace in finalize
Triton patch gptqmodel/utils/nogil_patcher.py +73/−39 thread-local nargs/best_config; reentrant apply lock
GGUF tuner gptqmodel/nn_modules/triton_utils/custom_autotune.py +74/−32 explicit nargs, TLS property, locked cache
Workspace pool gptqmodel/quantization/gptq.py +34/−8 generation-guarded release_workspace_cache()
JIT env gptqmodel/utils/cpp.py +76/−46 explicit arch flags and explicit verbose
Extension API gptqmodel/extension.py +12/−3 forward verbose
Docs README.md, pytorch_gil_0_compat.md, docs/thread-pool-error-contract.md +167 contract, ledger, diagrams
Tests tests/test_threadx.py, tests/test_torch_ops_jit_extension.py, 3 new files +423/−18 regression coverage

6. Tests / guarantees

Test Invariant
tests/test_threadx_error_propagation.py::test_task_and_warmup_failures_do_not_exit_the_process free-threaded subprocess: task and warmup futures raise, pool stays usable, atexit marker written
tests/test_triton_autotuner_concurrency.py::test_nogil_patch_keeps_autotuner_nargs_thread_local A's _bench still sees A's nargs while B runs
tests/test_triton_autotuner_concurrency.py::test_custom_autotuner_keeps_nargs_thread_local same contract for CustomizedTritonAutoTuner
tests/test_gptq_workspace_release.py (3 tests) pool cleared; an in-flight lease does not repopulate it; LoopProcessor.finalize calls release
tests/test_torch_ops_jit_extension.py arch flags are in extra_cuda_cflags; env unchanged; explicit verbose forwarded

7. Validation

Hardware: NVIDIA RTX 4090 GPU-50a20676-a7a4-8bb3-eb3d-f191fdc9fa42 (CUDA) and AMD Radeon R9700 HIP_VISIBLE_DEVICES=3 (ROCm). All runs used PYTHON_GIL=0, PYTHONPATH=$PWD, and the free-threaded venvs (sys._is_gil_enabled() is False).

Fail-before / pass-after (source fix temporarily reverted, then restored):

# threadx.py reverted to origin/main
PYTHON_GIL=0 .../cu130t/bin/python -m pytest -q tests/test_threadx_error_propagation.py
-> 1 failed in 4.34s; subprocess returncode=1 (os._exit), atexit marker missing
# fix restored
-> 1 passed in 5.04s

# nogil_patcher.py + custom_autotune.py reverted
-> 2 failed in 22.73s ("thread A did not finish" — A's second config read B's nargs)
# fix restored
-> 2 passed in 2.34s

# gptq.py + loop_processor.py reverted
-> 3 failed (AttributeError: no release_workspace_cache)
# fix restored
-> 3 passed in 2.64s

Pass-after suites:

CUDA, PYTHON_GIL=0, pytest -q <new tests + threadx + threadx_shutdown + p2p + torch_safety_gate
  + torch_ops_jit_extension + triton_patch_api + extension_load_api>
-> 251 passed, 34 skipped in 27.69s

CUDA, required regression set only
-> 141 passed, 34 skipped in 17.64s

CUDA, pytest -q tests/test_gptq_hessian_accumulation.py tests/test_gptq_hessian_memory.py tests/test_hessian.py
-> 21 passed, 17 skipped in 32.55s

ROCm, new tests
-> 6 passed in 10.12s

ROCm, threadx + threadx_shutdown + torch_ops_jit_extension + triton_patch_api
-> 106 passed, 24 skipped in 5.13s

ruff check <all changed files>
-> All checks passed!

Full lint gate: ruff check gptqmodel docs/eora tests setup.py reports one pre-existing F401 audioread in gptqmodel/utils/audio.py:16, which is unchanged by this PR and reproduces on origin/main.

8. Reviewer notes

  • No fail-fast switch was added; a caller that wants to abort can re-raise after cleanup. That is the issue's preferred contract and avoids a new GPTQMODEL_* behaviour switch.
  • release_workspace_cache() is called at LoopProcessor.finalize, not on every torch_empty_cache, so the pool still amortizes allocations during a run. The release API is public for hosts that tear down outside the looper.
  • test_triton_patch_api.py::test_patched_autotuner_lazily_initializes_concurrent_first_lookup has a pre-existing narrow race: a late thread can observe the cache entry published just before the per-key CacheFuture is removed and return used_cached_result=True. It reproduced once in five runs and is unchanged by this PR.
  • The committed reference page is docs/thread-pool-error-contract.md, linked from README.md next to the device thread pool shutdown documentation.

DeviceThreadPool task and warmup failures now resolve their future with the
exception instead of calling os._exit(1), so finally blocks, atexit handlers,
checkpoint restore, and caller try/except all run.

Triton Autotuner.nargs/best_config are per-instance thread-local data
descriptors, and CustomizedTritonAutoTuner passes nargs explicitly while
guarding its cache check-then-set.

The Hessian workspace pool gains release_workspace_cache(), called from
LoopProcessor.finalize(), and JIT builds receive explicit -gencode flags and
an explicit verbose argument instead of mutating process-wide os.environ.
@Qubitium
Qubitium merged commit 1a30538 into main Nov 14, 2026
4 of 6 checks passed
@Qubitium
Qubitium deleted the fix/issue-3972 branch November 14, 2026 12:26
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.

[GIL=0] DeviceThreadPool os._exit on task error, Triton autotuner nargs race, retained workspace and env mutation

1 participant