[None][feat] Hang detection for executor loop and worker.#10480
[None][feat] Hang detection for executor loop and worker.#10480yuxianq merged 7 commits intoNVIDIA:mainfrom
Conversation
Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
|
/bot run --disable-fail-fast |
📝 WalkthroughWalkthroughIntroduces a hang detection system for TensorRT-LLM executors using an asyncio-based HangDetector that monitors for execution hangs in a background thread. The detector is integrated into PyExecutor and ExecutorRequestQueue, with checkpointing at key execution points. Includes utility functions for periodic stack printing across initialization and worker processes. Changes
Sequence Diagram(s)sequenceDiagram
participant PyExec as PyExecutor
participant ReqQueue as ExecutorRequestQueue
participant Detector as HangDetector
participant AsyncLoop as Async Event Loop<br/>(Background Thread)
participant Callback as on_detected<br/>Callback
Note over PyExec,Callback: Hang Detection Flow
PyExec->>Detector: start() on warmup
Detector->>AsyncLoop: Create event loop in daemon thread
loop Each Execution Iteration
PyExec->>ReqQueue: fetch_requests()
ReqQueue->>Detector: checkpoint()
Detector->>AsyncLoop: schedule _detect_hang() task
AsyncLoop->>AsyncLoop: async sleep(timeout)
alt Execution Completes in Time
ReqQueue-->>PyExec: requests ready
PyExec->>Detector: checkpoint() at next point
Detector->>AsyncLoop: cancel prior task, schedule new
else Timeout Expires
AsyncLoop->>AsyncLoop: mark hang detected
AsyncLoop->>AsyncLoop: log error, print stacks
AsyncLoop->>Callback: invoke callback
Callback->>PyExec: signal error, set shutdown
PyExec->>PyExec: early exit, skip worker wait
end
end
PyExec->>Detector: stop() on shutdown
Detector->>AsyncLoop: cancel tasks, stop loop, join thread
Estimated Code Review Effort🎯 4 (Complex) | ⏱️ ~50 minutes 🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
tensorrt_llm/_common.py (1)
1-14: Update copyright header year to reflect latest modificationThis file now has new runtime behavior but the SPDX copyright line still ends at
2024. Per the project guidelines (“year of latest meaningful modification”), please bump the final year (e.g., to 2025/2026) so the header matches current changes.tensorrt_llm/_torch/pyexecutor/py_executor.py (1)
373-384: Checkpoint/stop usage is good; ensure HangDetector is stopped on all exit pathsThe new
checkpoint()calls at the top of each executor loop and thestop()calls whenshould_stop_processingorscheduled_batch is Noneare well placed and give you a clear notion of “no progress for N seconds” during normal operation.Two lifecycle gaps to address:
Stop detector on exceptional exits
_event_loop_wrapperwrapsself.event_loop()and always invokes_executor_loop_cleanup()infinally, but it never stops the HangDetector. Ifself.event_loop()exits early due to an exception before it reaches thehang_detector.stop()sites in the loops, the detector’s loop thread will keep running indefinitely for the lifetime of the process.You can make cleanup robust by always stopping the detector in the wrapper:
Proposed fix in
_event_loop_wrapperdef _event_loop_wrapper(self): try: with customized_gc_thresholds( self.garbage_collection_gen0_threshold): self.event_loop() except Exception as e: logger.error(f"Error in event loop: {e}") logger.error(traceback.format_exc()) raise e finally:
self._executor_loop_cleanup()
# Ensure hang detector loop is torn down even on exceptions.self.hang_detector.stop()self._executor_loop_cleanup()</details> `stop()` is idempotent relative to the explicit calls in the happy-path breaks.
Shutdown path after a detected hang
In
shutdown(), youenqueue_shutdown_request()andwait()onshutdown_event, then:if self.hang_detector.detected(): return self.worker_thread.join()Skipping
join()when a hang is detected makes sense to avoid blocking forever, but it also meanshang_detector.stop()is never invoked in that scenario unless it has already been called from inside the loop. With the change above in_event_loop_wrapper, you’ll ensure the detector is torn down even when the event loop exits via an internal error, and the early-return here becomes purely about not joining a wedged worker.Overall, the hang-detection checkpoints/stop calls in the loops look good; tightening the cleanup as above will avoid leaving detector threads alive after error or hang conditions.
Also applies to: 397-405, 483-491, 969-988, 1345-1363, 1548-1568
🤖 Fix all issues with AI agents
In @tensorrt_llm/_torch/pyexecutor/hang_detector.py:
- Around line 1-21: Add the standard NVIDIA SPDX/copyright header at the top of
this file (matching the header used in other modules like _utils.py, updating
the year range to include this change), and change the timeout assignment in
HangDetector.__init__ so that only timeout is None triggers the default; replace
"self.timeout = timeout or 300" with an explicit None check (e.g., if timeout is
None: self.timeout = 300 else: self.timeout = timeout) so callers can pass 0 or
negative values intentionally and PyExecutor's hang_detection_timeout=None
remains unambiguous; update any type hints/docstring if needed to reflect the
semantics.
In @tensorrt_llm/_torch/pyexecutor/py_executor.py:
- Around line 49-50: The HangDetector integration currently starts monitoring
when hang_detection_timeout is None and runs heavy cleanup from the detector
thread; change PyExecutor so that HangDetector is only constructed/started when
hang_detection_timeout is not None (making None mean “disabled”), and modify the
on_detected callback in PyExecutor to perform only minimal, thread-safe
signaling: set self.is_shutdown = True, call self.shutdown_event.set(), and log
an error; remove direct calls to self._handle_errors(...) or heavy resource
mutations from the on_detected callback so the main thread or executor shutdown
path observes is_shutdown/shutdown_event and performs _handle_errors and full
cleanup under the normal threading/event-loop assumptions (apply to on_detected
usages and construction sites involving HangDetector, hang_detection_timeout,
_handle_errors, shutdown_event, and is_shutdown).
🧹 Nitpick comments (3)
tensorrt_llm/executor/worker.py (1)
3-4: Worker stack-printing thread is fine; minor robustness/DRY opportunitiesThe periodic stack-printing daemon in
worker_mainis functionally sound and mirrors the pattern used in_common._init, and being a daemon thread avoids shutdown blocking.Two small suggestions:
print_stacks_period = int(os.getenv("TRTLLM_WORKER_PRINT_STACKS_PERIOD", "-1"))will raiseValueErrorif the env var is set to a non-integer; if misconfiguration is expected in the wild, consider wrapping this in atry/exceptwith a safe fallback.- The
_print_stacksloop is now duplicated between_common._initandworker_main; if this pattern grows, consider a shared helper (e.g.,start_stack_printer_thread(env_var_name: str, label: str)) in_utilsto avoid divergence.Also applies to: 14-15, 158-172
tensorrt_llm/_common.py (1)
19-20: Library-wide stack-printing daemon is fine; same minor nits as workerThe
_print_stackshelper and associated daemon thread in_initcorrectly gate onTRTLLM_PRINT_STACKS_PERIODand reuseprint_all_stacks(). Behavior is appropriate for low-frequency diagnostics and won’t block shutdown because the thread is daemonized.Minor suggestions (same as in
worker.py):
print_stacks_period = int(os.getenv("TRTLLM_PRINT_STACKS_PERIOD", "-1"))will raise if the env var is non-numeric; consider a smalltry/except ValueErrorwith a warning and disabling the feature instead of aborting init._print_stacksis now duplicated between_common._initandworker_main; consider a shared helper to centralize this behavior if you plan to evolve it further.Also applies to: 38-39, 86-97
tensorrt_llm/_torch/pyexecutor/hang_detector.py (1)
22-77: HangDetector core logic is sound; consider minor robustness tweaksThe overall design (own asyncio loop in a dedicated daemon thread,
checkpoint()reset,pause()for cancel,stop()to cancel all tasks and stop the loop) is reasonable and low overhead.A couple of small improvements you might consider:
- In
_detect_hang, cancellations frompause()will surface asCancelledErrorfromasyncio.sleep. Explicitly catchingasyncio.CancelledErrorand returning early can avoid any chance of noisy task-exception logs on some Python versions.- If there’s a risk of
start()being called twice, you may want to guard against reinitializingloop/loop_threadwhile an old loop is still alive (e.g., by no-op’ing or raising ifself.loopis notNone).These are non-blocking, but they’ll make the detector a bit more bulletproof across executor lifecycle edge cases.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
tensorrt_llm/_common.pytensorrt_llm/_torch/pyexecutor/executor_request_queue.pytensorrt_llm/_torch/pyexecutor/hang_detector.pytensorrt_llm/_torch/pyexecutor/py_executor.pytensorrt_llm/_utils.pytensorrt_llm/executor/worker.py
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.py: The code developed for TensorRT-LLM should conform to Python 3.8+
Indent Python code with 4 spaces. Do not use tabs
Always maintain the namespace when importing Python modules, even if only one class or function from a module is used
Python filenames should use snake_case (e.g.,some_file.py)
Python classes should use PascalCase (e.g.,class SomeClass)
Python functions and methods should use snake_case (e.g.,def my_awesome_function():)
Python local variables should use snake_case, with prefixkfor variable names that start with a number (e.g.,k_99th_percentile)
Python global variables should use upper snake_case with prefixG(e.g.,G_MY_GLOBAL)
Python constants should use upper snake_case (e.g.,MY_CONSTANT)
Avoid shadowing variables declared in an outer scope in Python
Initialize all externally visible members of a Python class in the constructor
For Python interfaces that may be used outside a file, prefer docstrings over comments
Use comments in Python for code within a function, or interfaces that are local to a file
Use Google-style docstrings for Python classes and functions, which can be parsed by Sphinx
Python attributes and variables can be documented inline with the format"""<type>: Description"""
Avoid using reflection in Python when functionality can be easily achieved without reflection
When using try-except blocks in Python, limit the except clause to the smallest set of errors possible
When using try-except blocks in Python to handle multiple possible variable types (duck-typing), keep the body of the try as small as possible and use the else block for the main logic
Files:
tensorrt_llm/executor/worker.pytensorrt_llm/_common.pytensorrt_llm/_torch/pyexecutor/executor_request_queue.pytensorrt_llm/_torch/pyexecutor/hang_detector.pytensorrt_llm/_utils.pytensorrt_llm/_torch/pyexecutor/py_executor.py
**/*.{cpp,cc,cxx,h,hpp,hxx,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
All TensorRT-LLM source files (.cpp, .h, .cu, .py, and other source files) should contain an NVIDIA copyright header with the year of latest meaningful modification
Files:
tensorrt_llm/executor/worker.pytensorrt_llm/_common.pytensorrt_llm/_torch/pyexecutor/executor_request_queue.pytensorrt_llm/_torch/pyexecutor/hang_detector.pytensorrt_llm/_utils.pytensorrt_llm/_torch/pyexecutor/py_executor.py
🧠 Learnings (3)
📚 Learning: 2025-09-02T13:42:44.885Z
Learnt from: pcastonguay
Repo: NVIDIA/TensorRT-LLM PR: 7455
File: tensorrt_llm/_torch/pyexecutor/py_executor.py:1852-1860
Timestamp: 2025-09-02T13:42:44.885Z
Learning: In MPI communication within TensorRT-LLM pipeline parallelism, different communication types (tokens, logits, termination sync) must use disjoint tag namespaces to avoid message routing collisions when using the same source/destination patterns.
Applied to files:
tensorrt_llm/_common.py
📚 Learning: 2025-12-12T03:27:08.565Z
Learnt from: tongyuantongyu
Repo: NVIDIA/TensorRT-LLM PR: 9655
File: tensorrt_llm/_torch/pyexecutor/sampler.py:3031-3031
Timestamp: 2025-12-12T03:27:08.565Z
Learning: In files under tensorrt_llm/_torch/pyexecutor, avoid accessing torch.Tensor objects inside for-loops when iterating over requests. Convert batched tensors to Python lists beforehand using tensor.tolist(), and then iterate over those lists. This improves performance by reducing tensor-bound operations inside hot loops. Apply this pattern to similar code paths that process batches to access simple Python data structures (lists) inside loops.
Applied to files:
tensorrt_llm/_torch/pyexecutor/executor_request_queue.pytensorrt_llm/_torch/pyexecutor/hang_detector.pytensorrt_llm/_torch/pyexecutor/py_executor.py
📚 Learning: 2025-08-19T12:45:11.997Z
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 7033
File: tensorrt_llm/_torch/pyexecutor/model_engine.py:0-0
Timestamp: 2025-08-19T12:45:11.997Z
Learning: In tensorrt_llm/_torch/pyexecutor/model_engine.py, DoRA (Delta Orthogonal Rank Adaptation) functionality was removed from the PyTorch flow to eliminate issues with inverted DoRA detection logic. The original is_dora condition was checking if scaling_vec_pointer == 0, which was potentially incorrect.
Applied to files:
tensorrt_llm/_torch/pyexecutor/py_executor.py
🧬 Code graph analysis (5)
tensorrt_llm/executor/worker.py (2)
tensorrt_llm/_utils.py (3)
mpi_comm(506-507)mpi_rank(540-547)print_all_stacks(766-770)tensorrt_llm/_common.py (1)
_print_stacks(86-92)
tensorrt_llm/_common.py (1)
tensorrt_llm/_utils.py (2)
print_all_stacks(766-770)str_dtype_to_trt(247-257)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1)
tensorrt_llm/_torch/pyexecutor/hang_detector.py (3)
HangDetector(9-77)pause(53-57)checkpoint(47-51)
tensorrt_llm/_torch/pyexecutor/hang_detector.py (2)
tensorrt_llm/_utils.py (1)
print_all_stacks(766-770)tensorrt_llm/_torch/pyexecutor/py_executor.py (1)
on_detected(282-286)
tensorrt_llm/_torch/pyexecutor/py_executor.py (1)
tensorrt_llm/_torch/pyexecutor/hang_detector.py (5)
HangDetector(9-77)start(22-32)detected(42-45)checkpoint(47-51)stop(59-77)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Pre-commit Check
🔇 Additional comments (3)
tensorrt_llm/_utils.py (1)
24-27: Stack dumping utility is correct and appropriately scoped
print_all_stacks()cleanly usessys._current_frames()+traceback.format_stackand logs via the sharedlogger. No correctness or concurrency issues from this helper; good reuse point for the rest of the PR.Also applies to: 766-771
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (2)
17-18: ExecutorRequestQueue HangDetector wiring is consistentAccepting an optional
hang_detectorand defaulting toHangDetector()whenNonekeeps the queue reusable while allowing PyExecutor to inject a shared instance. Because the queue itself never callsstart(), there’s no risk of a hidden background loop; lifecycle remains with the owner.No changes requested here.
Also applies to: 51-61, 76-78
285-318: Pausing hang detection around queue wait and non-root broadcast is reasonableBracketing
_get_from_request_queue(timeout)and the non-root_broadcast_new_requestscall withpause()/checkpoint()ensures:
- Long idle periods waiting on new requests don’t trigger false-positive hangs.
- A fresh timeout window starts after each successful fetch/broadcast.
Given HangDetector is started by PyExecutor and is otherwise inert, this integration looks safe and low-overhead.
Also applies to: 487-495
|
PR_Github #30842 [ run ] triggered by Bot. Commit: |
|
PR_Github #30842 [ run ] completed with state
|
|
/bot run --disable-fail-fast |
|
PR_Github #30999 [ run ] triggered by Bot. Commit: |
|
PR_Github #30999 [ run ] completed with state
|
|
/bot run --disable-fail-fast |
|
PR_Github #31176 [ run ] triggered by Bot. Commit: |
|
PR_Github #31176 [ run ] completed with state
|
|
/bot run --disable-fail-fast |
|
PR_Github #31303 [ run ] triggered by Bot. Commit: |
|
PR_Github #31303 [ run ] completed with state |
Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
Funatiq
left a comment
There was a problem hiding this comment.
IIUC we are not sure when the hangs happen, so this PR adds logging to help with that. I think that's fine to improve debugging.
Would it make sense to change CUDA event syncs to looping event queries to detect hangs? Then we could probably shut down more cleanly. We don't need to do this in this PR.
Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
|
/bot reuse-pipeline |
|
PR_Github #31727 [ reuse-pipeline ] triggered by Bot. Commit: |
|
PR_Github #31727 [ reuse-pipeline ] completed with state |
Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com> Signed-off-by: Daniil Kulko <kulkodaniil@gmail.com>
Description
This PR adds some hang detection functionality. We will print all thread stacks to show which function call gets stuck when:
TRTLLM_WORKER_PRINT_STACKS_PERIODis set, print thread stacks periodically on workers, it is designed for hang detection during e2e testsTRTLLM_PRINT_STACKS_PERIODis set, print thread stacks periodically on main process, it is designed for hang detection during unit testsTest Coverage
PR Checklist
Please review the following before submitting your PR:
PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.
PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.
Test cases are provided for new code paths (see test instructions)
Any new dependencies have been scanned for license and vulnerabilities
CODEOWNERS updated if ownership changes
Documentation updated as needed
Update tava architecture diagram if there is a significant design change in PR.
The reviewers assigned automatically/manually are appropriate for the PR.
Please check this after reviewing the above items as appropriate for this PR.
GitHub Bot Help
/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...Provide a user friendly way for developers to interact with a Jenkins server.
Run
/bot [-h|--help]to print this help message.See details below for each supported subcommand.
Details
run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]Launch build/test pipelines. All previously running jobs will be killed.
--reuse-test (optional)pipeline-id(OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.--disable-reuse-test(OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.--disable-fail-fast(OPTIONAL) : Disable fail fast on build/tests/infra failures.--skip-test(OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.--stage-list "A10-PyTorch-1, xxx"(OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.--gpu-type "A30, H100_PCIe"(OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.--test-backend "pytorch, cpp"(OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.--only-multi-gpu-test(OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.--disable-multi-gpu-test(OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.--add-multi-gpu-test(OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.--post-merge(OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx"(OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".--detailed-log(OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.--debug(OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in thestage-listparameter to access the appropriate container environment. Note: Does NOT update GitHub check status.For guidance on mapping tests to stage names, see
docs/source/reference/ci-overview.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip testing for latest commit on pull request.
--comment "Reason for skipping build/test"is required. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.reuse-pipeline
reuse-pipelineReuse a previous pipeline to validate current commit. This action will also kill all currently running builds associated with the pull request. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.