[None][chore] KV Connector Refactor#11078
Conversation
|
/bot run --disable-fail-fast |
|
PR_Github #33934 [ run ] triggered by Bot. Commit: |
|
PR_Github #33934 [ run ] completed with state
|
📝 WalkthroughWalkthroughThis pull request changes the Changes
Sequence Diagram(s)sequenceDiagram
participant Executor as PyExecutor
participant Connector as KvCacheConnectorManager
participant KVMgr as KVCacheManager
participant Scheduler as Scheduler
Executor->>Executor: _fetch_and_activate_new_requests()
Executor->>Connector: mark_ready_requests(fitting_disagg_gen_init_requests)
Connector-->>Executor: List[LlmRequest]
Executor->>Scheduler: reschedule()
Executor->>KVMgr: prepare_resources()
KVMgr->>KVMgr: add_sequence(req.py_request_id, ...)
alt Sequence Added Successfully
KVMgr->>KVMgr: allocate extra KV tokens
KVMgr->>KVMgr: add draft tokens
KVMgr->>Connector: update_state_after_alloc(block_ids)
else Sequence Add Failed
KVMgr-->>Executor: false
end
Executor->>Connector: get_num_new_matched_tokens()
alt Load KV Async
Connector->>Connector: add to loading state
end
Connector-->>Executor: num_matched_tokens
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Suggested reviewers
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
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 |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp (1)
1-3: Update the copyright year to include 2026.The file was modified this year, so the header should reflect the latest meaningful modification date.
✏️ Proposed update
- * SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.As per coding guidelines: All TensorRT-LLM source files (.cpp, .h, .cu, .py, and other source files) should contain an NVIDIA copyright header with the year of latest meaningful modification.
cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h (1)
1-3: Update the copyright year to include 2026.This header was modified this year, so the header should reflect the latest meaningful modification date.
✏️ Proposed update
- * Copyright (c) 2022-2024, NVIDIA CORPORATION. All rights reserved. + * Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved.As per coding guidelines: All TensorRT-LLM source files (.cpp, .h, .cu, .py, and other source files) should contain an NVIDIA copyright header with the year of latest meaningful modification.
cpp/tensorrt_llm/nanobind/batch_manager/kvCacheManager.cpp (1)
1-3: Update the copyright year to include 2026.This file was modified this year, so the header should reflect the latest meaningful modification date.
✏️ Proposed update
- * SPDX-FileCopyrightText: Copyright (c) 2022-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-FileCopyrightText: Copyright (c) 2022-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.As per coding guidelines: All TensorRT-LLM source files (.cpp, .h, .cu, .py, and other source files) should contain an NVIDIA copyright header with the year of latest meaningful modification.
tensorrt_llm/_torch/pyexecutor/resource_manager.py (1)
463-474: Handle add_sequence failure explicitly to avoid silent allocation gaps.
add_sequencenow returns a bool, but the failure path silently skips token allocation and connector updates while leaving the request scheduled. That can lead to missing KV cache state and downstream failures. Consider surfacing the failure immediately (raise/log + abort scheduling) so it can’t proceed in a half‑initialized state.🔧 Proposed fix
- if self.impl.add_sequence(req.py_request_id, req.prompt_len, - req_beam_width, req): - for _ in range(self.num_extra_kv_tokens): - self.impl.add_token(req.py_request_id) - for _ in range(get_draft_token_length(req)): - self.impl.add_token(req.py_request_id) - - if self.kv_connector_manager is not None: - block_ids = self.get_cache_indices(req) - self.kv_connector_manager.update_state_after_alloc( - req, block_ids) + added = self.impl.add_sequence(req.py_request_id, + req.prompt_len, + req_beam_width, req) + if not added: + raise RuntimeError( + f"KV cache add_sequence failed for request " + f"{req.py_request_id}") + for _ in range(self.num_extra_kv_tokens): + self.impl.add_token(req.py_request_id) + for _ in range(get_draft_token_length(req)): + self.impl.add_token(req.py_request_id) + + if self.kv_connector_manager is not None: + block_ids = self.get_cache_indices(req) + self.kv_connector_manager.update_state_after_alloc( + req, block_ids)
🤖 Fix all issues with AI agents
In `@tensorrt_llm/_torch/pyexecutor/kv_cache_connector.py`:
- Around line 438-458: The bug is inconsistent keying of async-load tracking:
get_num_new_matched_tokens stores entries in new_async_requests.loading keyed by
request.request_id while mark_ready_requests checks and writes using
req.py_request_id, causing missed matches/overwrites; update mark_ready_requests
to consistently use request.request_id (check new_async_requests.loading_ids for
req.request_id, append ready requests the same way, and set
new_async_requests.loading[req.request_id] = req when replacing the canonical
request) so keys match get_num_new_matched_tokens; reference symbols:
mark_ready_requests, get_num_new_matched_tokens, new_async_requests.loading,
new_async_requests.loading_ids, req.request_id, req.py_request_id, and
LlmRequestState.CONTEXT_INIT.
In `@tests/integration/defs/llmapi/test_llm_api_connector.py`:
- Around line 393-402: The test test_connector_disagg_prefill removed the sleep
that ensured asynchronous KV connector callbacks finished, causing racey
asserts; restore synchronization by calling the generate_and_sleep helper after
the prefill_worker.generate and after the decode_worker.generate calls (or
replace those calls with a proper await/wait that blocks until
scheduler.build_connector_meta and related connector callbacks complete) so the
subsequent assertions on scheduler.build_connector_meta.call_count and mock
state are executed only after callbacks have finished.
🧹 Nitpick comments (2)
cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp (1)
2412-2431: Consider warning on duplicate addSequence.Now that duplicates return
false, a warning helps avoid silent no-ops when callers ignore the return value.💡 Suggested tweak
- if (!emplaceDone) - { - return false; - } + if (!emplaceDone) + { + TLLM_LOG_WARNING("[kv cache manager] addSequence ignored; sequence %d already exists", requestId); + return false; + }tests/unittest/_torch/test_connector.py (1)
25-28: Prefer module-level imports to keep namespaces intact.This repo asks for namespace-preserving imports; consider importing the module and qualifying types to avoid
from … import …here.♻️ Suggested refactor
-from tensorrt_llm._torch.pyexecutor.kv_cache_connector import ( - AsyncRequests, KvCacheConnectorManager, - KvCacheConnectorSchedulerOutputManager) -from tensorrt_llm._torch.pyexecutor.llm_request import LlmRequestState +import tensorrt_llm._torch.pyexecutor.kv_cache_connector as kv_cache_connector +import tensorrt_llm._torch.pyexecutor.llm_request as llm_request- req.state = LlmRequestState.GENERATION_IN_PROGRESS + req.state = llm_request.LlmRequestState.GENERATION_IN_PROGRESS ... - manager = KvCacheConnectorSchedulerOutputManager() + manager = kv_cache_connector.KvCacheConnectorSchedulerOutputManager() ... - scheduler_output = manager.build_scheduler_output(scheduled_batch, - AsyncRequests({}, {}), - kv_cache_manager) + scheduler_output = manager.build_scheduler_output( + scheduled_batch, + kv_cache_connector.AsyncRequests({}, {}), + kv_cache_manager)As per coding guidelines, Always maintain the namespace when importing Python modules, even if only one class or function from a module is used.
|
/bot run --disable-fail-fast |
1 similar comment
|
/bot run --disable-fail-fast |
|
PR_Github #34516 [ run ] triggered by Bot. Commit: |
|
PR_Github #34516 [ run ] completed with state |
c229b67 to
5719de3
Compare
@thorjohnsen The primary motivation was to eliminate some additional state tracking login in the KV connector. If the KV connector is loading additional KV cache, after the loading is complete, the request is still in the |
5719de3 to
7e8a096
Compare
|
@thorjohnsen @eopXD can you resolve your threads if you're ok with John's response/changes. Thanks. |
thorjohnsen
left a comment
There was a problem hiding this comment.
This looks good to me. Let's give Eop some time to review his concerns before merge. Thanks!
eopXD
left a comment
There was a problem hiding this comment.
Thank you for patiently addressing my comments John : D
|
@jthomson04 can you resolve the conflict so we can run CI and get it merged? Thanks. |
Signed-off-by: jthomson04 <[email protected]>
Signed-off-by: jthomson04 <[email protected]>
Signed-off-by: jthomson04 <[email protected]>
7e8a096 to
500f3f4
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #36690 [ run ] triggered by Bot. Commit: |
|
PR_Github #36690 [ run ] completed with state |
This reverts commit 0338bb2.
Signed-off-by: jthomson04 <[email protected]>
Signed-off-by: jthomson04 <[email protected]>
Signed-off-by: jthomson04 <[email protected]> Signed-off-by: jthomson04 <[email protected]>
…1872) Signed-off-by: jthomson04 <[email protected]>
Signed-off-by: jthomson04 <[email protected]> Signed-off-by: jthomson04 <[email protected]>
…" (NVIDIA#11872) Signed-off-by: jthomson04 <[email protected]>
…" (NVIDIA#11872) Signed-off-by: jthomson04 <[email protected]>
Summary by CodeRabbit
Bug Fixes
Refactor
Tests
✏️ Tip: You can customize this high-level summary in your review settings.
Implements the remaining refactors from #9186.
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
Update tava architecture diagram if there is a significant design change in PR.
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.
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.