Skip to content

Conversation

@ChristinaZ
Copy link
Collaborator

@ChristinaZ ChristinaZ commented Nov 3, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Added custom CUDA kernel implementation for efficient Top-K indexing operations in sparse attention
    • Introduced use_custom_topk parameter enabling optimized Top-K selection path during attention computation
    • Supports both prefill and decode phases with specialized kernel implementations
  • Tests

    • Added comprehensive test coverage comparing custom kernel implementations against PyTorch fallback paths across multiple scenarios

Description

Add the customized topk kernels and related unit tests for DSA

Test Coverage

pytest -v -s tests/unittest/_torch/thop/parallel/test_indexer_topk.py
pytest -v -s tests/unittest/_torch/attention/sparse/test_dsa_indexer.py

PR Checklist

Please review the following before submitting your PR:

  • PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.

  • PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.

  • Test cases are provided for new code paths (see test instructions)

  • Any new dependencies have been scanned for license and vulnerabilities

  • CODEOWNERS updated if ownership changes

  • Documentation updated as needed

  • The reviewers assigned automatically/manually are appropriate for the PR.

  • Please check this after reviewing the above items as appropriate for this PR.

GitHub Bot Help

/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...

Provide a user friendly way for developers to interact with a Jenkins server.

Run /bot [-h|--help] to print this help message.

See details below for each supported subcommand.

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.

@ChristinaZ ChristinaZ requested a review from a team as a code owner November 3, 2025 12:20
@ChristinaZ ChristinaZ requested review from hlu1 and removed request for hlu1 November 3, 2025 12:20
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 3, 2025

📝 Walkthrough

Walkthrough

This PR introduces a custom CUDA top-K indexer kernel for sparse attention in TensorRT-LLM. It includes kernel implementation, Torch extension bindings, integration into the sparse attention backend with optional fallback, and comprehensive test coverage validating the custom kernel against PyTorch fallback paths across prefill and decode scenarios.

Changes

Cohort / File(s) Summary
CUDA Kernel Implementation
cpp/tensorrt_llm/kernels/IndexerTopK.h, cpp/tensorrt_llm/kernels/indexerTopK.cu
Declares and implements two public top-K indexer kernels: invokeIndexerTopKDecode for decoding with sequence lengths, and invokeIndexerTopKPrefill for prefilling with explicit row ranges. Kernel uses histogram binning, prefix-sum, and radix-sort operations to compute top-K indices per row with fixed width of 2048.
Torch Extension Binding
cpp/tensorrt_llm/thop/IndexerTopKOp.cpp
Exposes two CUDA top-K operations as Torch extensions: indexer_topk_decode_op and indexer_topk_prefill_op, validating input tensors, extracting CUDA stream, and invoking corresponding C++ kernels.
Build Configuration
cpp/tensorrt_llm/thop/CMakeLists.txt
Adds IndexerTopKOp.cpp to the th_common shared library source list.
Python Integration
tensorrt_llm/_torch/attention_backend/sparse/dsa.py
Adds use_custom_topk parameter (default True) to sparse_attn_indexer method, branching to custom CUDA kernels (indexer_topk_prefill_op / indexer_topk_decode_op) during prefill/decode when enabled, with PyTorch fallback as alternative.
Test Suite
tests/unittest/_torch/attention/sparse/test_dsa_indexer.py
Enhanced DSA indexer tests with Jaccard similarity-based comparison metrics replacing exact-match assertions, CPU/CUDA fallback handling for sequence lengths, and new test cases validating custom vs. fallback paths across chunked/single-pass prefill and decode scenarios.
Top-K Kernel Unit Tests
tests/unittest/_torch/thop/parallel/test_indexer_topk.py
New test module with parametrized tests for indexer_topk_decode_op and indexer_topk_prefill_op, including helper functions for logits generation, per-row top-K validation, and cross-validation against PyTorch reference implementations.

Sequence Diagram(s)

sequenceDiagram
    actor Python as Python Code
    participant DSA as sparse_attn_indexer<br/>(dsa.py)
    participant Torch as Torch Op<br/>(IndexerTopKOp.cpp)
    participant CUDA as CUDA Kernel<br/>(indexerTopK.cu)

    Python->>DSA: sparse_attn_indexer(metadata, ..., use_custom_topk=True)
    
    alt use_custom_topk == True
        DSA->>Torch: torch.ops.trtllm.indexer_topk_decode_op<br/>(logits, seq_lens, indices, ...)
        Torch->>CUDA: invokeIndexerTopKDecode(logits, seqLens,<br/>outIndices, numRows, ...)
        CUDA-->>Torch: Top-K indices computed
        Torch-->>DSA: Return
    else use_custom_topk == False
        DSA->>DSA: Use PyTorch topk() fallback
    end
    
    DSA-->>Python: topk_indices_buffer
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

  • CUDA kernel implementation (indexerTopK.cu): Dense algorithmic logic involving histogram binning with custom bin extraction, prefix-sum computation via cub::BlockScan, threshold determination, and final radix-sort. Requires careful validation of edge cases (rows ≤ top-K, bin overflow, shared memory usage).
  • Control flow branching (dsa.py): New conditional path on use_custom_topk affects prefill (chunked and non-chunked) and decode stages; careful attention needed to ensure equivalent behavior between branches.
  • Test integration (test_dsa_indexer.py): Shift from exact-match to Jaccard similarity metrics introduces new validation semantics; verify similarity threshold appropriateness (95%) and low-similarity diagnostics.
  • Cross-layer integration: Torch bindings, C++ kernel invocation, and Python dispatch all depend on correct parameter passing and tensor memory layout.

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Linked Issues check ❓ Inconclusive The pull request title uses '[None]' to indicate no linked JIRA ticket, GitHub issue, or NVBugs ID. While this is valid according to the template, it means there is no external issue or requirement reference to provide context or traceability for this feature. The PR description does not reference any issue or document why these customized kernels are needed. Consider linking a relevant GitHub issue or JIRA ticket if this PR addresses a tracked requirement or performance improvement. If no external issue exists, the PR description could be enhanced by explaining the motivation and benefits of adding these custom kernels (e.g., performance improvements, reduced latency, specific use-case support for DSA).
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The pull request title '[None][feat] Add customized topk and related unit tests for DSA' follows the required template format with [None] for no ticket and [feat] for feature type. It clearly describes the main change: adding customized topk kernels and related unit tests for DSA (Distributed Sparse Attention). The title is specific, concise, and accurately reflects the primary purpose of the changeset.
Description check ✅ Passed The pull request description includes a clear summary of what is being added ('Add the customized topk kernels and related unit tests for DSA'), provides specific test coverage commands for the two main test modules added, and marks the PR checklist as complete. However, it lacks detail on the 'why' aspect—the rationale for why these customized kernels are needed compared to alternatives, and how they improve performance or functionality. Despite this gap, the core required sections are present and the description adequately communicates the main changes.
Out of Scope Changes check ✅ Passed The changeset is focused and well-scoped: it adds new CUDA kernels (IndexerTopK.h/.cu) for top-K indexing, Torch bindings (IndexerTopKOp.cpp), integrates them into the DSA sparse attention backend (dsa.py with a new use_custom_topk parameter), and includes comprehensive unit tests (test_indexer_topk.py and test_dsa_indexer.py updates). CMakeLists.txt was minimally updated to include the new source file. All changes are directly related to the stated objective of adding customized topk kernels and tests for DSA.
✨ 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: 9

📜 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 d717676 and 8f4f53b.

📒 Files selected for processing (7)
  • cpp/tensorrt_llm/kernels/IndexerTopK.h (1 hunks)
  • cpp/tensorrt_llm/kernels/indexerTopK.cu (1 hunks)
  • cpp/tensorrt_llm/thop/CMakeLists.txt (1 hunks)
  • cpp/tensorrt_llm/thop/IndexerTopKOp.cpp (1 hunks)
  • tensorrt_llm/_torch/attention_backend/sparse/dsa.py (4 hunks)
  • tests/unittest/_torch/attention/sparse/test_dsa_indexer.py (3 hunks)
  • tests/unittest/_torch/thop/parallel/test_indexer_topk.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh}: Namespace closing braces must include a trailing comment with the namespace name (e.g., '} // namespace foo').
Prefer const or constexpr variables over #define for constants.
Declare variables that are not modified after initialization as const.
Avoid magic literals in code; except for 0, nullptr, true, false. Use named constants for comparisons and logic.
Use Allman brace style for formatting.
Place the semicolon of an empty for/while loop on a new line.
Bodies of switch/while/do-while/for must be compound statements (brace-delimited), and if/else must always be followed by brace-delimited statements.
Type names (e.g., classes) must be CamelCase starting with an uppercase letter (e.g., FooBar).
Local variables, methods, and namespaces use lowerCamelCase (e.g., localFooBar).
Non-magic-number global variables that are non-static and not in an anonymous namespace must be lowerCamelCase prefixed with 'g' (e.g., gDontUseGlobalFoos).
Non-magic-number globals that are static or in an anonymous namespace use lowerCamelCase prefixed with 's' (e.g., sMutableStaticGlobal).
Locally visible static variables use lowerCamelCase with 's' prefix (e.g., static std::once_flag sFlag).
Private/protected member variables use 'm' prefix with CamelCase (e.g., mNbFooValues). Public members may omit, but 'm' is encouraged for clarity.
Constants (enums, global constants, static constants, and function-scope magic/literal constants) use uppercase SNAKE_CASE with 'k' prefix (e.g., kDIGIT_NUM).
Function-scope constants that are not magic numbers or literals are named like non-constant variables (e.g., bool const pass = a && b).
If macros are necessary, name them in UPPER_SNAKE_CASE (e.g., FOO_VERSION) and prefer constants over #define.
Use LLVM clang-format; wrap lines at a maximum of 120 columns; use '// clang-format off/on' sparingly with justification.
Use smart pointers for heap allocations; prefer unique_ptr for sole ownership, shared_ptr for shared...

Files:

  • cpp/tensorrt_llm/kernels/IndexerTopK.h
  • cpp/tensorrt_llm/kernels/indexerTopK.cu
  • cpp/tensorrt_llm/thop/IndexerTopKOp.cpp
**/*.{cpp,cxx,cc,cu,h,hpp,hh,hxx,cuh}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

C++ filenames should be lowerCamelCase (first letter lowercase) and must be case-insensitive unique within a compilation target.

Files:

  • cpp/tensorrt_llm/kernels/IndexerTopK.h
  • cpp/tensorrt_llm/kernels/indexerTopK.cu
  • cpp/tensorrt_llm/thop/IndexerTopKOp.cpp
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Use only spaces, no tabs; indent with 4 spaces.

Files:

  • cpp/tensorrt_llm/kernels/IndexerTopK.h
  • tensorrt_llm/_torch/attention_backend/sparse/dsa.py
  • tests/unittest/_torch/attention/sparse/test_dsa_indexer.py
  • cpp/tensorrt_llm/kernels/indexerTopK.cu
  • cpp/tensorrt_llm/thop/IndexerTopKOp.cpp
  • tests/unittest/_torch/thop/parallel/test_indexer_topk.py
**/*.{h,hpp,hh,hxx}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Document new class interfaces and function prototypes with Doxygen; use //! for single-line and //!< for members.

Files:

  • cpp/tensorrt_llm/kernels/IndexerTopK.h
**/*.{h,hpp,hh,hxx,cpp,cxx,cc}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.{h,hpp,hh,hxx,cpp,cxx,cc}: Prefer anonymous namespaces over 'static' for internal linkage of functions.
All templates (class/function/member/static) must be instantiated at least once; non-POD classes should have private data members.

Files:

  • cpp/tensorrt_llm/kernels/IndexerTopK.h
  • cpp/tensorrt_llm/thop/IndexerTopKOp.cpp
**/*.{h,hpp,hh,hxx,cuh}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Use include guards named 'TRTLLM_<FILE_NAME_IN_CAPS_WITH_UNDERSCORES>_H' (no leading or trailing underscore; directory names excluded).

Files:

  • cpp/tensorrt_llm/kernels/IndexerTopK.h
**/*.{cpp,cxx,cc,h,hpp,hh,hxx,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Prepend the NVIDIA Apache-2.0 copyright header with current year to the top of all source files (e.g., .cpp, .h, .cu, .py).

Files:

  • cpp/tensorrt_llm/kernels/IndexerTopK.h
  • tensorrt_llm/_torch/attention_backend/sparse/dsa.py
  • tests/unittest/_torch/attention/sparse/test_dsa_indexer.py
  • cpp/tensorrt_llm/kernels/indexerTopK.cu
  • cpp/tensorrt_llm/thop/IndexerTopKOp.cpp
  • tests/unittest/_torch/thop/parallel/test_indexer_topk.py
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+.
Indent Python code with 4 spaces; do not use tabs.
Maintain module namespace when importing; prefer 'from package.subpackage import foo' then 'foo.SomeClass()' instead of importing the class directly.
Python filenames should be snake_case (e.g., some_file.py).
Python classes use PascalCase names.
Functions and methods use snake_case names.
Local variables use snake_case; prefix 'k' for variables that start with a number (e.g., k_99th_percentile).
Global variables use upper SNAKE_CASE prefixed with 'G' (e.g., G_MY_GLOBAL).
Constants use upper SNAKE_CASE (e.g., MY_CONSTANT).
Avoid shadowing variables from an outer scope.
Initialize all externally visible members of a class in the constructor.
Prefer docstrings for interfaces that may be used outside a file; comments for in-function or file-local interfaces.
Use Google-style docstrings for classes and functions (Sphinx-parsable).
Document attributes and variables inline so they render under the class/function docstring.
Avoid reflection when a simpler, explicit approach suffices (e.g., avoid dict(**locals()) patterns).
In try/except, catch the most specific exceptions possible.
For duck-typing try/except, keep the try body minimal and use else for the main logic.

Files:

  • tensorrt_llm/_torch/attention_backend/sparse/dsa.py
  • tests/unittest/_torch/attention/sparse/test_dsa_indexer.py
  • tests/unittest/_torch/thop/parallel/test_indexer_topk.py
🧠 Learnings (13)
📓 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: 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.
📚 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:

  • cpp/tensorrt_llm/kernels/IndexerTopK.h
  • tensorrt_llm/_torch/attention_backend/sparse/dsa.py
  • cpp/tensorrt_llm/kernels/indexerTopK.cu
📚 Learning: 2025-09-23T15:13:48.819Z
Learnt from: nv-lschneider
Repo: NVIDIA/TensorRT-LLM PR: 7910
File: cpp/tensorrt_llm/kernels/nccl_device/multimem.h:20-30
Timestamp: 2025-09-23T15:13:48.819Z
Learning: TRT-LLM targets modern CUDA toolkits that support FP8 datatypes, so cuda_fp8.h can be included unconditionally without version guards in TRT-LLM code.

Applied to files:

  • cpp/tensorrt_llm/kernels/IndexerTopK.h
  • cpp/tensorrt_llm/kernels/indexerTopK.cu
  • cpp/tensorrt_llm/thop/IndexerTopKOp.cpp
📚 Learning: 2025-09-23T15:01:00.070Z
Learnt from: nv-lschneider
Repo: NVIDIA/TensorRT-LLM PR: 7910
File: cpp/tensorrt_llm/kernels/nccl_device/config.cu:15-17
Timestamp: 2025-09-23T15:01:00.070Z
Learning: In TensorRT-LLM NCCL device kernels, the <sstream> header is not needed as an explicit include in config.cu because it's provided transitively through other headers. Local compilation testing confirms this works without the explicit include.

Applied to files:

  • cpp/tensorrt_llm/kernels/IndexerTopK.h
  • cpp/tensorrt_llm/kernels/indexerTopK.cu
📚 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:

  • cpp/tensorrt_llm/kernels/IndexerTopK.h
  • cpp/tensorrt_llm/kernels/indexerTopK.cu
  • cpp/tensorrt_llm/thop/IndexerTopKOp.cpp
📚 Learning: 2025-09-19T21:28:13.751Z
Learnt from: jhaotingc
Repo: NVIDIA/TensorRT-LLM PR: 7856
File: cpp/tensorrt_llm/thop/fp8BlockScaleMoe.cpp:159-166
Timestamp: 2025-09-19T21:28:13.751Z
Learning: In TensorRT-LLM blockScaleMoe routing (cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/runner.cu), the DeepSeek routing method performs reinterpret_cast<float*>(routingLogits) at line 89, which could cause issues if routing_logits are BF16. However, Qwen3-FP8 models use RenormalizeNaive routing method and are not affected by this dtype casting issue.

Applied to files:

  • cpp/tensorrt_llm/kernels/IndexerTopK.h
📚 Learning: 2025-09-23T15:01:00.070Z
Learnt from: nv-lschneider
Repo: NVIDIA/TensorRT-LLM PR: 7910
File: cpp/tensorrt_llm/kernels/nccl_device/config.cu:15-17
Timestamp: 2025-09-23T15:01:00.070Z
Learning: In TensorRT-LLM NCCL device kernels (cpp/tensorrt_llm/kernels/nccl_device/config.cu), std::ostringstream is used but <sstream> doesn't need to be explicitly included because it's provided transitively through other headers like tensorrt_llm/common/cudaUtils.h or config.h. Local compilation testing confirms this works without the explicit include.

Applied to files:

  • cpp/tensorrt_llm/kernels/indexerTopK.cu
  • cpp/tensorrt_llm/thop/IndexerTopKOp.cpp
📚 Learning: 2025-08-28T10:21:46.652Z
Learnt from: ixlmar
Repo: NVIDIA/TensorRT-LLM PR: 7294
File: tensorrt_llm/_torch/pyexecutor/sampler.py:1068-1085
Timestamp: 2025-08-28T10:21:46.652Z
Learning: torch.index_select works with int32 indices in practice despite documentation stating LongTensor requirement. In TensorRT-LLM codebase, int32 indices are used intentionally and work correctly.

Applied to files:

  • cpp/tensorrt_llm/thop/IndexerTopKOp.cpp
  • tests/unittest/_torch/thop/parallel/test_indexer_topk.py
📚 Learning: 2025-09-02T13:42:44.885Z
Learnt from: pcastonguay
Repo: NVIDIA/TensorRT-LLM PR: 7455
File: tensorrt_llm/_torch/pyexecutor/py_executor.py:1852-1860
Timestamp: 2025-09-02T13:42:44.885Z
Learning: In MPI communication within TensorRT-LLM pipeline parallelism, different communication types (tokens, logits, termination sync) must use disjoint tag namespaces to avoid message routing collisions when using the same source/destination patterns.

Applied to files:

  • cpp/tensorrt_llm/thop/IndexerTopKOp.cpp
📚 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:

  • tests/unittest/_torch/thop/parallel/test_indexer_topk.py
📚 Learning: 2025-09-09T09:40:45.658Z
Learnt from: fredricz-20070104
Repo: NVIDIA/TensorRT-LLM PR: 7645
File: tests/integration/test_lists/qa/llm_function_core.txt:648-648
Timestamp: 2025-09-09T09:40:45.658Z
Learning: In TensorRT-LLM test lists, it's common and intentional for the same test to appear in multiple test list files when they serve different purposes (e.g., llm_function_core.txt for comprehensive core functionality testing and llm_function_core_sanity.txt for quick sanity checks). This duplication allows tests to be run in different testing contexts.

Applied to files:

  • tests/unittest/_torch/thop/parallel/test_indexer_topk.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:

  • tests/unittest/_torch/thop/parallel/test_indexer_topk.py
📚 Learning: 2025-08-28T10:22:02.288Z
Learnt from: ixlmar
Repo: NVIDIA/TensorRT-LLM PR: 7294
File: tensorrt_llm/_torch/pyexecutor/sampler.py:1191-1197
Timestamp: 2025-08-28T10:22:02.288Z
Learning: In tensorrt_llm/_torch/pyexecutor/sampler.py, the object identity comparison `softmax_req_indices is not group_req_indices_cuda` on line ~1191 is intentional and used as an optimization to determine whether to reuse an existing indexer or create a new one, based on which code path was taken during tensor assignment.

Applied to files:

  • tests/unittest/_torch/thop/parallel/test_indexer_topk.py
🧬 Code graph analysis (5)
cpp/tensorrt_llm/kernels/IndexerTopK.h (1)
cpp/tensorrt_llm/kernels/indexerTopK.cu (4)
  • invokeIndexerTopKDecode (281-294)
  • invokeIndexerTopKDecode (281-282)
  • invokeIndexerTopKPrefill (297-308)
  • invokeIndexerTopKPrefill (297-298)
tensorrt_llm/_torch/attention_backend/sparse/dsa.py (1)
cpp/tensorrt_llm/thop/IndexerTopKOp.cpp (4)
  • indexer_topk_prefill_op (62-81)
  • indexer_topk_prefill_op (62-63)
  • indexer_topk_decode_op (39-60)
  • indexer_topk_decode_op (39-40)
tests/unittest/_torch/attention/sparse/test_dsa_indexer.py (2)
tensorrt_llm/_torch/attention_backend/interface.py (9)
  • seq_lens (171-172)
  • seq_lens (175-196)
  • num_contexts (199-200)
  • num_contexts (203-206)
  • num_generations (209-210)
  • num_generations (213-216)
  • num_ctx_tokens (267-268)
  • num_tokens (271-272)
  • prepare (274-277)
tensorrt_llm/_torch/attention_backend/sparse/dsa.py (4)
  • Indexer (558-1173)
  • prepare (418-521)
  • prepare (716-820)
  • sparse_attn_indexer (934-1113)
cpp/tensorrt_llm/thop/IndexerTopKOp.cpp (1)
cpp/tensorrt_llm/kernels/indexerTopK.cu (4)
  • invokeIndexerTopKDecode (281-294)
  • invokeIndexerTopKDecode (281-282)
  • invokeIndexerTopKPrefill (297-308)
  • invokeIndexerTopKPrefill (297-298)
tests/unittest/_torch/thop/parallel/test_indexer_topk.py (3)
cpp/tensorrt_llm/kernels/IndexerTopK.h (1)
  • tensorrt_llm (25-37)
tensorrt_llm/_torch/models/modeling_deepseekv3.py (1)
  • DeepseekV3Gate (651-717)
cpp/tensorrt_llm/thop/IndexerTopKOp.cpp (4)
  • indexer_topk_decode_op (39-60)
  • indexer_topk_decode_op (39-40)
  • indexer_topk_prefill_op (62-81)
  • indexer_topk_prefill_op (62-63)
🪛 Clang (14.0.6)
cpp/tensorrt_llm/kernels/IndexerTopK.h

[error] 20-20: 'cuda_bf16.h' file not found

(clang-diagnostic-error)

cpp/tensorrt_llm/thop/IndexerTopKOp.cpp

[error] 18-18: 'tensorrt_llm/common/opUtils.h' file not found

(clang-diagnostic-error)

🪛 Ruff (0.14.2)
tests/unittest/_torch/attention/sparse/test_dsa_indexer.py

1092-1092: f-string without any placeholders

Remove extraneous f prefix

(F541)


1304-1304: Do not catch blind exception: Exception

(BLE001)


1441-1441: Do not catch blind exception: Exception

(BLE001)


1561-1561: Do not catch blind exception: Exception

(BLE001)

tests/unittest/_torch/thop/parallel/test_indexer_topk.py

68-68: Local variable cuda_k is assigned to but never used

Remove assignment to unused variable cuda_k

(F841)


69-69: Local variable torch_k is assigned to but never used

Remove assignment to unused variable torch_k

(F841)


129-129: f-string without any placeholders

Remove extraneous f prefix

(F541)


200-200: Unused function argument: num_tokens

(ARG001)

⏰ 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

@ChristinaZ ChristinaZ force-pushed the customize_topk branch 2 times, most recently from a6e90b6 to eac8e81 Compare November 4, 2025 03:35
@ChristinaZ
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #23454 [ run ] triggered by Bot. Commit: eac8e81

@tensorrt-cicd
Copy link
Collaborator

PR_Github #23454 [ run ] completed with state FAILURE. Commit: eac8e81
/LLM/main/L0_MergeRequest_PR pipeline #17663 completed with status: 'FAILURE'

Copy link
Collaborator

@chang-l chang-l left a comment

Choose a reason for hiding this comment

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

@ChristinaZ Thank you for the work!
Btw, it seems there is a compilation error, could you double check?

@ChristinaZ
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #23734 [ run ] triggered by Bot. Commit: 569d53d

@tensorrt-cicd
Copy link
Collaborator

PR_Github #23734 [ run ] completed with state SUCCESS. Commit: 569d53d
/LLM/main/L0_MergeRequest_PR pipeline #17864 completed with status: 'FAILURE'

@ChristinaZ ChristinaZ requested a review from a team as a code owner November 7, 2025 02:40
@ChristinaZ ChristinaZ requested a review from yizhang-nv November 7, 2025 02:40
@ChristinaZ
Copy link
Collaborator Author

/bot run --disable-fail-fast

@ChristinaZ ChristinaZ removed the request for review from yizhang-nv November 7, 2025 02:41
@tensorrt-cicd
Copy link
Collaborator

PR_Github #23796 [ run ] triggered by Bot. Commit: 1c5ad2f

@tensorrt-cicd
Copy link
Collaborator

PR_Github #23796 [ run ] completed with state SUCCESS. Commit: 1c5ad2f
/LLM/main/L0_MergeRequest_PR pipeline #17913 completed with status: 'FAILURE'

Signed-off-by: Christina Zhang <83400082+ChristinaZ@users.noreply.github.com>
@ChristinaZ
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #23889 [ run ] triggered by Bot. Commit: 8ba2972

@tensorrt-cicd
Copy link
Collaborator

PR_Github #23889 [ run ] completed with state SUCCESS. Commit: 8ba2972
/LLM/main/L0_MergeRequest_PR pipeline #17984 completed with status: 'FAILURE'

@ChristinaZ
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #23892 [ run ] triggered by Bot. Commit: 8ba2972

@tensorrt-cicd
Copy link
Collaborator

PR_Github #23892 [ run ] completed with state SUCCESS. Commit: 8ba2972
/LLM/main/L0_MergeRequest_PR pipeline #17987 completed with status: 'FAILURE'

@lfr-0531
Copy link
Collaborator

lfr-0531 commented Nov 8, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #23899 [ run ] triggered by Bot. Commit: 8ba2972

@tensorrt-cicd
Copy link
Collaborator

PR_Github #23899 [ run ] completed with state SUCCESS. Commit: 8ba2972
/LLM/main/L0_MergeRequest_PR pipeline #17993 completed with status: 'FAILURE'

@chang-l
Copy link
Collaborator

chang-l commented Nov 8, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #23904 [ run ] triggered by Bot. Commit: 8ba2972

@tensorrt-cicd
Copy link
Collaborator

PR_Github #23904 [ run ] completed with state SUCCESS. Commit: 8ba2972
/LLM/main/L0_MergeRequest_PR pipeline #17996 completed with status: 'FAILURE'

@lfr-0531
Copy link
Collaborator

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #23951 [ run ] triggered by Bot. Commit: 27159db

@tensorrt-cicd
Copy link
Collaborator

PR_Github #23951 [ run ] completed with state SUCCESS. Commit: 27159db
/LLM/main/L0_MergeRequest_PR pipeline #18037 completed with status: 'FAILURE'

@ChristinaZ
Copy link
Collaborator Author

/bot run

@lfr-0531 lfr-0531 enabled auto-merge (squash) November 10, 2025 09:06
@tensorrt-cicd
Copy link
Collaborator

PR_Github #24000 [ run ] triggered by Bot. Commit: 27159db

@tensorrt-cicd
Copy link
Collaborator

PR_Github #24000 [ run ] completed with state SUCCESS. Commit: 27159db
/LLM/main/L0_MergeRequest_PR pipeline #18078 completed with status: 'SUCCESS'

@lfr-0531 lfr-0531 merged commit 2e7769d into NVIDIA:main Nov 10, 2025
5 checks passed
suyoggupta pushed a commit to nv-auto-deploy/TensorRT-LLM that referenced this pull request Nov 12, 2025
…IA#8882)

Signed-off-by: Christina Zhang <83400082+ChristinaZ@users.noreply.github.com>
outIndices[rowIt] = -1;
if constexpr (multipleBlocksPerRow)
{
outLogits[rowIt] = -FLT_MAX;
Copy link

@weireweire weireweire Nov 20, 2025

Choose a reason for hiding this comment

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

this is undefined when I build. did we missed include <cfloat>?

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.

7 participants