- 
                Notifications
    You must be signed in to change notification settings 
- Fork 1.8k
[https://nvbugs/5437384][test] cherry-pick fix trtllm-llmapi-launch multi tests #8567
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
…ith single launch (NVIDIA#8397) Signed-off-by: Yan Chunwei <[email protected]> Signed-off-by: Superjomn <[email protected]>
230495a    to
    d9fe0fe      
    Compare
  
    | /bot run | 
| PR_Github #22139 [ run ] triggered by Bot. Commit:  | 
| 📝 WalkthroughWalkthroughThis change introduces a global, reusable MPI communicator caching mechanism in mpi_session.py alongside a singleton pattern for remote client connections. It includes synchronization enhancements for multi-task execution and adds corresponding test utilities and integration tests for multi-task MPI session execution. Changes
 Sequence Diagram(s)sequenceDiagram
    participant Client as Remote Client
    participant Server as Remote Server
    participant Executor as MPICommExecutor
    
    rect rgb(200, 220, 255)
    Note over Client,Executor: Task Submission & Synchronization
    end
    
    Client->>+Server: Task 1 (submit)
    Server->>+Executor: Execute Task 1
    Executor-->>-Server: future1 returned
    Server->>Server: pending_futures += [future1]
    Server-->>-Client: Task 1 acknowledged
    
    rect rgb(240, 200, 200)
    Note over Server: Await pending_futures before<br/>accepting next task
    end
    
    Server->>+Executor: Wait for future1 completion
    Executor-->>-Server: Task 1 completed
    
    Client->>+Server: Task 2 (submit)
    Server->>+Executor: Execute Task 2
    Executor-->>-Server: future2 returned
    Server->>Server: pending_futures = [future2]
    Server-->>-Client: Task 2 acknowledged
sequenceDiagram
    participant Caller
    participant ClientFactory as RemoteMpiCommSessionClient
    participant GlobalCache as Global Singleton Cache
    
    rect rgb(200, 220, 255)
    Note over Caller,GlobalCache: First Connection (addr1)
    end
    
    Caller->>+ClientFactory: __new__("addr1")
    ClientFactory->>+GlobalCache: Check _global_instance["addr1"]
    GlobalCache-->>-ClientFactory: Not found
    ClientFactory->>ClientFactory: Create new instance
    ClientFactory->>GlobalCache: _global_instance["addr1"] = instance
    ClientFactory-->>-Caller: Return instance
    
    rect rgb(240, 200, 200)
    Note over Caller,GlobalCache: Subsequent Connection (addr1)
    end
    
    Caller->>+ClientFactory: __new__("addr1")
    ClientFactory->>+GlobalCache: Check _global_instance["addr1"]
    GlobalCache-->>-ClientFactory: Found existing instance
    ClientFactory-->>-Caller: Return cached instance
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes The changes introduce significant logic modifications: a global MPI communicator caching mechanism with per-address lifecycle management, a singleton pattern with thread-safe locking for remote clients, and task synchronization logic using pending futures. The core mpi_session.py file contains intricate state tracking and coordination logic across multiple components. While test files are mostly straightforward new additions, they integrate with the core logic changes, requiring careful verification of multi-task execution flow and MPI rank synchronization semantics. Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
 ✅ Passed checks (1 passed)
 ✨ Finishing touches
 🧪 Generate unit tests (beta)
 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.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️  Outside diff range comments (1)
tensorrt_llm/llmapi/mpi_session.py (1)
380-391: poll() return type mismatch.
Annotated as bool but returns either False or the actual result payload; update typing/docstring.-def poll(self) -> bool: +from typing import Any, Optional +def poll(self) -> Optional[Any]: @@ - Returns: - True if a response is received, False otherwise. + Returns: + The response payload if received, otherwise None. @@ - if response: - return self.queue.get() # should get a True if success - return False + if response: + return self.queue.get() + return NoneAdjust submit_sync accordingly to check for None rather than falsiness if needed.
🧹 Nitpick comments (9)
tests/integration/test_lists/test-db/l0_dgx_h100.yml (1)
46-47: Add a timeout to the new mpirun-based test entry to prevent pipeline hangs.
Long-running external launches can stall CI; other entries use TIMEOUT. Mirror that here.Apply:
- - unittest/llmapi/test_mpi_session.py::test_llmapi_launch_multiple_tasks + - unittest/llmapi/test_mpi_session.py::test_llmapi_launch_multiple_tasks TIMEOUT (600)tensorrt_llm/llmapi/mpi_session.py (3)
360-379: Polling interval is too coarse (8s); reduces responsiveness.
submit_sync can stall up to 8s per poll. Use a small interval or backoff.- SYNC_IDLE_INTERVAL = 8 + # Start small; back off to reduce spin while retaining responsiveness. + SYNC_IDLE_INTERVAL_BASE = 0.05 + SYNC_IDLE_INTERVAL_MAX = 1.0 @@ - while not ((res := self.poll()) or self._is_shutdown): - print_colored_debug(f"Waiting for task completion... {res}\n", - "grey") - time.sleep(self.SYNC_IDLE_INTERVAL) + backoff = self.SYNC_IDLE_INTERVAL_BASE + while not ((res := self.poll()) or self._is_shutdown): + print_colored_debug("Waiting for task completion...\n", "grey") + time.sleep(backoff) + backoff = min(backoff * 2, self.SYNC_IDLE_INTERVAL_MAX)Also drop the unused placeholder in the debug call.
463-485: Sequentialization via pending_futures looks correct; keep exceptions visible but don’t swallow BaseException.
Catching Exception is fine here; consider logging the full traceback for faster triage.- for future in pending_futures: - try: - future.result() # Wait for completion - except Exception as e: - print_colored( - f"RemoteMpiCommSessionServer future failed with exception: {e}\n", - "red") + for future in pending_futures: + try: + future.result() + except Exception as e: # keep broad; futures can raise varied types + print_colored(f"Future failed: {e}\n", "red") + traceback.print_exc()
558-599: Duplicate MPI env prefixes; simplify and dedupe.
Current list repeats several keys; use a set to avoid redundancy.- mpi_vars = set( - itertools.chain([ - var for var in current_env if var.startswith(( - 'MPI_', - 'OMPI_', - 'PMIX_', - 'PMI_', - 'OMPI_', - 'PMIX_', - 'PMI_', - 'SLURM_', - 'MPI_', - 'UCX_', - 'I_MPI_', - 'HYDRA_', - 'KMP_', - 'MPICH_', - 'MV2_', - 'CRAY_', - )) - ], mpi_env_keys or [])) + prefixes = { + 'MPI_', 'OMPI_', 'PMIX_', 'PMI_', 'SLURM_', 'UCX_', 'I_MPI_', + 'HYDRA_', 'KMP_', 'MPICH_', 'MV2_', 'CRAY_' + } + mpi_vars = set( + itertools.chain( + [var for var in current_env if any(var.startswith(p) for p in prefixes)], + mpi_env_keys or [], + ))tests/unittest/llmapi/test_mpi_session.py (1)
136-168: Add a subprocess timeout and ensure cleanup to avoid CI hangs.
If mpirun or the launcher deadlocks, the test will block indefinitely.- with Popen(command, + with Popen(command, env=os.environ, stdout=PIPE, stderr=PIPE, bufsize=1, start_new_session=True, universal_newlines=True, cwd=os.path.dirname(os.path.abspath(__file__))) as process: @@ - return_code = process.wait() + try: + return_code = process.wait(timeout=900) + except subprocess.TimeoutExpired: + # Kill the whole process group + try: + process.kill() + finally: + stdout_thread.join(timeout=5) + stderr_thread.join(timeout=5) + raisetests/unittest/llmapi/_run_multi_llm_tasks.py (2)
18-23: Add a short docstring for clarity.
Helps future readers understand the intent of this helper.def run_llm_tp2(): + """Run a tiny LLM with tensor_parallel_size=2 and print one short completion."""
25-30: Nit: add a brief docstring and make the loop count a named constant.
Small readability win.-def run_multi_llm_tasks(): - for i in range(3): +def run_multi_llm_tasks(): + """Run the LLM task multiple times to exercise multi-launch behavior.""" + rounds = 3 + for i in range(rounds): print_colored(f"Running LLM task {i}\n", "green") run_llm_tp2() print_colored(f"LLM task {i} completed\n", "green")tests/unittest/llmapi/_run_multi_mpi_comm_tasks.py (2)
11-18: Avoid KeyError on missing env; provide a clearer error.
Use os.environ.get(...) and check truthiness.- assert os.environ[ - LlmLauncherEnvs. - TLLM_SPAWN_PROXY_PROCESS_IPC_ADDR] is not None, "TLLM_SPAWN_PROXY_PROCESS_IPC_ADDR is not set" - client = RemoteMpiCommSessionClient( - os.environ[LlmLauncherEnvs.TLLM_SPAWN_PROXY_PROCESS_IPC_ADDR]) + addr = os.environ.get(LlmLauncherEnvs.TLLM_SPAWN_PROXY_PROCESS_IPC_ADDR) + if not addr: + raise RuntimeError("TLLM_SPAWN_PROXY_PROCESS_IPC_ADDR is not set") + client = RemoteMpiCommSessionClient(addr)
27-32: Add a brief docstring for run_multi_tasks.
Aids readability in test helpers.def run_multi_tasks(task_type: Literal["submit", "submit_sync"]): + """Run three rounds of MPI client tasks to validate multi-task orchestration."""
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
- tensorrt_llm/llmapi/mpi_session.py(9 hunks)
- tests/integration/test_lists/test-db/l0_dgx_h100.yml(1 hunks)
- tests/unittest/llmapi/_run_multi_llm_tasks.py(1 hunks)
- tests/unittest/llmapi/_run_multi_mpi_comm_tasks.py(1 hunks)
- tests/unittest/llmapi/test_mpi_session.py(2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Use only spaces, no tabs; indent with 4 spaces.
Files:
- tests/unittest/llmapi/_run_multi_llm_tasks.py
- tests/unittest/llmapi/_run_multi_mpi_comm_tasks.py
- tensorrt_llm/llmapi/mpi_session.py
- tests/unittest/llmapi/test_mpi_session.py
**/*.py
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.py: Python code must target Python 3.8+.
Indent Python code with 4 spaces; do not use tabs.
Maintain module namespace when importing; prefer 'from package.subpackage import foo' then 'foo.SomeClass()' instead of importing the class directly.
Python filenames should be snake_case (e.g., some_file.py).
Python classes use PascalCase names.
Functions and methods use snake_case names.
Local variables use snake_case; prefix 'k' for variables that start with a number (e.g., k_99th_percentile).
Global variables use upper SNAKE_CASE prefixed with 'G' (e.g., G_MY_GLOBAL).
Constants use upper SNAKE_CASE (e.g., MY_CONSTANT).
Avoid shadowing variables from an outer scope.
Initialize all externally visible members of a class in the constructor.
Prefer docstrings for interfaces that may be used outside a file; comments for in-function or file-local interfaces.
Use Google-style docstrings for classes and functions (Sphinx-parsable).
Document attributes and variables inline so they render under the class/function docstring.
Avoid reflection when a simpler, explicit approach suffices (e.g., avoid dict(**locals()) patterns).
In try/except, catch the most specific exceptions possible.
For duck-typing try/except, keep the try body minimal and use else for the main logic.
Files:
- tests/unittest/llmapi/_run_multi_llm_tasks.py
- tests/unittest/llmapi/_run_multi_mpi_comm_tasks.py
- tensorrt_llm/llmapi/mpi_session.py
- tests/unittest/llmapi/test_mpi_session.py
**/*.{cpp,cxx,cc,h,hpp,hh,hxx,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Prepend the NVIDIA Apache-2.0 copyright header with current year to the top of all source files (e.g., .cpp, .h, .cu, .py).
Files:
- tests/unittest/llmapi/_run_multi_llm_tasks.py
- tests/unittest/llmapi/_run_multi_mpi_comm_tasks.py
- tensorrt_llm/llmapi/mpi_session.py
- tests/unittest/llmapi/test_mpi_session.py
🧠 Learnings (2)
📚 Learning: 2025-07-28T17:06:08.621Z
Learnt from: moraxu
PR: NVIDIA/TensorRT-LLM#6303
File: tests/integration/test_lists/qa/examples_test_list.txt:494-494
Timestamp: 2025-07-28T17:06:08.621Z
Learning: In TensorRT-LLM testing, it's common to have both CLI flow tests (test_cli_flow.py) and PyTorch API tests (test_llm_api_pytorch.py) for the same model. These serve different purposes: CLI flow tests validate the traditional command-line workflow, while PyTorch API tests validate the newer LLM API backend. Both are legitimate and should coexist.
Applied to files:
- tests/unittest/llmapi/_run_multi_llm_tasks.py
📚 Learning: 2025-09-09T09:40:45.658Z
Learnt from: fredricz-20070104
PR: NVIDIA/TensorRT-LLM#7645
File: tests/integration/test_lists/qa/llm_function_core.txt:648-648
Timestamp: 2025-09-09T09:40:45.658Z
Learning: In TensorRT-LLM test lists, it's common and intentional for the same test to appear in multiple test list files when they serve different purposes (e.g., llm_function_core.txt for comprehensive core functionality testing and llm_function_core_sanity.txt for quick sanity checks). This duplication allows tests to be run in different testing contexts.
Applied to files:
- tests/unittest/llmapi/_run_multi_llm_tasks.py
🧬 Code graph analysis (4)
tests/unittest/llmapi/_run_multi_llm_tasks.py (1)
tensorrt_llm/llmapi/utils.py (1)
print_colored(47-63)
tests/unittest/llmapi/_run_multi_mpi_comm_tasks.py (3)
tensorrt_llm/executor/utils.py (1)
LlmLauncherEnvs(22-29)tensorrt_llm/llmapi/mpi_session.py (9)
RemoteMpiCommSessionClient(300-405)
submit(91-93)
submit(148-153)
submit(215-231)
submit(344-358)
submit_sync(96-97)
submit_sync(155-160)
submit_sync(233-235)
submit_sync(362-378)tensorrt_llm/llmapi/utils.py (1)
print_colored(47-63)
tensorrt_llm/llmapi/mpi_session.py (3)
tensorrt_llm/executor/proxy.py (1)
shutdown(369-416)tensorrt_llm/executor/utils.py (1)
shutdown(103-104)tensorrt_llm/llmapi/utils.py (2)
print_colored_debug(66-70)
print_colored(47-63)
tests/unittest/llmapi/test_mpi_session.py (1)
tensorrt_llm/llmapi/mpi_session.py (3)
MPINodeState(30-58)
MpiPoolSession(136-180)
split_mpi_env(558-599)
🪛 Ruff (0.14.1)
tensorrt_llm/llmapi/mpi_session.py
279-279: f-string without any placeholders
Remove extraneous f prefix
(F541)
310-310: Unused static method argument: hmac_key
(ARG004)
401-401: f-string without any placeholders
Remove extraneous f prefix
(F541)
404-404: Unused method argument: grace
(ARG002)
404-404: Unused method argument: reason
(ARG002)
477-477: Do not catch blind exception: Exception
(BLE001)
tests/unittest/llmapi/test_mpi_session.py
123-123: Unused function argument: task_script
(ARG001)
136-136: subprocess call: check for execution of untrusted input
(S603)
⏰ 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 (1)
tensorrt_llm/llmapi/mpi_session.py (1)
395-406: shutdown() no-op: confirm server lifecycle.
Client shutdown doesn’t send a sentinel; RemoteMpiCommSessionServer.serve() stops on None. Ensure server is terminated elsewhere (e.g., launcher lifecycle), or add an explicit “close” path if needed.Also fix the f-string with no placeholders:
- print_colored_debug( - f"RemoteMpiCommSessionClient.shutdown() called (no-op for singleton)\n", - "grey") + print_colored_debug( + "RemoteMpiCommSessionClient.shutdown() called (no-op for singleton)\n", + "grey")
| PR_Github #22139 [ run ] completed with state  | 
…ith single launch (#8397)
Summary by CodeRabbit
Release Notes
New Features
Tests
Description
Test 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
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.
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.