[None][feat] Support Ulysses CP for torch flow - #10276
Conversation
|
/bot run |
|
PR_Github #29814 [ run ] triggered by Bot. Commit: |
|
PR_Github #29814 [ run ] completed with state |
📝 WalkthroughWalkthroughThis pull request introduces context parallelism (CP) support with Ulysses type throughout the system. Changes include CLI argument addition, LLM initialization updates, attention module preprocessing/postprocessing methods, model engine input preparation, KV cache and executor modifications, and benchmarking utilities. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ 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: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
tensorrt_llm/bench/build/tuning.py (1)
21-30: Update the caller intensorrt_llm/bench/build/build.pyto include thecp_sizeparameter.The function signature change at lines 21-30 adds a required
cp_size: intparameter, and line 71 correctly multiplies GPU count asn_gpus = tp_size * pp_size * cp_size. However, the caller inbuild.py(lines 56-61) does not pass thecp_sizeargument, causing positional argument misalignment. Thetarget_input_lenand subsequent arguments are shifted by one position.Update the call to include
cp_sizebetweenpp_sizeandtarget_input_len.tensorrt_llm/_torch/modules/attention.py (2)
230-239: Clarify Ulysses CP invariants and tp/head divisibilityThe new block:
if config.mapping.has_cp_ulysses(): tp_size = tp_size * cp_size assert self.num_heads % tp_size == 0 assert self.num_key_value_heads % tp_size == 0tightens invariants for CP‑Ulysses by requiring both
num_headsandnum_key_value_headsto be divisible bytp_size * cp_size. That’s reasonable, but:
- It’s stricter than the existing MQA path (which allowed non‑divisible
num_key_value_headsand rounded up per‑rank KV heads).- It will fail hard for any config that previously relied on that behavior once CP‑Ulysses is turned on.
Please document this requirement (e.g., in model/config docs or error message) so users understand that CP‑Ulysses currently assumes clean head/kv‑head factorization across TP×CP.
873-878: MLA CP‑Ulysses guard is good; minor typo and safer cp_type accessThe new MLA guard:
if self.mapping.has_cp_ulysses(): raise NotImplementedError("MLA doesn't support CP Ulyssees yet") if self.mapping.cp_size > 1: assert self.mapping.has_cp_helix( ), f"CP type must be HELIX for MLA, but got {self.mapping.cp_config['cp_type']}."is the right move to avoid silently mis‑configuring MLA under CP‑Ulysses, but:
- The error string has a small typo (
Ulyssees→Ulysses).- Accessing
self.mapping.cp_config['cp_type']in the assert message can raiseKeyErrorifcp_typeis missing. Using.get("cp_type")would be more robust.Suggested tweak
- if self.mapping.has_cp_ulysses(): - raise NotImplementedError("MLA doesn't support CP Ulyssees yet") + if self.mapping.has_cp_ulysses(): + raise NotImplementedError("MLA doesn't support CP Ulysses yet") @@ - if self.mapping.cp_size > 1: - assert self.mapping.has_cp_helix( - ), f"CP type must be HELIX for MLA, but got {self.mapping.cp_config['cp_type']}." + if self.mapping.cp_size > 1: + assert self.mapping.has_cp_helix(), ( + f"CP type must be HELIX for MLA, but got " + f"{self.mapping.cp_config.get('cp_type')!r}." + )
🧹 Nitpick comments (5)
tensorrt_llm/_torch/pyexecutor/resource_manager.py (1)
199-203: Ulysses CP tp_size scaling looks consistent; consider a brief comment for future readersUsing
tp_size *= mapping.cp_sizewhenhas_cp_ulysses()is true correctly treats CP as an extra sharding dimension for KV heads, reducing per‑token KV bytes and increasingmax_tokensaccordingly while remaining compatible with the non‑CP estimation path that still forbids CP. A short comment here explaining that we intentionally treat Ulysses CP as “extra TP” for KV capacity could help avoid accidental regressions if the estimation path is later generalized to CP.tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1)
703-729: Ulysses CP now uses the default merge path — add a short comment for clarityBy turning the ULYSSES branch into a
pass,_merge_requestseffectively falls back to the genericexecutor_request_to_llm_requesthandling for Ulysses, while STAR and HELIX keep custom reshaping. That’s a reasonable choice if Ulysses context splitting is handled later in the pipeline, but the empty branch is a bit non‑obvious; consider adding a comment like “# ULYSSES uses the standard merge path” to make the intent explicit to future readers.examples/llm-api/quickstart_advanced.py (1)
11-11: Quickstart Ulysses CP wiring is fine; optional validation could improve UXThe example’s CP plumbing is coherent: a
--cp_sizeflag, a minimalcp_config = {"cp_type": CpType.ULYSSES}whencp_size > 1, and forwarding bothcontext_parallel_sizeandcp_configintoLLM(...). For a quickstart this is enough to exercise Ulysses CP; if you want to harden it further, consider validating thatcp_size > 1only when the environment and chosenattention_backendactually support Ulysses CP so users get an early, clear error instead of a later runtime failure.Also applies to: 80-80, 259-262, 292-293
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
592-597: Warmup skip for non‑Ulysses CP looks intentional but deserves a brief rationaleThe new guard skips warmup whenever
cp_size > 1andhas_cp_ulysses()is false. That effectively disables torch.compile/autotuner/CUDA‑graph warmup for STAR/HELIX (and any other CP types) while keeping it for Ulysses.If that’s the intended limitation, this is fine, but it’s worth:
- Adding a short comment clarifying that only CP‑Ulysses is supported for warmup today.
- Double‑checking there’s no existing CP configuration in production that relies on warmup (STAR/HELIX torch flow), since this is now a behavior change.
tensorrt_llm/_torch/modules/attention.py (1)
677-680: Double‑check CP‑Ulysses postprocess output shapes before feeding intoo_projThe CP‑Ulysses postprocess runs after attention and just before
o_proj:if attn_metadata.mapping.has_cp_ulysses(): attn_output = self.ulysses_context_postprocess(attn_output, attn_metadata) ... attn_output = self.o_proj(attn_output, ...)Given
ulysses_context_postprocessusesalltoall_helixand reshapes, please verify that:
attn_output.shape[0]still equalsattn_metadata.num_tokens, andattn_output.shape[1]still equalsself.o_proj.in_features.If they differ (e.g., feature dim scaled by
cp_size), this will misalign with the TP layout expected byLinear. Adding explicit asserts inulysses_context_postprocess(guarded by CP‑Ulysses) would make this contract obvious and catch regressions early.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (15)
examples/llm-api/quickstart_advanced.pytensorrt_llm/_torch/models/modeling_speculative.pytensorrt_llm/_torch/modules/attention.pytensorrt_llm/_torch/pyexecutor/_util.pytensorrt_llm/_torch/pyexecutor/cuda_graph_runner.pytensorrt_llm/_torch/pyexecutor/executor_request_queue.pytensorrt_llm/_torch/pyexecutor/model_engine.pytensorrt_llm/_torch/pyexecutor/py_executor.pytensorrt_llm/_torch/pyexecutor/resource_manager.pytensorrt_llm/bench/benchmark/throughput.pytensorrt_llm/bench/benchmark/utils/general.pytensorrt_llm/bench/build/tuning.pytensorrt_llm/bench/dataclasses/configuration.pytensorrt_llm/bench/dataclasses/reporting.pytensorrt_llm/commands/serve.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/models/modeling_speculative.pytensorrt_llm/bench/dataclasses/reporting.pytensorrt_llm/_torch/pyexecutor/resource_manager.pytensorrt_llm/_torch/pyexecutor/cuda_graph_runner.pytensorrt_llm/_torch/pyexecutor/model_engine.pytensorrt_llm/_torch/pyexecutor/py_executor.pytensorrt_llm/bench/benchmark/throughput.pytensorrt_llm/_torch/pyexecutor/_util.pytensorrt_llm/bench/benchmark/utils/general.pytensorrt_llm/bench/dataclasses/configuration.pyexamples/llm-api/quickstart_advanced.pytensorrt_llm/_torch/pyexecutor/executor_request_queue.pytensorrt_llm/_torch/modules/attention.pytensorrt_llm/commands/serve.pytensorrt_llm/bench/build/tuning.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/models/modeling_speculative.pytensorrt_llm/bench/dataclasses/reporting.pytensorrt_llm/_torch/pyexecutor/resource_manager.pytensorrt_llm/_torch/pyexecutor/cuda_graph_runner.pytensorrt_llm/_torch/pyexecutor/model_engine.pytensorrt_llm/_torch/pyexecutor/py_executor.pytensorrt_llm/bench/benchmark/throughput.pytensorrt_llm/_torch/pyexecutor/_util.pytensorrt_llm/bench/benchmark/utils/general.pytensorrt_llm/bench/dataclasses/configuration.pyexamples/llm-api/quickstart_advanced.pytensorrt_llm/_torch/pyexecutor/executor_request_queue.pytensorrt_llm/_torch/modules/attention.pytensorrt_llm/commands/serve.pytensorrt_llm/bench/build/tuning.py
🧠 Learnings (18)
📓 Common learnings
Learnt from: moraxu
Repo: NVIDIA/TensorRT-LLM PR: 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.
📚 Learning: 2025-08-14T21:04:50.248Z
Learnt from: thorjohnsen
Repo: NVIDIA/TensorRT-LLM PR: 6910
File: cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp:0-0
Timestamp: 2025-08-14T21:04:50.248Z
Learning: In KV cache onboarding logic during prefill in cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp, when calculating which blocks fall within the attention window, use getTokensPerBlock() to advance token indices rather than block->getUniqueTokens().size(), because the calculation needs to consider the post-prefill state where blocks will be filled to capacity, not their current token count.
Applied to files:
tensorrt_llm/_torch/pyexecutor/resource_manager.pytensorrt_llm/_torch/pyexecutor/cuda_graph_runner.pytensorrt_llm/_torch/modules/attention.py
📚 Learning: 2025-09-29T15:14:28.503Z
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 8063
File: tensorrt_llm/lora_manager.py:1080-1112
Timestamp: 2025-09-29T15:14:28.503Z
Learning: In tensorrt_llm/lora_manager.py, when calculating part_sizes for attn_qkv fused LoRA modules, the sizes are correctly multiplied by tp_size because model_config.num_heads and model_config.num_kv_heads are already divided by tp_size (per-TP-rank values), so multiplication is needed to get the original full concatenated dimension size. The interleave_fused_lora_weights_for_tp function provides proper validation with asserts for total size and TP divisibility.
Applied to files:
tensorrt_llm/_torch/pyexecutor/resource_manager.pytensorrt_llm/_torch/pyexecutor/cuda_graph_runner.pytensorrt_llm/_torch/modules/attention.pytensorrt_llm/bench/build/tuning.py
📚 Learning: 2025-09-29T15:14:28.503Z
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 8063
File: tensorrt_llm/lora_manager.py:1080-1112
Timestamp: 2025-09-29T15:14:28.503Z
Learning: In tensorrt_llm/lora_manager.py, when calculating part_sizes for attn_qkv fused LoRA modules, the sizes are correctly multiplied by tp_size because model_config.num_heads and model_config.num_kv_heads are already divided by tp_size (per-TP-rank values), so multiplication is needed to get the original full concatenated dimension size. The interleave_fused_lora_weights_for_tp function provides proper validation.
Applied to files:
tensorrt_llm/_torch/pyexecutor/resource_manager.pytensorrt_llm/_torch/modules/attention.pytensorrt_llm/bench/build/tuning.py
📚 Learning: 2025-08-15T06:46:53.813Z
Learnt from: eopXD
Repo: NVIDIA/TensorRT-LLM PR: 6767
File: cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp:0-0
Timestamp: 2025-08-15T06:46:53.813Z
Learning: In the TensorRT-LLM KV cache manager, SWA (Sliding Window Attention) combined with beam search is currently in a broken/non-functional state and is planned for future rework. During preparatory refactoring phases, code related to SWA+beam search may intentionally remain in a non-working state until the broader rework is completed.
Applied to files:
tensorrt_llm/_torch/pyexecutor/resource_manager.py
📚 Learning: 2025-08-15T06:46:54.897Z
Learnt from: eopXD
Repo: NVIDIA/TensorRT-LLM PR: 6767
File: cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp:0-0
Timestamp: 2025-08-15T06:46:54.897Z
Learning: In cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp addToken function, newly allocated blocks are unshared by design. The beam search path in addToken (when sequence.getNumTokens() > windowSize) is currently broken/non-functional with SWA, so the block allocation doesn't follow a shared-then-unshared pattern.
Applied to files:
tensorrt_llm/_torch/pyexecutor/resource_manager.py
📚 Learning: 2025-08-14T06:36:40.701Z
Learnt from: timlee0212
Repo: NVIDIA/TensorRT-LLM PR: 6886
File: tensorrt_llm/_torch/models/modeling_deepseekv3.py:0-0
Timestamp: 2025-08-14T06:36:40.701Z
Learning: In DeepSeek V3 model (tensorrt_llm/_torch/models/modeling_deepseekv3.py), the disagreement between AllReduce.__init__ guard and _compute_mlp_tp_size logic for MNNVL usage is expected by design. The AllReduce component and MLP TP-size computation intentionally use different criteria for MNNVL availability decisions.
Applied to files:
tensorrt_llm/_torch/pyexecutor/resource_manager.py
📚 Learning: 2025-08-21T09:41:49.347Z
Learnt from: eopXD
Repo: NVIDIA/TensorRT-LLM PR: 6768
File: cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp:2010-2045
Timestamp: 2025-08-21T09:41:49.347Z
Learning: In cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp, updateSequenceCacheBlockOffsets is specifically for updating bookkeeping when blocks are added during the context phase, not for refreshing offsets after detach operations. During detach operations, GenerationRequest::removeFrontBlock handles the necessary cache block bookkeeping internally.
Applied to files:
tensorrt_llm/_torch/pyexecutor/resource_manager.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/resource_manager.pytensorrt_llm/_torch/pyexecutor/cuda_graph_runner.pytensorrt_llm/_torch/pyexecutor/model_engine.pytensorrt_llm/_torch/pyexecutor/py_executor.pytensorrt_llm/_torch/pyexecutor/_util.pytensorrt_llm/_torch/pyexecutor/executor_request_queue.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/cuda_graph_runner.pytensorrt_llm/_torch/pyexecutor/py_executor.py
📚 Learning: 2025-08-09T20:57:04.084Z
Learnt from: sklevtsov-nvidia
Repo: NVIDIA/TensorRT-LLM PR: 3294
File: cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_tma_warp_specialized_input.cu:118-127
Timestamp: 2025-08-09T20:57:04.084Z
Learning: In the CUTLASS MoE finalize fusion implementation (cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_tma_warp_specialized_input.cu), when setting `fused_finalize_epilogue.stride_final_output` with shape `(hidden_size, num_output_tokens, 1)`, the `num_rows_in_final_output` should be set to `num_output_tokens` (not `hidden_size`) because of a swap+transpose operation that maps rows of the output tensor to `hidden_size` and columns to `num_output_tokens`.
Applied to files:
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
📚 Learning: 2025-08-26T09:37:10.463Z
Learnt from: jiaganc
Repo: NVIDIA/TensorRT-LLM PR: 7031
File: tensorrt_llm/bench/dataclasses/configuration.py:90-104
Timestamp: 2025-08-26T09:37:10.463Z
Learning: In TensorRT-LLM's bench configuration, the `get_pytorch_perf_config()` method returns `self.pytorch_config` which is a Dict[str, Any] that can contain default values including `cuda_graph_config`, making the fallback `llm_args["cuda_graph_config"]` safe to use.
Applied to files:
tensorrt_llm/_torch/pyexecutor/model_engine.pytensorrt_llm/bench/dataclasses/configuration.py
📚 Learning: 2025-12-12T03:27:18.859Z
Learnt from: tongyuantongyu
Repo: NVIDIA/TensorRT-LLM PR: 9655
File: tensorrt_llm/_torch/pyexecutor/sampler.py:3031-3031
Timestamp: 2025-12-12T03:27:18.859Z
Learning: In tensorrt_llm/_torch/pyexecutor/sampler.py, when reviewing code that iterates through requests, ensure it does not convert excessive data into Python lists. Instead, the code should use torch.gather or indexing to gather only the data that will be used in the for loop before converting to Python lists. This minimizes data movement and improves performance.
Applied to files:
tensorrt_llm/_torch/pyexecutor/py_executor.py
📚 Learning: 2025-08-14T15:38:01.771Z
Learnt from: MatthiasKohl
Repo: NVIDIA/TensorRT-LLM PR: 6904
File: cpp/tensorrt_llm/pybind/thop/bindings.cpp:55-57
Timestamp: 2025-08-14T15:38:01.771Z
Learning: In TensorRT-LLM Python bindings, tensor parameter collections like mla_tensor_params and spec_decoding_tensor_params are kept as required parameters without defaults to maintain API consistency, even when it might affect backward compatibility.
Applied to files:
tensorrt_llm/bench/benchmark/throughput.pytensorrt_llm/bench/dataclasses/configuration.pyexamples/llm-api/quickstart_advanced.py
📚 Learning: 2025-08-26T09:37:10.463Z
Learnt from: jiaganc
Repo: NVIDIA/TensorRT-LLM PR: 7031
File: tensorrt_llm/bench/dataclasses/configuration.py:90-104
Timestamp: 2025-08-26T09:37:10.463Z
Learning: In TensorRT-LLM, the `get_pytorch_perf_config()` method returns `self.pytorch_config` which can contain default `cuda_graph_config` values, so `llm_args` may already have this config before the extra options processing.
Applied to files:
tensorrt_llm/bench/dataclasses/configuration.pyexamples/llm-api/quickstart_advanced.py
📚 Learning: 2025-11-27T09:23:18.742Z
Learnt from: fredricz-20070104
Repo: NVIDIA/TensorRT-LLM PR: 9511
File: tests/integration/defs/examples/serve/test_serve.py:136-186
Timestamp: 2025-11-27T09:23:18.742Z
Learning: In TensorRT-LLM testing, when adding test cases based on RCCA commands, the command format should be copied exactly as it appears in the RCCA case, even if it differs from existing tests. For example, some RCCA commands for trtllm-serve may omit the "serve" subcommand while others include it.
Applied to files:
examples/llm-api/quickstart_advanced.pytensorrt_llm/commands/serve.py
📚 Learning: 2025-07-28T17:06:08.621Z
Learnt from: moraxu
Repo: NVIDIA/TensorRT-LLM PR: 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:
examples/llm-api/quickstart_advanced.py
📚 Learning: 2025-08-14T15:43:23.107Z
Learnt from: MatthiasKohl
Repo: NVIDIA/TensorRT-LLM PR: 6904
File: tensorrt_llm/_torch/attention_backend/trtllm.py:259-262
Timestamp: 2025-08-14T15:43:23.107Z
Learning: In TensorRT-LLM's attention backend, tensor parameters in the plan() method are assigned directly without validation (dtype, device, contiguity checks). This maintains consistency across all tensor inputs and follows the pattern of trusting callers to provide correctly formatted tensors.
Applied to files:
tensorrt_llm/_torch/modules/attention.py
🧬 Code graph analysis (12)
tensorrt_llm/_torch/models/modeling_speculative.py (2)
tensorrt_llm/_torch/models/checkpoints/base_weight_mapper.py (1)
mapping(162-163)cpp/tests/unit_tests/kernels/mixtureOfExpertsTest.cu (1)
hidden_states(2303-2303)
tensorrt_llm/_torch/pyexecutor/resource_manager.py (3)
tensorrt_llm/runtime/model_runner.py (1)
mapping(825-826)tensorrt_llm/mapping.py (1)
has_cp_ulysses(241-243)tensorrt_llm/_torch/distributed/communicator.py (3)
has_cp_ulysses(100-101)tp_size(64-65)cp_size(56-57)
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (2)
tensorrt_llm/_torch/distributed/communicator.py (1)
cp_size(56-57)tensorrt_llm/_torch/utils.py (1)
shape(141-142)
tensorrt_llm/_torch/pyexecutor/py_executor.py (1)
tensorrt_llm/mapping.py (1)
CpType(25-33)
tensorrt_llm/bench/benchmark/throughput.py (1)
tensorrt_llm/mapping.py (1)
CpType(25-33)
tensorrt_llm/_torch/pyexecutor/_util.py (2)
tensorrt_llm/_torch/distributed/communicator.py (3)
has_cp_ulysses(100-101)tp_size(64-65)cp_size(56-57)tensorrt_llm/_torch/pyexecutor/kv_cache_transceiver.py (1)
create_kv_cache_transceiver(31-65)
tensorrt_llm/bench/benchmark/utils/general.py (1)
tensorrt_llm/mapping.py (1)
CpType(25-33)
examples/llm-api/quickstart_advanced.py (2)
tensorrt_llm/mapping.py (1)
CpType(25-33)tensorrt_llm/_torch/distributed/communicator.py (2)
cp_config(108-109)cp_size(56-57)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1)
tensorrt_llm/mapping.py (1)
CpType(25-33)
tensorrt_llm/_torch/modules/attention.py (3)
tensorrt_llm/mapping.py (1)
has_cp_ulysses(241-243)tensorrt_llm/_torch/distributed/communicator.py (2)
has_cp_ulysses(100-101)cp_size(56-57)tensorrt_llm/_torch/distributed/ops.py (1)
alltoall_helix(329-365)
tensorrt_llm/commands/serve.py (3)
tensorrt_llm/_torch/distributed/communicator.py (3)
cp_config(108-109)tp_size(64-65)cp_size(56-57)tensorrt_llm/mapping.py (1)
CpType(25-33)tensorrt_llm/llmapi/llm_args.py (1)
ep_size(389-393)
tensorrt_llm/bench/build/tuning.py (1)
tensorrt_llm/_torch/distributed/communicator.py (3)
cp_size(56-57)tp_size(64-65)pp_size(60-61)
🪛 Ruff (0.14.10)
tensorrt_llm/_torch/pyexecutor/model_engine.py
3132-3132: Comment contains ambiguous , (FULLWIDTH COMMA). Did you mean , (COMMA)?
(RUF003)
3132-3132: Comment contains ambiguous , (FULLWIDTH COMMA). Did you mean , (COMMA)?
(RUF003)
tensorrt_llm/commands/serve.py
97-97: Expected ,, found <<
(invalid-syntax)
97-97: Expected ,, found <<
(invalid-syntax)
97-97: Expected ,, found <<
(invalid-syntax)
97-97: Expected ,, found <
(invalid-syntax)
97-97: Parameter without a default cannot follow a parameter with a default
(invalid-syntax)
98-98: Expected ,, found name
(invalid-syntax)
99-99: Expected ,, found ==
(invalid-syntax)
99-99: Expected ,, found ==
(invalid-syntax)
99-99: Expected ,, found ==
(invalid-syntax)
99-99: Expected ,, found =
(invalid-syntax)
101-101: Expected ,, found >>
(invalid-syntax)
101-101: Expected ,, found >>
(invalid-syntax)
101-101: Expected ,, found >>
(invalid-syntax)
101-101: Expected ,, found >
(invalid-syntax)
101-101: Parameter without a default cannot follow a parameter with a default
(invalid-syntax)
101-101: Expected ), found (
(invalid-syntax)
101-101: Expected ), found name
(invalid-syntax)
101-101: Simple statements must be separated by newlines or semicolons
(invalid-syntax)
101-101: Expected newline, found )
(invalid-syntax)
133-133: Expected a statement
(invalid-syntax)
133-133: Expected a statement
(invalid-syntax)
133-133: Expected a statement
(invalid-syntax)
133-133: Expected a statement
(invalid-syntax)
142-142: Expected a statement
(invalid-syntax)
142-142: Expected a statement
(invalid-syntax)
142-142: Expected a statement
(invalid-syntax)
142-142: Expected a statement
(invalid-syntax)
142-143: Expected a statement
(invalid-syntax)
143-143: Unexpected indentation
(invalid-syntax)
146-146: Expected a statement
(invalid-syntax)
146-146: Expected a statement
(invalid-syntax)
146-146: Expected a statement
(invalid-syntax)
146-146: Expected a statement
(invalid-syntax)
146-146: Expected ,, found name
(invalid-syntax)
146-146: Expected ), found pass
(invalid-syntax)
146-146: Expected a statement
(invalid-syntax)
155-155: Expected ,, found <<
(invalid-syntax)
155-155: Expected ,, found <<
(invalid-syntax)
155-155: Expected ,, found <<
(invalid-syntax)
155-155: Expected ,, found <
(invalid-syntax)
156-156: Expected :, found string
(invalid-syntax)
156-156: Expected ,, found :
(invalid-syntax)
156-156: Expected :, found ,
(invalid-syntax)
157-157: Expected ,, found ==
(invalid-syntax)
157-157: Expected ,, found ==
(invalid-syntax)
157-157: Expected ,, found ==
(invalid-syntax)
157-157: Expected ,, found =
(invalid-syntax)
159-159: Expected ,, found >>
(invalid-syntax)
159-159: Expected ,, found >>
(invalid-syntax)
159-159: Expected ,, found >>
(invalid-syntax)
159-159: Expected ,, found >
(invalid-syntax)
159-159: Expected ,, found name
(invalid-syntax)
159-159: Expected ), found pass
(invalid-syntax)
159-159: Expected ,, found )
(invalid-syntax)
450-450: Expected a parameter or the end of the parameter list
(invalid-syntax)
450-450: Expected a parameter or the end of the parameter list
(invalid-syntax)
450-450: Expected a parameter or the end of the parameter list
(invalid-syntax)
450-450: Expected a parameter or the end of the parameter list
(invalid-syntax)
451-451: Expected ,, found name
(invalid-syntax)
458-458: Expected ,, found ==
(invalid-syntax)
458-458: Expected ,, found ==
(invalid-syntax)
458-458: Expected ,, found ==
(invalid-syntax)
458-458: Expected ,, found =
(invalid-syntax)
465-465: Expected ,, found >>
(invalid-syntax)
465-465: Expected ,, found >>
(invalid-syntax)
465-465: Expected ,, found >>
(invalid-syntax)
465-465: Expected ,, found >
(invalid-syntax)
465-465: Expected ), found (
(invalid-syntax)
465-465: Expected ), found name
(invalid-syntax)
465-465: Simple statements must be separated by newlines or semicolons
(invalid-syntax)
465-465: Expected newline, found )
(invalid-syntax)
496-496: Expected ,, found <<
(invalid-syntax)
496-496: Expected ,, found <<
(invalid-syntax)
496-496: Expected ,, found <<
(invalid-syntax)
496-496: Expected ,, found <
(invalid-syntax)
496-496: Positional argument cannot follow keyword argument
(invalid-syntax)
497-497: Expected ,, found name
(invalid-syntax)
502-502: Expected ,, found ==
(invalid-syntax)
502-502: Expected ,, found ==
(invalid-syntax)
502-502: Expected ,, found ==
(invalid-syntax)
502-502: Expected ,, found =
(invalid-syntax)
503-503: Duplicate keyword argument "tensor_parallel_size"
(invalid-syntax)
504-504: Duplicate keyword argument "pipeline_parallel_size"
(invalid-syntax)
505-505: Duplicate keyword argument "context_parallel_size"
(invalid-syntax)
507-507: Duplicate keyword argument "moe_expert_parallel_size"
(invalid-syntax)
508-508: Duplicate keyword argument "moe_cluster_parallel_size"
(invalid-syntax)
509-509: Expected ,, found >>
(invalid-syntax)
509-509: Expected ,, found >>
(invalid-syntax)
509-509: Expected ,, found >>
(invalid-syntax)
509-509: Expected ,, found >
(invalid-syntax)
509-509: Positional argument cannot follow keyword argument
(invalid-syntax)
509-509: Expected ,, found name
(invalid-syntax)
509-509: Expected ), found pass
(invalid-syntax)
509-509: Expected ), found pass
(invalid-syntax)
509-509: Simple statements must be separated by newlines or semicolons
(invalid-syntax)
509-509: Expected a statement
(invalid-syntax)
⏰ 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 (10)
tensorrt_llm/bench/dataclasses/reporting.py (1)
387-398: cp_size reporting wiring is consistentAdding
cp_sizeinto both the structuredworld_infodict and the human‑readable WORLD + RUNTIME section keeps bench output aligned with the new CP configuration, assumingRuntimeConfig.mappingalways provides acp_sizeentry (defaulting to 1 when CP is disabled).Also applies to: 596-603
tensorrt_llm/_torch/models/modeling_speculative.py (1)
12-12: Confirm cp_allgather semantics and attn_metadata.mapping type for Ulysses CPThe Ulysses path that does
if attn_metadata.mapping.has_cp_ulysses(): hidden_states = cp_allgather(hidden_states, attn_metadata.mapping, dim=0)after truncating to
attn_metadata.num_tokensis conceptually right: we want full hidden states across CP ranks before feeding the draft path or logits. This assumes:
attn_metadata.mappingis aMapping(or equivalent) exposinghas_cp_ulysses()and all CP metadata, not just a plain dict.cp_allgather’s contract is to all‑gather along dim 0 for this tensor shape and mapping, returning per‑rankhidden_stateswith the same logical layout expected by the downstream spec worker and logits processor.Please double‑check those two assumptions (shape and mapping type) and that the gathered size matches
attn_metadata.num_tokensto avoid subtle CP shape bugs.Also applies to: 827-830
tensorrt_llm/bench/dataclasses/configuration.py (1)
40-58: LLM args CP wiring looks correctAdding
"context_parallel_size": self.mapping["cp_size"]and"cp_config": self.mapping["cp_config"]intoget_llm_argscleanly forwards CP settings into the LLM API alongside existing TP/PP/MoE knobs. This assumes all bench mappings populatecp_sizeandcp_config(with sensible defaults when CP is off), which aligns with the rest of the CP plumbing in this PR.tensorrt_llm/_torch/pyexecutor/_util.py (1)
1-1: Treating Ulysses CP as extra TP for the KV cache transceiver is reasonableThe
mapping_for_kv_cache_transceiverindirection with adeepcopyandtp_size *= cp_size; cp_size = 1cleanly scopes the “CP folded into TP” view to the KV cache transceiver without mutating the mainmappingused by the rest of PyExecutor. This matches the intent of sharing KV across Ulysses ranks while letting the transceiver reason in pure‑TP terms. Just keep in mind that ifMappingever gains non‑trivial, non‑copyable state,deepcopymight need revisiting, but with the current lightweight config it’s fine.Also applies to: 820-831
tensorrt_llm/_torch/pyexecutor/py_executor.py (1)
2282-2283: LGTM! Clean addition of Ulysses CP support.The change correctly extends CP type handling to treat ULYSSES equivalently to HELIX, both following the standard TP-based update path. This replaces the previous NotImplementedError for ULYSSES and aligns with the PR objective.
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (2)
389-390: Subtle change in position_ids length handling.The code now derives
seqlenfromposition_ids.shape[-1]instead ofinput_ids.shape[0]. The comment explains this is needed because "the length of position_ids may be different from input_ids in Ulysses context parallel."This is a subtle behavioral change. While the comment provides rationale for Ulysses CP, verify that this doesn't break non-Ulysses cases where the previous assumption (seqlen = input_ids.shape[0]) was valid.
327-332: Thehas_cp_ulysses()method exists and is correctly used.Verification confirms that
has_cp_ulysses()is defined intensorrt_llm/mapping.py:241and properly implements the check:return self.cp_size > 1 and self.cp_config.get("cp_type") == CpType.ULYSSES. The code at lines 327-332 correctly calls this method on the mapping object and applies sound ceiling division logic(num_tokens_for_capture + cp_size - 1) // cp_sizeto distribute tokens across CP ranks. No issues found.tensorrt_llm/bench/benchmark/throughput.py (1)
33-33: LGTM! Clean CLI additions for context parallelism.The new
--cpand--cp_typeoptions are well-integrated into the World Configuration group, following the same pattern as--tpand--pp. The defaults are sensible:
cp=1(no context parallelism by default)cp_type='ULYSSES'(matching the PR title)The dynamic generation of choices from
CpTypeenum members ensures consistency with the enum definition.Also applies to: 208-219
tensorrt_llm/bench/benchmark/utils/general.py (1)
18-18: LGTM! Proper integration of context parallelism configuration.The changes correctly extend the mapping configuration to include CP parameters:
cp_sizeis extracted from thecpparametercp_configconditionally includescp_typeonly whencpis truthy, defaulting to an empty dict otherwiseworld_sizecalculation properly multiplies bycp:pp * tp * cpThe conditional logic for
cp_configis good defensive coding, ensuring it's an empty dict rather than undefined when CP is not enabled.Also applies to: 102-106
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
3164-3185: Verify Ulysses CP integration in_prepare_inputsfor shape consistency and spec decodeThe new flow:
- Treats
CpType.ULYSSESlike HELIX w.r.t._prepare_tp_inputs.- Then, when
mapping.has_cp_ulysses()is true, further rewritesinputsvia_prepare_ulysses_context_parallel_inputs.Two things to double‑check:
Compatibility with speculative decoding
_prepare_tp_inputssets upspec_metadataandgather_ids._forward_stepprefersspec_metadata.gather_idswhen present. Please verify that the Ulysses sharding does not break:
spec_metadata.num_tokensvs the post‑CPinputs["input_ids"]length on each rank;- Any assumptions in the attention backend about
attn_metadata.num_tokensvs the actual Q/K/V token dimension after the Ulysses pre/post steps.Non‑CP and other CP types
The refactor correctly:
- routes STAR to
_prepare_star_attention_inputs,- routes HELIX/ULYSSES through
_prepare_tp_inputs,- and only applies Ulysses‑specific slicing when
has_cp_ulysses()is true.Given the complexity of these paths, I’d suggest running/expanding tests that cover:
- CP‑ULYSSES + TP + CUDA graphs,
- CP‑ULYSSES + spec decode (if supported),
- Plain TP and CP‑HELIX/STAR to confirm no regression.
| # ulysses context preprocess: convert CP to TP | ||
| if attn_metadata.mapping.has_cp_ulysses(): | ||
| q, k, v = self.ulysses_context_preprocess(q, k, v, attn_metadata, | ||
| position_ids.shape[1]) | ||
|
|
There was a problem hiding this comment.
Guard Ulysses preprocess against incompatible configurations (gated attention, missing position_ids)
The unconditional call:
if attn_metadata.mapping.has_cp_ulysses():
q, k, v = self.ulysses_context_preprocess(q, k, v, attn_metadata,
position_ids.shape[1])assumes:
position_idsis notNone, and- the configuration uses the fused‑QKV path (no
attn_output_gate), as the helper assertsk is None and v is None.
To make this safer and clearer:
- Early‑return or raise a more descriptive error if
position_ids is Nonebut CP‑Ulysses is requested. - Either:
- explicitly guard on
not self.attn_output_gateand document that CP‑Ulysses currently doesn’t support attention gating, or - extend the helper to handle the split q/gate + k/v case.
- explicitly guard on
This will avoid surprising assertion failures tied to configuration combinations.
🤖 Prompt for AI Agents
In tensorrt_llm/_torch/modules/attention.py around lines 656 to 660, the call to
ulysses_context_preprocess assumes position_ids is present and that QKV are
fused (no attn_output_gate); add explicit guards: if
attn_metadata.mapping.has_cp_ulysses() then first check position_ids is not None
and raise a clear ValueError if it is None, and also check that
self.attn_output_gate is False and raise a NotImplementedError (or return/skip)
with a message that CP‑Ulysses does not support gated attention; alternatively,
if you prefer to support gated attention now, update ulysses_context_preprocess
to accept split q and gate (q,g,k,v) and handle k/v being None — but at minimum
add the two explicit checks and descriptive errors to prevent the current
assertion failure.
|
/bot run |
|
PR_Github #30485 [ run ] triggered by Bot. Commit: |
|
PR_Github #30485 [ run ] completed with state
|
|
/bot run |
c220e7c to
91fab5d
Compare
|
/bot run |
|
PR_Github #30590 [ run ] triggered by Bot. Commit: |
|
PR_Github #30590 [ run ] completed with state
|
|
Hi @DylanChen-NV, this MR swaps TP and CP order of grouping: #10350. I think it'll be a good idea for you to rebase to |
91fab5d to
e897ee5
Compare
|
/bot run |
|
@DylanChen-NV does this only work with MPI? I get the following error when I try to use
|
|
/bot run |
|
PR_Github #36670 [ run ] triggered by Bot. Commit: |
Hi @NVShreyas , I'm using MPI and haven't met this error. How do you use the |
I use |
|
|
PR_Github #36670 [ run ] completed with state
|
|
/bot run |
|
PR_Github #36781 [ run ] triggered by Bot. Commit: |
|
PR_Github #36781 [ run ] completed with state
|
|
/bot run |
|
PR_Github #36861 [ run ] triggered by Bot. Commit: |
|
PR_Github #36861 [ run ] completed with state
|
577de82 to
5d26bd0
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #36927 [ run ] triggered by Bot. Commit: |
|
PR_Github #36927 [ run ] completed with state
|
|
/bot run --reuse-test |
|
PR_Github #37019 [ run ] triggered by Bot. Commit: |
|
PR_Github #37019 [ run ] completed with state
|
|
/bot run --reuse-test --debug |
Signed-off-by: Dylan Chen <191843203+DylanChen-NV@users.noreply.github.com>
5d26bd0 to
2745f88
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #37307 [ run ] triggered by Bot. Commit: |
|
PR_Github #37307 [ run ] completed with state
|
|
/bot run --disable-fail-fast |
|
PR_Github #37320 [ run ] triggered by Bot. Commit: |
|
PR_Github #37320 [ run ] completed with state
|
|
Maybe we can have test coverage for CP on Qwen (as you described in the MR description) and GPT-OSS into the CI as well? |
Summary by CodeRabbit
Release Notes
--cpand--cp_typecommand-line options for context parallelism configuration in serving and benchmarking tools✏️ Tip: You can customize this high-level summary in your review settings.
Description
Ulysses CP reduces communication volume compared to TP while requiring no modification to the attention operation, by keeping TP in attention and applying CP to other parts of the model. Since Ulysses does not split weights, it requires higher memory consumption. Moreover, the overhead from CP–TP layout conversion means that the benefits only appear when handling long input sequences.
Therefore, Ulysses CP is recommended for use in the prefill stage of long-context inputs with PD disaggregation.
In the tests:
This PR:
Test Coverage
tests/unittest/llmapi/test_llm_multi_gpu.py::test_llm_cp2
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.