Skip to content

Conversation

@MrGeva
Copy link
Collaborator

@MrGeva MrGeva commented Dec 31, 2025

Problem
Failure seen in CI:


[2025-12-29T21:42:44.381Z] [W1229 12:47:08.489869130 TCPStore.cpp:340] [c10d] TCP client failed to connect/validate to host 127.0.0.1:30325 - retrying (try=0, timeout=600000ms, delay=385ms): Ping failed, invalid value returned from server. Expected: 297731, Got: 68681728

[2025-12-29T21:42:44.381Z] Exception raised from ping at /opt/pytorch/pytorch/torch/csrc/distributed/c10d/TCPStore.cpp:427 (most recent call first):

https://prod.blsm.nvidia.com/sw-tensorrt-top-1/blue/organizations/jenkins/LLM%2Fmain%2FL0_Test-x86_64-Multi-GPU/detail/L0_Test-x86_64-Multi-GPU/3663/pipeline/3347

The spawn_multiprocess_job function had a TOCTOU (Time-Of-Check-To-Time-Of-Use) race condition when selecting ports for distributed process group initialization. The original flow was:

  1. Call get_free_port() which binds to port 0, gets an available port, and closes the socket
  2. Spawn child processes with that port number
  3. Child processes try to bind to the port via dist.init_process_group()
    Between steps 1 and 3, another process could claim the port, causing EADDRINUSE errors and test failures in CI.

Solution
Implemented a retry mechanism with shared state synchronization:
Rank 0 retries: If init_process_group fails with EADDRINUSE, rank 0 picks a new port and retries (up to 5 attempts)
Shared port communication: Use multiprocessing.Value to share the working port with other ranks
Barrier synchronization: Use multiprocessing.Barrier so other ranks wait until rank 0 successfully binds
Explicit spawn context: Use mp.get_context("spawn") to create synchronization primitives, ensuring they work correctly with spawned processes

Summary by CodeRabbit

  • New Features
    • Enhanced distributed training initialization with automatic port binding and retry capability for improved synchronization across multiple ranks.

✏️ Tip: You can customize this high-level summary in your review settings.

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

  • 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 the stage-list parameter 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.md
and the scripts/test_to_stage_mapping.py helper.

kill

kill

Kill all running builds associated with pull request.

skip

skip --comment COMMENT

Skip 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-pipeline

Reuse 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.

@MrGeva MrGeva requested review from a team as code owners December 31, 2025 15:27
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 31, 2025

📝 Walkthrough

Walkthrough

The changes introduce explicit port-aware, retry-capable distributed initialization with inter-process synchronization primitives for PyTorch setup, while removing four helix-related fake operation registrations from the custom operators module.

Changes

Cohort / File(s) Summary
Distributed initialization with port retry and synchronization
tensorrt_llm/_torch/auto_deploy/distributed/common.py
Updated initialize() and initialize_or_skip() signatures to accept optional shared_port (mp.Value) and port_ready_barrier (mp.Barrier) parameters. Added new _try_init_process_group() helper that attempts process group initialization with fallback on port-in-use errors. Implemented shared-port synchronization mode where Rank 0 retries port binding up to max_retries, broadcasts working port to other ranks via shared_port, and coordinates via port_ready_barrier. Updated init_and_run_process() to propagate synchronization primitives. Modified _start_multiprocess_job() to create and pass shared_port and port_ready_barrier objects to spawned workers.
Helix fake op removal
tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py
Removed (commented out) four fake operation registrations: trtllm::alltoall_helix_native, trtllm::initialize_helix_workspace, trtllm::helix_post_process, and trtllm::helix_post_process_native.

Sequence Diagram(s)

sequenceDiagram
    participant R0 as Rank 0 Process
    participant R1 as Other Ranks
    participant SP as shared_port<br/>(mp.Value)
    participant PB as port_ready_barrier<br/>(mp.Barrier)
    participant DPG as dist.init_<br/>process_group

    rect rgb(220, 240, 255)
    Note over R0,DPG: Retry Loop (up to max_retries)
    end

    loop Retry attempt
        R0->>R0: Try binding port
        R0->>DPG: _try_init_process_group(port)
        alt Success
            DPG-->>R0: True
            R0->>SP: Write port to shared_port
            R0->>PB: Wait on port_ready_barrier
            Note over R0: Rank 0 bound successfully
        else Port in use
            DPG-->>R0: False (warning logged)
            R0->>R0: Continue loop
        end
    end

    rect rgb(240, 255, 240)
    Note over R0,PB: Synchronization Phase
    end

    par Rank 0 Path
        R0->>PB: Signal barrier (port ready)
    and Other Ranks Path
        R1->>PB: Wait on port_ready_barrier
        PB-->>R1: Barrier released
        R1->>SP: Read port from shared_port
        R1->>DPG: init_process_group(port)
        DPG-->>R1: Success
    end

    R0->>PB: Barrier exit
    Note over R0,R1: All ranks initialized with same port
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

The distributed initialization changes introduce multi-branch retry logic, inter-process synchronization coordination, and modified control flow across spawning and initialization paths. The fake op removals require verification that no external code depends on these registrations. Heterogeneous changes demand separate reasoning for synchronization correctness and removal impacts.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description check ✅ Passed PR description clearly explains the problem (TOCTOU race condition), solution (retry mechanism with shared state), and implementation details. However, the PR title and test coverage sections are not filled out.
Title check ✅ Passed The title accurately describes the main change: fixing a race condition in AutoDeploy's multiprocessing port acquisition, which directly matches the core problem and solution described in the PR objectives.
✨ Finishing touches
  • 📝 Generate docstrings

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py (1)

755-775: Remove commented-out code instead of leaving it in place.

These fake-op registrations appear to be intentionally disabled. Commented-out code is a maintenance burden and should be deleted. If these ops are no longer needed, remove them entirely. If they might be needed later, version control history will preserve them.

Additionally, these changes seem unrelated to the PR objective (fixing port acquisition race condition). Consider splitting unrelated changes into a separate PR for cleaner review history.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0d2e271 and e519caf.

📒 Files selected for processing (2)
  • tensorrt_llm/_torch/auto_deploy/distributed/common.py
  • tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: 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 in Python, even if only one class or function from a module is used
Python files should use snake_case naming: some_file.py
Python classes should use PascalCase naming: class SomeClass
Python functions and methods should use snake_case naming: def my_awesome_function():
Python local variables should use snake_case naming: my_variable = ...
Python variable names that start with a number should be prefixed with 'k': k_99th_percentile = ...
Python global variables should use upper snake_case with prefix 'G': G_MY_GLOBAL = ...
Python constants should use upper snake_case naming: 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
Python comments should be reserved for code within a function, or interfaces that are local to a file
Use Google style docstrings in Python for classes and functions, which can be parsed by Sphinx
Python attributes and variables can be documented inline with type and description
Avoid using reflection in Python when functionality can be easily achieved without reflection
When using try-except blocks in Python, limit the except 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, using the else block for logic

Files:

  • tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py
  • tensorrt_llm/_torch/auto_deploy/distributed/common.py
**/*.{cpp,h,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

All TensorRT-LLM Open Source Software code should contain an NVIDIA copyright header that includes the year of its latest meaningful modification

Files:

  • tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py
  • tensorrt_llm/_torch/auto_deploy/distributed/common.py
🧠 Learnings (5)
📓 Common learnings
Learnt from: lirundong
Repo: NVIDIA/TensorRT-LLM PR: 9725
File: tensorrt_llm/_torch/custom_ops/cuda_tile_custom_ops.py:110-178
Timestamp: 2025-12-12T10:07:36.866Z
Learning: In PyTorch custom operators registered with torch.library.custom_op, mutable operators that return None and specify mutates_args do NOT require a register_fake decorator. The mutation tracking is handled automatically without needing a FakeTensor kernel, as documented in the PyTorch tutorial on mutable Python custom operators.
📚 Learning: 2025-12-12T10:07:31.564Z
Learnt from: lirundong
Repo: NVIDIA/TensorRT-LLM PR: 9725
File: tensorrt_llm/_torch/custom_ops/cuda_tile_custom_ops.py:110-178
Timestamp: 2025-12-12T10:07:31.564Z
Learning: In PyTorch custom operators registered with torch.library.custom_op, mutable operators that return None and specify mutates_args do not require a register_fake decorator. Mutation tracking is handled automatically without needing a FakeTensor kernel. This applies to Python custom op definitions in tensorrt_llm/_torch/custom_ops that use mutates_args and return None; verify you are not relying on register_fake in these cases.

Applied to files:

  • tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py
📚 Learning: 2025-08-27T16:22:10.695Z
Learnt from: Fridah-nv
Repo: NVIDIA/TensorRT-LLM PR: 7227
File: tensorrt_llm/_torch/auto_deploy/utils/quantization_utils.py:94-100
Timestamp: 2025-08-27T16:22:10.695Z
Learning: When there are inconsistent operator detection methods (like custom_op() vs target_op()), removing one method and standardizing on the other is often cleaner than supporting both methods simultaneously.

Applied to files:

  • tensorrt_llm/_torch/custom_ops/cpp_custom_ops.py
📚 Learning: 2025-11-14T11:22:03.729Z
Learnt from: nzmora-nvidia
Repo: NVIDIA/TensorRT-LLM PR: 9163
File: tensorrt_llm/_torch/auto_deploy/custom_ops/quant.py:107-113
Timestamp: 2025-11-14T11:22:03.729Z
Learning: In TensorRT-LLM AutoDeploy custom ops, when adding hardware capability checks to select between kernel implementations (e.g., cuBLAS vs. CUDA kernel), use descriptive variable names that identify the specific GPU architectures or families being targeted (e.g., `is_blackwell_geforce_or_ada`) rather than generic names like `enable_cuda_core`. This makes it clear that the code is selecting an implementation path based on hardware capabilities, not enabling/disabling hardware features.

Applied to files:

  • tensorrt_llm/_torch/custom_ops/cpp_custom_ops.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/custom_ops/cpp_custom_ops.py
🧬 Code graph analysis (1)
tensorrt_llm/_torch/auto_deploy/distributed/common.py (1)
tensorrt_llm/_utils.py (1)
  • get_free_port (477-478)
🪛 Ruff (0.14.10)
tensorrt_llm/_torch/auto_deploy/distributed/common.py

142-142: Consider moving this statement to an else block

(TRY300)


211-211: Avoid specifying long messages outside the exception class

(TRY003)


217-217: Avoid specifying long messages outside the exception class

(TRY003)

⏰ 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 (5)
tensorrt_llm/_torch/auto_deploy/distributed/common.py (5)

88-103: LGTM!

Clean signature update that forwards the new synchronization parameters to initialize().


127-148: Good implementation of retry-capable initialization.

The helper correctly catches port-in-use errors and returns False for retry logic. The exception string matching is reasonable given PyTorch doesn't expose specific exception types for this case.

Minor: Static analysis suggests moving the success return True to an else block for the try statement (TRY300), but this is stylistic and doesn't affect correctness.


225-233: Existing path retained for OMPI/torchelastic/single-process cases.

This path correctly relies on the launcher (OMPI/torchelastic) having already set the required environment variables. No issues for the intended use cases.


244-261: LGTM!

Properly forwards synchronization primitives to initialize_or_skip.


300-323: Good use of explicit spawn context for synchronization primitives.

Using mp.get_context("spawn") ensures that Value and Barrier objects are properly compatible with spawned processes. The synchronization pattern is correct: rank 0 attempts port binding and always signals via the barrier—setting shared_port.value to the successful port or -1 on failure—while other ranks wait at the barrier before reading the shared port value and raising an error if rank 0 failed.

@MrGeva
Copy link
Collaborator Author

MrGeva commented Dec 31, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #30289 [ run ] triggered by Bot. Commit: 655d78a

@tensorrt-cicd
Copy link
Collaborator

PR_Github #30289 [ run ] completed with state SUCCESS. Commit: 655d78a
/LLM/main/L0_MergeRequest_PR pipeline #23323 completed with status: 'FAILURE'

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

@MrGeva MrGeva changed the title [http://nvbugs/5766982][fix] fixed race condition in AutoDeploy's mpi tests port acquisition [#10374][fix] fixed race condition in AutoDeploy's mpi tests port acquisition Jan 1, 2026
@MrGeva
Copy link
Collaborator Author

MrGeva commented Jan 1, 2026

/bot run --add-multi-gpu-test

@tensorrt-cicd
Copy link
Collaborator

PR_Github #30325 [ run ] triggered by Bot. Commit: b085bfb

@tensorrt-cicd
Copy link
Collaborator

PR_Github #30325 [ run ] completed with state SUCCESS. Commit: b085bfb
/LLM/main/L0_MergeRequest_PR pipeline #23358 completed with status: 'FAILURE'

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

@MrGeva
Copy link
Collaborator Author

MrGeva commented Jan 1, 2026

/bot run --add-multi-gpu-test --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #30336 [ run ] triggered by Bot. Commit: b085bfb

Copy link
Collaborator

@galagam galagam left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, added some small comments.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #30336 [ run ] completed with state SUCCESS. Commit: b085bfb
/LLM/main/L0_MergeRequest_PR pipeline #23368 completed with status: 'FAILURE'

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

@MrGeva MrGeva force-pushed the egeva/fix_race_port branch from b085bfb to 91e2b27 Compare January 1, 2026 17:06
@MrGeva
Copy link
Collaborator Author

MrGeva commented Jan 1, 2026

/bot run --add-multi-gpu-test

@MrGeva MrGeva changed the title [#10374][fix] fixed race condition in AutoDeploy's mpi tests port acquisition [#10374][fix] fixed race condition in AutoDeploy's mp tests port acquisition Jan 1, 2026
@tensorrt-cicd
Copy link
Collaborator

PR_Github #30348 [ run ] triggered by Bot. Commit: 91e2b27

@tensorrt-cicd
Copy link
Collaborator

PR_Github #30348 [ run ] completed with state SUCCESS. Commit: 91e2b27
/LLM/main/L0_MergeRequest_PR pipeline #23380 completed with status: 'FAILURE'

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

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.

3 participants