Skip to content

[None][feat] Support Ulysses CP for torch flow - #10276

Open
DylanChen-NV wants to merge 1 commit into
NVIDIA:mainfrom
DylanChen-NV:feature/torch_flow_ulysses
Open

[None][feat] Support Ulysses CP for torch flow#10276
DylanChen-NV wants to merge 1 commit into
NVIDIA:mainfrom
DylanChen-NV:feature/torch_flow_ulysses

Conversation

@DylanChen-NV

@DylanChen-NV DylanChen-NV commented Dec 24, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

Release Notes

  • New Features
    • Added context parallelism (ULYSSES type) support for distributed model execution
    • New --cp and --cp_type command-line options for context parallelism configuration in serving and benchmarking tools
    • Context parallelism parameters added to LLM initialization and configuration

✏️ 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:

  1. Qwen3-32B + L20 + ISL=6k + BS=1, compared with TP4, CP2TP2 speedup 50% while CP4 speedup 100%
  2. Qwen3-32B + H800 + ISL=10k + BS=1, compared with TP2, CP2 speedup 13%

This PR:

  1. Support Ulysses CP, and make it compatible with cuda graph, TP, trtllm-serve, trtllm-bench and disagg
  2. Add doc and UT

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

@DylanChen-NV

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #29814 [ run ] triggered by Bot. Commit: 7d2a66e

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #29814 [ run ] completed with state FAILURE. Commit: 7d2a66e

@coderabbitai

coderabbitai Bot commented Dec 24, 2025

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This 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

Cohort / File(s) Summary
CLI and Configuration
tensorrt_llm/bench/benchmark/throughput.py, tensorrt_llm/commands/serve.py, tensorrt_llm/bench/benchmark/utils/general.py
Added --cp and --cp_type CLI options; updated get_settings and get_llm_args to construct cp_config with CpType mapping and compute world_size as pp * tp * cp
LLM API and Quickstart
examples/llm-api/quickstart_advanced.py
Added cp_size CLI argument and CP configuration; passed context_parallel_size and cp_config to LLM initialization
Attention Module
tensorrt_llm/_torch/modules/attention.py
Added ulysses_context_preprocess and ulysses_context_postprocess public methods for Attention and MLA classes; modified Attention.__init__ to fold cp_size into tp_size when has_cp_ulysses() is true; integrated preprocessing/postprocessing into forward pass
Model Engine and Input Preparation
tensorrt_llm/_torch/pyexecutor/model_engine.py
Added _prepare_ulysses_context_parallel_inputs method; updated warmup logic to skip CP warmup; refactored CP type comparisons; integrated CP input preparation in _prepare_inputs
Executor and Request Handling
tensorrt_llm/_torch/pyexecutor/py_executor.py, tensorrt_llm/_torch/pyexecutor/executor_request_queue.py, tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
Changed CpType.ULYSSES handling from error to supported path; added CP-aware input adjustments in cuda graph capture/replay; adjusted num_tokens_for_capture and seqlen computation
Resource and Cache Management
tensorrt_llm/_torch/pyexecutor/_util.py, tensorrt_llm/_torch/pyexecutor/resource_manager.py
Added deep copy and mapping modification for KV cache transceiver when has_cp_ulysses() is true; updated tp_size multiplication by cp_size in KVCacheManager.__init__
Speculative Decoding
tensorrt_llm/_torch/models/modeling_speculative.py
Added cp_allgather import and conditional gather on hidden_states when has_cp_ulysses() is true
Benchmarking and Reporting
tensorrt_llm/bench/build/tuning.py, tensorrt_llm/bench/dataclasses/configuration.py, tensorrt_llm/bench/dataclasses/reporting.py
Added cp_size parameter to calc_engine_setting and updated GPU count calculation; added context_parallel_size and cp_config to LLM args; added CP size to statistics reporting

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.31% 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
Title check ✅ Passed The title clearly and specifically describes the main change: adding Ulysses CP (Context Parallelism) support for the torch flow implementation.
Description check ✅ Passed PR description includes structured content covering the technical rationale for Ulysses CP, performance benchmarks, implementation scope, and test coverage, with the PR checklist completed.
✨ 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 in tensorrt_llm/bench/build/build.py to include the cp_size parameter.

The function signature change at lines 21-30 adds a required cp_size: int parameter, and line 71 correctly multiplies GPU count as n_gpus = tp_size * pp_size * cp_size. However, the caller in build.py (lines 56-61) does not pass the cp_size argument, causing positional argument misalignment. The target_input_len and subsequent arguments are shifted by one position.

Update the call to include cp_size between pp_size and target_input_len.

tensorrt_llm/_torch/modules/attention.py (2)

230-239: Clarify Ulysses CP invariants and tp/head divisibility

The 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 == 0

tightens invariants for CP‑Ulysses by requiring both num_heads and num_key_value_heads to be divisible by tp_size * cp_size. That’s reasonable, but:

  • It’s stricter than the existing MQA path (which allowed non‑divisible num_key_value_heads and 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 access

The 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 (UlysseesUlysses).
  • Accessing self.mapping.cp_config['cp_type'] in the assert message can raise KeyError if cp_type is 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 readers

Using tp_size *= mapping.cp_size when has_cp_ulysses() is true correctly treats CP as an extra sharding dimension for KV heads, reducing per‑token KV bytes and increasing max_tokens accordingly 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 clarity

By turning the ULYSSES branch into a pass, _merge_requests effectively falls back to the generic executor_request_to_llm_request handling 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 UX

The example’s CP plumbing is coherent: a --cp_size flag, a minimal cp_config = {"cp_type": CpType.ULYSSES} when cp_size > 1, and forwarding both context_parallel_size and cp_config into LLM(...). For a quickstart this is enough to exercise Ulysses CP; if you want to harden it further, consider validating that cp_size > 1 only when the environment and chosen attention_backend actually 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 rationale

The new guard skips warmup whenever cp_size > 1 and has_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 into o_proj

The 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_postprocess uses alltoall_helix and reshapes, please verify that:

  • attn_output.shape[0] still equals attn_metadata.num_tokens, and
  • attn_output.shape[1] still equals self.o_proj.in_features.

If they differ (e.g., feature dim scaled by cp_size), this will misalign with the TP layout expected by Linear. Adding explicit asserts in ulysses_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

📥 Commits

Reviewing files that changed from the base of the PR and between 69152c4 and 7d2a66e.

📒 Files selected for processing (15)
  • examples/llm-api/quickstart_advanced.py
  • tensorrt_llm/_torch/models/modeling_speculative.py
  • tensorrt_llm/_torch/modules/attention.py
  • tensorrt_llm/_torch/pyexecutor/_util.py
  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
  • tensorrt_llm/bench/benchmark/throughput.py
  • tensorrt_llm/bench/benchmark/utils/general.py
  • tensorrt_llm/bench/build/tuning.py
  • tensorrt_llm/bench/dataclasses/configuration.py
  • tensorrt_llm/bench/dataclasses/reporting.py
  • tensorrt_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.py
  • tensorrt_llm/bench/dataclasses/reporting.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/bench/benchmark/throughput.py
  • tensorrt_llm/_torch/pyexecutor/_util.py
  • tensorrt_llm/bench/benchmark/utils/general.py
  • tensorrt_llm/bench/dataclasses/configuration.py
  • examples/llm-api/quickstart_advanced.py
  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py
  • tensorrt_llm/_torch/modules/attention.py
  • tensorrt_llm/commands/serve.py
  • tensorrt_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.py
  • tensorrt_llm/bench/dataclasses/reporting.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/bench/benchmark/throughput.py
  • tensorrt_llm/_torch/pyexecutor/_util.py
  • tensorrt_llm/bench/benchmark/utils/general.py
  • tensorrt_llm/bench/dataclasses/configuration.py
  • examples/llm-api/quickstart_advanced.py
  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py
  • tensorrt_llm/_torch/modules/attention.py
  • tensorrt_llm/commands/serve.py
  • tensorrt_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.py
  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
  • tensorrt_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.py
  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
  • tensorrt_llm/_torch/modules/attention.py
  • tensorrt_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.py
  • tensorrt_llm/_torch/modules/attention.py
  • tensorrt_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.py
  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/_torch/pyexecutor/_util.py
  • tensorrt_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.py
  • tensorrt_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.py
  • tensorrt_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.py
  • tensorrt_llm/bench/dataclasses/configuration.py
  • examples/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.py
  • examples/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.py
  • tensorrt_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 consistent

Adding cp_size into both the structured world_info dict and the human‑readable WORLD + RUNTIME section keeps bench output aligned with the new CP configuration, assuming RuntimeConfig.mapping always provides a cp_size entry (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 CP

The 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_tokens is conceptually right: we want full hidden states across CP ranks before feeding the draft path or logits. This assumes:

  • attn_metadata.mapping is a Mapping (or equivalent) exposing has_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‑rank hidden_states with 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_tokens to avoid subtle CP shape bugs.

Also applies to: 827-830

tensorrt_llm/bench/dataclasses/configuration.py (1)

40-58: LLM args CP wiring looks correct

Adding "context_parallel_size": self.mapping["cp_size"] and "cp_config": self.mapping["cp_config"] into get_llm_args cleanly forwards CP settings into the LLM API alongside existing TP/PP/MoE knobs. This assumes all bench mappings populate cp_size and cp_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 reasonable

The mapping_for_kv_cache_transceiver indirection with a deepcopy and tp_size *= cp_size; cp_size = 1 cleanly scopes the “CP folded into TP” view to the KV cache transceiver without mutating the main mapping used 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 if Mapping ever gains non‑trivial, non‑copyable state, deepcopy might 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 seqlen from position_ids.shape[-1] instead of input_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: The has_cp_ulysses() method exists and is correctly used.

Verification confirms that has_cp_ulysses() is defined in tensorrt_llm/mapping.py:241 and 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_size to 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 --cp and --cp_type options are well-integrated into the World Configuration group, following the same pattern as --tp and --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 CpType enum 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_size is extracted from the cp parameter
  • cp_config conditionally includes cp_type only when cp is truthy, defaulting to an empty dict otherwise
  • world_size calculation properly multiplies by cp: pp * tp * cp

The conditional logic for cp_config is 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_inputs for shape consistency and spec decode

The new flow:

  • Treats CpType.ULYSSES like HELIX w.r.t. _prepare_tp_inputs.
  • Then, when mapping.has_cp_ulysses() is true, further rewrites inputs via _prepare_ulysses_context_parallel_inputs.

Two things to double‑check:

  1. Compatibility with speculative decoding
    _prepare_tp_inputs sets up spec_metadata and gather_ids. _forward_step prefers spec_metadata.gather_ids when present. Please verify that the Ulysses sharding does not break:

    • spec_metadata.num_tokens vs the post‑CP inputs["input_ids"] length on each rank;
    • Any assumptions in the attention backend about attn_metadata.num_tokens vs the actual Q/K/V token dimension after the Ulysses pre/post steps.
  2. 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.

Comment thread tensorrt_llm/_torch/modules/attention.py
Comment on lines +656 to +660
# 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])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

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_ids is not None, and
  • the configuration uses the fused‑QKV path (no attn_output_gate), as the helper asserts k is None and v is None.

To make this safer and clearer:

  • Early‑return or raise a more descriptive error if position_ids is None but CP‑Ulysses is requested.
  • Either:
    • explicitly guard on not self.attn_output_gate and document that CP‑Ulysses currently doesn’t support attention gating, or
    • extend the helper to handle the split q/gate + k/v case.

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.

Comment thread tensorrt_llm/_torch/pyexecutor/model_engine.py
Comment thread tensorrt_llm/commands/serve.py Outdated
@juney-nvidia
juney-nvidia requested a review from brb-nv December 30, 2025 23:12
@DylanChen-NV
DylanChen-NV requested a review from a team as a code owner January 4, 2026 07:22
@DylanChen-NV

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #30485 [ run ] triggered by Bot. Commit: 55ab6eb

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #30485 [ run ] completed with state SUCCESS. Commit: 55ab6eb
/LLM/main/L0_MergeRequest_PR pipeline #23507 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

@DylanChen-NV

Copy link
Copy Markdown
Collaborator Author

/bot run

@DylanChen-NV
DylanChen-NV force-pushed the feature/torch_flow_ulysses branch from c220e7c to 91fab5d Compare January 5, 2026 10:47
@DylanChen-NV

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #30590 [ run ] triggered by Bot. Commit: 91fab5d

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #30590 [ run ] completed with state FAILURE. Commit: 91fab5d
/LLM/main/L0_MergeRequest_PR pipeline #23600 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

@brb-nv

brb-nv commented Jan 5, 2026

Copy link
Copy Markdown
Collaborator

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 main to make sure there are no surprises.

@DylanChen-NV
DylanChen-NV force-pushed the feature/torch_flow_ulysses branch from 91fab5d to e897ee5 Compare January 14, 2026 16:56
@DylanChen-NV

Copy link
Copy Markdown
Collaborator Author

/bot run

@NVShreyas

NVShreyas commented Feb 24, 2026

Copy link
Copy Markdown
Collaborator

@DylanChen-NV does this only work with MPI? I get the following error when I try to use AllToAllHelixOp

MPI is disabled, DON'T USE MPI

@DylanChen-NV

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #36670 [ run ] triggered by Bot. Commit: 854c256 Link to invocation

@DylanChen-NV

DylanChen-NV commented Feb 24, 2026

Copy link
Copy Markdown
Collaborator Author

@DylanChen-NV does this only work with MPI? I get the following error when I try to use AllToAllHelixOp

MPI is disabled, DON'T USE MPI

Hi @NVShreyas , I'm using MPI and haven't met this error. How do you use the AllToAllHelixOp ?

@NVShreyas

Copy link
Copy Markdown
Collaborator

@DylanChen-NV does this only work with MPI? I get the following error when I try to use AllToAllHelixOp

MPI is disabled, DON'T USE MPI

Hi @NVShreyas , I'm using MPI and haven't met this error. How do you use the AllToAllHelixOp ?

I use TLLM_DISABLE_MPI=1 which uses torch distributed backend. This is needed for visual_gen but I thought the _torch backend was deprecating MPI (I could be wrong here)?

@DylanChen-NV

Copy link
Copy Markdown
Collaborator Author

@DylanChen-NV does this only work with MPI? I get the following error when I try to use AllToAllHelixOp

MPI is disabled, DON'T USE MPI

Hi @NVShreyas , I'm using MPI and haven't met this error. How do you use the AllToAllHelixOp ?

I use TLLM_DISABLE_MPI=1 which uses torch distributed backend. This is needed for visual_gen but I thought the _torch backend was deprecating MPI (I could be wrong here)?

mpiUilts.h is included in cpp/tensorrt_llm/thop/alltoallOp.cpp, so it depends on MPI. I think the meaning of the error is that do not use something depends on MPI when TLLM_DISABLE_MPI=1 is set.
Maybe you could try simply commenting out mpiUtils or remove other MPI-related part if necessary.

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #36670 [ run ] completed with state SUCCESS. Commit: 854c256
/LLM/main/L0_MergeRequest_PR pipeline #28390 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

Link to invocation

@DylanChen-NV

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #36781 [ run ] triggered by Bot. Commit: 6c6db18 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #36781 [ run ] completed with state SUCCESS. Commit: 6c6db18
/LLM/main/L0_MergeRequest_PR pipeline #28484 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

Link to invocation

@DylanChen-NV

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #36861 [ run ] triggered by Bot. Commit: d3d7f41 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #36861 [ run ] completed with state SUCCESS. Commit: d3d7f41
/LLM/main/L0_MergeRequest_PR pipeline #28541 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

Link to invocation

@DylanChen-NV
DylanChen-NV force-pushed the feature/torch_flow_ulysses branch from 577de82 to 5d26bd0 Compare February 26, 2026 12:21
@DylanChen-NV

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #36927 [ run ] triggered by Bot. Commit: 5d26bd0 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #36927 [ run ] completed with state SUCCESS. Commit: 5d26bd0
/LLM/main/L0_MergeRequest_PR pipeline #28590 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

Link to invocation

@DylanChen-NV

Copy link
Copy Markdown
Collaborator Author

/bot run --reuse-test

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #37019 [ run ] triggered by Bot. Commit: 5d26bd0 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #37019 [ run ] completed with state SUCCESS. Commit: 5d26bd0
/LLM/main/L0_MergeRequest_PR pipeline #28663 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

Link to invocation

@DylanChen-NV

Copy link
Copy Markdown
Collaborator Author

/bot run --reuse-test --debug

Signed-off-by: Dylan Chen <191843203+DylanChen-NV@users.noreply.github.com>
@DylanChen-NV
DylanChen-NV force-pushed the feature/torch_flow_ulysses branch from 5d26bd0 to 2745f88 Compare March 2, 2026 08:46
@DylanChen-NV

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #37307 [ run ] triggered by Bot. Commit: 2745f88 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #37307 [ run ] completed with state FAILURE. Commit: 2745f88
/LLM/main/L0_MergeRequest_PR pipeline #28873 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

Link to invocation

@DylanChen-NV

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #37320 [ run ] triggered by Bot. Commit: 2745f88 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #37320 [ run ] completed with state SUCCESS. Commit: 2745f88
/LLM/main/L0_MergeRequest_PR pipeline #28882 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

Link to invocation

@eopXD

eopXD commented Mar 4, 2026

Copy link
Copy Markdown
Collaborator

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?

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.

6 participants