---
name: trtllm-codebase-exploration-c7816276e54f
tags: [tensorrt-llm, workflow, exploration]
description: >
  Systematic approach to exploring the TensorRT-LLM codebase before implementing
  new features or optimizations. Teaches how to discover existing infrastructure,
  trace code paths, and avoid reimplementing what already exists. Derived from
  real mistakes where ~250 lines of code were written and deleted because
  existing forward methods weren't discovered upfront.
  Use when starting any new feature, optimization, or code modification in TRT-LLM.
license: Apache-2.0
metadata:
  author: NVIDIA Corporation
---

# TensorRT-LLM Codebase Exploration Guide

## Why This Matters

TRT-LLM is a large codebase (~500K lines) with many reusable abstractions. The most common source of wasted effort is reimplementing something that already exists. On the short-seq MHA branch, ~250 lines were written across 4 iterations before discovering that a 10-line dispatch to an existing method (`forward_context_default`) was the right solution.

**Rule of thumb**: Spend 30 minutes reading existing code before writing 1 line of new code.

## MANDATORY: Ignore the TensorRT backend, focus on the PyTorch backend

## Step-by-Step Exploration Workflow

### Step 1: Map the Class You're Modifying

Before adding code to a class, understand its full structure:

```bash
# List all methods (not just forward*)
grep -n "def " tensorrt_llm/_torch/modules/attention.py | head -50

# List all attributes set in __init__
grep -n "self\." tensorrt_llm/_torch/modules/attention.py | grep "__init__" -A 200 | head -80

# Find the class hierarchy
grep -n "class MLA\|class Attention\|class TrtllmAttention" tensorrt_llm/_torch/modules/attention.py
```

### Step 2: Trace Existing Forward Methods

Read EVERY forward method in the class. Understand what each one does, what inputs it expects, and what backends it uses.

```bash
# Find all forward methods
grep -n "def forward" tensorrt_llm/_torch/modules/attention.py

# For each one, read the full implementation (not just the signature)
```

**Ask yourself:**
- Does any existing forward method already compute what I need?
- Can I dispatch to an existing method by setting up the right state?
- What would I need to change (attributes, guards, assertions) to reuse it?

### Step 3: Search for Existing Backends and Utilities

| What you need | Search for | Common hits |
|--------------|-----------|-------------|
| Attention computation | `TrtllmAttention`, `create_attention`, `FlashInferAttention` | Handles packed seqs, variable lengths, KV cache natively |
| Compiled fusion | `maybe_compile`, `maybe_compiled_cat`, `maybe_compiled_copy_` | Already in `tensorrt_llm/_torch/utils.py` |
| RoPE application | `RotaryEmbedding`, `apply_rotary_pos_emb`, `rope_fusion` | Multiple implementations exist; check which one the current code path uses |
| KV cache management | `mla_rope_append_paged_kv`, `append_paged_kv`, `latent_cache` | Fused RoPE + cache operations in C++ kernels |
| Sparse attention | `DSATrtllmAttention`, `indexer`, `topk_indices` | DSA-specific backend with sparse routing |

```bash
# Generic search pattern
grep -rn "KEYWORD" tensorrt_llm/_torch/ --include="*.py" | head -20
```

### Step 4: Check What the Fused Kernels Handle

Many operations you might implement manually are already handled by fused C++ kernels:

```bash
# Find what the attention kernel handles internally
grep -rn "latent_cache\|rope.*fuse\|rope_fusion" tensorrt_llm/_torch/attention_backend/
```

**Common surprise**: When `rope_fusion=True` (`apply_rotary_emb=False`), the fused attention kernel handles RoPE internally via `latent_cache`. Writing custom RoPE code in Python is unnecessary and will double-apply RoPE.

### Step 5: Check Assertions and Invariants

Existing assertions may need updating when you add a new code path. Don't work around them — change them if your new path makes them invalid:

```bash
# Find assertions in the class
grep -n "assert " tensorrt_llm/_torch/modules/attention.py
```

**Example**: DSA models had `assert self.mha is None`. When adding short-seq MHA (which creates `self.mha` for DSA models), the assertion was changed to `assert self.mqa is not None` — the actual invariant being tested.

### Step 6: Understand Weight Layouts

Weight layouts often differ between HuggingFace checkpoints and TRT-LLM's loaded format:

```bash
# Find weight loading/transformation code
grep -rn "load_.*weight\|weight.*transform\|load_kv_b_proj" tensorrt_llm/_torch/models/

# Check how weights are laid out after loading
grep -n "def load_" tensorrt_llm/_torch/models/modeling_deepseekv3.py
```

**Critical for tests**: Always initialize test weights in the **loaded layout**, not the HF checkpoint layout.

### Step 7: Trace Method Limitations

After identifying a method to reuse, understand what it does **NOT** handle:

```bash
# Find all callers of the method to see its dispatch context
grep -rn "forward_context_default\|forward_context(" tensorrt_llm/_torch/modules/attention.py

# Look for the dispatcher that routes to this method
# Often named similarly but without a suffix (e.g., forward_context dispatches to forward_context_default)
```

**Ask yourself:**
- What scenarios does this method handle? (fresh prefill? cached KV? chunked context?)
- What scenarios does it NOT handle?
- Is there a higher-level dispatcher that routes to this method for the correct subset of cases?
- If I call this method directly, which scenarios will I silently mishandle?

**Example:** `forward_context_default()` handles fresh prefill but does NOT attend over cached KV tokens. `forward_context()` is the dispatcher that routes to `forward_context_default`, `forward_context_with_cached_kv`, or `forward_context_with_chunked_prefill` based on context state and SM version. Calling `forward_context_default` directly during chunked context silently drops cached tokens.

## Key Discovery Patterns

### Pattern: "Can I Reuse an Existing Forward Method?"

1. Read the target forward method (e.g., `forward_context_default`)
2. Compare it to what your new code path needs to do
3. If >70% overlap, dispatch to the existing method instead of writing a new one
4. Adjust attributes/state in `__init__` to make the dispatch work

### Pattern: "Is This Already Handled by a Fused Kernel?"

1. Check if the operation is in the attention backend's scope
2. Check the `apply_rotary_emb` / `rope_fusion` flag
3. Check `latent_cache` handling
4. If the fused kernel handles it, DON'T reimplement in Python

### Pattern: "Am I Calling the Right Abstraction Level?"

1. Identify the method you plan to call
2. Search for methods that CALL this method — there may be a dispatcher above it
3. Check if the dispatcher handles edge cases your direct call would miss
4. Prefer calling the dispatcher over the specific handler

```bash
# Find what calls forward_context_default to discover the dispatch chain
grep -n "forward_context_default" tensorrt_llm/_torch/modules/attention.py
```

### Pattern: "Does a Utility Already Exist?"

1. Search `tensorrt_llm/_torch/utils.py` for compiled helpers
2. Search `tensorrt_llm/_torch/modules/` for module-level utilities
3. Search test fixtures in `tests/unittest/_torch/` for test setup patterns

## Common Exploration Mistakes

| Mistake | Consequence | Prevention |
|---------|------------|------------|
| Reading only the method you're modifying | Miss that another method does what you need | Read ALL methods in the class |
| Searching only for the exact function name | Miss equivalent implementations | Search for the *concept* (e.g., "attention", "rope", "expand kv") |
| Assuming assertions are immutable | Work around them with hacks (separate attributes) | Question whether the assertion's intent still applies |
| Not reading the fused kernel's capabilities | Reimplement what it already does | Check what `latent_cache`, `rope_fusion` etc. control |
| Only reading Python code | Miss C++ implementations called via bindings | Check `tensorrt_llm/_torch/attention_backend/` for native kernels |
| Calling a method directly instead of through its dispatcher | Miss edge cases (cached KV, chunked prefill, SM-version gating) | Search for callers of the method to find the dispatch chain |
| Assuming hardware-uniform numerical behavior | Silent accuracy degradation on specific SM versions | Check for `get_sm_version()` guards near the call site; test on multiple hardware |

## File Reference for Exploration

| Area | Key files to read |
|------|-------------------|
| Attention modules | `tensorrt_llm/_torch/modules/attention.py` |
| Attention backends | `tensorrt_llm/_torch/attention_backend/` (trtllm_attention.py, sparse/) |
| Model definitions | `tensorrt_llm/_torch/models/modeling_*.py` |
| Utilities | `tensorrt_llm/_torch/utils.py` |
| RoPE | `tensorrt_llm/_torch/modules/rotary_embedding.py` |
| Test fixtures | `tests/unittest/_torch/attention/` |
| Weight loading | `tensorrt_llm/_torch/models/modeling_deepseekv3.py` (search `load_`) |


---
Source attribution: yo-steven
Original project: https://github.com/yo-steven/skills-exploration-20260522/blob/6e1127ffb7690aa8038b172d0ae7cc720754870d/skills/TensorRT-LLM/trtllm-codebase-exploration/SKILL.md
License: Apache-2.0
License information: https://www.apache.org/licenses/LICENSE-2.0
Original upstream instructions; downloaded from Mega AI Hub.

## Upstream license notice

SPDX-License-Identifier: Apache-2.0 AND CC-BY-4.0

Copyright (c) 2026 NVIDIA Corporation

This project is licensed under a dual license:
- Apache License 2.0 (for code and configuration)
- Creative Commons Attribution 4.0 International (CC BY 4.0) (for documentation)

You may use the contents of this repository under the terms of either license,
or both, as applicable to the type of content.

================================================================================
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to the Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by the Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding any notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

================================================================================
              Creative Commons Attribution 4.0 International License
                              (CC BY 4.0)

                https://creativecommons.org/licenses/by/4.0/

You are free to:

  Share — copy and redistribute the material in any medium or format for any
  purpose, even commercially.

  Adapt — remix, transform, and build upon the material for any purpose, even
  commercially.

  The licensor cannot revoke these freedoms as long as you follow the license
  terms.

Under the following terms:

  Attribution — You must give appropriate credit, provide a link to the license,
  and indicate if changes were made. You may do so in any reasonable manner, but
  not in any way that suggests the licensor endorses you or your use.

  No additional restrictions — You may not apply legal terms or technological
  measures that legally restrict others from doing anything the license permits.

Notices:

  You do not have to comply with the license for elements of the material in the
  public domain or where your use is permitted by an applicable exception or
  limitation.

  No warranties are given. The license may not give you all of the permissions
  necessary for your intended use. For example, other rights such as publicity,
  privacy, or moral rights may limit how you use the material.

For the full legal text, see:
https://creativecommons.org/licenses/by/4.0/legalcode



# Mega AI Hub resource metadata

Creator / publisher: yo-steven
Original project: https://github.com/yo-steven/skills-exploration-20260522/blob/6e1127ffb7690aa8038b172d0ae7cc720754870d/skills/TensorRT-LLM/trtllm-codebase-exploration/SKILL.md
Attribution basis: Source repository record

Fields of work: Development & Engineering
Roles: Backend Developer, Data Engineer, ML / AI Engineer
Specialties: Backend
Tools: Tensorrt Llm
Country applicability: Country not specified
Classification basis: Source catalog labels
Instruction SHA-256: ff160ff7b8b47ac6a5ac989b309d40aa1eae211aba0492f4d98473939a6b4bcd
