KEMBAR78
[TRTLLM-7775][feat] Integrate tinygemm2 for gpt-oss by dongfengy · Pull Request #7916 · NVIDIA/TensorRT-LLM · GitHub
Skip to content

Conversation

@dongfengy
Copy link
Collaborator

@dongfengy dongfengy commented Sep 23, 2025

Summary by CodeRabbit

  • New Features

    • Added a CUDA-accelerated TinyGEMM path for BF16 linear layers with bias, exposed via a Torch op and integrated into model gating for small token counts.
    • Introduced a latency-based threshold to automatically choose TinyGEMM for faster small-batch execution.
  • Tests

    • Added unit tests validating output shape and numerical accuracy against standard linear layers across multiple sizes.
  • Chores

    • Updated build configuration to compile the new CUDA components and include them in the library.

Description

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

@dongfengy dongfengy self-assigned this Sep 23, 2025
@dongfengy dongfengy marked this pull request as ready for review September 23, 2025 22:23
@dongfengy dongfengy requested a review from a team as a code owner September 23, 2025 22:23
@dongfengy
Copy link
Collaborator Author

/bot run

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 23, 2025

📝 Walkthrough

Walkthrough

Adds a TinyGEMM2 CUDA kernel and launcher, integrates it into a Torch extension op (trtllm.gptoss_tinygemm), wires model code to conditionally use it based on token count, updates CMake to build new sources, and introduces unit tests validating numerical parity with torch.nn.functional.linear.

Changes

Cohort / File(s) Summary
Build system: new kernel target
cpp/tensorrt_llm/kernels/gptoss_tinygemm2/CMakeLists.txt
Adds OBJECT library gptoss_tinygemm2_src, gathers .cpp/.cu, sets PIC, CUDA device symbol resolution, and private -maxrregcount=32.
CUDA kernel + launcher
cpp/tensorrt_llm/kernels/gptoss_tinygemm2/tinygemm2_kernel.cuh, cpp/tensorrt_llm/kernels/gptoss_tinygemm2/tinygemm2_cuda.cu
Introduces templated BF16 TinyGEMM2 kernel with HMMA helpers, synchronization, optional profiling; adds BF16 launcher and PyTorch-facing CUDA forward.
Torch extension binding
cpp/tensorrt_llm/thop/CMakeLists.txt, cpp/tensorrt_llm/thop/gptossTinyGemm.cpp
Adds source to th_common; defines tinygemm2_forward with shape/dtype checks; registers Torch op trtllm.gptoss_tinygemm (CUDA impl).
Model integration (routing)
tensorrt_llm/_torch/models/modeling_gpt_oss.py
Adds MIN_LATENCY_TINYGEMM_NUM_TOKENS constant and compute_gate_output helpers in AttentionBlock/MLPBlock to select tinygemm vs. existing gate by token count; updates call sites.
Tests
tests/unittest/_torch/thop/parallel/test_gptoss_tinygemm.py
Adds bf16 CUDA unit test comparing trtllm.gptoss_tinygemm to F.linear across parameterized shapes; skipped pre-Hopper.

Sequence Diagram(s)

sequenceDiagram
  participant PyModel as Python Model (Attention/MLP)
  participant TorchOp as torch.ops.trtllm.gptoss_tinygemm
  participant CppBind as C++ Binding (tinygemm2_forward)
  participant CudaFwd as CUDA Forward (tinygemm2_cuda_forward)
  participant Launcher as Kernel Launcher (launch_tinygemm2)
  participant Kernel as CUDA Kernel (kernel<>)

  PyModel->>PyModel: compute_gate_output(x)\n(if tokens <= threshold)
  alt Use TinyGEMM
    PyModel->>TorchOp: gptoss_tinygemm(x, W, b)
    TorchOp->>CppBind: validate shapes/dtypes
    CppBind->>CudaFwd: dispatch tensors
    CudaFwd->>Launcher: setup maps, grid/block, smem
    Launcher->>Kernel: launch<<<grid, block, smem, stream>>>
    Kernel-->>CudaFwd: output bf16
    CudaFwd-->>PyModel: return Tensor
  else Fallback
    PyModel->>PyModel: self.gate(x)
  end
Loading
sequenceDiagram
  participant Test as Unit Test
  participant TorchOp as torch.ops.trtllm.gptoss_tinygemm
  participant Ref as torch.nn.functional.linear

  Test->>TorchOp: run(x, W, b) on CUDA bf16
  Test->>Ref: linear(x, W, b)
  Test->>Test: assert shape and allclose
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The PR body contains the repository template but the Description and Test Coverage sections remain as placeholders with no actual summary, rationale, or list of tests, so it does not explain what changed or how to validate it; only the template text and checklist are present. Because those key sections are unpopulated, the description is largely incomplete and insufficient for reviewers to understand the change or test coverage. Please populate the Description with a concise summary of the changes (e.g., new tinygemm2 CUDA kernel and header, CMake OBJECT target, C++/Torch binding, model routing changes, and added unit test), add a Test Coverage section listing the new test(s) and how to run them (for example tests/unittest/_torch/thop/parallel/test_gptoss_tinygemm.py), and confirm any checklist items such as CODEOWNERS or documentation updates as applicable.
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The title "[TRTLLM-7775][feat] Integrate tinygemm2 for gpt-oss" follows the repository convention (ticket + type), is concise, and directly describes the primary change to integrate tinygemm2 into gpt-oss, which aligns with the added CUDA kernel, CMake target, C++/Torch bindings, and tests in the changeset.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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: 11

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
cpp/tensorrt_llm/thop/CMakeLists.txt (1)

96-101: Link the tinygemm2 object library to resolve symbols.

gptossTinyGemm.cpp calls tinygemm2_cuda_forward, but th_common does not link gptoss_tinygemm2_src. This will cause undefined references at link time.

Apply this diff to link the object library:

 target_link_libraries(th_common PRIVATE ${TORCH_LIBRARIES} th_utils
-                                        ${Python3_LIBRARIES} ${SHARED_TARGET})
+                                        ${Python3_LIBRARIES} ${SHARED_TARGET}
+                                        gptoss_tinygemm2_src)
🧹 Nitpick comments (13)
tensorrt_llm/_torch/models/modeling_gpt_oss.py (1)

39-41: Make the token threshold configurable.

Allow override via env or model config to tune crossover without code changes.

-# Use TinyGEMM when the number of tokens is not larger than this threshold
-MIN_LATENCY_TINYGEMM_NUM_TOKENS = 128
+# Use TinyGEMM when the number of tokens is not larger than this threshold
+# Allow override via env var for tuning: TRTLLM_TINYGEMM_TOKEN_THRESHOLD
+MIN_LATENCY_TINYGEMM_NUM_TOKENS = int(os.environ.get("TRTLLM_TINYGEMM_TOKEN_THRESHOLD", 128))
cpp/tensorrt_llm/thop/gptossTinyGemm.cpp (2)

14-25: Strengthen input validation (device + layout).

Ensure all tensors are on the same CUDA device and have dense layout before launching CUDA.

 torch::Tensor tinygemm2_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias)
 {
     TORCH_CHECK(input.dim() == 2, "input must be 2D");
     TORCH_CHECK(weight.dim() == 2, "weight must be 2D");
     TORCH_CHECK(bias.dim() == 1, "bias must be 1D");
     TORCH_CHECK(input.sizes()[1] == weight.sizes()[1], "input.size(1) must match weight.size(1)");
     TORCH_CHECK(weight.sizes()[0] == bias.sizes()[0], "weight.size(0) must match bias.size(0)");
+    TORCH_CHECK(input.is_cuda() && weight.is_cuda() && bias.is_cuda(), "All tensors must be CUDA tensors");
+    TORCH_CHECK(
+        input.get_device() == weight.get_device() && weight.get_device() == bias.get_device(),
+        "All tensors must be on the same CUDA device");
+    TORCH_CHECK(
+        input.is_non_overlapping_and_dense() && weight.is_non_overlapping_and_dense() && bias.is_non_overlapping_and_dense(),
+        "All tensors must be dense (non-overlapping) for the CUDA kernel");
     CHECK_INPUT(input, torch::kBFloat16);
     CHECK_INPUT(weight, torch::kBFloat16);
     CHECK_INPUT(bias, torch::kBFloat16);
     return tinygemm2_cuda_forward(input, weight, bias);
 }

28-33: Optional: rename schema arg to 'weight' for consistency.

Purely cosmetic; avoids confusion vs. conv usage elsewhere.

-    m.def(
-        "gptoss_tinygemm(Tensor input, Tensor conv_weight, "
-        "Tensor bias) -> Tensor");
+    m.def("gptoss_tinygemm(Tensor input, Tensor weight, Tensor bias) -> Tensor");
cpp/tensorrt_llm/kernels/gptoss_tinygemm2/tinygemm2_kernel.cuh (10)

17-22: Use C++ headers and drop unused include.

Replace C headers with C++ equivalents and remove (unused).

-#include "cuda_bf16.h"
-#include <assert.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <vector>
+#include "cuda_bf16.h"
+#include <cassert>
+#include <cstdint>
+#include <cstdio>

132-134: Prefer #if defined over #ifdef.

Aligns with coding guideline.

-#ifdef INTERNAL
+#if defined(INTERNAL)
     asm volatile(".pragma \"set knob DontInsertYield\";\n" : : : "memory");
-#endif
+#endif

55-85: Potential alignment/aliasing risk when writing 32-bit regs into bf16 arrays.

Reinterpreting __nv_bfloat16* as int* assumes 4-byte alignment. Guard this by asserting/alignment hints, or store through a uint32_t temp and a properly aligned pointer.

Example fix for one site (repeat for others):

-    int* rvi = reinterpret_cast<int*>(&rv[0]);
-    rvi[0] = dst;
+    // rv is 2 x 16-bit; enforce 4-byte aligned store
+    auto* rvi = reinterpret_cast<uint32_t*>(__builtin_assume_aligned(&rv[0], alignof(uint32_t)));
+    *rvi = static_cast<uint32_t>(dst);

Alternatively, change rv to be an aligned buffer type at call sites or pass a uint32_t reference and reinterpret after.


179-181: Always use braces for if/else bodies.

Guideline requires braces even for single statements.

-    if (PROFILE && threadIdx.x == 0 && blockIdx.y == 0)
-        profile[blockIdx.x].start = gclock64();
+    if (PROFILE && threadIdx.x == 0 && blockIdx.y == 0)
+    {
+        profile[blockIdx.x].start = gclock64();
+    }

263-267: Braces for profiling branches.

Apply braces for consistency.

-            if (PROFILE && blockIdx.y == 0 && ki == 0 && weight_warp)
-                profile[blockIdx.x].weight_load_start = gclock64();
-            if (PROFILE && blockIdx.y == 0 && ki == 0 && !weight_warp)
-                profile[blockIdx.x].act_load_start = gclock64();
+            if (PROFILE && blockIdx.y == 0 && ki == 0 && weight_warp)
+            {
+                profile[blockIdx.x].weight_load_start = gclock64();
+            }
+            if (PROFILE && blockIdx.y == 0 && ki == 0 && !weight_warp)
+            {
+                profile[blockIdx.x].act_load_start = gclock64();
+            }

323-327: Eliminate commented-out code and ensure row offsets are equal.

Dead/commented lines should be removed per guidelines. If row_offset equality is required, assert it when debugging.

-        // int row_offset_act = (reinterpret_cast <uintptr_t>(ptr_act)/128)%8;
-        // assert(row_offset_wt==row_offset_act);
         int row_offset_act = row_offset_wt;

352-354: Braces for profiling write.

-            if (PROFILE && blockIdx.y == 0 && threadIdx.x == 0 && ki == 0)
-                profile[blockIdx.x].compute_start = gclock64();
+            if (PROFILE && blockIdx.y == 0 && threadIdx.x == 0 && ki == 0)
+            {
+                profile[blockIdx.x].compute_start = gclock64();
+            }

395-401: mbarrier arrive: consider .expect_tx or comment intent.

Compute path uses mbarrier.arrive.shared (no expect_tx) whereas loader path uses expect_tx. If intentional, add a short comment; otherwise, use the matching variant.


195-196: Type consistency: use __nv_bfloat16 consistently.

sh_bias declared as nv_bfloat16 while the rest uses __nv_bfloat16. Unify to a single type.

-    __shared__ nv_bfloat16 sh_bias[TILE_M];
+    __shared__ __nv_bfloat16 sh_bias[TILE_M];

1-1: Filename style.

C++ filenames should be lowerCamelCase without underscores. Consider renaming to tinyGemm2Kernel.cuh.

📜 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 d471655 and 48ed7be.

📒 Files selected for processing (7)
  • cpp/tensorrt_llm/kernels/gptoss_tinygemm2/CMakeLists.txt (1 hunks)
  • cpp/tensorrt_llm/kernels/gptoss_tinygemm2/tinygemm2_cuda.cu (1 hunks)
  • cpp/tensorrt_llm/kernels/gptoss_tinygemm2/tinygemm2_kernel.cuh (1 hunks)
  • cpp/tensorrt_llm/thop/CMakeLists.txt (1 hunks)
  • cpp/tensorrt_llm/thop/gptossTinyGemm.cpp (1 hunks)
  • tensorrt_llm/_torch/models/modeling_gpt_oss.py (4 hunks)
  • tests/unittest/_torch/thop/parallel/test_gptoss_tinygemm.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{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/thop/gptossTinyGemm.cpp
  • cpp/tensorrt_llm/kernels/gptoss_tinygemm2/tinygemm2_cuda.cu
  • cpp/tensorrt_llm/kernels/gptoss_tinygemm2/tinygemm2_kernel.cuh
**/*.{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/thop/gptossTinyGemm.cpp
  • cpp/tensorrt_llm/kernels/gptoss_tinygemm2/tinygemm2_cuda.cu
  • cpp/tensorrt_llm/kernels/gptoss_tinygemm2/tinygemm2_kernel.cuh
**/*.{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/thop/gptossTinyGemm.cpp
  • tensorrt_llm/_torch/models/modeling_gpt_oss.py
  • tests/unittest/_torch/thop/parallel/test_gptoss_tinygemm.py
  • cpp/tensorrt_llm/kernels/gptoss_tinygemm2/tinygemm2_cuda.cu
  • cpp/tensorrt_llm/kernels/gptoss_tinygemm2/tinygemm2_kernel.cuh
**/*.{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/thop/gptossTinyGemm.cpp
**/*.{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/thop/gptossTinyGemm.cpp
  • tensorrt_llm/_torch/models/modeling_gpt_oss.py
  • tests/unittest/_torch/thop/parallel/test_gptoss_tinygemm.py
  • cpp/tensorrt_llm/kernels/gptoss_tinygemm2/tinygemm2_cuda.cu
  • cpp/tensorrt_llm/kernels/gptoss_tinygemm2/tinygemm2_kernel.cuh
**/*.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/models/modeling_gpt_oss.py
  • tests/unittest/_torch/thop/parallel/test_gptoss_tinygemm.py
**/*.{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/gptoss_tinygemm2/tinygemm2_kernel.cuh
🧬 Code graph analysis (1)
cpp/tensorrt_llm/thop/gptossTinyGemm.cpp (1)
cpp/tensorrt_llm/kernels/gptoss_tinygemm2/tinygemm2_cuda.cu (2)
  • tinygemm2_cuda_forward (89-112)
  • tinygemm2_cuda_forward (89-89)
🔇 Additional comments (9)
tests/unittest/_torch/thop/parallel/test_gptoss_tinygemm.py (2)

20-28: LGTM: functional parity and tolerances look reasonable.

Shape checks and BF16 allclose against F.linear with rtol/atol 1e-2 are appropriate for this path.


1-3: Add the NVIDIA Apache-2.0 header to comply with repository policy.

Tests are included in the scope for headers per guidelines.

+# SPDX-FileCopyrightText: Copyright (c) 1993-2025 NVIDIA CORPORATION & AFFILIATES.
+# All rights reserved. SPDX-License-Identifier: Apache-2.0
+
 import pytest
 import torch
 from utils.util import skip_pre_hopper
⛔ Skipped due to learnings
Learnt from: CR
PR: NVIDIA/TensorRT-LLM#0
File: CODING_GUIDELINES.md:0-0
Timestamp: 2025-09-04T17:00:29.500Z
Learning: Applies to **/*.{cpp,cxx,cc,h,hpp,hh,hxx,cu,cuh,py} : Prepend the NVIDIA Apache-2.0 copyright header with current year to the top of all source files (e.g., .cpp, .h, .cu, .py).
Learnt from: galagam
PR: NVIDIA/TensorRT-LLM#6487
File: tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py:1-12
Timestamp: 2025-08-06T13:58:07.506Z
Learning: In TensorRT-LLM, test files (files under tests/ directories) do not require NVIDIA copyright headers, unlike production source code files. Test files typically start directly with imports, docstrings, or code.
Learnt from: EmmaQiaoCh
PR: NVIDIA/TensorRT-LLM#7370
File: tests/unittest/trt/model_api/test_model_quantization.py:24-27
Timestamp: 2025-08-29T14:07:45.863Z
Learning: In TensorRT-LLM's CI infrastructure, pytest skip markers (pytest.mark.skip) are properly honored even when test files have __main__ blocks that call test functions directly. The testing system correctly skips tests without requiring modifications to the __main__ block execution pattern.
tensorrt_llm/_torch/models/modeling_gpt_oss.py (2)

243-244: LGTM: routed gate through the configurable compute path.


278-279: LGTM: attention_dp path uses the same compute gate logic.

cpp/tensorrt_llm/kernels/gptoss_tinygemm2/CMakeLists.txt (1)

18-27: Ensure gptoss_tinygemm2_src is included in the build graph and linked. Confirm the top-level CMakeLists.txt calls add_subdirectory(cpp/tensorrt_llm/kernels/gptoss_tinygemm2) and that consumers (e.g., th_common) use target_link_libraries(... gptoss_tinygemm2_src). Repository search didn't locate a top-level CMakeLists.txt to verify automatically.

cpp/tensorrt_llm/kernels/gptoss_tinygemm2/tinygemm2_kernel.cuh (4)

172-177: Kernel header should not depend on grid-constant CUtensorMap name without include.

Ensure the declaring header for CUtensorMap is included or forward-declared appropriately to avoid fragile transitive includes.

  • Verify that including this header alone compiles, or explicitly include the defining header (e.g., <cuda/pipe/tensor_map...> as appropriate).

228-303: Clarify elect_one_sync usage scope.

Assuming elect.sync is warp-scoped, this yields 1 elected lane per warp, which is intended here. Please confirm; if not warp-scoped on your toolchain, this would reduce to a single loader thread per block.

  • Confirm SASS or PTX semantics for elect.sync on the targeted CUDA version show warp scope election for the given mask (0xFFFFFFFF).

307-313: Bias load bounds.

Ensure TILE_M <= 128 (compute warps’ threads) or guard the load loop accordingly; otherwise, sh_bias won’t be fully populated.

  • Confirm max TILE_M used by launcher; if >128, load bias with a loop stride of blockDim.x.

411-441: Indexing conventions: confirm column-major output.

Stores use output[tn * M + tm]; confirm tensor map descriptors and upstream consumers expect column-major (N x M) layout.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19725 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19725 [ run ] completed with state FAILURE
/LLM/main/L0_MergeRequest_PR pipeline #14847 completed with status: 'FAILURE'

@dongfengy
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19730 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19730 [ run ] completed with state FAILURE
/LLM/main/L0_MergeRequest_PR pipeline #14851 completed with status: 'FAILURE'

@dongfengy dongfengy force-pushed the user/dongfengy/gptoss-tinygemm branch 2 times, most recently from ed65bf7 to a344ec2 Compare September 24, 2025 20:33
@dongfengy
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19839 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19839 [ run ] completed with state FAILURE
/LLM/main/L0_MergeRequest_PR pipeline #14928 completed with status: 'FAILURE'

@dongfengy
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19842 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19842 [ run ] completed with state FAILURE
/LLM/main/L0_MergeRequest_PR pipeline #14931 completed with status: 'FAILURE'

@dongfengy
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19846 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19846 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #14935 completed with status: 'FAILURE'

@dongfengy
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19984 [ run ] triggered by Bot

@dongfengy
Copy link
Collaborator Author

@ameynaik-hub could you review when you have time thanks!

@tensorrt-cicd
Copy link
Collaborator

PR_Github #19984 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #15046 completed with status: 'FAILURE'

@dongfengy dongfengy force-pushed the user/dongfengy/gptoss-tinygemm branch from 5a462ca to 0202d29 Compare September 26, 2025 18:46
@dongfengy dongfengy requested a review from a team as a code owner September 26, 2025 18:46
@dongfengy dongfengy requested a review from brb-nv October 1, 2025 16:45
@brb-nv
Copy link
Collaborator

brb-nv commented Oct 1, 2025

Changes to tensorrt_llm/_torch/models/modeling_gpt_oss.py look good to me.

dongfengy and others added 14 commits October 1, 2025 17:26
Signed-off-by: Dongfeng Yu <dongfengy@nvidia.com>
Signed-off-by: Dongfeng Yu <dongfengy@nvidia.com>
Signed-off-by: Dongfeng Yu <dongfengy@nvidia.com>
Signed-off-by: Dongfeng Yu <dongfengy@nvidia.com>
Signed-off-by: Dongfeng Yu <dongfengy@nvidia.com>
Signed-off-by: Dongfeng Yu <dongfengy@nvidia.com>
Signed-off-by: Dongfeng Yu <dongfengy@nvidia.com>
Signed-off-by: Dongfeng Yu <dongfengy@nvidia.com>
Signed-off-by: Dongfeng Yu <dongfengy@nvidia.com>
Signed-off-by: Dongfeng Yu <dongfengy@nvidia.com>
Signed-off-by: dongfengy <99041270+dongfengy@users.noreply.github.com>
Co-authored-by: Jin Li <59594262+liji-nv@users.noreply.github.com>
Signed-off-by: dongfengy <99041270+dongfengy@users.noreply.github.com>
Co-authored-by: Jin Li <59594262+liji-nv@users.noreply.github.com>
Signed-off-by: dongfengy <99041270+dongfengy@users.noreply.github.com>
Co-authored-by: Jin Li <59594262+liji-nv@users.noreply.github.com>
Signed-off-by: dongfengy <99041270+dongfengy@users.noreply.github.com>
@dongfengy dongfengy force-pushed the user/dongfengy/gptoss-tinygemm branch from 426d575 to 4484cca Compare October 2, 2025 00:26
@dongfengy
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20499 [ run ] triggered by Bot

Signed-off-by: dongfengy <99041270+dongfengy@users.noreply.github.com>
@dongfengy
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20500 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20499 [ run ] completed with state ABORTED
LLM/main/L0_MergeRequest_PR #15461 (Blue Ocean) completed with status: ABORTED

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20500 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #15462 completed with status: 'SUCCESS'
Pipeline passed with automatic retried tests. Check the rerun report for details.

@dongfengy dongfengy merged commit 6568e56 into NVIDIA:main Oct 2, 2025
5 checks passed
evezhier pushed a commit to evezhier/TensorRT-LLM that referenced this pull request Oct 3, 2025
Signed-off-by: Dongfeng Yu <dongfengy@nvidia.com>
Signed-off-by: dongfengy <99041270+dongfengy@users.noreply.github.com>
Co-authored-by: Jin Li <59594262+liji-nv@users.noreply.github.com>
faradawn pushed a commit to faradawn/TensorRT-LLM that referenced this pull request Oct 3, 2025
Signed-off-by: Dongfeng Yu <dongfengy@nvidia.com>
Signed-off-by: dongfengy <99041270+dongfengy@users.noreply.github.com>
Co-authored-by: Jin Li <59594262+liji-nv@users.noreply.github.com>
Signed-off-by: Faradawn Yang <faradawny@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants