KEMBAR78
[None][fix] Fix get_num_tokens_per_image for nano-v2-vlm by Wanli-Jiang · Pull Request #8425 · NVIDIA/TensorRT-LLM · GitHub
Skip to content

Conversation

@Wanli-Jiang
Copy link
Collaborator

@Wanli-Jiang Wanli-Jiang commented Oct 16, 2025

Root cause: the HF codes are updated for best_ratio calculation.

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced image aspect ratio selection logic for improved tiling behavior in vision model processing.

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.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 16, 2025

📝 Walkthrough

Walkthrough

The change updates the aspect ratio selection algorithm in the image tiling logic for NanoV2VLM. It replaces factor-based selection with absolute difference-based selection between actual and target aspect ratios, introducing a tie-break condition that prefers larger areas subject to a threshold.

Changes

Cohort / File(s) Summary
Aspect ratio selection algorithm update
tensorrt_llm/_torch/models/modeling_nanov2vlm.py
Modified logic for selecting the closest target aspect ratio: replaced factor-based selection (computed from area and aspect ratio with max area cap) with absolute difference-based selection; added tie-break condition that prefers larger areas when differences are equal (area > 0.5 × image_size² × ratio[0] × ratio[1]).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

The change involves a localized but non-trivial algorithm modification. Review requires understanding the original factor-based selection logic, the new ratio difference approach, and the tie-break heuristic to verify correctness and confirm it produces expected aspect ratio selections for typical image dimensions and ratios.

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description Check ⚠️ Warning The PR description is largely incomplete and fails to adequately fill the required template sections. While the raw summary clearly explains the technical changes, the author's submitted description contains only a brief root cause statement ("the HF codes are updated for best_ratio calculation") followed by empty template placeholders. The Description section lacks any explanation of the issue or solution, the Test Coverage section is blank, and most PR Checklist items are not addressed (only one generic checkbox is marked). This minimal content does not meet the standard for a complete PR description that would help reviewers understand the context and validation of these changes.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The PR title [None][fix] Fix get_num_tokens_per_image for nano-v2-vlm is clear, specific, and directly related to the changeset. It correctly identifies the file being modified (modeling_nanov2vlm.py), specifies the function being fixed (get_num_tokens_per_image), and follows the required template format [None][fix]. The raw summary confirms that changes are indeed in the nano-v2-vlm model file and relate to updating the aspect ratio selection logic. While the title doesn't capture all implementation details (such as the shift from best_factor to ratio_diff-based selection), this level of detail is not expected in a PR title as per the guidelines.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

@Wanli-Jiang Wanli-Jiang changed the title [none][fix] Fix get_nunm_tokens_per_image for nano-v2-vlm [None][fix] Fix get_nunm_tokens_per_image for nano-v2-vlm Oct 16, 2025
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: 0

🧹 Nitpick comments (1)
tensorrt_llm/_torch/models/modeling_nanov2vlm.py (1)

207-221: Consider adding a docstring for maintainability.

The nested function _find_closest_aspect_ratio lacks a docstring explaining its algorithm and parameters. Given the recent algorithm change, adding documentation would aid future maintenance.

Example docstring:

 def _find_closest_aspect_ratio(aspect_ratio, target_ratios, width,
                                height, image_size):
+    """Find the closest aspect ratio from target_ratios to the given aspect_ratio.
+    
+    Selects based on minimum absolute difference between aspect ratios.
+    In case of a tie, prefers ratios where the image area exceeds
+    0.5 * image_size^2 * ratio[0] * ratio[1].
+    
+    Args:
+        aspect_ratio: The aspect ratio of the input image (width/height).
+        target_ratios: List of (width_tiles, height_tiles) tuples.
+        width: Image width in pixels.
+        height: Image height in pixels.
+        image_size: Target tile size.
+    
+    Returns:
+        The best matching (width_tiles, height_tiles) tuple.
+    """
     best_ratio_diff = float("inf")
📜 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 f70eff3 and 20fead8.

📒 Files selected for processing (1)
  • tensorrt_llm/_torch/models/modeling_nanov2vlm.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/_torch/models/modeling_nanov2vlm.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/_torch/models/modeling_nanov2vlm.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/_torch/models/modeling_nanov2vlm.py
⏰ 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 (1)
tensorrt_llm/_torch/models/modeling_nanov2vlm.py (1)

209-220: ****

The tie-breaking logic in lines 218–220 is correct. Verification confirms the code matches the HuggingFace implementation exactly (as seen in InternVL and nanoVLM repositories). When aspect ratios are equally close (ratio_diff == best_ratio_diff), the algorithm selects the ratio that yields a larger tiled area (area > 0.5 * image_size * image_size * ratio[0] * ratio[1]), ensuring optimal canvas utilization. This is the intended behavior and requires no changes.

@Wanli-Jiang
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21575 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21575 [ run ] completed with state DISABLED
L0 testing is limited to prioritized users. User Wanli-Jiang is not in the prioritized list. L0 testing cannot be triggered.

@yechank-nvidia yechank-nvidia changed the title [None][fix] Fix get_nunm_tokens_per_image for nano-v2-vlm [None][fix] Fix get_num_tokens_per_image for nano-v2-vlm Oct 17, 2025
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
@Wanli-Jiang Wanli-Jiang force-pushed the user/williamj/fix-nanov2vlm branch from 20fead8 to 5e71da6 Compare October 17, 2025 05:36
@Wanli-Jiang
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21664 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@Wanli-Jiang
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21682 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@Wanli-Jiang
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21701 [ run ] triggered by Bot. Commit: 5e71da6

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21701 [ run ] completed with state SUCCESS. Commit: 5e71da6
/LLM/main/L0_MergeRequest_PR pipeline #16352 completed with status: 'SUCCESS'

@Wanli-Jiang Wanli-Jiang merged commit 58b43a6 into NVIDIA:main Oct 18, 2025
5 checks passed
govind-ramnarayan pushed a commit to nv-auto-deploy/TensorRT-LLM that referenced this pull request Oct 21, 2025
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@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.

3 participants