-
Notifications
You must be signed in to change notification settings - Fork 1.9k
[None] [feat] Use triton kernels for RocketKV prediction module #8682
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[None] [feat] Use triton kernels for RocketKV prediction module #8682
Conversation
📝 WalkthroughWalkthroughThis PR introduces comprehensive enhancements to the sparse attention system, including kernel optimizations with new template parameters, extended sparse attention metadata structures, new Triton-based GPU kernels for sparse operations (argsort, top-k selection, QK split, KT cache management), expanded sparse attention configuration options with interleaving support, and updated Python/C++ bindings to propagate a new sparse_attn_indices_block_size parameter throughout the attention operation pipeline. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant TrtLLMAttention
participant TrtLLMWrapper
participant RocketKV
participant TritonKernels
participant ThorpOp
User->>TrtLLMAttention: forward(q, k, v, sparse_attention_config)
TrtLLMAttention->>TrtLLMAttention: compute sparse_attn_indices_block_size<br/>from config.get_indices_block_size()
TrtLLMAttention->>TrtLLMWrapper: plan(..., sparse_attn_indices_block_size)
TrtLLMWrapper->>TrtLLMWrapper: store sparse_attn_indices_block_size
alt Context Phase
TrtLLMWrapper->>RocketKV: prepare_for_context()
RocketKV->>TritonKernels: triton_update_kt_cache_ctx()
TritonKernels-->>RocketKV: KT cache updated
end
alt Generation Phase
TrtLLMWrapper->>RocketKV: sparse_attn_predict()
RocketKV->>RocketKV: preprocess_for_gen(q, k)
RocketKV->>TritonKernels: triton_kt_cache_update_and_bmm()
TritonKernels-->>RocketKV: attention scores
RocketKV->>TritonKernels: triton_softmax()
TritonKernels-->>RocketKV: normalized scores
RocketKV->>TritonKernels: triton_topk()
TritonKernels-->>RocketKV: top-k sparse indices
end
TrtLLMWrapper->>ThorpOp: run(..., sparse_attn_indices_block_size)
ThorpOp->>ThorpOp: propagate to sparse attention params
ThorpOp-->>User: attention output
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
Areas requiring extra attention:
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 7
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
cpp/tensorrt_llm/thop/attentionOp.h (1)
17-17: Add include guard macro (guideline requirement).Replace pragma once with TRTLLM_ATTENTIONOP_H guard.
[coding_guidelines]
Apply this diff:-#pragma once +#ifndef TRTLLM_ATTENTIONOP_H +#define TRTLLM_ATTENTIONOP_H ... -} // namespace torch_ext +} // namespace torch_ext + +#endif // TRTLLM_ATTENTIONOP_Hcpp/tests/unit_tests/kernels/sparseAttentionKernelsTest.cpp (1)
1-1: Missing NVIDIA Apache-2.0 header.Add the standard 2025 NVIDIA license header at file top.
[coding_guidelines]
Apply this diff:+/* + * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */tests/unittest/_torch/attention/sparse/test_rocketkv.py (1)
1-1: Missing NVIDIA Apache-2.0 header.Add standard header at top of Python file.
[coding_guidelines]
Apply this diff:+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License.tensorrt_llm/_torch/attention_backend/sparse/rocket.py (1)
1-26: Missing NVIDIA Apache‑2.0 headerAdd the standard NVIDIA Apache‑2.0 header with current year at the top of the file.
♻️ Duplicate comments (1)
tests/unittest/_torch/attention/sparse/test_rocketkv.py (1)
545-547: Useless standalone expression (duplicate).Remove stray arithmetic.
Apply this diff:
- end_idx - start_idx
🧹 Nitpick comments (23)
examples/longbench/eval_longbench_v2.py (1)
366-368: Consider adding explanatory comment.The conditional CUDA graph configuration logic is correct. However, consider adding a brief comment explaining why CUDA graph is only enabled for the TRTLLM backend, which would improve code maintainability.
Optionally apply this diff to add explanatory comments:
+ # Enable CUDA graph only for TRTLLM backend for performance optimization + # Note: enable_padding defaults to False to avoid accuracy issues (see PR objectives) cuda_graph_config = CudaGraphConfig( max_batch_size=args.max_batch_size ) if args.attention_backend == "TRTLLM" else Nonetensorrt_llm/llmapi/llm_args.py (1)
221-224: Document and surface interleave behaviorAdd a brief docstring to clarify that when use_interleave is True, indices are per-token (block size 1); when False, indices group by page. This helps downstream users wire correct metadata.
cpp/tensorrt_llm/kernels/sparseAttentionKernels.cu (3)
79-91: Remove unnecessary atomic on shared memory maskMultiple threads setting a flag from 0 to 1 in shared memory does not need atomics; a plain store is sufficient and faster.
- atomicExch(&s_page_mask[src_page_idx - src_page_idx_offset], 1); + s_page_mask[src_page_idx - src_page_idx_offset] = 1;
160-179: Sequence length logic: document non‑contiguous page handlingIf sparse indices can produce non‑contiguous valid pages, num_valid_pages based length may overcount. Either enforce contiguity or document that we assume contiguous pages from 0..max_page_index except possibly the last partial page.
193-195: Template constant MAX_NUM_PAGES=512: expose or derive from runtimeHard‑coding 512 is fine as a default, but consider making it a constexpr tied to max_num_pages_per_seq or exposing a compile‑time knob so tests with larger per‑seq capacities can reuse the kernel without rebuilds.
examples/llm-api/llm_sparse_attention.py (1)
73-75: Expose interleave/page sizing in the example CLISince RocketKV now uses indices block size semantics, add flags to control interleave/page size to make behavior explicit and to help reproduce perf/accuracy trade‑offs.
Example additions:
- --rocketkv_use_interleave (bool)
- --rocketkv_page_size (int, when interleave is False)
Also applies to: 108-109
cpp/tensorrt_llm/thop/attentionOp.h (2)
64-65: Align type width with kernels (int32_t vs int64_t).SparseAttentionParams uses int32_t sparse_attn_indices_block_size; header exposes int64_t. Align to int32_t to avoid silent narrowing later.
Apply this diff:
- std::vector<std::optional<torch::Tensor>> spec_decoding_tensor_params, - std::vector<std::optional<torch::Tensor>> sparse_attention_params, int64_t const sparse_attn_indices_block_size); + std::vector<std::optional<torch::Tensor>> spec_decoding_tensor_params, + std::vector<std::optional<torch::Tensor>> sparse_attention_params, int32_t const sparse_attn_indices_block_size);Also ensure the corresponding cpp and bindings signatures match. Based on learnings.
25-36: Document the new parameter in the Doxygen block.Add a brief line for sparse_attn_indices_block_size.
Example:
* - Speculative decoding * - ... + * @param sparse_attn_indices_block_size Block size for sparse attention indices flattening/interleave.cpp/tests/unit_tests/kernels/sparseAttentionKernelsTest.cpp (1)
61-71: Use fixed-width int32_t for INT32 buffers.seq_lengths_host and sparse_indices_offsets_host are INT32; casting to int* is inconsistent. Use int32_t consistently.
Apply this diff:
- auto seq_lengths_ptr = bufferCast<int>(*seq_lengths_host); - auto sparse_indices_ptr = bufferCast<int>(*sparse_indices_host); - auto sparse_indices_offsets_ptr = bufferCast<int>(*sparse_indices_offsets_host); + auto seq_lengths_ptr = bufferCast<int32_t>(*seq_lengths_host); + auto sparse_indices_ptr = bufferCast<int32_t>(*sparse_indices_host); + auto sparse_indices_offsets_ptr = bufferCast<int32_t>(*sparse_indices_offsets_host);And later:
- auto output_seq_len_ptr = bufferCast<int>(*output_seq_lengths_host); + auto output_seq_len_ptr = bufferCast<int32_t>(*output_seq_lengths_host);tests/unittest/_torch/attention/sparse/test_rocketkv.py (4)
55-63: Skip E2E if input file missing to avoid CI flakes.Guard test_model with a skip when data is absent.
Apply this diff:
- with open(input_file, 'r') as f: + if not os.path.isfile(input_file): + pytest.skip(f"Missing test data: {input_file}") + with open(input_file, 'r') as f:
213-219: zip without strict — add strict=True.Make intent explicit and catch length mismatches.
Apply this diff:
- token_nums = [ - seq_len + past_token - for seq_len, past_token in zip(seq_lens, past_seen_tokens) - ] + token_nums = [ + seq_len + past_token + for seq_len, past_token in zip(seq_lens, past_seen_tokens, strict=True) + ]
236-246: Remove unused variable vanilla_metadata.It’s assigned but never used in this test.
Apply this diff:
- vanilla_metadata = create_test_metadata(seq_lens, num_contexts, - past_seen_tokens, request_ids, - vanilla_kv_cache_manager, - sparse_attn_config, - RocketVanillaAttentionMetadata)
406-411: zip without strict — add strict=True.Mirror change from earlier loop.
Apply this diff:
- token_nums = [ - seq_len + past_token - for seq_len, past_token in zip(seq_lens, past_seen_tokens) - ] + token_nums = [ + seq_len + past_token + for seq_len, past_token in zip(seq_lens, past_seen_tokens, strict=True) + ]tensorrt_llm/_torch/attention_backend/trtllm.py (1)
200-201: Expose default semantics in docstring for new parameter.Plan signature adds sparse_attn_indices_block_size; document it and its source (sparse_attention_config.get_indices_block_size()).
Apply this diff near the Args section:
Args: @@ - sparse_attn_offsets (torch.Tensor): The batch offsets for the sparse attention indices, with shape of (num_generations + 1) on GPU. + sparse_attn_offsets (torch.Tensor): The batch offsets for the sparse attention indices, with shape of (num_generations + 1) on GPU. + sparse_attn_indices_block_size (int): Block size to pack/flatten sparse attention indices. Defaults to 1. Typically set via sparse_attention_config.get_indices_block_size().tensorrt_llm/_torch/attention_backend/sparse/kernel.py (6)
80-96: argsort assumes power-of-two length; add guardThe bitonic merge relies on BLOCK_SIZE being a power of two. Add a static assert to prevent accidental misconfig.
def argsort(x, @@ - n_dims: core.constexpr = _log2(x.shape[_dim]) + n_dims: core.constexpr = _log2(x.shape[_dim]) + core.static_assert((1 << n_dims) == x.shape[_dim], + "argsort requires length to be a power of two")
429-495: Replace lambda grid with def and type Optional for sm_scaleSatisfy linters and PEP484 without behavior change.
- grid_bmm = lambda meta: (batch_size, num_q_heads) + def grid_bmm(meta): + return (batch_size, num_q_heads) @@ - sm_scale: float = None, + sm_scale: Optional[float] = None,
610-706: Replace lambda grid with def in flatten_to_batchedAlign with style and E731.
- grid = lambda meta: (batch_size, num_heads) + def grid(meta): + return (batch_size, num_heads)
1514-1567: Top‑k temp buffers and final tuple: drop unused value, keep masks solidfinal_sorted_values is unused; store to underscore to appease linters.
- final_sorted_values, final_sorted_indices = argsort(final_values, + _final_sorted_values, final_sorted_indices = argsort(final_values, final_indices, dim=0, descending=True)Also consider loading padded tails with -inf instead of 0.0 if you ever feed non‑softmaxed scores here; current pipeline uses softmax so zeros are fine.
Also applies to: 1642-1654
714-855: O(valid_batch_size) search per work‑item; precompute a mappingflatten_sparse_indices_kernel linearly scans valid_seq_indices for every batch/head, increasing kernel time when valid_batch_size is large.
- Precompute a dense boolean mask or an index map of size batch_size on CPU/GPU and pass it in; avoid the per‑kernel inner loop.
261-321: Remove unused function args (nits) to reduce register pressure_total_tokens and _prompt_budget are unused; prefix with underscore to make intent clear.
-def triton_rocket_qk_split(input_tensor: torch.Tensor, num_heads: int, num_kv_heads: int, - head_dim: int, window_size: int, prompt_budget: int, +def triton_rocket_qk_split(input_tensor: torch.Tensor, num_heads: int, num_kv_heads: int, + head_dim: int, window_size: int, _prompt_budget: int, @@ - total_tokens = input_tensor.shape[0] + _total_tokens = input_tensor.shape[0]tensorrt_llm/_torch/attention_backend/sparse/rocket.py (3)
258-265: Potential shape source for cumsumEnsure self.context_lens is a CPU Tensor with length == num_contexts. If not, compute cumsum on self.context_lens[:self.num_contexts] to avoid overrun.
- self.context_cumsum[1:self.num_contexts + 1] = torch.cumsum( - self.context_lens, dim=0) + self.context_cumsum[1:self.num_contexts + 1] = torch.cumsum( + self.context_lens[:self.num_contexts], dim=0)
579-586: sparse_attn_predict: kwargs unusedRemove unused kwargs or accept **_ to silence linters.
- def sparse_attn_predict( + def sparse_attn_predict( self, q: torch.Tensor, k: torch.Tensor, metadata: TrtllmAttentionMetadata, - **kwargs, + **_kwargs,
425-432: sparse_kv_predict: kwargs unusedSame as above.
- def sparse_kv_predict( + def sparse_kv_predict( self, q: torch.Tensor, k: torch.Tensor, metadata: TrtllmAttentionMetadata, - **kwargs, + **_kwargs,
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (15)
cpp/tensorrt_llm/kernels/sparseAttentionKernels.cu(4 hunks)cpp/tensorrt_llm/kernels/sparseAttentionKernels.h(1 hunks)cpp/tensorrt_llm/nanobind/thop/bindings.cpp(1 hunks)cpp/tensorrt_llm/pybind/thop/bindings.cpp(1 hunks)cpp/tensorrt_llm/thop/attentionOp.cpp(6 hunks)cpp/tensorrt_llm/thop/attentionOp.h(1 hunks)cpp/tests/unit_tests/kernels/sparseAttentionKernelsTest.cpp(7 hunks)examples/llm-api/llm_sparse_attention.py(4 hunks)examples/longbench/eval_longbench_v1.py(0 hunks)examples/longbench/eval_longbench_v2.py(3 hunks)tensorrt_llm/_torch/attention_backend/sparse/kernel.py(3 hunks)tensorrt_llm/_torch/attention_backend/sparse/rocket.py(7 hunks)tensorrt_llm/_torch/attention_backend/trtllm.py(6 hunks)tensorrt_llm/llmapi/llm_args.py(3 hunks)tests/unittest/_torch/attention/sparse/test_rocketkv.py(3 hunks)
💤 Files with no reviewable changes (1)
- examples/longbench/eval_longbench_v1.py
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{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:
examples/longbench/eval_longbench_v2.pycpp/tensorrt_llm/kernels/sparseAttentionKernels.hcpp/tensorrt_llm/thop/attentionOp.hcpp/tests/unit_tests/kernels/sparseAttentionKernelsTest.cppcpp/tensorrt_llm/pybind/thop/bindings.cppcpp/tensorrt_llm/kernels/sparseAttentionKernels.cutensorrt_llm/llmapi/llm_args.pytests/unittest/_torch/attention/sparse/test_rocketkv.pyexamples/llm-api/llm_sparse_attention.pycpp/tensorrt_llm/thop/attentionOp.cpptensorrt_llm/_torch/attention_backend/sparse/kernel.pycpp/tensorrt_llm/nanobind/thop/bindings.cpptensorrt_llm/_torch/attention_backend/trtllm.pytensorrt_llm/_torch/attention_backend/sparse/rocket.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:
examples/longbench/eval_longbench_v2.pytensorrt_llm/llmapi/llm_args.pytests/unittest/_torch/attention/sparse/test_rocketkv.pyexamples/llm-api/llm_sparse_attention.pytensorrt_llm/_torch/attention_backend/sparse/kernel.pytensorrt_llm/_torch/attention_backend/trtllm.pytensorrt_llm/_torch/attention_backend/sparse/rocket.py
**/*.{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:
examples/longbench/eval_longbench_v2.pycpp/tensorrt_llm/kernels/sparseAttentionKernels.hcpp/tensorrt_llm/thop/attentionOp.hcpp/tests/unit_tests/kernels/sparseAttentionKernelsTest.cppcpp/tensorrt_llm/pybind/thop/bindings.cppcpp/tensorrt_llm/kernels/sparseAttentionKernels.cutensorrt_llm/llmapi/llm_args.pytests/unittest/_torch/attention/sparse/test_rocketkv.pyexamples/llm-api/llm_sparse_attention.pycpp/tensorrt_llm/thop/attentionOp.cpptensorrt_llm/_torch/attention_backend/sparse/kernel.pycpp/tensorrt_llm/nanobind/thop/bindings.cpptensorrt_llm/_torch/attention_backend/trtllm.pytensorrt_llm/_torch/attention_backend/sparse/rocket.py
**/*.{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/sparseAttentionKernels.hcpp/tensorrt_llm/thop/attentionOp.hcpp/tests/unit_tests/kernels/sparseAttentionKernelsTest.cppcpp/tensorrt_llm/pybind/thop/bindings.cppcpp/tensorrt_llm/kernels/sparseAttentionKernels.cucpp/tensorrt_llm/thop/attentionOp.cppcpp/tensorrt_llm/nanobind/thop/bindings.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/sparseAttentionKernels.hcpp/tensorrt_llm/thop/attentionOp.hcpp/tests/unit_tests/kernels/sparseAttentionKernelsTest.cppcpp/tensorrt_llm/pybind/thop/bindings.cppcpp/tensorrt_llm/kernels/sparseAttentionKernels.cucpp/tensorrt_llm/thop/attentionOp.cppcpp/tensorrt_llm/nanobind/thop/bindings.cpp
**/*.{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/sparseAttentionKernels.hcpp/tensorrt_llm/thop/attentionOp.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/sparseAttentionKernels.hcpp/tensorrt_llm/thop/attentionOp.hcpp/tests/unit_tests/kernels/sparseAttentionKernelsTest.cppcpp/tensorrt_llm/pybind/thop/bindings.cppcpp/tensorrt_llm/thop/attentionOp.cppcpp/tensorrt_llm/nanobind/thop/bindings.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/sparseAttentionKernels.hcpp/tensorrt_llm/thop/attentionOp.h
🧠 Learnings (3)
📚 Learning: 2025-08-14T21:04:50.248Z
Learnt from: thorjohnsen
PR: NVIDIA/TensorRT-LLM#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/tests/unit_tests/kernels/sparseAttentionKernelsTest.cppcpp/tensorrt_llm/thop/attentionOp.cpp
📚 Learning: 2025-07-28T17:06:08.621Z
Learnt from: moraxu
PR: NVIDIA/TensorRT-LLM#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/attention/sparse/test_rocketkv.py
📚 Learning: 2025-08-14T15:43:23.107Z
Learnt from: MatthiasKohl
PR: NVIDIA/TensorRT-LLM#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/attention_backend/trtllm.py
🧬 Code graph analysis (8)
examples/longbench/eval_longbench_v2.py (1)
tensorrt_llm/llmapi/llm_args.py (1)
CudaGraphConfig(108-165)
cpp/tensorrt_llm/kernels/sparseAttentionKernels.h (2)
cpp/tensorrt_llm/common/attentionOp.cpp (2)
toString(2961-3026)toString(2961-2961)cpp/tensorrt_llm/plugins/gptAttentionPlugin/gptAttentionPlugin.cpp (2)
toString(91-148)toString(91-91)
cpp/tensorrt_llm/thop/attentionOp.h (1)
cpp/tensorrt_llm/kernels/sparseAttentionKernels.h (1)
sparse_attn_indices_block_size(36-36)
tensorrt_llm/llmapi/llm_args.py (2)
tensorrt_llm/builder.py (1)
default(48-56)tensorrt_llm/_torch/attention_backend/flashinfer.py (1)
page_size(185-189)
tests/unittest/_torch/attention/sparse/test_rocketkv.py (3)
tensorrt_llm/_torch/attention_backend/sparse/rocket.py (13)
RocketTrtllmAttention(389-635)RocketTrtllmAttentionMetadata(35-386)RocketVanillaAttention(682-949)RocketVanillaAttentionMetadata(638-679)prepare(219-386)prepare(659-679)add_dummy_requests(1024-1051)sparse_kv_predict(425-537)_get_snapkv_indices(782-843)get_kt_buffers(1053-1054)kt_tokens_per_block(213-217)sparse_attn_predict(574-635)_rocketkv_selection(884-949)tensorrt_llm/_torch/metadata.py (1)
KVCacheParams(9-31)tensorrt_llm/llmapi/llm_args.py (4)
CudaGraphConfig(108-165)KvCacheConfig(1258-1402)world_size(346-347)world_size(356-360)
cpp/tensorrt_llm/thop/attentionOp.cpp (1)
cpp/tensorrt_llm/kernels/sparseAttentionKernels.h (3)
sparse_attn_offsets(34-83)sparse_attn_indices_block_size(36-36)sparse_kv_offsets(33-84)
tensorrt_llm/_torch/attention_backend/trtllm.py (4)
cpp/tensorrt_llm/kernels/sparseAttentionKernels.h (3)
sparse_attn_indices_block_size(36-36)sparse_kv_offsets(33-84)sparse_attn_offsets(34-83)tensorrt_llm/_torch/attention_backend/sparse/rocket.py (2)
sparse_kv_predict(425-537)sparse_attn_predict(574-635)tensorrt_llm/_torch/attention_backend/sparse/dsa.py (2)
sparse_kv_predict(1172-1181)sparse_attn_predict(1160-1170)tensorrt_llm/llmapi/llm_args.py (2)
get_indices_block_size(204-205)get_indices_block_size(232-236)
tensorrt_llm/_torch/attention_backend/sparse/rocket.py (2)
tensorrt_llm/_torch/attention_backend/sparse/kernel.py (10)
triton_bmm(429-496)triton_flatten_sparse_indices(807-856)triton_flatten_to_batched(670-707)triton_index_gather(139-167)triton_kt_cache_update_and_bmm(1320-1415)triton_reduce_scores(1822-1862)triton_rocket_qk_split(262-322)triton_softmax(586-623)triton_topk(1657-1763)triton_update_kt_cache_ctx(1068-1123)tensorrt_llm/_torch/attention_backend/trtllm.py (3)
max_seq_len(595-605)max_seq_len(608-612)TrtllmAttentionMetadata(561-1156)
🪛 Ruff (0.14.1)
tests/unittest/_torch/attention/sparse/test_rocketkv.py
115-115: zip() without an explicit strict= parameter
Add explicit value for parameter strict=
(B905)
201-201: Avoid specifying long messages outside the exception class
(TRY003)
215-215: zip() without an explicit strict= parameter
Add explicit value for parameter strict=
(B905)
241-241: Local variable vanilla_metadata is assigned to but never used
Remove assignment to unused variable vanilla_metadata
(F841)
394-394: Avoid specifying long messages outside the exception class
(TRY003)
408-408: zip() without an explicit strict= parameter
Add explicit value for parameter strict=
(B905)
455-455: Found useless expression. Either assign it to a variable or remove it.
(B018)
tensorrt_llm/_torch/attention_backend/sparse/kernel.py
181-181: Unused function argument: total_tokens
(ARG001)
264-264: Unused function argument: prompt_budget
(ARG001)
434-434: PEP 484 prohibits implicit Optional
Convert to T | None
(RUF013)
474-474: Do not assign a lambda expression, use a def
Rewrite grid_bmm as a def
(E731)
474-474: Unused lambda argument: meta
(ARG005)
696-696: Do not assign a lambda expression, use a def
Rewrite grid as a def
(E731)
696-696: Unused lambda argument: meta
(ARG005)
728-728: Unused function argument: prompt_budget
(ARG001)
1226-1226: Unused function argument: max_num_kt_tokens
(ARG001)
1328-1328: Unused function argument: num_kt_tokens
(ARG001)
1334-1334: PEP 484 prohibits implicit Optional
Convert to T | None
(RUF013)
1496-1496: Unused lambda argument: kwargs
(ARG005)
1517-1517: Unused function argument: max_real_tokens
(ARG001)
1642-1642: Unpacked variable final_sorted_values is never used
Prefix it with an underscore or any other dummy variable pattern
(RUF059)
tensorrt_llm/_torch/attention_backend/sparse/rocket.py
430-430: Unused method argument: kwargs
(ARG002)
502-502: Undefined name qkv
(F821)
579-579: Unused method argument: kwargs
(ARG002)
⏰ 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 (14)
examples/longbench/eval_longbench_v2.py (2)
31-32: LGTM!The import statement correctly adds
CudaGraphConfigto the existing imports and follows the coding guidelines.
380-380: LGTM!The
cuda_graph_configparameter is correctly passed to the LLM initialization.tensorrt_llm/llmapi/llm_args.py (2)
204-206: Base default looks goodReturning 1 by default is a safe, explicit baseline for non-interleaved paths. No issues.
232-237: Type annotation mismatch requires correction; architectural assumptions in review need clarificationThe review identifies a real but partially mischaracterized issue. The actual problem is:
Type safety violation confirmed:
get_indices_block_size()has return typeintbut returnsself.page_sizewhich isOptional[int]. This violates the type contract.Validation concern is valid but overstated: While
page_sizehas a default of 3 (not None), theOptional[int]type annotation allows explicit None assignment. Adding validation for non-positive values is reasonable defensive programming since rocket.py uses it in modulo operations (line 1071).Architectural assumptions in review appear incorrect:
- The review mentions "tokens_per_page" should align with indices_block_size, but
tokens_per_blockis a metadata attribute, not a KvCacheConfig field- The review questions "page_size == kv_cache_config.tokens_per_block", but KvCacheConfig has no such field
- These suggestions suggest misunderstanding of the config architecture
Action: Apply the proposed validation to fix the type mismatch and defend against runtime errors, but manually verify that the validation level matches your sparse attention design intent.
cpp/tensorrt_llm/kernels/sparseAttentionKernels.h (1)
36-37: New field wiring looks correctsparse_attn_indices_block_size default and toString coverage look good. No issues.
Also applies to: 44-46
tensorrt_llm/_torch/attention_backend/trtllm.py (1)
1301-1310: Code is correct—no issues identified.Verification confirms the implementation matches the review's approval. The
get_indices_block_size()method is properly defined inBaseSparseAttentionConfigand correctly overridden inRocketSparseAttentionConfigwith theuse_interleavetoggle logic (return 1 if True, else page_size).DeepSeekSparseAttentionConfiginherits the base implementation. The code in trtllm.py correctly calls this method and threads the block size through tosparse_attn_indices_block_size.cpp/tensorrt_llm/pybind/thop/bindings.cpp (1)
58-60: Make new argument backward compatible (default = 1).Calling thop.attention directly from Python will now require an extra positional arg. Provide a default to avoid breakages.
Apply this diff:
- py::arg("spec_decoding_tensor_params"), py::arg("sparse_attention_params"), - py::arg("sparse_attn_indices_block_size"), "Multi-head attention operation", + py::arg("spec_decoding_tensor_params"), py::arg("sparse_attention_params"), + py::arg("sparse_attn_indices_block_size") = 1, "Multi-head attention operation",Run to find any direct callsites that would otherwise break:
cpp/tensorrt_llm/thop/attentionOp.cpp (2)
240-245: Runtime param set only for generation; confirm no stale state during contextYou set sparse_attn_indices/offsets on generation and assign sparse_attn_indices_block_size only in the generation branch. That’s fine if the field is unused in context. If kernels read it unconditionally, consider resetting it (e.g., to 1) in the context path to avoid stale reuse when op instances are cached and reused.
809-811: Plumbed correctly into both context and generation callsThe extra argument is forwarded consistently to Runner::run for both stages. LGTM.
Also applies to: 827-829
tensorrt_llm/_torch/attention_backend/sparse/kernel.py (1)
1210-1231: Autotune key args: keep, but unused in body is OKmax_num_kt_tokens participates in autotune key but is unused in the kernel body; that’s acceptable. No action.
Please ensure autotune keys cover representative shapes for KT_BLOCK_SIZE/DIM_BLOCK_SIZE space.
Also applies to: 1395-1413
tensorrt_llm/_torch/attention_backend/sparse/rocket.py (4)
426-447: Concatenate q|k correctly for context path; minor clarityqkv_input = torch.cat([q, k], dim=1) assumes q, k are aligned along dim=1; OK. Consider asserting same batch/device/dtype to fail fast.
539-573: @torch.compile on preprocess_for_gen: verify stability across dynamic batch sizesDynamic shapes and conditional slicing can inhibit specialization. If compile time is a concern, add a fallback path or disable compile in unit tests to avoid graph breaks.
219-257: prepare(): mutation of num_cached_tokens_per_seq can go negativeWhen prompt_lens[i] > prompt_budget you add (prompt_budget - prompt_lens[i]) which is negative. Confirm intended behavior and that the buffer can’t underflow.
512-531: Generation path wiring looks consistentpreprocess_for_gen and triton_kt_cache_update_and_bmm integration is coherent; offsets and lengths feed subsequent softmax/top‑k as expected. LGTM.
Please ensure tests cover:
- use_interleave True/False
- num_generations=0, num_contexts=0, mixed batches
- page_size not dividing seq_len (edge pages)
Based on learningsAlso applies to: 585-635
a5ffb58 to
4be7be4
Compare
|
/bot run |
1 similar comment
|
/bot run |
|
PR_Github #23731 [ run ] triggered by Bot. Commit: |
|
PR_Github #23731 [ run ] completed with state |
|
/bot run |
24abc87 to
ff738d3
Compare
|
/bot run |
|
PR_Github #23807 [ run ] triggered by Bot. Commit: |
|
PR_Github #23807 [ run ] completed with state |
Superjomn
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM on the llmapi changes.
|
/bot run |
Signed-off-by: yuhangh <58161490+heyuhhh@users.noreply.github.com> Added bached triton kernels for RocketKV, some accuracy drops due to context phase Signed-off-by: yuhangh <58161490+heyuhhh@users.noreply.github.com> Fix update kt cache in context Signed-off-by: yuhangh <58161490+heyuhhh@users.noreply.github.com> Fix kt cache memory issue Signed-off-by: yuhangh <58161490+heyuhhh@users.noreply.github.com> minor fix Signed-off-by: yuhangh <58161490+heyuhhh@users.noreply.github.com> Add tests for prediction module Signed-off-by: yuhangh <58161490+heyuhhh@users.noreply.github.com> Enable cuda graph for RocketKV Signed-off-by: yuhangh <58161490+heyuhhh@users.noreply.github.com> Pipe clean RocketKV triton kernels Signed-off-by: yuhangh <58161490+heyuhhh@users.noreply.github.com>
Signed-off-by: yuhangh <58161490+heyuhhh@users.noreply.github.com>
|
/bot run --disable-fail-fast |
|
PR_Github #24083 [ run ] triggered by Bot. Commit: |
|
PR_Github #24083 [ run ] completed with state |
|
/bot run |
|
PR_Github #24196 [ run ] triggered by Bot. Commit: |
|
PR_Github #24196 [ run ] completed with state |
|
/bot run |
|
PR_Github #24241 [ run ] triggered by Bot. Commit: |
|
PR_Github #24241 [ run ] completed with state |
|
/bot run --disable-fail-fast |
|
PR_Github #24324 [ run ] triggered by Bot. Commit: |
|
PR_Github #24324 [ run ] completed with state |
|
/bot run |
|
PR_Github #24417 [ run ] triggered by Bot. Commit: |
|
PR_Github #24417 [ run ] completed with state |
|
/bot reuse-pipeline |
|
PR_Github #24534 [ reuse-pipeline ] triggered by Bot. Commit: |
|
PR_Github #24534 [ reuse-pipeline ] completed with state |
…IA#8682) Signed-off-by: yuhangh <58161490+heyuhhh@users.noreply.github.com>
…IA#8682) Signed-off-by: yuhangh <58161490+heyuhhh@users.noreply.github.com>
Summary by CodeRabbit
New Features
Refactor
Tests
Description
Add triton kernels for RocketKV prediction module:
Limitation
Test Coverage
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.
run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]Launch build/test pipelines. All previously running jobs will be killed.
--reuse-test (optional)pipeline-id(OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.--disable-reuse-test(OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.--disable-fail-fast(OPTIONAL) : Disable fail fast on build/tests/infra failures.--skip-test(OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.--stage-list "A10-PyTorch-1, xxx"(OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.--gpu-type "A30, H100_PCIe"(OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.--test-backend "pytorch, cpp"(OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.--only-multi-gpu-test(OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.--disable-multi-gpu-test(OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.--add-multi-gpu-test(OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.--post-merge(OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx"(OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".--detailed-log(OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.--debug(OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in thestage-listparameter to access the appropriate container environment. Note: Does NOT update GitHub check status.For guidance on mapping tests to stage names, see
docs/source/reference/ci-overview.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip testing for latest commit on pull request.
--comment "Reason for skipping build/test"is required. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.reuse-pipeline
reuse-pipelineReuse a previous pipeline to validate current commit. This action will also kill all currently running builds associated with the pull request. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.