Skip to content

Conversation

@Wanli-Jiang
Copy link
Collaborator

@Wanli-Jiang Wanli-Jiang commented Sep 26, 2025

Summary by CodeRabbit

  • New Features
    • Added optional video token pruning for multimodal inputs, controlled by an environment variable ratio (default off).
    • Multimodal outputs now include modality type and video size metadata for videos.
    • Introduced public utilities to compute retained token counts and retention masks for video embeddings.
  • Behavior
    • When pruning is disabled, image and video processing remains unchanged.
  • Tests/Chores/Docs
    • No user-facing changes reported.

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.

Details

run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]

Launch build/test pipelines. All previously running jobs will be killed.

--reuse-test (optional)pipeline-id (OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.

--disable-reuse-test (OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.

--disable-fail-fast (OPTIONAL) : Disable fail fast on build/tests/infra failures.

--skip-test (OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.

--stage-list "A10-PyTorch-1, xxx" (OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.

--gpu-type "A30, H100_PCIe" (OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.

--test-backend "pytorch, cpp" (OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.

--only-multi-gpu-test (OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.

--disable-multi-gpu-test (OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.

--add-multi-gpu-test (OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.

--post-merge (OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.

--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" (OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".

--detailed-log (OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.

--debug (OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in the stage-list parameter to access the appropriate container environment. Note: Does NOT update GitHub check status.

For guidance on mapping tests to stage names, see docs/source/reference/ci-overview.md
and the scripts/test_to_stage_mapping.py helper.

kill

kill

Kill all running builds associated with pull request.

skip

skip --comment COMMENT

Skip testing for latest commit on pull request. --comment "Reason for skipping build/test" is required. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.

reuse-pipeline

reuse-pipeline

Reuse a previous pipeline to validate current commit. This action will also kill all currently running builds associated with the pull request. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 26, 2025

📝 Walkthrough

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The pull request description consists solely of the unmodified template and placeholder comments without any actual summary, explanation, or test coverage information, leaving the Description and Test Coverage sections blank and the PR Checklist unverified, which fails to inform reviewers about the changes, rationale, and validation approach. Please populate the Description section with a concise overview of the issue and the implemented solution, list relevant test cases under Test Coverage, and update or remove the placeholder comments in the template to clearly convey the necessary information for reviewers.
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% 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 correctly follows the repository’s templating convention by including the JIRA ticket and type tag, concisely summarizes the main change of adding EVS support to the Nano V2 VLM model, and directly reflects the pull request’s content.
✨ 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: 2

🧹 Nitpick comments (7)
tensorrt_llm/inputs/__init__.py (1)

2-2: Avoid eager torch import: lazily re‑export EVS functions to cut import‑time overhead.

Importing compute_retained_tokens_count/compute_retention_mask here brings torch into tensorrt_llm.inputs import path unconditionally. Prefer lazy export to keep lightweight imports for non‑EVS users.

Apply this diff to remove the eager import:

-from .evs import compute_retained_tokens_count, compute_retention_mask

Then add a lazy accessor near the bottom of the file (outside the selected range):

# Lazy re-exports to avoid importing torch during package import.
def __getattr__(name):
    if name in ("compute_retained_tokens_count", "compute_retention_mask"):
        from .evs import compute_retained_tokens_count as _cnt, compute_retention_mask as _msk
        globals()["compute_retained_tokens_count"] = _cnt
        globals()["compute_retention_mask"] = _msk
        return globals()[name]
    raise AttributeError(name)

As per coding guidelines

tensorrt_llm/inputs/evs.py (3)

69-74: Cast to float32 for stable cosine similarity.

cosine_similarity on bfloat16 (especially CPU) can be numerically unstable or unsupported on some backends. Cast embeds to float32 for the similarity step.

Apply this diff:

-    # Core EVS
-    similarity = torch.nn.functional.cosine_similarity(video_embeds[1:, ...],
+    # Core EVS
+    _emb = video_embeds.to(torch.float32)
+    similarity = torch.nn.functional.cosine_similarity(_emb[1:, ...],
-                                                       video_embeds[:-1, ...],
+                                                       _emb[:-1, ...],
                                                        dim=-1)

81-88: Use topk instead of full sort; clamp k to valid range.

argsort is O(N log N). topk is faster and avoids slicing beyond array bounds if mis‑configured. Also early‑return if k<=0.

Apply this diff:

-    order = torch.argsort(dissimilarity_flat,
-                          dim=-1,
-                          descending=True,
-                          stable=True)
-    retain_num_tokens = compute_retained_tokens_count(video_size,
-                                                      spatial_merge_size, q)
-    topk_indices = order[:retain_num_tokens]
+    retain_num_tokens = compute_retained_tokens_count(video_size,
+                                                      spatial_merge_size, q)
+    k = min(retain_num_tokens, dissimilarity_flat.numel())
+    if k <= 0:
+        mask = torch.zeros_like(dissimilarity_flat, dtype=torch.bool)
+        return mask.view(-1) if flatten_output else mask.view(dissimilarity.size())
+    _, topk_indices = torch.topk(dissimilarity_flat, k=k, largest=True, sorted=False)

61-68: Shape safety: guard reshape assumptions.

If T * (H//s) * (W//s) != video_embeds.size(0) * (video_embeds.size(1) if video_embeds.dim() > 2 else 1), this will error. Add an assertion to fail fast with a clear message.

Proposed addition:

     video_embeds = video_embeds.reshape(
         T,
         H // spatial_merge_size,
         W // spatial_merge_size,
         video_embeds.size(-1),
     )
+    assert (H // spatial_merge_size) > 0 and (W // spatial_merge_size) > 0, (
+        f"Invalid spatial merge: H={H}, W={W}, spatial_merge_size={spatial_merge_size}"
+    )
tensorrt_llm/_torch/models/modeling_nanov2vlm.py (3)

27-28: Validate and clamp VIDEO_PRUNING_RATIO from env.

Avoid crashes or over‑pruning when env var is malformed or out of [0,1).

Apply this diff:

-VIDEO_PRUNING_RATIO = float(os.getenv("TLLM_VIDEO_PRUNING_RATIO", "0"))
+try:
+    VIDEO_PRUNING_RATIO = float(os.getenv("TLLM_VIDEO_PRUNING_RATIO", "0"))
+except ValueError:
+    VIDEO_PRUNING_RATIO = 0.0
+# Clamp for safety
+VIDEO_PRUNING_RATIO = max(0.0, min(VIDEO_PRUNING_RATIO, 0.99))

53-54: Make spatial_merge_size computation robust.

Division and truncation can yield 0 or off‑by‑one for odd ratios. Validate result.

Apply this diff:

-        self.spatial_merge_size = int(self.patch_size / self.downsample_ratio)
+        self.spatial_merge_size = int(round(self.patch_size / self.downsample_ratio))
+        if self.spatial_merge_size <= 0:
+            raise ValueError(f"Invalid spatial_merge_size from patch_size={self.patch_size}, downsample_ratio={self.downsample_ratio}")

Please verify that for your configs: (H // spatial_merge_size) * (W // spatial_merge_size) == self.num_image_token per frame.


17-18: Import surface is fine, but consider dependency direction.

Keeping the EVS import local to this model (rather than package‑root re‑export) helps avoid global import side‑effects; if you keep the package re‑export, prefer the lazy import suggested in inputs/init.py.

📜 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 35edad3 and 9443704.

📒 Files selected for processing (3)
  • tensorrt_llm/_torch/models/modeling_nanov2vlm.py (9 hunks)
  • tensorrt_llm/inputs/__init__.py (2 hunks)
  • tensorrt_llm/inputs/evs.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{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:

  • tensorrt_llm/inputs/__init__.py
  • tensorrt_llm/_torch/models/modeling_nanov2vlm.py
  • tensorrt_llm/inputs/evs.py
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

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

Files:

  • tensorrt_llm/inputs/__init__.py
  • tensorrt_llm/_torch/models/modeling_nanov2vlm.py
  • tensorrt_llm/inputs/evs.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:

  • tensorrt_llm/inputs/__init__.py
  • tensorrt_llm/_torch/models/modeling_nanov2vlm.py
  • tensorrt_llm/inputs/evs.py
🧬 Code graph analysis (2)
tensorrt_llm/inputs/__init__.py (1)
tensorrt_llm/inputs/evs.py (2)
  • compute_retained_tokens_count (14-32)
  • compute_retention_mask (35-94)
tensorrt_llm/_torch/models/modeling_nanov2vlm.py (3)
tensorrt_llm/inputs/evs.py (1)
  • compute_retention_mask (35-94)
tensorrt_llm/inputs/registry.py (1)
  • register_input_processor (412-438)
tensorrt_llm/inputs/multimodal.py (1)
  • MultimodalParams (196-520)
⏰ 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 (2)
tensorrt_llm/inputs/__init__.py (1)

52-53: LGTM: public API updated with EVS utilities.

Re‑exported symbols correctly included in all.

tensorrt_llm/_torch/models/modeling_nanov2vlm.py (1)

123-163: EVS masking path looks consistent with token budgeting.

The mask is computed per video chunk and applied before final reshape; selection count matches the prompt’s inserted token budget. Good separation for non‑video paths.

Confirm that mm_embed.shape == (T, num_image_token, hidden) for video and that start_idx += video_size[0] correctly walks over multiple videos in a single sample (i.e., dimension 0 equals total frames).

Copy link
Collaborator

@rakib-hasan rakib-hasan left a comment

Choose a reason for hiding this comment

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

LGTM overall. Add some minor comments.

@Wanli-Jiang Wanli-Jiang requested a review from chang-l October 6, 2025 02:15
@chang-l chang-l force-pushed the user/williamj/nano-evs branch from ce53755 to c2ec907 Compare October 6, 2025 02:28
@BloodAxe
Copy link

BloodAxe commented Oct 9, 2025 via email

@Wanli-Jiang Wanli-Jiang force-pushed the user/williamj/nano-evs branch from c2ec907 to 50b6649 Compare October 15, 2025 06:47
@BloodAxe
Copy link

Overall, this could be a good starting point to EVS integration to TRT-LLM. I say starting point because it required a lot of mental effort to wrap head around EVS concept in general and make sure a video encoding in Nano V2 VL plays nicely with EVS.

So this code was evolving while you was learning how operates EVS. I'm not a big fan of modifying number of image tokens here and there by +2 to account for & .
Keep in mind where variable that holds num_tokens accounts for that extra tokens or not is very error prone.

What is still missing:

  • Timestamps in frame prefixes "Frame {i} sampled at {t.2f} seconds:" before
  • Reproduction of VideoMME scores for EVS at different pruning rates

Perhaps when you will be adding timestamps support, it would be a great opportunity to revisit existing code and write it in a less brittle way. Should you add comments of shapes of input/output arguments and document what the code is doing - the next person working on Nano would thank you :)

But first things first - make sure you can reproduce VideoMME scores with your implementation.

@Wanli-Jiang Wanli-Jiang force-pushed the user/williamj/nano-evs branch from 46cd482 to 6e1cd33 Compare October 22, 2025 10:38
@tensorrt-cicd
Copy link
Collaborator

PR_Github #22335 [ run ] completed with state FAILURE. Commit: e427ade
/LLM/main/L0_MergeRequest_PR pipeline #16839 completed with status: 'FAILURE'

@Wanli-Jiang
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22354 [ run ] triggered by Bot. Commit: e427ade

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22354 [ run ] completed with state SUCCESS. Commit: e427ade
/LLM/main/L0_MergeRequest_PR pipeline #16853 completed with status: 'FAILURE'

@Wanli-Jiang Wanli-Jiang force-pushed the user/williamj/nano-evs branch 2 times, most recently from d65aab3 to 1c481e9 Compare October 24, 2025 08:15
@Wanli-Jiang
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22408 [ run ] triggered by Bot. Commit: 1c481e9

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22408 [ run ] completed with state SUCCESS. Commit: 1c481e9
/LLM/main/L0_MergeRequest_PR pipeline #16890 completed with status: 'FAILURE'

@Wanli-Jiang Wanli-Jiang force-pushed the user/williamj/nano-evs branch from 1c481e9 to 3f9bfae Compare October 24, 2025 11:39
@Wanli-Jiang
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22438 [ run ] triggered by Bot. Commit: 3f9bfae

@tensorrt-cicd
Copy link
Collaborator

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

Wanli-Jiang and others added 2 commits October 24, 2025 19:51
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
Signed-off-by: Chang Liu <9713593+chang-l@users.noreply.github.com>
@Wanli-Jiang Wanli-Jiang force-pushed the user/williamj/nano-evs branch from 3f9bfae to 73fef72 Compare October 25, 2025 06:05
* Update EVS codes.

Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
@Wanli-Jiang Wanli-Jiang force-pushed the user/williamj/nano-evs branch from 73fef72 to eaf8a59 Compare October 25, 2025 09:05
@Wanli-Jiang
Copy link
Collaborator Author

/bot reuse-pipeline

@Wanli-Jiang Wanli-Jiang enabled auto-merge (squash) October 25, 2025 09:14
@tensorrt-cicd
Copy link
Collaborator

PR_Github #22497 [ reuse-pipeline ] triggered by Bot. Commit: eaf8a59

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22497 [ reuse-pipeline ] completed with state SUCCESS. Commit: eaf8a59
Reusing PR_Github #22438 for commit eaf8a59

@Wanli-Jiang Wanli-Jiang merged commit 95be56e into NVIDIA:main Oct 25, 2025
5 checks passed
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Nov 1, 2025
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
Signed-off-by: Chang Liu <9713593+chang-l@users.noreply.github.com>
Co-authored-by: Chang Liu <9713593+chang-l@users.noreply.github.com>
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Nov 3, 2025
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
Signed-off-by: Chang Liu <9713593+chang-l@users.noreply.github.com>
Co-authored-by: Chang Liu <9713593+chang-l@users.noreply.github.com>
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Nov 3, 2025
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
Signed-off-by: Chang Liu <9713593+chang-l@users.noreply.github.com>
Co-authored-by: Chang Liu <9713593+chang-l@users.noreply.github.com>
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Nov 3, 2025
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
Signed-off-by: Chang Liu <9713593+chang-l@users.noreply.github.com>
Co-authored-by: Chang Liu <9713593+chang-l@users.noreply.github.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.

7 participants