Repository navigation
fix(gil0): propagate thread-pool errors and isolate Triton autotuner state (#3972) - #3986
Merged
Merged
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #3972
TL;DR
DeviceThreadPoolno longer callsos._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-wideos.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._runset 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;Mechanisms removed (line numbers from base
origin/mainat00163850):_abort_processafterfut.set_exception(gptqmodel/utils/threadx.py:556-562,570-581)_DeviceWorker._runkeeps the worker alive_abort_processthenreturn(gptqmodel/utils/threadx.py:531-535)_on_task_finished;fut.set_exception;continue;_WorkerWarmupStatecaches the error_SyncWorker.submit)nargsself.nargsset/reset (gptqmodel/utils/nogil_patcher.py:257,291)Autotuner.nargs/best_configare thread-local data descriptorsself.nargs, unlockedself.cache(gptqmodel/nn_modules/triton_utils/custom_autotune.py:93-123)nargsargument plus thread-local property and_cache_lockgptqmodel/quantization/gptq.py:110-111,231-289)release_workspace_cache(); called fromLoopProcessor.finalize_temporary_merged_cuda_arch_overridemutatesTORCH_CUDA_ARCH_LIST(gptqmodel/utils/cpp.py:951-969,1911-1914)_merged_cuda_arch_flagspasses explicit-gencodeflags viaextra_cuda_cflagsGPTQMODEL_EXT_VERBOSE(gptqmodel/utils/cpp.py:2193-2203,2229-2237)verbose=throughextension.loadandTorchOpsJitExtension.load2. 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;LoopProcessor.log_save_asyncis fire-and-forget, so it attaches_on_async_log_failureto log a failed write instead of dropping it.stage_subset._collect_worker_results,stage_layer._drain_finalize_futures,forward_executor'sfut.result(),stream_sync'sfuture.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;CustomizedTritonAutoTuneradditionally passesnargsexplicitly to_benchandprune_configs; its_nargs_stateuses atomicdict.setdefaultso two threads cannot create competingthreading.localobjects.4. Failure and ambiguity contract
os._exit(1)future.result()raises; pool stays usableos._exit(1)_WorkerWarmupStateerrornargscould replace A's during_bench/prune_configs/pre_hooknargs; shared cache stays lockedrelease_workspace_cache()races an active lease_WORKSPACE_GENERATIONchange and drops its slotTORCH_CUDA_ARCH_LISTset during a buildextra_cuda_cflags5. Change inventory
gptqmodel/utils/threadx.py_abort_processfrom task and warmup pathsgptqmodel/looper/loop_processor.pyfinalizegptqmodel/utils/nogil_patcher.pynargs/best_config; reentrant apply lockgptqmodel/nn_modules/triton_utils/custom_autotune.pynargs, TLS property, locked cachegptqmodel/quantization/gptq.pyrelease_workspace_cache()gptqmodel/utils/cpp.pygptqmodel/extension.pyverboseREADME.md,pytorch_gil_0_compat.md,docs/thread-pool-error-contract.mdtests/test_threadx.py,tests/test_torch_ops_jit_extension.py, 3 new files6. Tests / guarantees
tests/test_threadx_error_propagation.py::test_task_and_warmup_failures_do_not_exit_the_processatexitmarker writtentests/test_triton_autotuner_concurrency.py::test_nogil_patch_keeps_autotuner_nargs_thread_local_benchstill sees A'snargswhile B runstests/test_triton_autotuner_concurrency.py::test_custom_autotuner_keeps_nargs_thread_localCustomizedTritonAutoTunertests/test_gptq_workspace_release.py(3 tests)LoopProcessor.finalizecalls releasetests/test_torch_ops_jit_extension.pyextra_cuda_cflags; env unchanged; explicitverboseforwarded7. Validation
Hardware: NVIDIA RTX 4090
GPU-50a20676-a7a4-8bb3-eb3d-f191fdc9fa42(CUDA) and AMD Radeon R9700HIP_VISIBLE_DEVICES=3(ROCm). All runs usedPYTHON_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):
Pass-after suites:
Full lint gate:
ruff check gptqmodel docs/eora tests setup.pyreports one pre-existingF401 audioreadingptqmodel/utils/audio.py:16, which is unchanged by this PR and reproduces onorigin/main.8. Reviewer notes
GPTQMODEL_*behaviour switch.release_workspace_cache()is called atLoopProcessor.finalize, not on everytorch_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_lookuphas a pre-existing narrow race: a late thread can observe the cache entry published just before the per-keyCacheFutureis removed and returnused_cached_result=True. It reproduced once in five runs and is unchanged by this PR.docs/thread-pool-error-contract.md, linked fromREADME.mdnext to the device thread pool shutdown documentation.