-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[TRTLLM-7918][feat] Support kvcache reuse and chunk prefill for phi4mm #7723
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-7918][feat] Support kvcache reuse and chunk prefill for phi4mm #7723
Conversation
📝 WalkthroughWalkthroughAdds encoder_kwargs to get_multimodal_embeddings and routes Phi-4-MM embedding generation through this wrapper with mm_token_ids. Updates Phi4MM input processing to inherit BaseMultimodalInputProcessor, exposes mm_token_ids and token-count helpers, and explicitly disallows DISAGG. Documentation matrices updated to mark KV Cache Reuse as Yes for Phi-4-MM. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Caller
participant Phi4MM as Phi4MMForCausalLM
participant Proc as Phi4MMInputProcessor
participant Utils as get_multimodal_embeddings
participant HFEnc as HF Encoder (forward)
participant Utils2 as find_input_mm_embeds
Caller->>Proc: preprocess(inputs)
Proc-->>Caller: multimodal_params
Caller->>Phi4MM: generate(multimodal_params)
Phi4MM->>Phi4MM: mm_token_ids (device-aware)
Phi4MM->>Utils: get_multimodal_embeddings(encoder_forward_fn=HFEnc, multimodal_params[0:num_context_requests], encoder_kwargs={mm_token_ids})
Utils->>HFEnc: forward(params, **encoder_kwargs)
HFEnc-->>Utils: raw_mm_embeddings
Utils-->>Phi4MM: mm_embeddings
Phi4MM->>Utils2: find_input_mm_embeds(mm_embeddings, inputs)
Utils2-->>Phi4MM: input_mm_embeds
Phi4MM->>Phi4MM: fuse_input_embeds(input_ids, input_mm_embeds)
Phi4MM-->>Caller: logits / tokens
rect rgba(255,230,200,0.4)
note over Phi4MM: New: wrapper-based MM embedding path with encoder_kwargs (mm_token_ids)
end
sequenceDiagram
autonumber
participant Caller
participant Phi4MM as Phi4MMForCausalLM
Caller->>Phi4MM: generate(disaggregated=True)
Phi4MM-->>Caller: NotImplementedError ("DISAGG not supported")
rect rgba(255,210,210,0.35)
note over Phi4MM: New explicit error path for DISAGG
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes ✨ 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. Comment Pre-merge checks❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
|
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
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
tensorrt_llm/_torch/models/modeling_multimodal_utils.py (1)
152-156: Potential KeyError when batch has text‑only params.Step 4 blindly reads multimodal_embedding for every param. If any param has no MM content, this will raise. Filter to params with content/cached embeddings.
Apply this diff:
- all_embeddings = torch.cat([ - param.multimodal_data["multimodal_embedding"] - for param in multimodal_params - ], - dim=0) - return [all_embeddings] + valid_params = [ + p for p in multimodal_params + if getattr(p, "has_content", lambda: True)() + and p.multimodal_data.get("multimodal_embedding") is not None + ] + if not valid_params: + return [] + all_embeddings = torch.cat( + [p.multimodal_data["multimodal_embedding"] for p in valid_params], + dim=0, + ) + return [all_embeddings]tensorrt_llm/_torch/models/modeling_phi4mm.py (2)
145-161: Device mismatch risk in _replace_special_token_ids due to CPU tensors in torch.where.Passing torch.tensor(...) (CPU) alongside GPU input_ids will error. Use masked_fill_ with Python ints to avoid allocations and device mismatches.
Apply this diff:
- 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 + def _replace_special_token_ids( + self, input_ids: torch.Tensor + ) -> torch.Tensor: + # In-place replacement; safe on any device. + image_mask = ( + (input_ids >= _COMPATIBLE_IMAGE_SPECIAL_TOKEN_ID_RANGE[0]) + & (input_ids <= _COMPATIBLE_IMAGE_SPECIAL_TOKEN_ID_RANGE[1]) + ) + audio_mask = ( + (input_ids >= _COMPATIBLE_AUDIO_SPECIAL_TOKEN_ID_RANGE[0]) + & (input_ids <= _COMPATIBLE_AUDIO_SPECIAL_TOKEN_ID_RANGE[1]) + ) + input_ids.masked_fill_(image_mask, _IMAGE_SPECIAL_TOKEN_ID) + input_ids.masked_fill_(audio_mask, _AUDIO_SPECIAL_TOKEN_ID) + return input_ids
1-1: Add NVIDIA Apache‑2.0 header (2025).tensorrt_llm/_torch/models/modeling_phi4mm.py is missing the required NVIDIA Apache‑2.0 copyright header at the top — prepend the standard header with year 2025.
🧹 Nitpick comments (7)
docs/source/models/supported-models.md (1)
54-54: Phi4MM: KV cache reuse marked “Yes”. Align with actual runtime flags and note any constraints.
- If reuse requires passing mm_token_ids and the AGGREGATE path, mention it here or in a footnote.
- If chunked prefill is intentionally “No” for now, consider calling that out in the PR description to avoid confusion.
tensorrt_llm/_torch/models/modeling_multimodal_utils.py (1)
113-121: Docstring missing new parameter.Add encoder_kwargs to Args with a brief note (e.g., passes mm_token_ids to encoder).
tensorrt_llm/_torch/models/modeling_phi4mm.py (5)
393-399: Processor ctor signature update looks fine; minor device default note.Defaulting to CPU is functional but slow for encoders. Consider setting self.device = "cuda" when available.
424-432: get_num_tokens_per_image(): robust but add try/except or validation.Some processors may not expose num_img_tokens; wrap with a clear error to avoid KeyError.
- data = self.processor.image_processor.preprocess(image) - return data["num_img_tokens"][0] + data = self.processor.image_processor.preprocess(image) + if "num_img_tokens" not in data: + raise RuntimeError("Processor did not return 'num_img_tokens'.") + return data["num_img_tokens"][0]
597-604: Good: pass mm_token_ids via encoder_kwargs; pairs with new utils API.Add a brief comment that only context requests are encoded here to avoid confusion during reuse.
606-609: Lint: extraneous f‑prefix in string literal (F541).Remove f since there are no placeholders.
Apply this diff:
- raise NotImplementedError( - "Phi-4-multimodal does not support disaggregated inference yet. Please unset " - f"the TLLM_MULTIMODAL_DISAGGREGATED environment variable, or set it to '0'." - ) + raise NotImplementedError( + "Phi-4-multimodal does not support disaggregated inference yet. Please unset " + "the TLLM_MULTIMODAL_DISAGGREGATED environment variable, or set it to '0'." + )
278-286: fuse_input_embeds kwargs is unused (Ruff ARG002).Either remove it (if API allows) or acknowledge it to satisfy linters.
- **kwargs, + **kwargs, @@ - if len(mm_embeds) == 0: + if len(mm_embeds) == 0: + # kwargs kept for forward-compatibility (e.g., precomputed indices). + # Deliberately unused here. + _ = kwargs return input_ids, None
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
docs/source/models/supported-models.md(1 hunks)docs/source/reference/multimodal-feature-support-matrix.md(1 hunks)tensorrt_llm/_torch/models/modeling_multimodal_utils.py(3 hunks)tensorrt_llm/_torch/models/modeling_phi4mm.py(5 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Use only spaces, no tabs; indent with 4 spaces.
Files:
tensorrt_llm/_torch/models/modeling_multimodal_utils.pytensorrt_llm/_torch/models/modeling_phi4mm.py
**/*.py
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.py: Python code must target Python 3.8+.
Indent Python code with 4 spaces; do not use tabs.
Maintain module namespace when importing; prefer 'from package.subpackage import foo' then 'foo.SomeClass()' instead of importing the class directly.
Python filenames should be snake_case (e.g., some_file.py).
Python classes use PascalCase names.
Functions and methods use snake_case names.
Local variables use snake_case; prefix 'k' for variables that start with a number (e.g., k_99th_percentile).
Global variables use upper SNAKE_CASE prefixed with 'G' (e.g., G_MY_GLOBAL).
Constants use upper SNAKE_CASE (e.g., MY_CONSTANT).
Avoid shadowing variables from an outer scope.
Initialize all externally visible members of a class in the constructor.
Prefer docstrings for interfaces that may be used outside a file; comments for in-function or file-local interfaces.
Use Google-style docstrings for classes and functions (Sphinx-parsable).
Document attributes and variables inline so they render under the class/function docstring.
Avoid reflection when a simpler, explicit approach suffices (e.g., avoid dict(**locals()) patterns).
In try/except, catch the most specific exceptions possible.
For duck-typing try/except, keep the try body minimal and use else for the main logic.
Files:
tensorrt_llm/_torch/models/modeling_multimodal_utils.pytensorrt_llm/_torch/models/modeling_phi4mm.py
**/*.{cpp,cxx,cc,h,hpp,hh,hxx,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Prepend the NVIDIA Apache-2.0 copyright header with current year to the top of all source files (e.g., .cpp, .h, .cu, .py).
Files:
tensorrt_llm/_torch/models/modeling_multimodal_utils.pytensorrt_llm/_torch/models/modeling_phi4mm.py
🧬 Code graph analysis (1)
tensorrt_llm/_torch/models/modeling_phi4mm.py (2)
tensorrt_llm/inputs/registry.py (4)
BaseMultimodalInputProcessor(45-178)InputProcessor(22-42)get_mm_token_ids(86-100)get_num_tokens_per_image(130-148)tensorrt_llm/_torch/models/modeling_multimodal_utils.py (3)
find_input_mm_embeds(160-235)fuse_input_embeds(278-332)get_multimodal_embeddings(99-157)
🪛 Ruff (0.12.2)
tensorrt_llm/_torch/models/modeling_phi4mm.py
428-428: Unused method argument: kwargs
(ARG002)
608-608: f-string without any placeholders
Remove extraneous f prefix
(F541)
⏰ 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 (8)
docs/source/reference/multimodal-feature-support-matrix.md (1)
11-11: KV cache reuse flip to “Yes” for Phi‑4‑multimodal looks good; confirm test coverage and gating.Please ensure:
- CI includes at least one KV‑reuse regression for Phi‑4‑MM (prefill→reuse) and failure gates docs if disabled by env/hardware.
- If support is conditional (dtype/GPU arch), add a footnote like other matrices to avoid over‑promising.
docs/source/models/supported-models.md (1)
48-48: Formatting‑only change for Gemma3 row.No content change; fine to keep as is.
tensorrt_llm/_torch/models/modeling_multimodal_utils.py (1)
20-20: Type imports extended (Any/Dict/Optional).Good addition to support encoder_kwargs typing.
tensorrt_llm/_torch/models/modeling_phi4mm.py (5)
21-24: Input processor now derives from BaseMultimodalInputProcessor.Good move; unlocks common MM utilities.
32-34: Using get_multimodal_embeddings/find_input_mm_embeds is the right abstraction.This aligns Phi‑4‑MM with the shared MM pathway.
419-423: get_mm_token_ids() implementation: OK.Explicit, device‑aware return.
610-612: find_input_mm_embeds usage is correct.Slices to uncached/current‑chunk tokens only.
562-565: Confirm mm_token_ids device.Using model.device is fine; just ensure it matches the embed layer device before fuse_input_embeds to avoid extra copies.
99226cc to
4cc4907
Compare
4cc4907 to
a900b2d
Compare
|
/bot run |
|
PR_Github #18764 [ run ] triggered by Bot |
|
PR_Github #18764 [ 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, just a few minor questions
a900b2d to
1016830
Compare
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
1016830 to
3f6cbc7
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #18964 [ run ] triggered by Bot |
|
PR_Github #18964 [ run ] completed with state |
f76aa9d to
56acfea
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #19111 [ run ] triggered by Bot |
|
PR_Github #19111 [ run ] completed with state |
* Only support image modality. * Audio modality is not supported yet. Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
56acfea to
492d41a
Compare
|
/bot reuse-pipeline |
|
PR_Github #19170 [ reuse-pipeline ] triggered by Bot |
|
PR_Github #19170 [ reuse-pipeline ] completed with state |
NVIDIA#7723) Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
NVIDIA#7723) Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
since #7563 is conflicted, we reverted it and add more contents about chunk prefilling in this PR.
Summary by CodeRabbit
New Features
Refactor
Documentation
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.