-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[TRTLLM-6308][feat] Support Aggregate mode for phi4-mm #7521
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[TRTLLM-6308][feat] Support Aggregate mode for phi4-mm #7521
Conversation
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
📝 WalkthroughWalkthroughIntroduces 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
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)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
There was a problem hiding this 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 clearlyThe 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 centralizedThe
PHI4_MM_PER_REQUEST_INFERenvironment variable check duplicates the pattern seen withTLLM_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 informativeThe 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 messageThe 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 inferenceThe 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:
- Use sparse representations when padding ratio is high
- Pre-allocate and reuse buffers across inference calls
- 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 operationsThe 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.
📒 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 clearThe 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 definitionThe HFPhi4MultimodalEncoder class properly inherits from the required base classes and sets up the necessary configuration attributes for Hugging Face compatibility.
|
/bot run |
|
PR_Github #17638 [ run ] triggered by Bot |
|
PR_Github #17638 [ run ] completed with state |
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com> Signed-off-by: Faraz Khoubsirat <58580514+farazkh80@users.noreply.github.com>
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
Summary by CodeRabbit
New Features
Changes
Refactor
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 thestage-listparameter 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.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip 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-pipelineReuse 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.