-
Notifications
You must be signed in to change notification settings - Fork 2k
[TRTLLM-6637][feat] Move KV cache preparation into ModelEngine #6452
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-6637][feat] Move KV cache preparation into ModelEngine #6452
Conversation
…_engine Signed-off-by: ziyixiong-nv <[email protected]>
📝 WalkthroughWalkthroughThe changes update the control flow for KV cache resource preparation in the PyTorch model execution pipeline. The method for preparing KV cache resources is renamed, and conditional logic is introduced to determine when KV cache preparation should be performed, especially in draft and warmup scenarios. Related adjustments are made in speculative model drafting. Changes
Sequence Diagram(s)sequenceDiagram
participant Engine as PyTorchModelEngine
participant KVCache as KVCacheManager
participant Drafter as ModelDrafter
participant ResourceMgr as ResourceManager
Engine->>Engine: forward()
alt KV cache manager exists AND not in warmup AND not draft model
Engine->>KVCache: prepare_resources_for_requests(scheduled_requests)
else
Engine-->>Engine: Skip KV cache preparation
end
Drafter->>ResourceMgr: get_kv_cache_manager(key)
alt KV cache manager exists
Drafter->>KVCache: prepare_resources_for_requests(scheduled_requests)
end
Drafter->>Drafter: Prepare draft batch
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. ✨ Finishing Touches
🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
|
/bot run |
|
PR_Github #13374 [ 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
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
tensorrt_llm/_torch/pyexecutor/model_engine.py(1 hunks)tensorrt_llm/_torch/pyexecutor/resource_manager.py(1 hunks)tensorrt_llm/_torch/speculative/model_drafter.py(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py
📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)
**/*.py: The code developed for TensorRT-LLM 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 class in the constructor in Python.
For interfaces that may be used outside a file, prefer docstrings over comments in Python.
Comments in Python should be reserved for code within a function, or interfaces that are local to a file.
Use Google style docstrings for classes and functions in Python, which can be parsed by Sphinx.
Attributes and variables in Python can be documented inline; attribute docstrings will be rendered under the docstring for the class.
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/pyexecutor/model_engine.pytensorrt_llm/_torch/speculative/model_drafter.pytensorrt_llm/_torch/pyexecutor/resource_manager.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/pyexecutor/model_engine.pytensorrt_llm/_torch/speculative/model_drafter.pytensorrt_llm/_torch/pyexecutor/resource_manager.py
🧠 Learnings (2)
📓 Common learnings
Learnt from: amitz-nv
PR: NVIDIA/TensorRT-LLM#5616
File: tensorrt_llm/executor/worker.py:375-384
Timestamp: 2025-07-17T09:01:27.402Z
Learning: In tensorrt_llm/executor/worker.py, the LoRA adapter cache optimization logic that checks `is_adapter_in_cpu_cache()` and conditionally passes None for weights/config has a known race condition issue that cannot be solved with simple error handling or verification checks. This is a known limitation that requires a more comprehensive solution.
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
Learnt from: amitz-nv
PR: #5616
File: tensorrt_llm/executor/worker.py:375-384
Timestamp: 2025-07-17T09:01:27.402Z
Learning: In tensorrt_llm/executor/worker.py, the LoRA adapter cache optimization logic that checks is_adapter_in_cpu_cache() and conditionally passes None for weights/config has a known race condition issue that cannot be solved with simple error handling or verification checks. This is a known limitation that requires a more comprehensive solution.
🔇 Additional comments (2)
tensorrt_llm/_torch/speculative/model_drafter.py (1)
345-348: Excellent integration of KV cache preparation for draft models.The addition properly integrates KV cache resource preparation into the draft model workflow. The implementation demonstrates good defensive programming practices:
- Safe retrieval of the KV cache manager using the draft engine's key
- Proper null-checking before method invocation
- Correct usage of the renamed method
prepare_resources_for_requestsThis change aligns well with the PR objective of centralizing KV cache preparation in ModelEngine components.
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
2072-2075: LGTM! Well-implemented KV cache preparation centralization.The conditional logic correctly implements the PR objective of moving KV cache preparation into the ModelEngine. The three conditions for skipping preparation are appropriate:
- No KV cache manager present
- Warmup mode (where preparation isn't needed)
- Draft model (which handles preparation separately in the drafter)
This change effectively addresses the synchronization issues between draft and target KV cache managers mentioned in the PR description.
| def prepare_resources_for_requests(self, | ||
| scheduled_batch: ScheduledRequests): |
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.
💡 Verification agent
🧩 Analysis chain
Method rename looks good and aligns with PR objectives.
The rename from prepare_resources to prepare_resources_for_requests is clear and more descriptive. The implementation remains unchanged, which maintains existing functionality.
Let me verify that all callers have been updated to use the new method name:
🏁 Script executed:
#!/bin/bash
# Description: Verify that all callers use the new method name and no old references remain
# Expected: Only new method name should be found, no calls to old method name on KVCacheManager
echo "=== Searching for old method name 'prepare_resources' on KVCacheManager ==="
rg -A 3 -B 3 "\.prepare_resources\(" --type py
echo "=== Searching for new method name 'prepare_resources_for_requests' ==="
rg -A 3 -B 3 "\.prepare_resources_for_requests\(" --type py
echo "=== Checking for any remaining method definitions with old name ==="
ast-grep --pattern $'def prepare_resources($$$):
$$$'Length of output: 15165
Incomplete rename: remaining prepare_resources definitions and calls must be updated
The new prepare_resources_for_requests method has been added, but there are still many legacy definitions and call-sites of prepare_resources across the codebase. Please rename both the method definitions in the cache managers and all their callers to the new name.
Locations to update:
- tensorrt_llm/_torch/pyexecutor/resource_manager.py
- Rename
prepare_resources→prepare_resources_for_requestsin KVCacheManager and MambaCacheManager class definitions. - Update the composite dispatcher methods where they call
KVCacheManager.prepare_resources(self, …)andMambaCacheManager.prepare_resources(self, …).
- Rename
- tensorrt_llm/_torch/pyexecutor/py_executor.py
- Change all
self.resource_manager.prepare_resources(scheduled_batch)→self.resource_manager.prepare_resources_for_requests(scheduled_batch).
- Change all
- tests/unittest/_torch/test_pytorch_model_engine.py
- Change
kv_cache_manager.prepare_resources(batch)→kv_cache_manager.prepare_resources_for_requests(batch).
- Change
Example diff:
--- a/tensorrt_llm/_torch/pyexecutor/resource_manager.py
@@ class KVCacheManager(BaseManager):
- def prepare_resources(self, scheduled_batch: ScheduledRequests):
+ def prepare_resources_for_requests(self, scheduled_batch: ScheduledRequests):
…
@@ class MambaCacheManager(BaseManager):
- def prepare_resources(self, scheduled_batch: ScheduledRequests):
+ def prepare_resources_for_requests(self, scheduled_batch: ScheduledRequests):
…
@@ CompositeResourceManager.dispatch(…):
- KVCacheManager.prepare_resources(self, scheduled_batch)
- MambaCacheManager.prepare_resources(self, scheduled_batch)
+ KVCacheManager.prepare_resources_for_requests(self, scheduled_batch)
+ MambaCacheManager.prepare_resources_for_requests(self, scheduled_batch)
--- a/tensorrt_llm/_torch/pyexecutor/py_executor.py
@@
- self.resource_manager.prepare_resources(scheduled_batch)
+ self.resource_manager.prepare_resources_for_requests(scheduled_batch)
--- a/tests/unittest/_torch/test_pytorch_model_engine.py
@@
- kv_cache_manager.prepare_resources(batch)
+ kv_cache_manager.prepare_resources_for_requests(batch)🤖 Prompt for AI Agents
In tensorrt_llm/_torch/pyexecutor/resource_manager.py around lines 334-335 and
other related locations, rename all method definitions and calls from
prepare_resources to prepare_resources_for_requests. This includes updating the
method names in KVCacheManager and MambaCacheManager classes, changing calls in
composite dispatcher methods that invoke these cache managers, modifying calls
in tensorrt_llm/_torch/pyexecutor/py_executor.py where
self.resource_manager.prepare_resources is used, and updating
tests/unittest/_torch/test_pytorch_model_engine.py to call
prepare_resources_for_requests instead of prepare_resources. Ensure all
references are consistently renamed to avoid legacy usage.
|
PR_Github #13374 [ run ] completed with state |
mikeiovine
left a comment
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.
I don't think this really solves the KV cache divergence issue. What we should do is get rid of the mutation in kv_cache_manager.add_request. That is: instead of mutating context_current_position when we allocate pages for the request, we should have the model engine ask the KV cache manager how many tokens are cached when it's preparing metadata.
Oh, I misunderstood it. Seems the core point is to remove the usage of |
|
/bot run |
|
PR_Github #13521 [ run ] triggered by Bot |
|
PR_Github #13521 [ run ] completed with state |
…_engine
Summary by CodeRabbit
Description
The KV cache managers for the draft and target must currently be kept "in sync", meaning that if the target KV cache manager chooses to evict a page corresponding to some token prefix, the draft KV cache manager must do the same (and vice versa).
Given that the KV cache managers can be configured differently, it's better to query the KV cache manager in ModelEngine instead of relying on it to mutate the requests.
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.
Details
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.