Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[None][feat] Update multimodal utilityget_num_tokens_per_image for better generalization#7544

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
chang-l merged 1 commit intoNVIDIA:mainfromchang-l:find_mm_token_from_image
Sep 8, 2025

Conversation

@chang-l
Copy link
Collaborator

@chang-lchang-l commentedSep 4, 2025
edited by coderabbitaibot
Loading

Summary by CodeRabbit

  • New Features
    • Multimodal token counting now accepts image and video objects directly (no need to pass dimensions or frame counts).
    • Added support for PIL Image inputs.
  • Improvements
    • More robust video token estimation with a fallback to per-frame counting if full video tokenization fails.
  • Tests
    • Updated unit tests to reflect the new image/video object-based API.

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 FollowsTRT-LLM CODING GUIDELINES to the best of your knowledge.

  • Test cases are provided for new code paths (seetest 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: DoesNOT update GitHub check status.

--stage-list "A10-PyTorch-1, xxx"(OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: DoesNOT 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: DoesNOT 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: DoesNOT update GitHub pipeline status.

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

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

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

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

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

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

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

For guidance on mapping tests to stage names, seedocs/source/reference/ci-overview.md
and thescripts/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.

@chang-lchang-l changed the title[None][feat] Update multimodal utilityget_num_tokens_per_image for better generalization[None][feat] Update multimodal utilityget_num_tokens_per_image for better generalizationSep 4, 2025
@coderabbitai
Copy link
Contributor

📝 Walkthrough

Walkthrough

Refactors multimodal token counting to accept image/video objects instead of explicit dimensions. Updates find_mm_token_lengths to pass full objects. In the registry, image/video token computations derive sizes from objects and add a video fallback to per-frame counting. Tests are updated to use the new object-based API.

Changes

Cohort / File(s)Summary of changes
Input length discovery
tensorrt_llm/inputs/multimodal.py
Updated find_mm_token_lengths to call input_processor.get_num_tokens_per_image(image=item) and get_num_tokens_per_video(video=item), passing full objects instead of width/height/num_frames.
Multimodal registry and processors
tensorrt_llm/inputs/registry.py
Switched default token counting to operate on PIL Image objects and lists of images. Changed BaseMultimodalInputProcessor signatures: get_num_tokens_per_image now takes image: Image.Image; get_num_tokens_per_video takes video: List[Image.Image]. Added video tokenization try/fallback to per-frame counting scaled by temporal_patch_size.
Unit tests for multimodal token counts
tests/unittest/_torch/multimodal/test_find_num_image_tokens.py
Adjusted tests to pass image/video objects to get_num_tokens_per_image and get_num_tokens_per_video. Removed explicit dimension and num_frames arguments; kept assertions unchanged.

Sequence Diagram(s)

sequenceDiagram  autonumber  actor Caller  participant Multimodal as find_mm_token_lengths  participant Processor as BaseMultimodalInputProcessor  Note over Caller,Processor: Image token counting  Caller->>Multimodal: request token lengths (image)  Multimodal->>Processor: get_num_tokens_per_image(image)  Processor->>Processor: derive (H, W) from image  Processor-->>Multimodal: image token count  Multimodal-->>Caller: token lengths  rect rgba(200,230,255,0.25)  Note over Caller,Processor: Video token counting with fallback  Caller->>Multimodal: request token lengths (video frames)  Multimodal->>Processor: get_num_tokens_per_video(video)  Processor->>Processor: derive (T, H, W) from frames  alt Tokenizer supports video    Processor-->>Multimodal: video token count  else Tokenizer fails for video    Processor->>Processor: per-frame image token count (frame 0)    Processor-->>Multimodal: scaled token count by temporal_patch_size  end  Multimodal-->>Caller: token lengths  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • rakib-hasan
  • jaedeokk
  • ruodil
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • 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
🪧 Tips

Chat

There are 3 ways to chat withCodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag@coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag@coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on oursupport page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type@coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add@coderabbitai ignore or@coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add@coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add@coderabbitai or@coderabbitai title anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit ourStatus Page to check the current availability of CodeRabbit.
  • Visit ourDocumentation for detailed information on how to use CodeRabbit.
  • Join ourDiscord Community to get help, request features, and share feedback.
  • Follow us onX/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitaicoderabbitaibot 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: 3

Caution

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

⚠️ Outside diff range comments (4)
tensorrt_llm/inputs/registry.py (1)

1-1:Add NVIDIA Apache-2.0 header (2025).

Per repo guidelines, prepend the copyright header.

Apply:

+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#     http://www.apache.org/licenses/LICENSE-2.0+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.
tensorrt_llm/inputs/multimodal.py (2)

1-1:Add NVIDIA Apache-2.0 header (2025).

Same header requirement applies here.

Apply:

+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#     http://www.apache.org/licenses/LICENSE-2.0+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.

486-494:Fix return type and doc for find_mm_token_lengths.

Function returns a dict by modality, not List[int]. Update annotation and comment.

Apply:

-def find_mm_token_lengths(mm_data: Dict[str, Any],-                          input_processor: Any) -> List[int]:-    """Get multimodal token lengths from multimodal data items. """+def find_mm_token_lengths(mm_data: Dict[str, Any],+                          input_processor: Any) -> Dict[str, List[int]]:+    """Get multimodal token lengths grouped by modality."""@@-    return num_mm_tokens  # flatten all mm instances to a single list+    return num_mm_tokens

Also applies to: 523-524

tests/unittest/_torch/multimodal/test_find_num_image_tokens.py (1)

1-1:Add NVIDIA Apache-2.0 header (2025).

Apply standard header at file top.

Apply:

+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#     http://www.apache.org/licenses/LICENSE-2.0+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.
🧹 Nitpick comments (2)
tensorrt_llm/inputs/registry.py (1)

161-163:Clarify fallback temporal scaling; avoid truncation.

Integer division can undercount when num_frames < temporal_patch_size or not divisible. Prefer ceil groups.

Apply:

-            return num_tokens_per_frame * num_frames // temporal_patch_size+            groups = (num_frames + temporal_patch_size - 1) // temporal_patch_size+            return num_tokens_per_frame * groups
tests/unittest/_torch/multimodal/test_find_num_image_tokens.py (1)

17-26:Optional: mark as network tests or add offline fallback.

Remote URLs can make unit tests flaky. Consider @pytest.mark.network and/or local cached assets.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between89889fb and3f14a1c.

📒 Files selected for processing (3)
  • tensorrt_llm/inputs/multimodal.py (1 hunks)
  • tensorrt_llm/inputs/registry.py (4 hunks)
  • tests/unittest/_torch/multimodal/test_find_num_image_tokens.py (2 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/multimodal.py
  • tests/unittest/_torch/multimodal/test_find_num_image_tokens.py
  • tensorrt_llm/inputs/registry.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/multimodal.py
  • tests/unittest/_torch/multimodal/test_find_num_image_tokens.py
  • tensorrt_llm/inputs/registry.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/multimodal.py
  • tests/unittest/_torch/multimodal/test_find_num_image_tokens.py
  • tensorrt_llm/inputs/registry.py
🧬 Code graph analysis (2)
tensorrt_llm/inputs/multimodal.py (1)
tensorrt_llm/inputs/registry.py (1)
  • get_num_tokens_per_video (136-163)
tests/unittest/_torch/multimodal/test_find_num_image_tokens.py (1)
tensorrt_llm/inputs/registry.py (2)
  • get_num_tokens_per_image (117-134)
  • get_num_tokens_per_video (136-163)
⏰ 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 (4)
tensorrt_llm/inputs/multimodal.py (2)

502-509:Image path switch to object-based API looks good.


514-516:Video path switch to object-based API looks good.

tests/unittest/_torch/multimodal/test_find_num_image_tokens.py (2)

137-143:LGTM: tests updated to pass image object to API.


244-251:LGTM: tests updated to pass video object to API.

@chang-l
Copy link
CollaboratorAuthor

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17819 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17819 [ run ] completed with stateSUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13339 completed with status: 'FAILURE'

@chang-l
Copy link
CollaboratorAuthor

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17828 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17828 [ run ] completed with stateSUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13346 completed with status: 'FAILURE'

@chang-l
Copy link
CollaboratorAuthor

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17949 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17949 [ run ] completed with stateSUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13452 completed with status: 'FAILURE'

@chang-lchang-lforce-pushed thefind_mm_token_from_image branch fromf841169 to0222b62CompareSeptember 7, 2025 21:38
@chang-l
Copy link
CollaboratorAuthor

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17952 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17952 [ run ] completed with stateSUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13455 completed with status: 'FAILURE'

@chang-l
Copy link
CollaboratorAuthor

/bot run --reuse-test

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17955 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17955 [ run ] completed with stateSUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13458 completed with status: 'FAILURE'

@chang-l
Copy link
CollaboratorAuthor

/bot run --reuse-test

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17976 [ run ] triggered by Bot

@chang-lchang-lenabled auto-merge (squash)September 8, 2025 04:18
@tensorrt-cicd
Copy link
Collaborator

PR_Github #17976 [ run ] completed with stateSUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13472 completed with status: 'FAILURE'

Signed-off-by: Chang Liu (Enterprise Products) <9713593+chang-l@users.noreply.github.com>
@chang-lchang-lforce-pushed thefind_mm_token_from_image branch from0222b62 to6a6d9abCompareSeptember 8, 2025 07:21
@chang-l
Copy link
CollaboratorAuthor

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17996 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17996 [ run ] completed with stateSUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13487 completed with status: 'SUCCESS'
Pipeline passed with automatic retried tests. Check thererun report for details.

@chang-lchang-l merged commit4a1e138 intoNVIDIA:mainSep 8, 2025
5 checks passed
Wong4j pushed a commit to Wong4j/TensorRT-LLM that referenced this pull requestSep 20, 2025
… better generalization (NVIDIA#7544)Signed-off-by: Chang Liu (Enterprise Products) <9713593+chang-l@users.noreply.github.com>
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment

Reviewers

@coderabbitaicoderabbitai[bot]coderabbitai[bot] left review comments

@amukkaraamukkaraamukkara approved these changes

@Wanli-JiangWanli-JiangAwaiting requested review from Wanli-Jiang

@2ez4bz2ez4bzAwaiting requested review from 2ez4bz

@brb-nvbrb-nvAwaiting requested review from brb-nv

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

3 participants

@chang-l@tensorrt-cicd@amukkara

[8]ページ先頭

©2009-2025 Movatter.jp