KEMBAR78
[TRTLLM-6308][feat] Support Aggregate mode for phi4-mm by Wanli-Jiang · Pull Request #7521 · NVIDIA/TensorRT-LLM · GitHub
Skip to content

Conversation

@Wanli-Jiang
Copy link
Collaborator

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

Summary by CodeRabbit

  • New Features

    • Added aggregate-mode multimodal support for image and audio embeddings with a unified encoder.
    • Supports both batch and per-request inference, configurable via environment variable.
  • Changes

    • Disaggregated mode is currently disabled and will raise an error if selected.
    • Updated token handling for improved compatibility with multimodal inputs.
    • Input processing now requires enabling trust in remote code and defaults to CPU execution.
  • Refactor

    • Streamlined multimodal embedding pipeline to improve integration and runtime flexibility.

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.

Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
@Wanli-Jiang Wanli-Jiang requested review from a team as code owners September 4, 2025 06:26
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 4, 2025

📝 Walkthrough

Walkthrough

Introduces AGGREGATE-mode for Phi4MM by adding a runtime-loaded multimodal encoder, new token-ID handling, and environment-driven control paths for per-request vs batch embedding. Replaces legacy in-model wiring with an encoder that produces mm embeddings and fuses them into language model inputs. Disaggregated mode is currently guarded.

Changes

Cohort / File(s) Summary
Phi4MM AGGREGATE encoder and dynamic loading
tensorrt_llm/_torch/models/modeling_phi4mm.py
Added HFPhi4MultimodalEncoder with image/audio batch and per-request inference; dynamic _load_phi4mm_classes to import HF Phi4MM components; integrated encoder into Phi4MMForCausalLM initialization and forward flow.
Runtime mode and token handling
tensorrt_llm/_torch/models/modeling_phi4mm.py
Added _is_disagg() env check; PHI4_MM_PER_REQUEST_INFER to toggle per-request vs batch paths; introduced _IMAGE_SPECIAL_TOKEN_ID, _AUDIO_SPECIAL_TOKEN_ID, _PAD_TOKEN_ID; removed public MM_TOKEN_IDS; added instance mm_token_ids set during load_weights.
Input processor updates
tensorrt_llm/_torch/models/modeling_phi4mm.py
Phi4MMInputProcessor now requires trust_remote_code=True and defaults to CPU.
Legacy path removal and helpers
tensorrt_llm/_torch/models/modeling_phi4mm.py
Removed previous shim/pure-PyTorch wiring; added internal methods for encoding and embedding fusion; added guard against disaggregated mode at init.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App
  participant Phi4 as Phi4MMForCausalLM
  participant Enc as HFPhi4MultimodalEncoder
  participant Img as ImageEmbedding
  participant Aud as AudioEmbedding
  participant LM as LanguageModel

  App->>Phi4: generate(inputs, multimodal_params)
  alt Disaggregated mode detected
    Phi4-->>App: raise / guard (not supported)
  else Aggregated mode
    alt PHI4_MM_PER_REQUEST_INFER=true
      Phi4->>Enc: encode_per_request(requests)
      Enc->>Img: infer image embeds (per-request) [if images]
      Enc->>Aud: infer audio embeds (per-request) [if audio]
      Enc-->>Phi4: mm_embedding
    else Batch inference
      Phi4->>Enc: encode_batch(batch)
      Enc->>Img: batch image embeds [if images]
      Enc->>Aud: batch audio embeds [if audio]
      Enc-->>Phi4: mm_embedding
    end
    Phi4->>LM: fuse tokens + mm_embedding
    LM-->>Phi4: logits
    Phi4-->>App: outputs
  end

  note over Phi4,Enc: Token IDs sourced from instance mm_token_ids<br/>(image/audio/pad)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • amukkara
  • nv-yilinf
  • lucaslie
  • schetlur-nv
✨ 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 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 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.

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

🧹 Nitpick comments (6)
tensorrt_llm/_torch/models/modeling_phi4mm.py (6)

36-42: Special token IDs should be documented more clearly

The special token constants reference HF source files but could benefit from documenting their semantic meaning. Also, the float('-inf') usage in line 41 is unusual for a token ID range.

Consider adding more descriptive comments and verifying the float range intention:

-# Special token ids from the original Phi-4-multimodal-instruct implementation
-_IMAGE_SPECIAL_TOKEN_ID = 200010  # '<|endoftext10|>' from HF `modeling_phi4mm.py`
-_AUDIO_SPECIAL_TOKEN_ID = 200011  # '<|endoftext11|>' from HF `modeling_phi4mm.py`
-_PAD_TOKEN_ID = 199999  # '<|endoftext|>' from HF `special_tokens_map.json`
-_COMPATIBLE_IMAGE_SPECIAL_TOKEN_ID_RANGE = [-9999,
-                                            -1]  # from HF `modeling_phi4mm.py`
-_COMPATIBLE_AUDIO_SPECIAL_TOKEN_ID_RANGE = [float('-inf'), -10000
-                                            ]  # from HF `modeling_phi4mm.py`
+# Special token ids from the original Phi-4-multimodal-instruct implementation
+# These tokens are used to mark placeholder positions for multimodal content
+_IMAGE_SPECIAL_TOKEN_ID = 200010  # '<|endoftext10|>' marks image position
+_AUDIO_SPECIAL_TOKEN_ID = 200011  # '<|endoftext11|>' marks audio position
+_PAD_TOKEN_ID = 199999  # '<|endoftext|>' padding token from HF `special_tokens_map.json`
+# Compatible ranges for legacy token IDs that may appear in older checkpoints
+_COMPATIBLE_IMAGE_SPECIAL_TOKEN_ID_RANGE = [-9999, -1]  # from HF `modeling_phi4mm.py`
+# Note: Using sys.float_info.min would be more explicit than float('-inf')
+_COMPATIBLE_AUDIO_SPECIAL_TOKEN_ID_RANGE = [-2147483648, -10000]  # from HF `modeling_phi4mm.py`

383-389: Environment variable control flow should be centralized

The PHI4_MM_PER_REQUEST_INFER environment variable check duplicates the pattern seen with TLLM_MULTIMODAL_DISAGGREGATED. Consider centralizing environment variable handling.

Create a centralized configuration helper:

+def _use_per_request_inference() -> bool:
+    """Check if per-request inference mode is enabled."""
+    return os.getenv("PHI4_MM_PER_REQUEST_INFER", "0") == "1"
+
 @torch.inference_mode()
 def forward(self, multimodal_params: List[MultimodalParams],
             mm_token_ids: torch.Tensor) -> List[torch.FloatTensor]:
-    if os.getenv("PHI4_MM_PER_REQUEST_INFER", "0") == "1":
+    if _use_per_request_inference():
         # Reference code path to check correctness of batch inference and further dev.
         # (TODO) Remove this path after accuracy bench and data parallelism are supported.
         return self._encoding_per_request(multimodal_params, mm_token_ids)
     else:
         # Batch inference as default path.
         return self._encoding_batch_request(multimodal_params, mm_token_ids)

399-401: Error message should be more informative

The ValueError for trust_remote_code provides insufficient context about why it's required.

 if not trust_remote_code:
-    raise ValueError("trust_remote_code must be True for Phi4MM")
+    raise ValueError(
+        "trust_remote_code must be True for Phi4MM to load the required "
+        "model-specific components from the Hugging Face repository"
+    )

482-485: Improve disaggregated mode error message

The error message could be more helpful by indicating when support might be available or what alternatives exist.

 if _is_disagg():
     raise ValueError(
-        "Phi4MM does not support disaggregated inference yet.")
+        "Phi4MM does not support disaggregated inference yet. "
+        "Please use AGGREGATE mode by setting TLLM_MULTIMODAL_DISAGGREGATED=0"
+    )

163-265: Consider memory optimization for batched inference

The batch inference methods create zero-initialized tensors for padding (lines 187-193, 237-244). For large batch sizes or high-resolution images, this could consume significant memory.

Consider these optimizations:

  1. Use sparse representations when padding ratio is high
  2. Pre-allocate and reuse buffers across inference calls
  3. Add memory profiling to track peak usage

Would you like me to suggest a memory-efficient implementation using buffer pooling?


267-332: The _encoding_per_request method has redundant tensor operations

The method processes each request individually, which could be inefficient for batches. Also, the tensor masking operations (lines 291-292, 328-329) are performed per request.

Consider caching common operations or moving invariant computations outside the loop. The current implementation is correct but could be optimized when this becomes the production path.

📜 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 between 3755f8a and 4e71288.

📒 Files selected for processing (1)
  • tensorrt_llm/_torch/models/modeling_phi4mm.py (10 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Filenames compiled into a target must be case-insensitively unique

Files:

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

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Use spaces, not tabs; indent 4 spaces

Files:

  • tensorrt_llm/_torch/models/modeling_phi4mm.py
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: Code must target Python 3.8+
Indent with 4 spaces; do not use tabs (Python)
Maintain module namespace on import: prefer from package.subpackage import foo; use foo.Symbol()
Python filenames use snake_case
Python class names use PascalCase
Python functions and methods use snake_case
Python local variables use snake_case; if starting with a number concept, prefix with k (e.g., k_99th_percentile)
Python global variables use G_ prefix with UPPER_SNAKE_CASE
Python constants use UPPER_SNAKE_CASE
Avoid shadowing variables from outer scopes
Initialize all externally visible class members in init
For public interfaces, prefer docstrings over comments; comments should be for in-function or file-local interfaces
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes and variables inline with docstrings immediately after assignment
Avoid reflection when a non-reflective approach suffices
Limit except clauses to specific exceptions where possible
When using try/except for duck-typing, keep try body minimal and move logic to else

Files:

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

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

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

Files:

  • tensorrt_llm/_torch/models/modeling_phi4mm.py
🧠 Learnings (1)
📚 Learning: 2025-09-03T13:16:06.824Z
Learnt from: nvpohanh
PR: NVIDIA/TensorRT-LLM#7478
File: tensorrt_llm/_torch/models/modeling_llama.py:1315-1315
Timestamp: 2025-09-03T13:16:06.824Z
Learning: The Llama4VisionEncoder.load_weights method signature is `def load_weights(self, weights: Dict)` and should not be confused with Llama4ForConditionalGeneration.load_weights which has a different signature including weight_mapper parameter.

Applied to files:

  • tensorrt_llm/_torch/models/modeling_phi4mm.py
🧬 Code graph analysis (1)
tensorrt_llm/_torch/models/modeling_phi4mm.py (3)
tensorrt_llm/inputs/multimodal.py (1)
  • MultimodalParams (152-410)
tensorrt_llm/_torch/model_config.py (1)
  • torch_dtype (183-188)
tensorrt_llm/_torch/models/modeling_multimodal_utils.py (1)
  • fuse_input_embeds (108-167)
⏰ 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/_torch/models/modeling_phi4mm.py (2)

1-7: Documentation is helpful and clear

The step-by-step implementation plan clearly outlines the completed and pending work. This helps maintainers understand the current state of the implementation.


103-112: LGTM! Well-structured encoder class definition

The HFPhi4MultimodalEncoder class properly inherits from the required base classes and sets up the necessary configuration attributes for Hugging Face compatibility.

@Wanli-Jiang
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17638 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@Wanli-Jiang Wanli-Jiang merged commit 4e3dded into NVIDIA:main Sep 4, 2025
8 of 9 checks passed
pamelap-nvidia pushed a commit to pamelap-nvidia/TensorRT-LLM that referenced this pull request Sep 9, 2025
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
farazkh80 pushed a commit to farazkh80/TensorRT-LLM that referenced this pull request Sep 9, 2025
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
farazkh80 pushed a commit to farazkh80/TensorRT-LLM that referenced this pull request Sep 14, 2025
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
Signed-off-by: Faraz Khoubsirat <58580514+farazkh80@users.noreply.github.com>
Wong4j pushed a commit to Wong4j/TensorRT-LLM that referenced this pull request Sep 20, 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