Skip to content

feat: support KV reuse in llava raw embedding case - #11967

Closed
furionw wants to merge 1 commit into
NVIDIA:mainfrom
furionw:qiwa/llava_raw_embedding_kv_reuse
Closed

furionw wants to merge 1 commit into
NVIDIA:mainfrom
furionw:qiwa/llava_raw_embedding_kv_reuse

Conversation

@furionw

@furionw furionw commented Mar 6, 2026 •

Copy link
Copy Markdown

Why

When LLaVA-Next receives pre-computed (raw) embeddings from an external encoder, the _process_raw_embedding path does not produce multimodal_input metadata. Without it, the KV cache block-reuse mechanism cannot identify which token spans correspond to multimodal content, so cached KV blocks are never matched — defeating prefix caching for the disaggregated encode → prefill → decode pipeline.

What Changed

  • In _process_raw_embedding, compute per-image token counts, content-based hashes (default_hasher / hexdigest_to_int32), and start positions (find_mm_token_positions), then build a MultimodalInput and return it alongside the embeddings so the KV cache reuse path has the same metadata as the vision-processing path.

Test Plan

  • E2E test with disaggregated encoder + prefill/decode pipeline (existing e_pd_embedding_e2e_test.sh)
  • Verify KV cache hit rate increases when the same image is sent repeatedly
curl -s localhost:8000/v1/chat/completions -H "Content-Type: application/json" -d '{
  "model": "llava-hf/llava-v1.6-mistral-7b-hf",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "image_url",
          "image_url": {
            "url": "https://vllm-public-assets.s3.us-west-2.amazonaws.com/multimodal_asset/duck.jpg"
          }
        },
        {
          "type": "text",
          "text": "What is in this image?"
        }
      ]
    }
  ],
  "max_tokens": 300
}'

Prior to this PR, I will get the below error with the 2nd identical request (because of KV cache hit)

"/opt/dynamo/venv/lib/python3.12/site-packages/tensorrt_llm/_torch/models/modeling_multimodal_utils.py", line 354, in fuse_input_embeds
    raise ValueError(
ValueError: Multimodal token count mismatch: found 0 image tokens in input_ids but received 2046 image embeddings. This is likely due to KV cache reuse, chunk prefill, or other optimizations that cause token count mismatches within the inference batch.

After this PR, multiple identical requests will yield successfully with identical response

Summary by CodeRabbit

  • New Features
    • Enhanced multimodal input handling with improved token positioning and hash computation for image embeddings.
    • Added KV cache reuse optimization for multimodal scenarios, improving memory efficiency and inference performance in multi-image processing.
    • Implemented comprehensive metadata management for multimodal inputs to support advanced image handling capabilities.

@furionw
furionw requested a review from a team as a code owner March 6, 2026 02:30
@furionw
furionw requested a review from yechank-nvidia March 6, 2026 02:30
@coderabbitai

coderabbitai Bot commented Mar 6, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Enhanced the attach_multimodal_embeddings function in the LLaVA Next model to compute multimodal metadata including per-image token counts, MM hashes derived from embeddings, and token start positions. These components are packaged into a MultimodalInput object for KV cache reuse.

Changes

Cohort / File(s) Summary
Multimodal Metadata Computation
tensorrt_llm/_torch/models/modeling_llava_next.py
Added imports for multimodal utilities and types. Enhanced attach_multimodal_embeddings to compute MM hashes from image embeddings (with dtype conversion for bf16), determine token start positions via find_mm_token_positions, and construct MultimodalInput metadata. Updated function docstring and return signature to include multimodal_input in ExtraProcessedInputs.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The PR description provides comprehensive context (Why, What Changed, Test Plan) explaining the issue and solution. However, it lacks the required title format with ticket ID/issue and does not follow the template structure for the standard PR description. Align PR title with the template format by adding a ticket/issue identifier (e.g., [TRTLLM-xxxx] or [#xxxx]) and consider using the standard description template structure with Description, Test Coverage, and PR Checklist sections.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: support KV reuse in llava raw embedding case' clearly and specifically describes the main change: adding KV cache reuse support for LLaVA-Next's raw embedding path.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
tensorrt_llm/_torch/models/modeling_llava_next.py (1)

18-21: Consider importing the module instead of individual classes/functions.

Per coding guidelines, Python imports should use from package.subpackage import module form to maintain namespaces. While the existing imports in this file (lines 23-28) follow the same direct-import pattern, consider aligning with the guideline for new additions.

♻️ Suggested refactor
-from tensorrt_llm.inputs.multimodal import (MultimodalInput, MultimodalParams,
-                                            default_hasher,
-                                            find_mm_token_positions,
-                                            hexdigest_to_int32)
+from tensorrt_llm.inputs import multimodal

Then update usages:

  • multimodal.MultimodalInput
  • multimodal.MultimodalParams
  • multimodal.default_hasher
  • multimodal.find_mm_token_positions
  • multimodal.hexdigest_to_int32

As per coding guidelines: "Python imports must use form from package.subpackage import module (never from module import Class)".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tensorrt_llm/_torch/models/modeling_llava_next.py` around lines 18 - 21,
Replace the direct imports of MultimodalInput, MultimodalParams, default_hasher,
find_mm_token_positions, and hexdigest_to_int32 with a module import (import
tensorrt_llm.inputs.multimodal as multimodal) and update all references in this
file to use the module namespace (e.g., replace MultimodalInput ->
multimodal.MultimodalInput, MultimodalParams -> multimodal.MultimodalParams,
default_hasher -> multimodal.default_hasher, find_mm_token_positions ->
multimodal.find_mm_token_positions, hexdigest_to_int32 ->
multimodal.hexdigest_to_int32) so the file follows the package.module import
guideline.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@tensorrt_llm/_torch/models/modeling_llava_next.py`:
- Around line 18-21: Replace the direct imports of MultimodalInput,
MultimodalParams, default_hasher, find_mm_token_positions, and
hexdigest_to_int32 with a module import (import tensorrt_llm.inputs.multimodal
as multimodal) and update all references in this file to use the module
namespace (e.g., replace MultimodalInput -> multimodal.MultimodalInput,
MultimodalParams -> multimodal.MultimodalParams, default_hasher ->
multimodal.default_hasher, find_mm_token_positions ->
multimodal.find_mm_token_positions, hexdigest_to_int32 ->
multimodal.hexdigest_to_int32) so the file follows the package.module import
guideline.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 7ee1b4bd-cbf9-4f71-a999-41d0a5b31294

📥 Commits

Reviewing files that changed from the base of the PR and between 5f1fb7c and 2be1bb0.

📒 Files selected for processing (1)
  • tensorrt_llm/_torch/models/modeling_llava_next.py

@svc-trtllm-gh-bot svc-trtllm-gh-bot added the Community want to contribute PRs initiated from Community label Mar 6, 2026
@pengbowang-nv
pengbowang-nv requested a review from a team March 6, 2026 07:16
@pengbowang-nv

Copy link
Copy Markdown
Collaborator

@NVIDIA/trt-llm-torch-models-vlm-devs Hi could you take a look at this? It is a multimodal issue. Maybe @chang-l can take a look as you are the author of this file? Thanks!

@moraxu moraxu self-assigned this Mar 7, 2026
@brnguyen2

Copy link
Copy Markdown
Collaborator

👋 As part of an effort to reduce the TensorRT-LLM open-PR backlog, we're checking in on PRs with no activity in over 120 days. This one qualifies.

Could you let us know whether you still plan to land it?

  • If yes: please rebase onto the latest main, resolve any merge conflicts, and re-request review (or just leave a comment with where it stands).
  • If it's no longer needed: you can close it, or let us know and we'll close it for you.

If we don't hear back within 14 days, we'll close this PR to keep the review queue manageable. Closing isn't a rejection: the branch, commits, and discussion are all preserved, and you can reopen or resubmit at any time.

Thanks for the contribution!

@brnguyen2

Copy link
Copy Markdown
Collaborator

👋 Closing this as part of the TensorRT-LLM open-PR backlog cleanup. We pinged on 2026-08-10 about 120+ days of inactivity and didn't hear back within the 14-day window.

This isn't a rejection — your branch, commits, and discussion are all preserved. If it's still relevant, just reopen the PR any time and we'll pick it back up; please rebase onto the latest main when you do. Thanks again for the contribution!

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.

6 participants