-
Notifications
You must be signed in to change notification settings - Fork 1.9k
[TRTLLM-7008][fix] cherrypick to main Add automatic shared memory delete if already exist #7727
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
[TRTLLM-7008][fix] cherrypick to main Add automatic shared memory delete if already exist #7727
Conversation
|
/bot run --disable-fail-fast |
|
PR_Github #18616 [ run ] triggered by Bot |
📝 WalkthroughWalkthroughDocumentation refocused to describe EPLB shared memory configuration and cleanup, including an env-var-driven naming scheme and manual cleanup commands. Code updates add environment-based defaulting for shared-memory base name and robust handling of pre-existing shared memory segments. Two DeepSeekV3Lite test waivers were removed to re-enable those tests. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor User
participant App as App (Trainer)
participant MLB as MoeLoadBalancer
participant OS as OS Env
participant SHM as SharedMemory
Note over App,MLB: Initialization
User->>App: Construct MoeLoadBalancer(...)
App->>MLB: __init__(shared_memory_base_name=None)
MLB->>OS: getenv("TRTLLM_EPLB_SHM_NAME", "moe_shared")
OS-->>MLB: base_name (resolved)
MLB-->>App: instance ready
Note over App,SHM: Per-layer finalize
App->>MLB: finalize_layer_weights(...)
rect rgba(200, 240, 200, 0.3)
MLB->>SHM: Create(name=base_lX_lr0_all, size=N)
alt FileExistsError
MLB-->>App: log warning
MLB->>SHM: close + unlink(existing)
MLB->>SHM: Recreate(name, size=N)
else Created OK
MLB-->>App: proceed
end
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests
Tip 👮 Agentic pre-merge checks are now available in preview!Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.
Please see the documentation for more information. Example: reviews:
pre_merge_checks:
custom_checks:
- name: "Undocumented Breaking Changes"
mode: "warning"
instructions: |
Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).Please share your feedback with us on this Discord post. 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: 1
🧹 Nitpick comments (5)
tensorrt_llm/_torch/modules/fused_moe/moe_load_balancer.py (2)
180-193: SHM recreate path: unify logger usage and prefer reuse when size matches; add race-safe handling.
- Use the module’s
loggerinstance for consistency (logger.warning(...)).- If an existing segment matches the required size, reuse instead of unlinking to avoid churn and reduce cross‑instance interference.
- Guard unlink path with additional handling for races (
FileNotFoundError) between open and unlink.Apply:
- except FileExistsError: - tensorrt_llm.logger.warning( - f'Found exist EPLB shared memory name: {shm_name}, unlinking...' - ) - existing_shm = shared_memory.SharedMemory(name=shm_name) - existing_shm.close() - existing_shm.unlink() - shm = shared_memory.SharedMemory(name=shm_name, - create=True, - size=total_size) + except FileExistsError: + # An SHM with the same name exists. Reuse if size matches; otherwise, unlink and recreate. + logger.warning(f"Found existing EPLB shared memory: {shm_name}. " + f"Attempting reuse if size matches; else unlinking and recreating...") + existing_shm = shared_memory.SharedMemory(name=shm_name) + try: + # Prefer reuse if the size matches our layout. + if getattr(existing_shm, "size", None) == total_size: + shm = existing_shm + else: + existing_shm.close() + try: + existing_shm.unlink() + except FileNotFoundError: + # Already unlinked by another process; proceed to create. + pass + shm = shared_memory.SharedMemory(name=shm_name, + create=True, + size=total_size) + except Exception: + # Ensure descriptor is closed on unexpected exceptions before re-raising. + try: + existing_shm.close() + finally: + raiseNote: If you intentionally want unconditional cleanup even when sizes match, keep the unlink path but still switch to
logger.warning(...)and add the race-safeFileNotFoundErrorguard.
737-746: Env-var defaulting: handle empty values and align docstring with behavior.
- Docstring says fallback to 'moe_shared' when None, but code also respects
TRTLLM_EPLB_SHM_NAME. Document that.- Treat empty strings as unset so an accidental
TRTLLM_EPLB_SHM_NAME=''doesn’t produce names like"_l0_lr0_all".Apply:
- shared_memory_base_name: Optional[str] = None): + shared_memory_base_name: Optional[str] = None): @@ - shared_memory_base_name: Shared memory base name, will use 'moe_shared' if None + shared_memory_base_name: Shared memory base name. + If None or empty, uses os.getenv('TRTLLM_EPLB_SHM_NAME') if set and non-empty, + otherwise falls back to 'moe_shared'. @@ - self.shared_memory_base_name = shared_memory_base_name or os.getenv( - 'TRTLLM_EPLB_SHM_NAME', 'moe_shared') + env_base = os.getenv('TRTLLM_EPLB_SHM_NAME') + if shared_memory_base_name not in (None, ''): + self.shared_memory_base_name = shared_memory_base_name + elif env_base not in (None, ''): + self.shared_memory_base_name = env_base + else: + self.shared_memory_base_name = 'moe_shared'Also applies to: 755-756
examples/wide_ep/README.md (3)
103-106: Tighten wording and reflect env-var fallback.Minor grammar and clarity: “There is an environment variable…”; also mention fallback to default name.
Apply:
-There is one environment variable `TRTLLM_EPLB_SHM_NAME` to specify the base name of the shared memory. This environment variable may need to be specified if there are multiple instances on one node. If not, you can ignore it. +There is an environment variable `TRTLLM_EPLB_SHM_NAME` to specify the base name of the shared memory. Set this if multiple instances run on the same node; otherwise the default is used.
107-110: Call out behavior precisely (auto-cleanup scope).Clarify that cleanup targets segments with the same base name and may affect concurrently running instances that rely on the same base.
Apply:
-Normally, these shared memory segments will be cleaned up automatically at process exit. However, they may not get the chance to be cleaned up if an abnormal exit occurs. Therefore, EPLB will automatically clean up leftover shared memory with the same name that already exists before creating new segments. +Normally, these shared memory segments are cleaned up at process exit. If a previous run exited abnormally, EPLB will remove any pre-existing segments using the same base name before creating new ones. To avoid impacting other live jobs on the same node, use a unique `TRTLLM_EPLB_SHM_NAME` per instance.
111-124: Make cleanup commands respect the configured base name.Parameterize commands by
TRTLLM_EPLB_SHM_NAMEso users don’t accidentally delete segments for a different base name.Apply:
-#### Manual Cleanup Commands +#### Manual Cleanup Commands @@ -For manual cleanup of shared memory, you can use the following commands: +For manual cleanup of shared memory, you can use the following commands (replace the base name if you customized it): @@ -# List all moe_shared related shared memory -ls -la /dev/shm/moe_shared_* +# Base name (defaults to moe_shared if the variable is unset or empty) +BASE_NAME="${TRTLLM_EPLB_SHM_NAME:-moe_shared}" + +# List all related shared memory +ls -la "/dev/shm/${BASE_NAME}_*" @@ -# Remove all moe_shared related shared memory -rm -f /dev/shm/moe_shared_* +# Remove all related shared memory +rm -f "/dev/shm/${BASE_NAME}_*" @@ -# Or remove specific shared memory segments -rm -f /dev/shm/moe_shared_l0_lr0_all +# Or remove a specific shared memory segment +rm -f "/dev/shm/${BASE_NAME}_l0_lr0_all" @@ -**Warning:** Be careful when removing shared memory manually, as this may affect running processes that depend on these shared memory segments. +**Warning:** Removing shared memory manually can affect running processes that depend on these segments.Also applies to: 126-126
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
examples/wide_ep/README.md(1 hunks)tensorrt_llm/_torch/modules/fused_moe/moe_load_balancer.py(4 hunks)tests/integration/test_lists/waives.txt(0 hunks)
💤 Files with no reviewable changes (1)
- tests/integration/test_lists/waives.txt
🧰 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:
tensorrt_llm/_torch/modules/fused_moe/moe_load_balancer.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:
tensorrt_llm/_torch/modules/fused_moe/moe_load_balancer.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:
tensorrt_llm/_torch/modules/fused_moe/moe_load_balancer.py
🧬 Code graph analysis (1)
tensorrt_llm/_torch/modules/fused_moe/moe_load_balancer.py (2)
tensorrt_llm/_torch/expert_statistic.py (1)
create(18-29)tensorrt_llm/logger.py (1)
warning(132-133)
⏰ 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/_torch/modules/fused_moe/moe_load_balancer.py (1)
733-738: Signature change OK — callers compatible; no non-None assumptions found.All observed MoeLoadBalancer constructions use the 3-arg form (positional). The wrapper falls back to self.shared_memory_base_name = shared_memory_base_name or os.getenv(...); the only explicit string usage is in tests (tests/unittest/_torch/modules/test_moe_host_sharer.py). No other references to shared_memory_base_name were found.
|
PR_Github #18616 [ run ] completed with state |
|
/bot run --disable-fail-fast |
|
PR_Github #18625 [ run ] triggered by Bot |
|
PR_Github #18625 [ run ] completed with state |
|
/bot run --disable-fail-fast |
|
PR_Github #18641 [ run ] triggered by Bot |
|
PR_Github #18641 [ run ] completed with state |
d5efe32 to
0691978
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #18792 [ run ] triggered by Bot |
|
PR_Github #18792 [ run ] completed with state |
|
/bot run --disable-fail-fast |
|
PR_Github #18853 [ run ] triggered by Bot |
|
PR_Github #18853 [ run ] completed with state |
0691978 to
f918d1f
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #19141 [ run ] triggered by Bot |
|
PR_Github #19141 [ run ] completed with state |
|
/bot run --disable-fail-fast |
|
PR_Github #19260 [ run ] triggered by Bot |
|
PR_Github #19260 [ run ] completed with state |
NVIDIA#7377) Signed-off-by: Dongxu Yang <[email protected]>
f918d1f to
d0af03e
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #19337 [ run ] triggered by Bot |
|
/bot run --disable-fail-fast |
|
PR_Github #19401 [ run ] triggered by Bot |
|
PR_Github #19401 [ run ] completed with state |
|
/bot run --disable-fail-fast |
|
PR_Github #19434 [ run ] triggered by Bot |
|
PR_Github #19434 [ run ] completed with state |
…ete if already exist (NVIDIA#7727) Signed-off-by: Dongxu Yang <[email protected]>
…t (#7377)
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Tests
Description
Cherrypick PR #7377 to main.
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.