Skip to content

Conversation

dongfengy
Copy link
Collaborator

@dongfengy dongfengy commented Aug 12, 2025

Following #6478
Make vision model standalone.

Summary by CodeRabbit

  • New Features

    • Added an optional dedicated vision encoder path for multimodal image inputs, controllable via an environment flag.
    • Improved handling of image features and automatic fetching of required vision components when needed.
  • Documentation

    • Updated the Multimodal Feature Support Matrix to reflect that Llama 4 now supports an image-feature encoder pathway.
  • Refactor

    • Decoupled vision processing from the text pathway to enhance reliability, configurability, and future extensibility without changing APIs.

Description

Test Coverage

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.

Copy link
Contributor

coderabbitai bot commented Aug 12, 2025

📝 Walkthrough

Walkthrough

Introduces a disaggregated multimodal path via TLLM_MULTIMODAL_DISAGGREGATED, adds Llama4VisionEncoder to handle vision feature extraction, updates Llama4ForConditionalGeneration to use the encoder conditionally, adjusts Llama4InputProcessor to pass pixel_values instead of embeddings, and updates documentation to reflect Encoder IFB support for Llama 4.

Changes

Cohort / File(s) Summary
Documentation update
docs/source/reference/multimodal-feature-support-matrix.md
Changed Llama 4 row: Encoder IFB from No to Yes. No code changes.
Llama4 multimodal refactor
tensorrt_llm/_torch/models/modeling_llama.py
Added Llama4VisionEncoder (loads HF vision components, projects image features); introduced DISAGG flag; updated Llama4ForConditionalGeneration to use mm_encoder when DISAGG=0 and pass-through when DISAGG=1; Llama4InputProcessor now passes pixel_values via multimodal_data instead of precomputing embeddings; added encoder load/detach logic during TRT-LLM weight handling.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as User/Input
  participant IP as Llama4InputProcessor
  participant M as Llama4ForConditionalGeneration
  participant E as Llama4VisionEncoder
  participant T as Text Model

  Note over M: DISAGG=0 (default)
  U->>IP: Provide text + images
  IP->>M: tokens + multimodal_params (pixel_values)
  M->>E: forward(multimodal_params)
  E->>M: mm_embeds (image_features)
  M->>T: generate(tokens, mm_embeds)
  T-->>U: outputs
Loading
sequenceDiagram
  autonumber
  participant U as User/Input
  participant IP as Llama4InputProcessor
  participant M as Llama4ForConditionalGeneration
  participant T as Text Model

  Note over M: DISAGG=1 (disaggregated)
  U->>IP: Provide text + images
  IP->>M: tokens + multimodal_embedding (passthrough) or params
  M->>T: generate(tokens, multimodal_embedding)
  T-->>U: outputs
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • QiJune
  • Shixiaowei02
  • nv-guomingz
  • amukkara
✨ 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 with CodeRabbit:

  • 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 our support 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 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 our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@dongfengy dongfengy requested a review from chang-l August 12, 2025 23:43
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: 4

🔭 Outside diff range comments (1)
tensorrt_llm/_torch/models/modeling_llama.py (1)

1219-1232: Potential memory leak: Store full_model_config as instance variable.

The full_model_config is created but only used locally. If it's needed for the mm_encoder, it should be stored as an instance variable to ensure proper lifecycle management.

     def __init__(
         self,
         model_config: ModelConfig[Llama4Config],
     ):
         # Keep a reference to the full config (with vision) before switching to text-only
-        full_model_config = model_config
+        self.full_model_config = model_config
 
         # TODO: figure out a better way to handle multimodality.
         model_config = copy.copy(model_config)
         architectures = model_config.pretrained_config.architectures
         model_config.pretrained_config = model_config.pretrained_config.text_config
         model_config.pretrained_config.architectures = architectures
         super().__init__(Llama4Model(model_config), model_config)
         self.preload_weight_modules = self.model.preload_weight_modules
 
         if not DISAGG:
-            self.mm_encoder = Llama4VisionEncoder(full_model_config)
+            self.mm_encoder = Llama4VisionEncoder(self.full_model_config)
🧹 Nitpick comments (1)
tensorrt_llm/_torch/models/modeling_llama.py (1)

48-49: Consider making the environment variable name more descriptive.

The environment variable TLLM_MULTIMODAL_DISAGGREGATED controls a critical architectural decision. Consider:

  1. Adding documentation about what "disaggregated" means in this context
  2. Using a more descriptive name like TLLM_LLAMA4_USE_EXTERNAL_VISION_ENCODER
-DISAGG = os.getenv('TLLM_MULTIMODAL_DISAGGREGATED', '0') == '1'
+# Controls whether to use an external vision encoder (disaggregated mode)
+# When False (default): Use dedicated mm_encoder (Llama4VisionEncoder) for vision processing
+# When True: Use existing multimodal_embedding tokens path
+DISAGG = os.getenv('TLLM_MULTIMODAL_DISAGGREGATED', '0') == '1'
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bd9a6dd and 94b0263.

📒 Files selected for processing (2)
  • docs/source/reference/multimodal-feature-support-matrix.md (1 hunks)
  • tensorrt_llm/_torch/models/modeling_llama.py (8 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else

Files:

  • tensorrt_llm/_torch/models/modeling_llama.py
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • tensorrt_llm/_torch/models/modeling_llama.py
🔇 Additional comments (3)
docs/source/reference/multimodal-feature-support-matrix.md (1)

9-9: LGTM! Documentation update aligns with code changes.

The documentation correctly reflects that Llama 4 now supports Encoder IFB, which is consistent with the introduction of the disaggregated multimodal pathway via Llama4VisionEncoder in the implementation.

tensorrt_llm/_torch/models/modeling_llama.py (2)

19-19: MultimodalParams import is correct

The class MultimodalParams is defined in tensorrt_llm/inputs/multimodal.py (line 152), so importing it directly from tensorrt_llm.inputs.multimodal is valid. No changes are needed.

  • Definition location: tensorrt_llm/inputs/multimodal.py:152
  • No export needed in __init__.py when importing directly from the module

1273-1283: Thread safety concern with temporary attribute manipulation.

The load_weights method temporarily removes and restores the mm_encoder attribute. This pattern could cause issues in multi-threaded scenarios or if an exception occurs.

Consider using a context manager pattern for safer attribute manipulation:

+    @contextlib.contextmanager
+    def _temporarily_remove_mm_encoder(self):
+        """Context manager to temporarily remove mm_encoder during weight loading."""
+        had_mm_encoder = hasattr(self, "mm_encoder")
+        saved_mm_encoder = getattr(self, "mm_encoder", None)
+        if had_mm_encoder:
+            delattr(self, "mm_encoder")
+        try:
+            yield
+        finally:
+            if had_mm_encoder:
+                self.mm_encoder = saved_mm_encoder
+
     def load_weights(self, weights: Dict, weight_mapper: BaseWeightMapper):
-        # Temporarily detach mm_encoder so the TRT-LLM loader doesn't try to load it
-        had_mm_encoder = hasattr(self, "mm_encoder")
-        saved_mm_encoder = getattr(self, "mm_encoder", None)
-        if had_mm_encoder:
-            delattr(self, "mm_encoder")
-        try:
+        with self._temporarily_remove_mm_encoder():
             super().load_weights(weights, weight_mapper)
-        finally:
-            if had_mm_encoder:
-                self.mm_encoder = saved_mm_encoder

Note: You'll need to add import contextlib at the top of the file.

Likely an incorrect or invalid review comment.

Copy link
Collaborator

@yechank-nvidia yechank-nvidia left a comment

Choose a reason for hiding this comment

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

Thx for the work.

@chang-l chang-l requested review from milesial and chang-l and removed request for chang-l August 14, 2025 00:25
Signed-off-by: Dongfeng Yu <[email protected]>
Signed-off-by: Dongfeng Yu <[email protected]>
@dongfengy dongfengy force-pushed the user/dongfengy/l4_mm branch from 94b0263 to f0f9abe Compare August 26, 2025 23:27
Signed-off-by: Dongfeng Yu <[email protected]>
@dongfengy
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16628 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16628 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #12484 completed with status: 'SUCCESS'

Copy link
Collaborator

@laikhtewari laikhtewari left a comment

Choose a reason for hiding this comment

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

We should also note the addition of vision support with Llama4 in the supported models table (currently just "L", should be made "L+V")

Copy link
Collaborator

@laikhtewari laikhtewari left a comment

Choose a reason for hiding this comment

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

@chang-l pointed out that the "L+I" update has already been made here:

| `Llama4ForConditionalGeneration` | Llama 4 | `meta-llama/Llama-4-Scout-17B-16E-Instruct` | L + I |

@chang-l chang-l merged commit 367ff88 into NVIDIA:main Aug 28, 2025
4 checks passed
chang-l pushed a commit to chang-l/TensorRT-LLM that referenced this pull request Sep 2, 2025
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.

8 participants