Skip to content

Conversation

@brb-nv
Copy link
Collaborator

@brb-nv brb-nv commented Dec 5, 2025

Description

Background:

  • Helix parallelism is a form of context parallelism used in disaggregated setting where only gen servers would have helix.
  • This involves sharding the request's seqlen across multiple CP (context parallel) ranks.
  • In each forward iteration of a given request, KV cache is appended for the incoming token only on one of the CP ranks (called active rank for that request).
  • Previously, last rank (cpSize - 1) was considered the active rank for all requests. So, KV cache only keeps growing there in decode phase.
  • This MR lifts that limitation and distributes KV cache for decode tokens (or blocks rather) in a round-robin fashion. This makes sure KV cache grows equally on all CP ranks.

Example:
ISL=400, token_per_block=100, cpSize=4, token range notation is left-inclusive.

Before:
Iteration 1: <0-100> (Rank 0), <100-200> (Rank 1), <200-300> (Rank 2), <300-400> (Rank 3)
Iteration 400: <0-100> (Rank 0), <100-200> (Rank 1), <200-300> (Rank 2), <300-800> (Rank 3)
KV cache is only growing on rank3 during decode. ranks 0,1,2 will have exactly what they received from prefill-decode transmission.

After:
Iteration 1: <0-100> (Rank 0), <100-200> (Rank 1), <200-300> (Rank 2), <300-400> (Rank 3)
Iteration 400: <0-100, 400-500> (Rank 0), <100-200, 500-600> (Rank 1), <200-300, 600-700> (Rank 2), <300-400, 700-800> (Rank 3)
First decode block goes to rank0, second decode block goes to rank1, third decode block goes to rank2, fourth decode block goes to rank3. And then the cycle repeats.

Thanks to @Tabrizian for discussing the example with me.

Test Coverage

Existing test:

$ pytest tests/integration/defs/accuracy/test_disaggregated_serving.py::TestDeepSeekV3Lite::test_auto_dtype_with_helix -s -v

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.

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.

Summary by CodeRabbit

  • Chores
    • Optimized token sequence management in distributed inference scenarios by enhancing per-rank tracking and coordination
    • Improved compute block distribution across processing ranks for more efficient resource utilization

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

@brb-nv brb-nv force-pushed the user/brb/load-balance-helix-decode-tokens branch 2 times, most recently from 4839014 to 6b60df1 Compare December 5, 2025 21:55
@brb-nv brb-nv marked this pull request as ready for review December 5, 2025 21:55
@brb-nv brb-nv requested review from a team as code owners December 5, 2025 21:55
Copy link
Collaborator

@thorjohnsen thorjohnsen left a comment

Choose a reason for hiding this comment

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

LGTM

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 5, 2025

📝 Walkthrough

Walkthrough

The changes enhance CP Helix generation by adding per-rank sequence length tracking, refining past token count computation based on rank status, and implementing round-robin decode block distribution across CP ranks to control which ranks process tokens during generation.

Changes

Cohort / File(s) Summary
CP Helix Generation Enhancement
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py, tensorrt_llm/_torch/pyexecutor/model_engine.py, tensorrt_llm/_torch/pyexecutor/resource_manager.py
Added per-rank sequence length metadata (seqlen_this_rank_cp). Refined past token count computation in _prepare_tp_inputs to distinguish inactive vs active ranks using py_helix_is_inactive_rank flag. Introduced round-robin decode block distribution across CP ranks with dynamic rank activation/deactivation logic and refined KV cache allocation handling.

Sequence Diagram

sequenceDiagram
    participant ReqQueue as Request Queue
    participant ResMgr as Resource Manager
    participant ModelEngine as Model Engine
    
    ReqQueue->>ReqQueue: Set req.seqlen_this_rank_cp = len(input_ids_this_rank)
    
    ResMgr->>ResMgr: Compute decode_block_id from generation iteration
    
    rect rgb(200, 220, 255)
        Note over ResMgr: Round-robin activation logic
        alt decode_block_id % cp_size == cp_rank
            ResMgr->>ResMgr: req.py_helix_is_inactive_rank = False
            ResMgr->>ResMgr: Increment seqlen_this_rank_cp
        else
            ResMgr->>ResMgr: req.py_helix_is_inactive_rank = True
            ResMgr->>ResMgr: Skip KV cache allocation
        end
    end
    
    ModelEngine->>ModelEngine: Check py_helix_is_inactive_rank
    
    rect rgb(220, 240, 220)
        Note over ModelEngine: Past token computation
        alt Rank is inactive
            ModelEngine->>ModelEngine: past_seen_token_num = seqlen_this_rank_cp
        else
            ModelEngine->>ModelEngine: past_seen_token_num = seqlen_this_rank_cp - 1
        end
    end
    
    ModelEngine->>ModelEngine: Compute position_id and token lengths
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • resource_manager.py: Round-robin distribution logic with rank activation/deactivation and conditional KV cache allocation—requires careful verification of modulo arithmetic and control flow.
  • model_engine.py: Past token count computation tied to rank status; ensure consistency between inactive/active rank logic and its impact on position IDs.
  • executor_request_queue.py: Verify integration point where seqlen_this_rank_cp is initially populated and consistent with downstream rank-based computations.
  • Cross-component dependencies: Trace how py_helix_is_inactive_rank and seqlen_this_rank_cp flow across all three components to ensure correctness.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% 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 concisely summarizes the main change: load balancing decode token KV cache distribution across CP ranks using helix parallelism, which aligns with the changeset modifications.
Description check ✅ Passed PR description clearly explains the background, problem, solution, and provides concrete examples with before/after scenarios.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1)

687-701: Ensure seqlen_this_rank_cp is correctly set for all Helix LlmRequest instances (including beams).

Initializing req.seqlen_this_rank_cp = len(input_ids_this_rank) at prefill is correct and matches its later use as “tokens with KV on this CP rank.” Please double‑check that:

  • Any req.child_requests created by executor_request_to_llm_request for beam search also get a valid seqlen_this_rank_cp (either via the helper or by explicitly copying the parent’s value here), and
  • No Helix generation request reaches model_engine._prepare_tp_inputs / KVCacheManager.prepare_resources without this field set.

Otherwise, beam children or special paths could see an AttributeError or inconsistent per‑rank KV lengths at decode.

If needed, one simple defensive option is:

            req.total_input_len_cp = input_len
-            req.seqlen_this_rank_cp = len(input_ids_this_rank)
+            req.seqlen_this_rank_cp = len(input_ids_this_rank)
+            if req.child_requests:
+                for child in req.child_requests:
+                    setattr(child, "seqlen_this_rank_cp",
+                            getattr(child, "seqlen_this_rank_cp",
+                                    req.seqlen_this_rank_cp))
📜 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 31ab367 and 6b60df1.

📒 Files selected for processing (3)
  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1 hunks)
  • tensorrt_llm/_torch/pyexecutor/model_engine.py (1 hunks)
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: The 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 (e.g., use from package.subpackage import foo and then foo.SomeClass() instead of from package.subpackage.foo import SomeClass)
Python filenames should use snake_case (e.g., some_file.py)
Python class names should use PascalCase (e.g., class SomeClass)
Python function and method names should use snake_case (e.g., def my_awesome_function():)
Python local variable names should use snake_case, with prefix k for variable names that start with a number (e.g., k_99th_percentile = ...)
Python global variables should use upper snake_case with prefix G (e.g., G_MY_GLOBAL = ...)
Python constants should use upper snake_case (e.g., 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 for Python classes and functions, which can be parsed by Sphinx
Python attributes and variables can be documented inline with type and description (e.g., self.x = 5 followed by """<type>: Description of 'x'""" )
Avoid using reflection in Python when functionality can be easily achieved without reflection
When using try-except blocks in Python, limit the except clause to the smallest set of specific errors possible instead of catching all exceptions
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 and use the else block to implement the logic

Files:

  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
**/*.{cpp,h,cu,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

All TensorRT-LLM Open Source Software code files should contain an NVIDIA copyright header that includes the current year at the top

Files:

  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
🧠 Learnings (14)
📓 Common learnings
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.
Learnt from: nv-lschneider
Repo: NVIDIA/TensorRT-LLM PR: 7910
File: cpp/tensorrt_llm/kernels/nccl_device/config.cu:42-49
Timestamp: 2025-09-23T14:58:05.372Z
Learning: In TensorRT-LLM NCCL device kernels (cpp/tensorrt_llm/kernels/nccl_device/), the token partitioning intentionally uses ceil-like distribution (same token_per_rank for all ranks) to ensure all ranks launch the same number of blocks. This is required for optimal NCCL device API barrier performance, even though it may launch extra blocks for non-existent tokens on later ranks. Runtime bounds checking in the kernel (blockID validation) handles the overshoot cases.
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.
📚 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/model_engine.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
📚 Learning: 2025-09-23T14:58:05.372Z
Learnt from: nv-lschneider
Repo: NVIDIA/TensorRT-LLM PR: 7910
File: cpp/tensorrt_llm/kernels/nccl_device/config.cu:42-49
Timestamp: 2025-09-23T14:58:05.372Z
Learning: In TensorRT-LLM NCCL device kernels (cpp/tensorrt_llm/kernels/nccl_device/), the token partitioning intentionally uses ceil-like distribution (same token_per_rank for all ranks) to ensure all ranks launch the same number of blocks. This is required for optimal NCCL device API barrier performance, even though it may launch extra blocks for non-existent tokens on later ranks. Runtime bounds checking in the kernel (blockID validation) handles the overshoot cases.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
📚 Learning: 2025-08-26T06:07:02.166Z
Learnt from: shaharmor98
Repo: NVIDIA/TensorRT-LLM PR: 7231
File: tensorrt_llm/_torch/pyexecutor/_util.py:504-509
Timestamp: 2025-08-26T06:07:02.166Z
Learning: In tensorrt_llm/_torch/pyexecutor/_util.py, when calling model_engine.set_lora_model_config(), pass model_binding_config.mlp_hidden_size directly without multiplying by mapping.tp_size, as the mlp_hidden_size from get_bindings_model_config() is already the per-TP rank value needed for LoRA weight packaging.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py
📚 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/model_engine.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.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/model_engine.py
📚 Learning: 2025-08-19T12:45:35.429Z
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 7033
File: tensorrt_llm/_torch/pyexecutor/model_engine.py:2086-2092
Timestamp: 2025-08-19T12:45:35.429Z
Learning: DoRA (Delta Orthogonal Rank Adaptation) functionality has been removed from the PyTorch flow in tensorrt_llm/_torch/pyexecutor/model_engine.py. The is_dora field is computed but not used downstream in the PyTorch flow, so converting it to a tensor would be wasteful overhead.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/model_engine.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/model_engine.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/model_engine.py
📚 Learning: 2025-08-18T08:42:02.640Z
Learnt from: samuellees
Repo: NVIDIA/TensorRT-LLM PR: 6974
File: tensorrt_llm/serve/scripts/benchmark_dataset.py:558-566
Timestamp: 2025-08-18T08:42:02.640Z
Learning: In TensorRT-LLM's RandomDataset (tensorrt_llm/serve/scripts/benchmark_dataset.py), when using --random-token-ids option, sequence length accuracy is prioritized over semantic correctness for benchmarking purposes. The encode/decode operations should use skip_special_tokens=True and add_special_tokens=False to ensure exact target token lengths.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/model_engine.py
📚 Learning: 2025-08-20T06:56:02.889Z
Learnt from: eopXD
Repo: NVIDIA/TensorRT-LLM PR: 6768
File: cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp:577-579
Timestamp: 2025-08-20T06:56:02.889Z
Learning: In cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp, maxSequenceLength is now enforced as a non-optional argument in the BlockManager constructor, so concerns about std::nullopt defaulting to 0 are not applicable. When windowSize > maxSequenceLength, a warning should be added instead of handling optional parameter cases.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.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-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-08-20T06:48:45.368Z
Learnt from: eopXD
Repo: NVIDIA/TensorRT-LLM PR: 6768
File: cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h:0-0
Timestamp: 2025-08-20T06:48:45.368Z
Learning: In cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp, updateSequenceCacheBlockOffsets is only called when adding a sequence, not during detach operations. During detach, the cache block bookkeeping is handled by GenerationRequest::removeFrontBlock.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
🧬 Code graph analysis (1)
tensorrt_llm/_torch/pyexecutor/resource_manager.py (5)
tensorrt_llm/_torch/attention_backend/trtllm.py (1)
  • tokens_per_block (674-678)
tensorrt_llm/runtime/generation.py (1)
  • tokens_per_block (1218-1219)
tensorrt_llm/_torch/distributed/communicator.py (2)
  • cp_size (56-57)
  • cp_rank (68-69)
tensorrt_llm/mapping.py (1)
  • cp_rank (560-561)
tensorrt_llm/_torch/device_mesh.py (1)
  • cp_rank (84-86)
⏰ 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 (2)
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)

1668-1688: Guard Helix-only fields to avoid potential AttributeError on dummy/warmup requests.

The new Helix logic unconditionally accesses request.py_helix_is_inactive_rank and request.seqlen_this_rank_cp within the if self.mapping.has_cp_helix() block, which may not hold these attributes for:

  • Dummy requests created via KVCacheManager.add_dummy_requests (if used during warmup)
  • Any path using Helix mapping without initializing these fields through _merge_helix_requests

While position_id computation is guarded by the if not self.is_warmup and not request.is_cuda_graph_dummy check, the subsequent attribute accesses are not. Use defensive defaults to gracefully handle missing attributes:

                if self.mapping.has_cp_helix():
                    if not self.is_warmup and not request.is_cuda_graph_dummy:
                        position_id = request.total_input_len_cp + request.py_decoding_iter - 1
-                    if request.py_helix_is_inactive_rank:
-                        past_seen_token_num = request.seqlen_this_rank_cp
-                    else:
-                        # Discount the token added to active rank in resource manager as it hasn't
-                        # been previously seen.
-                        past_seen_token_num = request.seqlen_this_rank_cp - 1
+                    helix_inactive = getattr(request, "py_helix_is_inactive_rank", False)
+                    seqlen_this_rank_cp = getattr(request, "seqlen_this_rank_cp",
+                                                  past_seen_token_num)
+                    if helix_inactive:
+                        past_seen_token_num = seqlen_this_rank_cp
+                    else:
+                        # Discount the token added to active rank in resource manager as it hasn't
+                        # been previously seen.
+                        past_seen_token_num = max(seqlen_this_rank_cp - 1, 0)
tensorrt_llm/_torch/pyexecutor/resource_manager.py (1)

470-485: Helix decode round-robin implementation is sound, but defensive initialization of seqlen_this_rank_cp is needed.

The new code correctly distributes decode blocks across CP ranks in round-robin fashion and properly skips KV allocation on inactive ranks. However, req.seqlen_this_rank_cp += 1 will raise AttributeError if the attribute is not initialized on all request objects—particularly for dummy/warmup requests created by add_dummy_requests or any requests bypassing _merge_helix_requests.

Add defensive initialization:

if decode_block_id % self.mapping.cp_size == self.mapping.cp_rank:
    req.py_helix_is_inactive_rank = False
    # Initialize per-rank seqlen if not already set (e.g., for dummy/warmup).
    if not hasattr(req, "seqlen_this_rank_cp"):
        base = getattr(req, "cached_tokens", getattr(req, "py_prompt_len", 0))
        req.seqlen_this_rank_cp = base
    req.seqlen_this_rank_cp += 1

Also verify that self.tokens_per_block aligns with the Helix cp_config['tokens_per_block'] used during context partitioning; divergence would cause round-robin ownership to misalign with actual sharding.

@brb-nv
Copy link
Collaborator Author

brb-nv commented Dec 5, 2025

/bot run

@brb-nv
Copy link
Collaborator Author

brb-nv commented Dec 5, 2025

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #27159 [ run ] triggered by Bot. Commit: 6b60df1

@tensorrt-cicd
Copy link
Collaborator

PR_Github #27160 [ run ] triggered by Bot. Commit: 6b60df1

@tensorrt-cicd
Copy link
Collaborator

PR_Github #27159 [ run ] completed with state ABORTED. Commit: 6b60df1

@brb-nv brb-nv removed request for Tabrizian and ixlmar December 5, 2025 22:52
@brb-nv brb-nv enabled auto-merge (squash) December 5, 2025 22:52
@tensorrt-cicd
Copy link
Collaborator

PR_Github #27160 [ run ] completed with state SUCCESS. Commit: 6b60df1
/LLM/main/L0_MergeRequest_PR pipeline #20724 completed with status: 'FAILURE'

@brb-nv brb-nv force-pushed the user/brb/load-balance-helix-decode-tokens branch from 6b60df1 to aa61480 Compare December 9, 2025 21:12
…rallelism

Signed-off-by: Balaram Buddharaju <169953907+brb-nv@users.noreply.github.com>
@brb-nv brb-nv force-pushed the user/brb/load-balance-helix-decode-tokens branch from 268fe67 to 15a0c2b Compare December 9, 2025 21:36
@brb-nv
Copy link
Collaborator Author

brb-nv commented Dec 9, 2025

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #27553 [ run ] triggered by Bot. Commit: 15a0c2b

@tensorrt-cicd
Copy link
Collaborator

PR_Github #27553 [ run ] completed with state FAILURE. Commit: 15a0c2b

@brb-nv
Copy link
Collaborator Author

brb-nv commented Dec 9, 2025

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #27564 [ run ] triggered by Bot. Commit: 15a0c2b

@tensorrt-cicd
Copy link
Collaborator

PR_Github #27564 [ run ] completed with state SUCCESS. Commit: 15a0c2b
/LLM/main/L0_MergeRequest_PR pipeline #21035 completed with status: 'FAILURE'

@brb-nv
Copy link
Collaborator Author

brb-nv commented Dec 10, 2025

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #27626 [ run ] triggered by Bot. Commit: 15a0c2b

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.

4 participants