Repository navigation
Conversation
Signed-off-by: Mindy Li <[email protected]>
Signed-off-by: Mindy Li <[email protected]>
Signed-off-by: Mindy Li <[email protected]>
Signed-off-by: Mindy Li <[email protected]>
Signed-off-by: Mindy Li <[email protected]>
Signed-off-by: Mindy Li <[email protected]>
📝 WalkthroughWalkthroughThe changes introduce TVM-FFI integration into NVFP4 Blackwell GEMM operations, with an optional toggle to use prebuilt shared objects or traditional TVM/CuteDSL compilation. Dependencies are added, kernel signatures are updated with explicit typing and tensor-based alpha parameters, and tests are modified to use dynamic alpha tensors. Changes
Sequence Diagram(s)sequenceDiagram
participant Client as Client Code
participant CuteDSL as CuteDSL Op
participant LibMgr as Library Manager
participant TVMPath as TVM-FFI Path
participant NonTVMPath as Non-TVM Path
participant Kernel as Kernel Execution
Client->>CuteDSL: Forward with use_tvm_ffi flag
CuteDSL->>LibMgr: Check use_tvm_ffi & validate alpha.numel()
alt use_tvm_ffi = True
LibMgr->>TVMPath: Load prebuilt .so from temp
alt .so exists
TVMPath->>TVMPath: Load shared object
else .so missing
TVMPath->>TVMPath: Compile via TVM/CuteDSL
TVMPath->>TVMPath: Export to .so
end
TVMPath->>Kernel: Invoke with tensor data_ptr() + alpha tensor
Kernel->>Kernel: Execute TVM-FFI path
else use_tvm_ffi = False
NonTVMPath->>NonTVMPath: Build shared library via TVM
NonTVMPath->>Kernel: Invoke with cute pointers + cuda stream + alpha tensor
Kernel->>Kernel: Execute non-TVM path
end
Kernel->>CuteDSL: Return output
CuteDSL->>Client: Return result
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes
Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ 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.
Actionable comments posted: 2
🧹 Nitpick comments (7)
tensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.py (5)
244-245: Remove commented-out placeholder code.The commented
obj_fileslist appears to be debug or placeholder code. Consider removing it or adding a TODO comment explaining its intended purpose.- # obj_files = [] -
484-534: Consider extracting swap_ab tensor selection to reduce duplication.The swap_ab logic for selecting kernel tensors is duplicated. While functionally correct, this could be simplified.
+ # Select tensors based on swap_ab + if swap_ab: + kernel_a_tensor, kernel_b_tensor = b_tensor, a_tensor + kernel_a_sf_tensor, kernel_b_sf_tensor = b_sf_tensor, a_sf_tensor + else: + kernel_a_tensor, kernel_b_tensor = a_tensor, b_tensor + kernel_a_sf_tensor, kernel_b_sf_tensor = a_sf_tensor, b_sf_tensor + if not self.use_tvm_ffi: a_ptr = self.make_cute_dsl_global_pointer( - a_tensor, cutlass.Float4E2M1FN, 32) + kernel_a_tensor, cutlass.Float4E2M1FN, 32) # ... similar for other pointers
536-558: Duplicate filename construction and redundant variable assignment.
- The
fnameconstruction logic (lines 538-543) is duplicated at lines 636-641. Extract this to a helper method.full_obj_pathandshared_lib_pathare assigned identical paths (lines 544-546 and 551-553).- Remove commented debug print statements (lines 554-558).
+ def _make_cache_filename(self, sf_vec_size, mma_tiler_mn, cluster_shape_mn, swap_ab, use_prefetch): + return (f"{sf_vec_size}_{mma_tiler_mn[0]}x{mma_tiler_mn[1]}_" + f"{cluster_shape_mn[0]}x{cluster_shape_mn[1]}_{swap_ab}_{use_prefetch}") # In forward method: if cache_key not in self.__class__.kernel_cache: if self.use_tvm_ffi: - fname = str(sf_vec_size) + "_" + str( - mma_tiler_mn[0]) + "x" + str( - mma_tiler_mn[1]) + "_" + str( - cluster_shape_mn[0]) + "x" + str( - cluster_shape_mn[1]) + "_" + str( - swap_ab) + "_" + str(use_prefetch) - full_obj_path = os.path.join(tempfile.gettempdir(), - "cute_dsl_kernels", - fname + ".so") - if os.path.isfile(full_obj_path): - file_hit = True - else: - file_hit = False - shared_lib_path = os.path.join(tempfile.gettempdir(), - "cute_dsl_kernels", - fname + ".so") + fname = self._make_cache_filename(sf_vec_size, mma_tiler_mn, cluster_shape_mn, swap_ab, use_prefetch) + shared_lib_path = os.path.join(tempfile.gettempdir(), "cute_dsl_kernels", fname + ".so") + file_hit = os.path.isfile(shared_lib_path)
652-658: Add error handling for subprocess compilation and verify gcc availability.The subprocess call compiles a shared library using
gcc. Consider:
- Adding a check for
gccavailability before attempting compilation.- Handling potential
subprocess.CalledProcessErrorwith a more informative message.- The commented print statement on line 658 should be removed.
+ import shutil + if shutil.which("gcc") is None: + raise RuntimeError("gcc is required for TVM-FFI kernel compilation but was not found in PATH") + try: subprocess.run(cmd, check=True) - # print(f"Successfully created shared library: {fpath + "/" + fname + ".so"}") + except subprocess.CalledProcessError as e: + raise RuntimeError(f"Failed to compile TVM-FFI kernel: {e}") from e
625-626: Remove unnecessary f-string prefix.The string on line 625 has no placeholders, so the
fprefix is unnecessary.- options=f"--opt-level 2 --enable-tvm-ffi" + options="--opt-level 2 --enable-tvm-ffi" if self.use_tvm_ffi else "--opt-level 2",tests/unittest/_torch/thop/parallel/test_fp4_linear.py (2)
314-323: LGTM!The
alpha_tensoris correctly created as a 1-element CUDA tensor. TheAutoTuner.get().print_statistics()call provides useful debugging information during development.Consider guarding the statistics printing behind a verbose flag or environment variable for production test runs.
747-763: Reduced test coverage in main block.The comprehensive test cases (group-1 and group-2) are commented out, leaving only a single minimal test case. While
__main__is typically for local testing, consider:
- Keeping the commented tests for easy re-enabling during development.
- Adding a comment explaining why they were disabled (e.g., long execution time).
- Ensuring the parametrized pytest tests (
test_fp4_linear_cute_dsl, etc.) provide equivalent coverage.if __name__ == "__main__": # m, n, k nvfp4_gemm_perf_test(torch.bfloat16, 128, 7168, 16384) - # # group-1 test cases + # group-1 test cases (disabled for faster local runs; use pytest for full coverage)
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
requirements.txt(1 hunks)tensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.py(8 hunks)tensorrt_llm/_torch/cute_dsl_kernels/blackwell/dense_blockscaled_gemm_persistent.py(2 hunks)tests/unittest/_torch/thop/parallel/test_fp4_linear.py(4 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., usefrom package.subpackage import fooand thenfoo.SomeClass()instead offrom 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 prefixkfor variable names that start with a number (e.g.,k_99th_percentile = ...)
Python global variables should use upper snake_case with prefixG(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 = 5followed 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:
tests/unittest/_torch/thop/parallel/test_fp4_linear.pytensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.pytensorrt_llm/_torch/cute_dsl_kernels/blackwell/dense_blockscaled_gemm_persistent.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:
tests/unittest/_torch/thop/parallel/test_fp4_linear.pytensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.pytensorrt_llm/_torch/cute_dsl_kernels/blackwell/dense_blockscaled_gemm_persistent.py
🧠 Learnings (2)
📚 Learning: 2025-11-14T11:22:03.729Z
Learnt from: nzmora-nvidia
Repo: NVIDIA/TensorRT-LLM PR: 9163
File: tensorrt_llm/_torch/auto_deploy/custom_ops/quant.py:107-113
Timestamp: 2025-11-14T11:22:03.729Z
Learning: In TensorRT-LLM AutoDeploy custom ops, when adding hardware capability checks to select between kernel implementations (e.g., cuBLAS vs. CUDA kernel), use descriptive variable names that identify the specific GPU architectures or families being targeted (e.g., `is_blackwell_geforce_or_ada`) rather than generic names like `enable_cuda_core`. This makes it clear that the code is selecting an implementation path based on hardware capabilities, not enabling/disabling hardware features.
Applied to files:
tensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.py
📚 Learning: 2025-08-22T01:54:35.850Z
Learnt from: djns99
Repo: NVIDIA/TensorRT-LLM PR: 7104
File: cpp/tensorrt_llm/kernels/cutlass_kernels/include/moe_kernels.h:999-1000
Timestamp: 2025-08-22T01:54:35.850Z
Learning: The `internal_cutlass_kernels` directory in TensorRT-LLM is a mirror of an internal NVIDIA repository and maintains its own implementation and API that may diverge from the public `cutlass_kernels` version. API inconsistencies between these two directories are intentional and by design, not bugs to be fixed.
Applied to files:
tensorrt_llm/_torch/cute_dsl_kernels/blackwell/dense_blockscaled_gemm_persistent.py
🧬 Code graph analysis (1)
tests/unittest/_torch/thop/parallel/test_fp4_linear.py (1)
tensorrt_llm/_torch/autotuner.py (4)
autotune(228-259)AutoTuner(532-1348)get(567-570)print_statistics(1225-1228)
🪛 Ruff (0.14.7)
tensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.py
477-478: Avoid specifying long messages outside the exception class
(TRY003)
625-625: f-string without any placeholders
Remove extraneous f prefix
(F541)
657-657: subprocess call: check for execution of untrusted input
(S603)
764-764: Unused function argument: use_tvm_ffi
(ARG001)
tensorrt_llm/_torch/cute_dsl_kernels/blackwell/dense_blockscaled_gemm_persistent.py
2026-2026: Ambiguous variable name: l
(E741)
⏰ 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 (7)
tensorrt_llm/_torch/custom_ops/cute_dsl_custom_ops.py (3)
476-479: LGTM!The alpha size validation ensures the kernel receives a scalar alpha value as expected. The error message is clear and informative.
662-695: Verify intentional omission ofmax_active_clustersin TVM-FFI path.The TVM-FFI kernel invocation (lines 665-678) doesn't pass
max_active_clusters, while the non-TVM path (lines 681-695) does. Confirm this is intentional - does the TVM-FFI compiled kernel havemax_active_clustersbaked in at compile time?
755-772: LGTM!The
use_tvm_ffiparameter is correctly included in the fake registration signature to match the custom op, even though it doesn't affect shape inference. This is expected behavior for fake registrations.tensorrt_llm/_torch/cute_dsl_kernels/blackwell/dense_blockscaled_gemm_persistent.py (2)
2099-2100: LGTM!The kernel invocation correctly passes
alpha_tensorandepilogue_op, consistent with the updated wrapper signature.
2018-2037: Breaking API change:alphaparameter renamed toalpha_tensor.This is a breaking change for any callers using the
wrappermethod directly. Ensure all call sites are updated:
- Parameter
alpha(pointer) →alpha_tensor(cute.Tensor)- Added
epilogue_opparameter for custom epilogue operationsThe explicit type annotations (
cutlass.Int32, etc.) improve code clarity and JIT compilation.tests/unittest/_torch/thop/parallel/test_fp4_linear.py (1)
339-362: LGTM!The warmup and run loops consistently use
alpha_tensorin the kernel calls, properly aligned with the updated API.requirements.txt (1)
76-77: torch-c-dlpack-ext version 0.1.3 does not exist on PyPI.The package
apache-tvm-ffi==0.1.4exists and is legitimate, buttorch-c-dlpack-ext==0.1.3is not available on the official PyPI repository (latest release is 0.1.2 from Nov 12, 2025). This will cause installation failures. Correct the version to 0.1.2 or verify with the maintainer if 0.1.3 should be released.⛔ Skipped due to learnings
Learnt from: djns99 Repo: NVIDIA/TensorRT-LLM PR: 7104 File: cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/fusion/sm90_visitor_scatter.hpp:399-417 Timestamp: 2025-08-21T21:48:35.135Z Learning: CUTLASS extensions in TensorRT-LLM (located under cpp/tensorrt_llm/cutlass_extensions/) are designed to integrate with and extend functionality in the external CUTLASS repository. When analyzing these extensions, their consumers and functionality wiring may exist in the CUTLASS codebase rather than within TensorRT-LLM itself.
Signed-off-by: Mindy Li <[email protected]>
Signed-off-by: Mindy Li <[email protected]>
hyukn
left a comment
There was a problem hiding this comment.
Acceleration is tremendous. Some of my concerns:
- gcc may not always be available. It will be dangerous to call it in the op.
- It requires users to write too much extra logic to enable the cache feature.
- How to determine if a cache can be reused? Can we rely on it even if the kernel has changed?
Is it possible to make it completely transparent to the op? And make cutedsl handle it by default?
Signed-off-by: Mindy Li <[email protected]>
nvidia-cutlass-dsl==4.3.1 only supports tvm-ffi export, for tvm-ffi export, it only could load .so. For dsl 4.4 release, it will support non-tvm-ffi export, it could load .so/.o. At that time, we don't need gcc.
It's difficult for dsl to determine the cache_key. So we provide two kinds of caching: explicit and implict.
By the cache_key set in the op. If the kernel change, the kernel/op developer need to update the cache key too (also need to delete the existing filed cached before). |
Signed-off-by: Mindy Li <[email protected]>
Signed-off-by: Mindy Li <[email protected]>
|
👋 Thanks for this contribution! As part of a one-time effort to trim the TensorRT-LLM open-PR backlog, we're closing PRs that have had no activity in over 180 days and currently have merge conflicts with |
Summary by CodeRabbit
New Features
Chores
✏️ Tip: You can customize this high-level summary in your review settings.
Description
enable tvm-ffi export feature, now we could reuse the compiled jit function among different runs
Perf:
trtllm::cute_dsl_nvfp4_gemm_blackwell: [205661.1111](tel:2056611111) millisecondstrtllm::cute_dsl_nvfp4_gemm_blackwell: 4557.5627 millisecondsLimitations:
nvidia-cutlass-dsl==4.3.1only supports tvm-ffi export, for tvm-ffi export, it only could load .so. For upcoming nvidia-cutlass-dsl 4.4 release, it will support non-tvm-ffi export, it could load .so/.o. At that time, we don't need gcc.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
Update tava architecture diagram if there is a significant design change in PR.
The reviewers assigned automatically/manually are appropriate for the PR.
Please check this after reviewing the above items as appropriate for this PR.
GitHub Bot Help
/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...Provide a user friendly way for developers to interact with a Jenkins server.
Run
/bot [-h|--help]to print this help message.See details below for each supported subcommand.
Details
run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]Launch build/test pipelines. All previously running jobs will be killed.
--reuse-test (optional)pipeline-id(OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.--disable-reuse-test(OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.--disable-fail-fast(OPTIONAL) : Disable fail fast on build/tests/infra failures.--skip-test(OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.--stage-list "A10-PyTorch-1, xxx"(OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.--gpu-type "A30, H100_PCIe"(OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.--test-backend "pytorch, cpp"(OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.--only-multi-gpu-test(OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.--disable-multi-gpu-test(OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.--add-multi-gpu-test(OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.--post-merge(OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx"(OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".--detailed-log(OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.--debug(OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in thestage-listparameter to access the appropriate container environment. Note: Does NOT update GitHub check status.For guidance on mapping tests to stage names, see
docs/source/reference/ci-overview.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip testing for latest commit on pull request.
--comment "Reason for skipping build/test"is required. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.reuse-pipeline
reuse-pipelineReuse a previous pipeline to validate current commit. This action will also kill all currently running builds associated with the pull request. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.