-
Notifications
You must be signed in to change notification settings - Fork 1.7k
[None][fix] Revert phi4-mm aggregate mode #6907
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
Conversation
📝 WalkthroughWalkthroughReplaces the disaggregated Phi4MM encoder with a runtime HuggingFace-based multimodal encoder loaded via from_pretrained; updates input processing to require model_path and emit a single multimodal_embedding; adds runtime loading support, MM token IDs, and fuses multimodal embedding into the LM input. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant InputProcessor as Phi4MMInputProcessor
participant HF as HF Phi4MM (from_pretrained)
participant Encoder as phi4mm_modal_encoder
participant WTE as phi4mm_wte
participant LM as Phi4MMForCausalLM
User->>InputProcessor: init(model_path, config, tokenizer, trust_remote_code)
InputProcessor->>HF: from_pretrained(model_path, trust_remote_code, flash_attention_2)
HF-->>InputProcessor: encoder & wte moved to CUDA
User->>InputProcessor: preprocess(text, images/audio)
InputProcessor->>Encoder: multimodal_forward(PIL images/audio)
Encoder-->>InputProcessor: mm_features
InputProcessor->>InputProcessor: filter MM positions → multimodal_embedding
InputProcessor-->>LM: tokens + multimodal_embedding
LM->>LM: fuse_input_embeds(input_embeds, multimodal_embedding, MM_TOKEN_IDS)
LM-->>User: logits/output
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested reviewers
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ 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.
Approving the revert, but I would be remiss if I didn't point out that the original PR likely would have made the cut for release/1.0
if CI weren't so flaky.
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
🔭 Outside diff range comments (1)
tensorrt_llm/_torch/models/modeling_phi4mm.py (1)
90-95
: Add error handling for tensor-to-PIL conversion.The conversion from normalized tensors to PIL images lacks error handling. Invalid tensor shapes or values could cause runtime errors.
if images is not None: if isinstance(images[0], torch.Tensor): # Convert normalized tensors (0-1) to PIL images (0-255). - images = [ - Image.fromarray((image.permute(1, 2, 0) * 255).to( - torch.uint8).cpu().numpy()) for image in images - ] + try: + converted_images = [] + for image in images: + if image.dim() != 3 or image.shape[0] not in [1, 3, 4]: + raise ValueError(f"Invalid image tensor shape: {image.shape}") + img_array = (image.permute(1, 2, 0) * 255).clamp(0, 255).to(torch.uint8).cpu().numpy() + converted_images.append(Image.fromarray(img_array)) + images = converted_images + except Exception as e: + raise ValueError(f"Failed to convert tensor to PIL image: {e}")
🧹 Nitpick comments (4)
tensorrt_llm/_torch/models/modeling_phi4mm.py (4)
3-3
: Update or remove the TODO comment.Since this PR reverts the aggregate mode support that was just implemented, this TODO comment about implementing aggregate mode is now outdated and misleading. Either update it to reflect the current state or remove it.
-# (todo) step 2: refactor the inference pipeline to use AGGREGATE mode (https://github.com/NVIDIA/TensorRT-LLM/pull/5522). +# (reverted) step 2: refactor the inference pipeline to use AGGREGATE mode - reverted in PR #6907
29-33
: Document the workaround for transformers compatibility.This custom PreTrainedModel class appears to be a workaround for a transformers version upgrade. Consider adding a more detailed docstring explaining why this is needed and when it can be removed.
# Create a PreTrainedModel class for transformers=4.53.1 upgrade. # Core idea is to provide `prepare_inputs_for_generation` method from `GenerationMixin`. class NewPreTrainedModel(transformers.modeling_utils.PreTrainedModel, transformers.generation.GenerationMixin): + """Temporary workaround for transformers 4.53.1 compatibility. + + This class bridges compatibility by combining PreTrainedModel with GenerationMixin + to provide the prepare_inputs_for_generation method required by newer transformers versions. + This can be removed once the minimum transformers version requirement is updated. + """ pass
127-130
: Verify mask application efficiency.The multimodal token masking creates boolean masks for each token type and then combines them. For large sequences, this could be optimized.
- image_token_mask = inputs['input_ids'] == _IMAGE_SPECIAL_TOKEN_ID - audio_token_mask = inputs['input_ids'] == _AUDIO_SPECIAL_TOKEN_ID - mm_token_mask = image_token_mask | audio_token_mask + # Combine token ID checks in a single operation for better efficiency + mm_token_mask = torch.isin(inputs['input_ids'], torch.tensor([_IMAGE_SPECIAL_TOKEN_ID, _AUDIO_SPECIAL_TOKEN_ID], device=inputs['input_ids'].device))
25-26
: Document the special token IDs.The special token IDs should have more detailed documentation explaining their purpose and relationship to the tokenizer vocabulary.
# Special tokens -_IMAGE_SPECIAL_TOKEN_ID = 200010 # '<|endoftext10|>' -_AUDIO_SPECIAL_TOKEN_ID = 200011 # '<|endoftext11|>' +# Special tokens for multimodal inputs +# These IDs correspond to special tokens in the Phi4MM tokenizer vocabulary +_IMAGE_SPECIAL_TOKEN_ID = 200010 # '<|endoftext10|>' - Used to mark image positions in input +_AUDIO_SPECIAL_TOKEN_ID = 200011 # '<|endoftext11|>' - Used to mark audio positions in input
📜 Review details
Configuration used: .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 settings in your CodeRabbit configuration.
📒 Files selected for processing (1)
tensorrt_llm/_torch/models/modeling_phi4mm.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_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
84-84: Local variable mm_processor_kwargs
is assigned to but never used
Remove assignment to unused variable mm_processor_kwargs
(F841)
PR_Github #15330 [ run ] triggered by Bot |
/bot run |
PR_Github #15334 [ run ] triggered by Bot |
PR_Github #15330 [ run ] completed with state |
Signed-off-by: Anurag Mukkara <[email protected]>
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: 7
🔭 Outside diff range comments (1)
tensorrt_llm/_torch/models/modeling_phi4mm.py (1)
89-95
: Potential IndexError when images is an empty list; also clamp before scaling.
images[0]
will crash for[]
. Clamp values to [0,1] before scaling to uint8.- if images is not None: - if isinstance(images[0], torch.Tensor): + if images: + if isinstance(images[0], torch.Tensor): # Convert normalized tensors (0-1) to PIL images (0-255). - images = [ - Image.fromarray((image.permute(1, 2, 0) * 255).to( - torch.uint8).cpu().numpy()) for image in images - ] + images = [ + Image.fromarray( + (image.permute(1, 2, 0).clamp(0, 1) * 255) + .to(torch.uint8) + .cpu() + .numpy() + ) + for image in images + ]
♻️ Duplicate comments (3)
tensorrt_llm/_torch/models/modeling_phi4mm.py (3)
61-73
: Global monkey-patching of transformers.PreTrainedModel is unsafe and not exception-safe.This can cause race conditions and persistent global side-effects if an exception occurs during model loading.
Make the patching atomic and exception-safe with a lock and try/finally.
- OldPreTrainedModel = transformers.modeling_utils.PreTrainedModel - transformers.modeling_utils.PreTrainedModel = NewPreTrainedModel - # TODO: Make separate Phi4VisionEncoder and Phi4AudioEncoder, and move them to LLM-side. - ref_phi4mm_model = transformers.AutoModelForCausalLM.from_pretrained( - model_path, - trust_remote_code=True, - # Flash_attn_2 only supports bf16 or fp16 and set in HF config. - torch_dtype='auto', - _attn_implementation='flash_attention_2', - ).eval() - transformers.modeling_utils.PreTrainedModel = OldPreTrainedModel + _model_load_lock = threading.Lock() + with _model_load_lock: + OldPreTrainedModel = transformers.modeling_utils.PreTrainedModel + try: + transformers.modeling_utils.PreTrainedModel = NewPreTrainedModel + # TODO: Make separate Phi4VisionEncoder and Phi4AudioEncoder, and move them to LLM-side. + ref_phi4mm_model = transformers.AutoModelForCausalLM.from_pretrained( + model_path, + trust_remote_code=True, + # Flash_attn_2 only supports bf16 or fp16 and set in HF config. + torch_dtype='auto', + _attn_implementation='flash_attention_2', + ).eval() + finally: + transformers.modeling_utils.PreTrainedModel = OldPreTrainedModelAdditionally, ensure the module imports threading:
# near other imports import threadingAnd validate expected attributes on the loaded model to fail fast:
ref_phi4mm_model = transformers.AutoModelForCausalLM.from_pretrained( @@ ).eval() + if not hasattr(ref_phi4mm_model.model, "embed_tokens_extend"): + raise AttributeError("Loaded model is missing 'embed_tokens_extend'; ensure the Phi-4 MM variant is used.")
84-85
: Remove unused variablemm_processor_kwargs
.This triggers Ruff F841 and is dead code.
- text_prompt, mm_data, mm_processor_kwargs = inputs.get("prompt"), \ - inputs.get("multi_modal_data", {}), inputs.get("mm_processor_kwargs", {}) + text_prompt = inputs.get("prompt") + mm_data = inputs.get("multi_modal_data", {})
217-223
: Validate multimodal data before access and surface clear errors.Avoid AttributeError/KeyError by validating structure before indexing.
- if len(multimodal_params) > 0: - mm_embeds = [ - multimodal_param.multimodal_data["multimodal_embedding"] - for multimodal_param in multimodal_params - ] + if len(multimodal_params) > 0: + mm_embeds = [] + for idx, multimodal_param in enumerate(multimodal_params): + if not hasattr(multimodal_param, 'multimodal_data') or not isinstance(multimodal_param.multimodal_data, dict): + raise ValueError(f"multimodal_param[{idx}] missing valid 'multimodal_data'") + if "multimodal_embedding" not in multimodal_param.multimodal_data: + raise KeyError(f"multimodal_param[{idx}] missing 'multimodal_embedding'") + mm_embeds.append(multimodal_param.multimodal_data["multimodal_embedding"])
🧹 Nitpick comments (4)
tensorrt_llm/_torch/models/modeling_phi4mm.py (4)
98-101
: Confirm AutoProcessor returns a .to()-capable object.BatchFeature typically supports
.to
, but some processors can return Python lists for missing modalities. Add a defensive conversion for CPU fallback or missing keys.If needed:
- Wrap with
isinstance(inputs, transformers.feature_extraction_utils.BatchFeature)
before calling.to
.- Alternatively, move tensors individually to
self.device
.
224-229
: Possible dtype/device mismatch between input_ids and MM_TOKEN_IDS.Ensure
input_ids
dtype equalstorch.long
and device matches the model’s device; otherwise==
and indexing infuse_input_embeds
can fail or trigger slow copies.Consider normalizing upstream:
- Ensure
input_ids
aretorch.long
on the same device as embeddings before callingfuse_input_embeds
.
24-26
: Hardcoding special token IDs is brittle.If upstream token IDs change, masking/fusion breaks. Prefer resolving from tokenizer/config with a runtime assert.
Example approach during InputProcessor init:
- Validate
_IMAGE_SPECIAL_TOKEN_ID
and_AUDIO_SPECIAL_TOKEN_ID
equal tokenizer’s special token IDs (if available), otherwise warn or override via model config.
29-33
: NewPreTrainedModel lacks documentation.Add a short docstring explaining why this MRO shim is needed for the specific transformers version upgrade.
📜 Review details
Configuration used: .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 settings in your CodeRabbit configuration.
📒 Files selected for processing (1)
tensorrt_llm/_torch/models/modeling_phi4mm.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_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
84-84: Local variable mm_processor_kwargs
is assigned to but never used
Remove assignment to unused variable mm_processor_kwargs
(F841)
⏰ 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
/bot skip --comment "Revert PR. Just changes one file, with no conflicts on release branch since original PR" |
PR_Github #15339 [ skip ] triggered by Bot |
PR_Github #15334 [ run ] completed with state |
PR_Github #15339 [ skip ] completed with state |
Signed-off-by: Anurag Mukkara <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Signed-off-by: Anurag Mukkara <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
This reverts #6820. Not accepting feature changes to release/1.0.
Summary by CodeRabbit
New Features
Refactor
Breaking Changes
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.