fix: use current CUDA device instead of tp_rank for SymmDeviceMemory allocation#2662
Conversation
…allocation `trtllm_create_ipc_workspace_for_all_reduce_fusion` passes `tp_rank` as the `device_idx` to `SymmDeviceMemory`, which internally calls `cudaSetDevice(device_idx)`. This assumes `tp_rank == gpu_device_id`, which breaks when the caller uses a non-zero base GPU offset (e.g. SGLang's `--base-gpu-id 4` maps TP ranks 0-3 to cuda:4-7). The mismatch causes SymmDeviceMemory to allocate buffers on the wrong GPU and clobber the active CUDA device context, leading to `CUBLAS_STATUS_EXECUTION_FAILED` on subsequent operations. Fix both the TRTLLM and MNNVL workspace creation paths to use `torch.cuda.current_device()` — which reflects the actual GPU the caller has selected — instead of deriving the device index from the TP rank.
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request addresses a critical bug in distributed GPU environments where the system's Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
📝 WalkthroughWalkthroughThe PR fixes device identifier handling in all-reduce and multicast operations by using Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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.
Code Review
This pull request addresses a bug where the tensor parallelism rank (tp_rank) or local rank was incorrectly assumed to be the CUDA device index. This assumption fails in scenarios with a non-zero base GPU offset, leading to memory allocation on the wrong device and subsequent CUDA errors. The fix correctly replaces the usage of tp_rank and mapping.local_rank with torch.cuda.current_device() to ensure that memory is allocated on the actual active CUDA device for the process. The changes in flashinfer/comm/trtllm_ar.py and flashinfer/comm/trtllm_mnnvl_ar.py are accurate and effectively resolve the described issue. I've added one suggestion to improve code clarity by adding a comment for consistency.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@flashinfer/comm/trtllm_mnnvl_ar.py`:
- Around line 135-143: The device used to create the workspace is inconsistent:
McastGPUBuffer is constructed with torch.device("cuda",
torch.cuda.current_device()) but self.buffer_flags is allocated using
mapping.local_rank, which can point to a different CUDA device when base_gpu_id
!= 0; update the allocation of self.buffer_flags to use the same CUDA device as
McastGPUBuffer (use torch.cuda.current_device() or the previously built
torch.device) instead of mapping.local_rank so both workspace objects reference
the same GPU (look for McastGPUBuffer construction and the code that allocates
self.buffer_flags).
- Add explanatory comment for torch.cuda.current_device() usage in trtllm_ar.py (gemini review) - Fix buffer_flags allocation to also use current_device() instead of mapping.local_rank (coderabbit review)
…educe bug FlashInfer allreduce fusion crashes with base_gpu_id != 0 (colocate mode). Enable DP attention so the auto-enable logic is skipped. See flashinfer-ai/flashinfer#2662
Test validates that allreduce fusion works correctly when the CUDA device index differs from the TP rank, simulating sglang colocate mode where inference engines run on non-zero base GPUs (e.g. GPUs 4-7 with TP ranks 0-3). Tests both legacy and unified APIs with CUDA graph capture.
Instead of a separate test file, extend the existing worker and multi_process_parallel with a gpu_offset parameter (default 0, no behavior change for existing tests). New test_trtllm_allreduce_fusion_gpu_offset reuses the same worker with gpu_offset = available_gpus - world_size, validating that allreduce fusion works when CUDA device index != TP rank.
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
tests/comm/test_allreduce_fusion_gpu_offset.py (1)
255-262: Use iterable unpacking forproc_args(RUF005).Ruff flagged tuple concatenation here; unpacking is cleaner and avoids the lint warning.
♻️ Suggested refactor
- proc_args: tuple[Any, ...] = ( - world_size, - i, - gpu_offset, - dtype, - hidden_dim, - distributed_init_port, - ) + target_args + proc_args: tuple[Any, ...] = ( + world_size, + i, + gpu_offset, + dtype, + hidden_dim, + distributed_init_port, + *target_args, + )🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/comm/test_allreduce_fusion_gpu_offset.py` around lines 255 - 262, Replace the tuple concatenation that builds proc_args with iterable unpacking: instead of joining two tuples, use the starred-unpacking form to include target_args directly (update the proc_args assignment where proc_args and target_args are used in tests/comm/test_allreduce_fusion_gpu_offset.py). Ensure proc_args = (world_size, i, gpu_offset, dtype, hidden_dim, distributed_init_port, *target_args) so Ruff RUF005 is satisfied and behavior is unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@tests/comm/test_allreduce_fusion_gpu_offset.py`:
- Around line 1-314: The test file was reformatted by ruff-format; run the
project's formatter (pre-commit / ruff-format) on this file and commit the
changes so CI passes. Specifically, run the formatter (or `pre-commit run
--all-files` / `ruff format tests/comm/test_allreduce_fusion_gpu_offset.py`),
review the changes affecting functions like _worker_with_gpu_offset,
_run_multi_process, and test_allreduce_fusion_gpu_offset, stage and commit the
reformatted file, and push the commit.
- Around line 51-83: Initialize ipc_handles and workspace to None before the
setup try-block and guard all teardown/cleanup code to only act if those
variables are not None (references: ipc_handles, workspace,
comm.trtllm_create_ipc_workspace_for_all_reduce_fusion,
comm.create_allreduce_fusion_workspace). Also protect the unconditional teardown
barrier/torch.distributed calls by checking torch.distributed.is_available() and
torch.distributed.is_initialized() (and that world_size>1) or wrap the barrier
in a try/except to avoid hangs when another rank has failed; apply the same
guards to the other similar block around the code referenced for lines 220-228.
- Around line 272-293: Add an architecture-based skip at the start of
test_allreduce_fusion_gpu_offset to avoid RuntimeError when calling allreduce on
unsupported GPUs: import and call the flashinfer.utils helper (e.g.,
is_sm80_supported) and call pytest.skip(...) if it returns False. Place this
check before any CUDA seeds or device-count logic so the test is skipped early;
reference the test function name (test_allreduce_fusion_gpu_offset) and the
backend-protected function (allreduce) to clarify why the helper is required.
---
Nitpick comments:
In `@tests/comm/test_allreduce_fusion_gpu_offset.py`:
- Around line 255-262: Replace the tuple concatenation that builds proc_args
with iterable unpacking: instead of joining two tuples, use the
starred-unpacking form to include target_args directly (update the proc_args
assignment where proc_args and target_args are used in
tests/comm/test_allreduce_fusion_gpu_offset.py). Ensure proc_args = (world_size,
i, gpu_offset, dtype, hidden_dim, distributed_init_port, *target_args) so Ruff
RUF005 is satisfied and behavior is unchanged.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
tests/comm/test_trtllm_allreduce_fusion.py (1)
437-447: Consider iterable unpacking for cleaner tuple construction.The static analyzer flags the tuple concatenation. Iterable unpacking improves readability and avoids nested parentheses.
♻️ Suggested refactor
proc_args = ( - ( - world_size, - i, - dtype, - hidden_dim, - distributed_init_port, - ) - + target_args - + (gpu_offset,) + world_size, + i, + dtype, + hidden_dim, + distributed_init_port, + *target_args, + gpu_offset, )🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/comm/test_trtllm_allreduce_fusion.py` around lines 437 - 447, Replace the tuple concatenation used to build proc_args with iterable unpacking to improve readability: instead of joining tuples with +, construct proc_args by listing the fixed elements (world_size, i, dtype, hidden_dim, distributed_init_port), then unpack target_args with *target_args and append gpu_offset as the final element; update the code that assigns proc_args accordingly (look for the proc_args variable near target_args and gpu_offset).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@tests/comm/test_trtllm_allreduce_fusion.py`:
- Around line 437-447: Replace the tuple concatenation used to build proc_args
with iterable unpacking to improve readability: instead of joining tuples with
+, construct proc_args by listing the fixed elements (world_size, i, dtype,
hidden_dim, distributed_init_port), then unpack target_args with *target_args
and append gpu_offset as the final element; update the code that assigns
proc_args accordingly (look for the proc_args variable near target_args and
gpu_offset).
|
/bot run |
|
[CANCELING] Pipeline #45169844: canceled |
|
/bot run |
|
[FAILED] Pipeline #46827216: 13/20 passed |
Summary
trtllm_create_ipc_workspace_for_all_reduce_fusionpassestp_rankas thedevice_idxtoSymmDeviceMemory, which internally callscudaSetDevice(device_idx). This assumestp_rank == gpu_device_id.--base-gpu-id 4maps TP ranks 0–3 to cuda:4–7).CUBLAS_STATUS_EXECUTION_FAILEDon subsequent operations.MNNVLAllReduceFusionWorkspace) wheremapping.local_rankis used as device index.Fix
Use
torch.cuda.current_device()— which reflects the actual GPU the caller has selected — instead of deriving the device index from the TP rank.Repro
Test plan
--base-gpu-id 4 --tp 4crashes without fix, passes with fixtp_rank == device_id, which is the common case)Summary by CodeRabbit
Release Notes
Bug Fixes
Tests