KEMBAR78
[TRTLLM-7410][feat] Enable KV cache reuse and chunked prefill for mistral3.1 by 2ez4bz · Pull Request #7628 · NVIDIA/TensorRT-LLM · GitHub
Skip to content

Conversation

@2ez4bz
Copy link
Collaborator

@2ez4bz 2ez4bz commented Sep 8, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced multimodal input processing for Mistral 3, including automatic handling and fusion of multimodal embeddings.
    • Added interfaces to retrieve vocabulary size and image token IDs.
    • Improved compatibility with image inputs (e.g., PIL Images) for accurate multimodal token counting.
  • Chores

    • Removed extraneous debug logging during input preparation.
  • Tests

    • Added parameterized tests validating multimodal token counts across image sizes.
    • Standardized vision patch size in test fixtures for consistency.

Description

[TRTLLM-7410][feat] Implement image token counting for Mistral3 VLM

Test Coverage

Unit test added for new code.

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.

@2ez4bz 2ez4bz requested review from a team as code owners September 8, 2025 21:04
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 8, 2025

📝 Walkthrough

Walkthrough

Adds multimodal support enhancements to Mistral3 input processing, including updating multimodal embeddings before fusion and exposing vocab and multimodal token IDs. Cleans up a debug print in the model engine. Introduces parameterized tests validating image-to-token calculations via mocked processor behavior and sets a shared patch size constant.

Changes

Cohort / File(s) Summary
Mistral multimodal input processing
`tensorrt_llm/_torch/models/modeling_mistral.py`
Extends `Mistral3InputProcessor` to inherit from `BaseMultimodalInputProcessor`; imports and uses `find_uncached_mm_embeds` before `fuse_input_embeds` when multimodal context exists; adds public methods `get_vocab_size()` and `get_mm_token_ids()`; updates imports accordingly.
Executor logging cleanup
`tensorrt_llm/_torch/pyexecutor/model_engine.py`
Removes a debug print in `_prepare_tp_inputs`; retains multimodal indices preparation logic unchanged.
Tests for Mistral multimodal tokens
`tests/unittest/_torch/modeling/test_modeling_mistral.py`
Adds `_PATCH_SIZE = 14`; uses it in `mistral_small_3_1_24b_config`; adds parameterized test `test_processor_get_num_tokens_per_image` mocking `AutoProcessor` to validate image dimension-based token count querying.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor U as User
  participant P as Mistral3InputProcessor
  participant V as Vision/AutoProcessor
  participant M as Model

  U->>P: provide input_ids, images (optional)
  alt multimodal context present
    P->>P: find_uncached_mm_embeds(images)
    P->>P: fuse_input_embeds(input_ids, mm_embeds)
  else
    P->>P: prepare text-only embeds
  end
  P->>M: forward(embeds, mm_token_indices)

  note over P,V: For token counts per image, P queries V._get_num_multimodal_tokens(...)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • rakib-hasan
  • liji-nv

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.

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Pre-merge checks

❌ Failed checks (3 warnings)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description Check ⚠️ Warning The pull request description does not adhere to the repository’s required template: it omits the @coderabbitai summary directive, provides only the title line under the Description section without context or rationale, fails to list specific tests under Test Coverage, and does not render checklist items as checkboxes. Revise the PR description to include the @coderabbitai summary placeholder or custom summary, expand the Description section with an overview of the issue and solution, enumerate the exact test cases under Test Coverage, and convert each PR Checklist line into a checkbox according to the template.
Title Check ⚠️ Warning The provided title "[TRTLLM-7410][feat] Enable KV cache reuse and chunked prefill for mistral3.1" does not match the changes summarized in the PR, which implement image token counting and multimodal input-processor updates for Mistral3 VLM (plus unit tests); there is no evidence in the diffs or objectives of KV-cache reuse or chunked prefill work, so the title is misleading and off-topic. Rename the PR title to reflect the actual primary change (for example: "[TRTLLM-7410][feat] Implement image token counting and multimodal input-processor updates for Mistral3 VLM") and update the PR description to match; if KV-cache reuse/chunked prefill are intended, include those code changes or split them into a separate PR.

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

Caution

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

⚠️ Outside diff range comments (2)
tensorrt_llm/_torch/models/modeling_mistral.py (1)

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

Per repo guidelines, prepend the NVIDIA Apache-2.0 header to all Python sources.

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.
tests/unittest/_torch/modeling/test_modeling_mistral.py (1)

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

Tests are Python sources too; add the standard 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.
🧹 Nitpick comments (3)
tensorrt_llm/_torch/models/modeling_mistral.py (2)

216-216: Constructor/MRO fine; consider cleaning unused arg.

trust_remote_code is accepted but unused; either thread it through or drop it to avoid confusion. Also consider documenting the new public methods in the class docstring.


286-291: Return a stable dtype for token IDs.

Downstream often compares against int32 input_ids; returning an explicit int32 CPU tensor avoids dtype surprises.

Apply:

-    def get_mm_token_ids(self) -> torch.Tensor:
-        return torch.tensor([
-            self._processor.image_token_id,
-            self._processor.image_break_token_id,
-            self._processor.image_end_token_id,
-        ])
+    def get_mm_token_ids(self) -> torch.Tensor:
+        # Keep on CPU; callers can .to(...) if needed.
+        return torch.tensor(
+            [
+                self._processor.image_token_id,
+                self._processor.image_break_token_id,
+                self._processor.image_end_token_id,
+            ],
+            dtype=torch.int32,
+        )
tests/unittest/_torch/modeling/test_modeling_mistral.py (1)

507-541: Strengthen the new unit test by asserting the return value.

Also stub the processor method’s return to a concrete value to ensure end-to-end behavior.

Apply:

 @pytest.mark.parametrize("height, width", [(37, 91), (128, 256), (512, 512)])
 @torch.no_grad()
 def test_processor_get_num_tokens_per_image(
@@
-    with mock.patch(
+    with mock.patch(
         "tensorrt_llm._torch.models.modeling_mistral.AutoProcessor"
     ) as mocked_auto_processor:
+        # Provide a deterministic return for token counting
+        mocked_auto_processor.from_pretrained.return_value._get_num_multimodal_tokens.return_value = {
+            "num_image_tokens": [123]
+        }
         input_processor = modeling_mistral.Mistral3InputProcessor(
             model_path=str(tmp_path),
             model_config=mistral_3_config,
             tokenizer=mock.MagicMock(),
         )
 
-    input_processor.get_num_tokens_per_image(
+    ret = input_processor.get_num_tokens_per_image(
         image=Image.new("RGB", (width, height), color=(255, 128, 0))
     )
 
     mocked_auto_processor.from_pretrained.return_value._get_num_multimodal_tokens.assert_called_once_with(
         [(height, width)]
     )
+    assert ret == 123
📜 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 fdd5bd4 and 1051e64.

📒 Files selected for processing (3)
  • tensorrt_llm/_torch/models/modeling_mistral.py (5 hunks)
  • tensorrt_llm/_torch/pyexecutor/model_engine.py (0 hunks)
  • tests/unittest/_torch/modeling/test_modeling_mistral.py (4 hunks)
💤 Files with no reviewable changes (1)
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
🧰 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:

  • tests/unittest/_torch/modeling/test_modeling_mistral.py
  • tensorrt_llm/_torch/models/modeling_mistral.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:

  • tests/unittest/_torch/modeling/test_modeling_mistral.py
  • tensorrt_llm/_torch/models/modeling_mistral.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:

  • tests/unittest/_torch/modeling/test_modeling_mistral.py
  • tensorrt_llm/_torch/models/modeling_mistral.py
🧠 Learnings (1)
📓 Common learnings
Learnt from: dbari
PR: NVIDIA/TensorRT-LLM#6714
File: tests/integration/defs/triton_server/build_model.sh:724-726
Timestamp: 2025-08-13T08:21:13.006Z
Learning: Mistral Small 3.1 multimodal (pixtral model type) supports any batch size for the multimodal encoder, not just batch size 1. The max_batch_size parameter can be set to values like 2 without conflicts with the runtime batching logic.
🧬 Code graph analysis (2)
tests/unittest/_torch/modeling/test_modeling_mistral.py (3)
tests/unittest/_torch/helpers.py (1)
  • create_mock_engine (181-194)
tensorrt_llm/_torch/models/modeling_mistral.py (1)
  • Mistral3InputProcessor (216-291)
tensorrt_llm/inputs/registry.py (1)
  • get_num_tokens_per_image (115-133)
tensorrt_llm/_torch/models/modeling_mistral.py (2)
tensorrt_llm/_torch/models/modeling_multimodal_utils.py (2)
  • find_uncached_mm_embeds (33-105)
  • fuse_input_embeds (148-202)
tensorrt_llm/inputs/registry.py (4)
  • BaseMultimodalInputProcessor (45-163)
  • InputProcessor (22-42)
  • get_vocab_size (64-84)
  • get_mm_token_ids (86-98)
⏰ 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 (7)
tensorrt_llm/_torch/models/modeling_mistral.py (4)

17-18: Good: fuse helpers imported where used.

Brings in find_uncached_mm_embeds before fusion; aligns with mixed batches and KV reuse handling.


32-33: Good: adopt BaseMultimodalInputProcessor.

This connects Mistral3 to shared multimodal utilities (token counting, processor access).


280-285: LGTM: vocab size override matches Mistral3 config layout.


418-419: No action needed: multimodal_params_list is ordered context-first. model_engine appends all context-phase MultimodalParams (from scheduled_requests.context_requests) before any generation-phase entries, so slicing by [:num_context_requests] correctly isolates context embeds.

Likely an incorrect or invalid review comment.

tests/unittest/_torch/modeling/test_modeling_mistral.py (3)

10-13: LGTM: imports for PIL and Mistral3 module.


26-27: LGTM: shared _PATCH_SIZE for tests.


71-71: LGTM: vision_config.patch_size uses constant.

@2ez4bz 2ez4bz force-pushed the dev-mistral3-num-tokens branch 2 times, most recently from d8bceca to 80590ef Compare September 8, 2025 22:54
@2ez4bz
Copy link
Collaborator Author

2ez4bz commented Sep 8, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18103 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@2ez4bz 2ez4bz force-pushed the dev-mistral3-num-tokens branch from 80590ef to 4ada633 Compare September 16, 2025 18:21
@2ez4bz 2ez4bz requested review from a team as code owners September 16, 2025 18:21
@2ez4bz 2ez4bz requested review from Shixiaowei02 and kxdc September 16, 2025 18:21
@2ez4bz 2ez4bz force-pushed the dev-mistral3-num-tokens branch from 4ada633 to 5655c89 Compare September 16, 2025 19:24
@chang-l
Copy link
Collaborator

chang-l commented Sep 16, 2025

@2ez4bz 2ez4bz force-pushed the dev-mistral3-num-tokens branch from 5655c89 to fb92867 Compare September 16, 2025 21:15
@2ez4bz 2ez4bz requested a review from a team as a code owner September 16, 2025 21:15
@2ez4bz 2ez4bz requested a review from chzblych September 16, 2025 21:15
@2ez4bz 2ez4bz closed this Sep 16, 2025
@2ez4bz 2ez4bz reopened this Sep 16, 2025
@2ez4bz 2ez4bz force-pushed the dev-mistral3-num-tokens branch from fb92867 to 4a60897 Compare September 16, 2025 21:18
@2ez4bz
Copy link
Collaborator Author

2ez4bz commented Sep 16, 2025

/bot run --extra-stage "H100_PCIe-PyTorch-Post-Merge-1"

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18832 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

Signed-off-by: William Zhang <133824995+2ez4bz@users.noreply.github.com>
@2ez4bz 2ez4bz force-pushed the dev-mistral3-num-tokens branch from 4a60897 to ee5db78 Compare September 17, 2025 07:29
@2ez4bz 2ez4bz changed the title [TRTLLM-7410][feat] Implement image token counting for Mistral3 VLM [TRTLLM-7410][feat] Enable KV cache reuse and chunked prefill for mistral3.1 Sep 17, 2025
@2ez4bz
Copy link
Collaborator Author

2ez4bz commented Sep 17, 2025

/bot run --extra-stage "H100_PCIe-PyTorch-Post-Merge-1"

@2ez4bz
Copy link
Collaborator Author

2ez4bz commented Sep 17, 2025

@QiJune could I get a review on behalf of trt-llm-doc-owners? 🙏
@hypdeb could I get a review on behalf of trt-llm-torch-models-mistral-devs? 🙏

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18935 [ run ] triggered by Bot

Copy link
Collaborator

@hypdeb hypdeb left a comment

Choose a reason for hiding this comment

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

LGTM

@tensorrt-cicd
Copy link
Collaborator

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

@2ez4bz 2ez4bz enabled auto-merge (squash) September 17, 2025 15:07
@2ez4bz 2ez4bz merged commit 2614d71 into NVIDIA:main Sep 17, 2025
7 checks passed
Wong4j pushed a commit to Wong4j/TensorRT-LLM that referenced this pull request Sep 20, 2025
…tral3.1 (NVIDIA#7628)

Signed-off-by: William Zhang <133824995+2ez4bz@users.noreply.github.com>
MrGeva pushed a commit to nv-auto-deploy/TensorRT-LLM that referenced this pull request Sep 21, 2025
…tral3.1 (NVIDIA#7628)

Signed-off-by: William Zhang <133824995+2ez4bz@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