-
Notifications
You must be signed in to change notification settings - Fork 1.7k
[TRTLLM-6308][feat] Support Aggregate mode for phi4-mm #6820
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 #6820
Conversation
📝 WalkthroughWalkthroughLoads HF Phi4MM encoder components at runtime and introduces HFPhi4MultimodalEncoder to perform aggregator-based multimodal encoding (per-request and batch). Phi4MMForCausalLM and the input processor are refactored to use multimodal payloads and a runtime mm_token_ids; several token-range constants and dynamic-loading helpers are added. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Model as Phi4MMForCausalLM
participant Encoder as HFPhi4MultimodalEncoder
participant Img as Phi4MMImageEmbedding
participant Aud as Phi4MMAudioEmbedding
User->>Model: forward(input_ids, multimodal_data)
Model->>Encoder: encode(multimodal_data, mode=per-request|batch)
alt per-request
loop per sample
Encoder->>Img: encode(image)
Img-->>Encoder: image_emb
Encoder->>Aud: encode(audio)
Aud-->>Encoder: audio_emb
end
else batch
Encoder->>Img: encode(batch_images)
Img-->>Encoder: batched_image_emb
Encoder->>Aud: encode(batch_audios)
Aud-->>Encoder: batched_audio_emb
end
Encoder-->>Model: mm_embedding (+positions, mm_token_ids)
Model->>Model: fuse_input_embeds(mm_embedding)
Model-->>User: logits
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 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
|
/bot run |
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: 0
🧹 Nitpick comments (2)
tensorrt_llm/_torch/models/modeling_phi4mm.py (2)
19-20
: Consider adding copyright header.According to the coding guidelines, all TensorRT-LLM Open Source Software code should contain an NVIDIA copyright header that includes the current year.
54-96
: Consider breaking up the long comment line.Line 55 exceeds the 120 character limit. Consider splitting it:
-# Load the Phi4MM classes from HuggingFace Phi-4-multimodal-instruct repo. -# Remove this function by using the transformers version of Phi4Multimodal when weights/configs are converted to transformers format. +# Load the Phi4MM classes from HuggingFace Phi-4-multimodal-instruct repo. +# Remove this function by using the transformers version of Phi4Multimodal +# when weights/configs are converted to transformers format.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
tensorrt_llm/_torch/models/modeling_phi4mm.py
(10 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py
📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)
**/*.py
: Python code should conform to Python 3.8+.
Indent Python code with 4 spaces. Do not use tabs.
Always maintain the namespace when importing in Python, even if only one class or function from a module is used.
Python filenames should use snake_case (e.g., some_file.py).
Python classes should use PascalCase (e.g., class SomeClass).
Python functions and methods should use snake_case (e.g., def my_awesome_function():).
Python local variables should use snake_case. Prefix k for variable names that start with a number (e.g., k_99th_percentile).
Python global variables should use upper snake_case and prefix G (e.g., G_MY_GLOBAL).
Python constants should use upper snake_case (e.g., MY_CONSTANT).
Avoid shadowing variables declared in an outer scope in Python.
Initialize all externally visible members of a Python class in the constructor.
For interfaces that may be used outside a Python file, prefer docstrings over comments.
Comments in Python should be reserved for code within a function, or interfaces that are local to a file.
Use Google style docstrings for Python classes and functions, which can be parsed by Sphinx.
Attributes and variables in Python can be documented inline; attribute docstrings will be rendered under the class docstring.
Avoid using reflection in Python when functionality can be easily achieved without it.
When using try-except blocks in Python, limit the except to the smallest set of errors possible.
When using try-except blocks to handle multiple possible variable types in Python, keep the body of the try as small as possible, using the else block to implement the logic.
Files:
tensorrt_llm/_torch/models/modeling_phi4mm.py
**/*.{cpp,h,hpp,cc,cxx,cu,py}
📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)
All TensorRT-LLM Open Source Software code should contain an NVIDIA copyright header that includes the current year. This includes .cpp, .h, .cu, .py, and any other source files which are compiled or interpreted.
Files:
tensorrt_llm/_torch/models/modeling_phi4mm.py
🪛 Ruff (0.12.2)
tensorrt_llm/_torch/models/modeling_phi4mm.py
55-55: Line too long (133 > 120)
(E501)
🔇 Additional comments (21)
tensorrt_llm/_torch/models/modeling_phi4mm.py (21)
1-7
: LGTM! Good documentation of implementation phases.The comments clearly document the three-step plan for phi4-mm model support, with step 2 now marked as done. This provides good context for future development.
8-13
: LGTM! Required imports for dynamic module loading.The new imports (
importlib
,os
,sys
,Path
) are necessary for the dynamic loading of Phi4MM classes from HuggingFace code.
33-41
: LGTM! Well-documented special token constants.The special token constants are clearly defined with helpful comments explaining their origin. The compatible range constants will help with backward compatibility during token replacement.
42-47
: Good approach with global placeholders for dynamic loading.Setting these as
None
initially and loading them dynamically helps avoid import errors when the HuggingFace code is not immediately available.
49-52
: LGTM! Clear runtime configuration check.The function provides a clean way to check for disaggregated mode, with a helpful comment about testing benefits.
56-96
: Dynamic module loading implementation looks robust.The function properly manages sys.path modifications, handles exceptions with a finally block to restore sys.path, and includes appropriate error checking for missing files. The use of importlib for dynamic loading is appropriate for this use case.
98-110
: LGTM! Good inheritance hierarchy for the encoder.The class properly inherits from both
PreTrainedModel
andGenerationMixin
, and sets appropriate configuration attributes for Phi4MM compatibility.
111-141
: LGTM! Proper initialization of multimodal components.The initialization correctly sets up both image and audio embedding layers with validation to ensure distinct input IDs for each modality.
142-160
: Consider optimizing tensor operations.The method uses two separate
torch.where
operations without=
parameter for in-place replacement. This is efficient for memory usage.
161-213
: Well-structured batch processing for image embeddings.The method efficiently batches image inputs with proper padding along the patch dimension and handles cases where attention masks might be None.
214-264
: Good parallel structure with image batch processing.The audio batch processing follows the same pattern as image processing, maintaining consistency and making the code easier to maintain.
265-331
: Per-request processing path properly handles all modality combinations.The method correctly handles image-only, audio-only, both, or neither modalities with appropriate conditional logic.
332-377
: Efficient batch processing implementation.The batch processing path properly pads input_ids and delegates to the batch inference methods for each modality. The use of a single batched_hidden_states list as return value is appropriate for batch processing.
378-388
: Good use of environment variable for inference mode selection.The forward method provides flexibility between per-request and batch processing modes via environment variable, with batch as the sensible default.
397-399
: LGTM! Appropriate validation for trust_remote_code.The requirement for
trust_remote_code=True
is necessary for loading custom Phi4MM code from HuggingFace.
419-461
: Good refactoring to return multimodal_data instead of embeddings.The change to return a dictionary of multimodal data allows the aggregator path to process the data appropriately, improving modularity.
469-473
: LGTM! Clear error for unsupported disaggregated mode.The check provides a clear error message when disaggregated mode is attempted.
481-489
: Proper setup for aggregated mode.The code correctly loads Phi4MM classes and initializes the HF encoder only when not in disaggregated mode.
502-539
: LGTM! Proper weight loading and device management.The load_weights method correctly filters and renames weights for the HF encoder, and ensures mm_token_ids are on the correct device.
566-586
: Good integration of multimodal embeddings.The forward method properly handles both aggregated and disaggregated paths (though disaggregated is not yet functional), and correctly fuses multimodal embeddings with text embeddings.
599-645
: LGTM! Proper LoRA configuration for multimodal support.The static methods provide appropriate LoRA configurations for vision and speech modalities with correct target modules and paths.
PR_Github #14940 [ run ] triggered by Bot |
PR_Github #14940 [ run ] completed with state |
/bot run |
Signed-off-by: Wanli Jiang <[email protected]>
3ff7c2d
to
99e1457
Compare
/bot run |
PR_Github #15101 [ run ] triggered by Bot |
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: 1
🧹 Nitpick comments (6)
tensorrt_llm/_torch/models/modeling_phi4mm.py (6)
55-95
: Fix line length issue and improve error handlingThe function has good error handling with the try/finally for sys.path restoration, but there's a line length violation and potential improvement in the validation logic.
-# Remove this function by using the transformers version of Phi4Multimodal when weights/configs are converted to transformers format. +# Remove this function by using the transformers version of Phi4Multimodal +# when weights/configs are converted to transformers format.
56-60
: Consider thread safety for global variable assignmentThe global variable check and assignment could be susceptible to race conditions in multi-threaded environments. Consider using a lock or atomic operations for safer initialization.
+import threading + +_load_lock = threading.Lock() + def _load_phi4mm_classes(local_path): """Load Phi4MM classes from the specified local path.""" global Phi4MMAudioEmbedding, Phi4MMImageEmbedding, Phi4MMConfig - if Phi4MMAudioEmbedding is not None and Phi4MMImageEmbedding is not None and Phi4MMConfig is not None: - return + + with _load_lock: + if Phi4MMAudioEmbedding is not None and Phi4MMImageEmbedding is not None and Phi4MMConfig is not None: + return + # ... rest of the function
142-159
: Potential performance issue with in-place tensor operationsThe special token ID replacement uses
torch.where
without=input_ids
which modifies the input tensor in-place. This could cause issues if the input tensor is used elsewhere or if gradients are needed.def _replace_special_token_ids(self, input_ids: torch.Tensor) -> torch.Tensor: - # Inplace-replacement for special token ids. - torch.where( - (input_ids >= _COMPATIBLE_IMAGE_SPECIAL_TOKEN_ID_RANGE[0]) - & (input_ids <= _COMPATIBLE_IMAGE_SPECIAL_TOKEN_ID_RANGE[1]), - torch.tensor(_IMAGE_SPECIAL_TOKEN_ID), - input_ids, - out=input_ids, - ) - torch.where( - (input_ids >= _COMPATIBLE_AUDIO_SPECIAL_TOKEN_ID_RANGE[0]) - & (input_ids <= _COMPATIBLE_AUDIO_SPECIAL_TOKEN_ID_RANGE[1]), - torch.tensor(_AUDIO_SPECIAL_TOKEN_ID), - input_ids, - out=input_ids, - ) - return input_ids + # Replace special token ids (creates new tensor to avoid modifying input) + input_ids = input_ids.clone() + input_ids = torch.where( + (input_ids >= _COMPATIBLE_IMAGE_SPECIAL_TOKEN_ID_RANGE[0]) + & (input_ids <= _COMPATIBLE_IMAGE_SPECIAL_TOKEN_ID_RANGE[1]), + torch.tensor(_IMAGE_SPECIAL_TOKEN_ID, device=input_ids.device), + input_ids, + ) + input_ids = torch.where( + (input_ids >= _COMPATIBLE_AUDIO_SPECIAL_TOKEN_ID_RANGE[0]) + & (input_ids <= _COMPATIBLE_AUDIO_SPECIAL_TOKEN_ID_RANGE[1]), + torch.tensor(_AUDIO_SPECIAL_TOKEN_ID, device=input_ids.device), + input_ids, + ) + return input_ids
161-212
: Potential memory inefficiency in batching logicThe batching logic creates full-sized tensors and then fills them selectively. For sparse data, this could be memory-inefficient. Consider using more memory-efficient approaches for large batch sizes.
The current implementation pre-allocates full tensors with zeros and then selectively fills them. For better memory efficiency, especially with sparse multimodal data, consider using tensor concatenation or a more dynamic allocation approach.
332-377
: Verify batch encoding correctnessThe batch encoding implementation looks correct but needs validation to ensure it produces identical results to the per-request path. The TODO comment on Line 383 suggests this validation is still pending.
Would you like me to generate a unit test that compares the outputs of both encoding paths to ensure they produce equivalent results?
573-579
: Clarify disaggregated path statusThe comment indicates this path is not functional yet. Consider adding a more prominent warning or removing this path entirely until it's ready.
- # This path is not functional now. `multimodal_params` will be prepared in PyExecutor. + # TODO: This disaggregated path is not yet implemented. + # multimodal_params preparation will be handled in PyExecutor. + raise NotImplementedError("Disaggregated inference path is not yet functional")
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
tensorrt_llm/_torch/models/modeling_phi4mm.py
(10 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_phi4mm.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_phi4mm.py
🪛 Ruff (0.12.2)
tensorrt_llm/_torch/models/modeling_phi4mm.py
55-55: Line too long (133 > 120)
(E501)
⏰ 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 (13)
tensorrt_llm/_torch/models/modeling_phi4mm.py (13)
50-51
: LGTM - Good abstraction for disaggregated mode detectionThe runtime lookup approach makes this more testable compared to using a module-wide constant.
98-140
: LGTM - Well-structured HF integrationThe HFPhi4MultimodalEncoder class follows the established patterns for transformers integration. The initialization properly handles configuration and embedding setup.
214-263
: LGTM - Consistent batching patternThe audio batching logic follows the same pattern as image batching, maintaining consistency across the codebase.
265-330
: LGTM - Clear per-request encoding implementationThe per-request encoding provides a clear reference implementation that's useful for debugging and validation.
378-387
: LGTM - Good environment variable controlThe environment variable toggle between per-request and batch inference provides flexibility for debugging and development.
397-399
: Good improvement to error handlingReplacing the assertion with a proper
ValueError
is a good improvement that provides clearer error messaging.
401-401
: LGTM - Sensible device defaultChanging the default device to 'cpu' is sensible for the input processor, as device placement should be handled explicitly elsewhere.
448-460
: LGTM - Clean multimodal data packagingThe multimodal data packaging approach is clean and well-structured for the aggregate mode.
470-472
: LGTM - Clear disaggregation limitationThe early check and clear error message for disaggregated inference is appropriate.
481-488
: LGTM - Proper HF model initializationThe HF model setup follows good practices with proper evaluation mode and dtype configuration.
503-513
: LGTM - Appropriate weight filtering and loadingThe weight filtering logic properly maps the weights from the TensorRT-LLM format to the HF model format.
535-538
: LGTM - Proper device placement for token IDsThe runtime assignment of
mm_token_ids
with proper device placement is well-implemented.
567-584
: LGTM - Clean multimodal embedding integrationThe integration of multimodal embeddings through
fuse_input_embeds
is clean and follows the established pattern.
PR_Github #15101 [ run ] completed with state |
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.
LGTM. There were no updates to modeling_phi4mm.py
after release/1.0 branch out.
Signed-off-by: Wanli Jiang <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Wanli Jiang <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
The code changes have been merged into main branch (#6184), cherry-pick to release/1.0 branch now.
Summary by CodeRabbit
New Features
Improvements
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 thestage-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.