Skip to content

[https://nvbugs/5717993][fix] Add execution_stream across PyExecutor, KVCacheManager, PeftCacheManager to ensure proper CUDA stream synchronization between KV cache transfer operations and model forward kernels.#10060

Merged
SimengLiu-nv merged 6 commits intoNVIDIA:mainfrom
SimengLiu-nv:sync-kvcache-xqa
Dec 31, 2025

Conversation

@SimengLiu-nv
Copy link
Collaborator

@SimengLiu-nv SimengLiu-nv commented Dec 16, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Extended PyExecutor with optional execution_stream parameter for custom CUDA stream configuration during model execution.
    • KVCacheManager and PeftCacheManager now support optional execution_stream specification.
  • Tests

    • Added verification tests for execution_stream propagation and integration across PyExecutor and KVCacheManager components.

✏️ Tip: You can customize this high-level summary in your review settings.

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 the stage-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.

@SimengLiu-nv SimengLiu-nv requested review from a team as code owners December 16, 2025 19:34
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 16, 2025

📝 Walkthrough

Walkthrough

This change threads an optional CUDA execution stream parameter through KV-cache and PyExecutor initialization paths. The stream is propagated from high-level creation through KvCacheCreator, KVCacheManager, PeftCacheManager, and PyExecutor to synchronize forward passes with KV cache transfer/offload operations.

Changes

Cohort / File(s) Summary
Stream parameter propagation in utility and creation layers
tensorrt_llm/_torch/pyexecutor/_util.py, tensorrt_llm/_torch/pyexecutor/py_executor_creator.py
Extended KvCacheCreator and _create_kv_cache_manager signatures to accept optional execution_stream parameter; threaded stream through all KV cache manager construction branches (MLA, NemotronHybrid, Qwen3Next, default). Extended create_py_executor_instance to accept and propagate execution_stream to PEFT cache manager and PyExecutor constructors.
Stream initialization and usage in resource managers
tensorrt_llm/_torch/pyexecutor/resource_manager.py
Added optional execution_stream parameter to KVCacheManager and PeftCacheManager __init__ signatures. Both managers now initialize their internal streams from the provided stream or create new defaults; KVCacheManager passes stream to BufferManager and logs initialization.
Stream storage and context application in executor
tensorrt_llm/_torch/pyexecutor/py_executor.py
Added optional execution_stream parameter to PyExecutor __init__, storing it as instance attribute (defaulting to new CUDA stream if not provided). Warmup and forward execution now run within the execution_stream context for synchronization with KV cache operations.
Test configuration and new functional tests
tests/integration/test_lists/test-db/l0_a100.yml, tests/integration/test_lists/waives.txt, tests/unittest/_torch/executor/test_pytorch_model_engine.py, tests/unittest/_torch/executor/test_resource_manager.py, tests/unittest/llmapi/test_memory_profiling.py
Updated test selectors to target specific test functions. Extended create_model_engine_and_kvcache helper with execution_stream parameter. Added new test test_kv_cache_manager_with_execution_stream verifying stream propagation through forward passes. Added tests for KVCacheManager and PeftCacheManager stream initialization and a comprehensive integration test verifying PyExecutor and KVCacheManager share the same execution stream.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Key areas requiring attention:
    • All four branches within _create_kv_cache_manager (MLA, NemotronHybrid, Qwen3Next, default) to ensure execution_stream=execution_stream is consistently passed to each manager constructor
    • Stream lifecycle in both KVCacheManager and PeftCacheManager: verify that the internal stream is correctly initialized from the provided parameter and that existing code paths (when stream is None) maintain backward compatibility
    • Context manager application in PyExecutor warmup and forward paths—verify the stream context correctly wraps model execution without introducing race conditions
    • Integration test coverage: trace stream identity from PyExecutor creation through resource manager access to KVCacheManager to ensure consistent object references

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description check ⚠️ Warning PR description is incomplete; the template sections (Description, Test Coverage, PR Checklist items) are not filled out with actual content. Fill in the Description section explaining the issue and solution, list relevant test coverage in Test Coverage section, and provide details about changes made and testing performed.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: adding execution_stream across PyExecutor, KVCacheManager, and PeftCacheManager for CUDA stream synchronization, with the NVBugs ID and [fix] type properly formatted.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

🧹 Nitpick comments (1)
tests/unittest/_torch/executor/test_resource_manager.py (1)

837-852: Missing cleanup call for PeftCacheManager.

Unlike the other tests in this file, test_peft_cache_manager_with_execution_stream doesn't call peft_cache_manager.shutdown() at the end. While PeftCacheManager.shutdown() currently does nothing, adding it maintains consistency with other tests and future-proofs against implementation changes.

         # The PeftCacheManager should be created successfully with the provided stream
         self.assertTrue(peft_cache_manager.impl.enabled)
+
+        peft_cache_manager.shutdown()
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dba9036 and 83e47b9.

📒 Files selected for processing (9)
  • tensorrt_llm/_torch/pyexecutor/_util.py (11 hunks)
  • tensorrt_llm/_torch/pyexecutor/py_executor.py (3 hunks)
  • tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (4 hunks)
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py (5 hunks)
  • tests/integration/test_lists/test-db/l0_a100.yml (1 hunks)
  • tests/integration/test_lists/waives.txt (1 hunks)
  • tests/unittest/_torch/executor/test_pytorch_model_engine.py (3 hunks)
  • tests/unittest/_torch/executor/test_resource_manager.py (1 hunks)
  • tests/unittest/llmapi/test_memory_profiling.py (2 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 (e.g., use from package.subpackage import foo and then foo.SomeClass() instead of from package.subpackage.foo import SomeClass)
Python filenames should use snake_case (e.g., some_file.py)
Python class names should use PascalCase (e.g., class SomeClass)
Python function and method names should use snake_case (e.g., def my_awesome_function():)
Python local variable names should use snake_case, with prefix k for variable names that start with a number (e.g., k_99th_percentile = ...)
Python global variables should use upper snake_case with 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 Python class in the constructor
For Python interfaces that may be used outside a file, prefer docstrings over comments
Python comments should be reserved for code within a function, or interfaces that are local to a file
Use Google style docstrings for Python classes and functions, which can be parsed by Sphinx
Python attributes and variables can be documented inline with type and description (e.g., self.x = 5 followed by """<type>: Description of 'x'""" )
Avoid using reflection in Python when functionality can be easily achieved without reflection
When using try-except blocks in Python, limit the except clause to the smallest set of specific errors possible instead of catching all exceptions
When using try-except blocks in Python to handle multiple possible variable types (duck-typing), keep the body of the try as small as possible and use the else block to implement the logic

Files:

  • tests/unittest/llmapi/test_memory_profiling.py
  • tensorrt_llm/_torch/pyexecutor/py_executor_creator.py
  • tests/unittest/_torch/executor/test_pytorch_model_engine.py
  • tests/unittest/_torch/executor/test_resource_manager.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/_torch/pyexecutor/_util.py
**/*.{cpp,h,cu,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

All TensorRT-LLM Open Source Software code files should contain an NVIDIA copyright header that includes the current year at the top

Files:

  • tests/unittest/llmapi/test_memory_profiling.py
  • tensorrt_llm/_torch/pyexecutor/py_executor_creator.py
  • tests/unittest/_torch/executor/test_pytorch_model_engine.py
  • tests/unittest/_torch/executor/test_resource_manager.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/_torch/pyexecutor/_util.py
🧠 Learnings (14)
📚 Learning: 2025-09-17T02:48:52.732Z
Learnt from: tongyuantongyu
Repo: NVIDIA/TensorRT-LLM PR: 7781
File: tests/integration/test_lists/waives.txt:313-313
Timestamp: 2025-09-17T02:48:52.732Z
Learning: In TensorRT-LLM, `tests/integration/test_lists/waives.txt` is specifically for waiving/skipping tests, while other test list files like those in `test-db/` and `qa/` directories are for different test execution contexts (pre-merge, post-merge, QA tests). The same test appearing in both waives.txt and execution list files is intentional - the test is part of test suites but will be skipped due to the waiver.

Applied to files:

  • tests/integration/test_lists/waives.txt
  • tests/integration/test_lists/test-db/l0_a100.yml
📚 Learning: 2025-08-29T14:07:45.863Z
Learnt from: EmmaQiaoCh
Repo: NVIDIA/TensorRT-LLM PR: 7370
File: tests/unittest/trt/model_api/test_model_quantization.py:24-27
Timestamp: 2025-08-29T14:07:45.863Z
Learning: In TensorRT-LLM's CI infrastructure, pytest skip markers (pytest.mark.skip) are properly honored even when test files have __main__ blocks that call test functions directly. The testing system correctly skips tests without requiring modifications to the __main__ block execution pattern.

Applied to files:

  • tests/integration/test_lists/waives.txt
📚 Learning: 2025-09-09T09:40:45.658Z
Learnt from: fredricz-20070104
Repo: NVIDIA/TensorRT-LLM PR: 7645
File: tests/integration/test_lists/qa/llm_function_core.txt:648-648
Timestamp: 2025-09-09T09:40:45.658Z
Learning: In TensorRT-LLM test lists, it's common and intentional for the same test to appear in multiple test list files when they serve different purposes (e.g., llm_function_core.txt for comprehensive core functionality testing and llm_function_core_sanity.txt for quick sanity checks). This duplication allows tests to be run in different testing contexts.

Applied to files:

  • tests/integration/test_lists/waives.txt
  • tests/integration/test_lists/test-db/l0_a100.yml
📚 Learning: 2025-08-26T09:49:04.956Z
Learnt from: pengbowang-nv
Repo: NVIDIA/TensorRT-LLM PR: 7192
File: tests/integration/test_lists/test-db/l0_dgx_b200.yml:56-72
Timestamp: 2025-08-26T09:49:04.956Z
Learning: In TensorRT-LLM test configuration files, the test scheduling system handles wildcard matching with special rules that prevent duplicate test execution even when the same tests appear in multiple yaml files with overlapping GPU wildcards (e.g., "*b200*" and "*gb200*").

Applied to files:

  • tests/integration/test_lists/waives.txt
📚 Learning: 2025-07-28T17:06:08.621Z
Learnt from: moraxu
Repo: NVIDIA/TensorRT-LLM PR: 6303
File: tests/integration/test_lists/qa/examples_test_list.txt:494-494
Timestamp: 2025-07-28T17:06:08.621Z
Learning: In TensorRT-LLM testing, it's common to have both CLI flow tests (test_cli_flow.py) and PyTorch API tests (test_llm_api_pytorch.py) for the same model. These serve different purposes: CLI flow tests validate the traditional command-line workflow, while PyTorch API tests validate the newer LLM API backend. Both are legitimate and should coexist.

Applied to files:

  • tests/integration/test_lists/waives.txt
  • tests/unittest/llmapi/test_memory_profiling.py
  • tests/integration/test_lists/test-db/l0_a100.yml
📚 Learning: 2025-08-06T13:58:07.506Z
Learnt from: galagam
Repo: NVIDIA/TensorRT-LLM PR: 6487
File: tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py:1-12
Timestamp: 2025-08-06T13:58:07.506Z
Learning: In TensorRT-LLM, test files (files under tests/ directories) do not require NVIDIA copyright headers, unlike production source code files. Test files typically start directly with imports, docstrings, or code.

Applied to files:

  • tests/integration/test_lists/waives.txt
📚 Learning: 2025-08-18T08:42:02.640Z
Learnt from: samuellees
Repo: NVIDIA/TensorRT-LLM PR: 6974
File: tensorrt_llm/serve/scripts/benchmark_dataset.py:558-566
Timestamp: 2025-08-18T08:42:02.640Z
Learning: In TensorRT-LLM's RandomDataset (tensorrt_llm/serve/scripts/benchmark_dataset.py), when using --random-token-ids option, sequence length accuracy is prioritized over semantic correctness for benchmarking purposes. The encode/decode operations should use skip_special_tokens=True and add_special_tokens=False to ensure exact target token lengths.

Applied to files:

  • tests/integration/test_lists/waives.txt
📚 Learning: 2025-11-27T09:23:18.742Z
Learnt from: fredricz-20070104
Repo: NVIDIA/TensorRT-LLM PR: 9511
File: tests/integration/defs/examples/serve/test_serve.py:136-186
Timestamp: 2025-11-27T09:23:18.742Z
Learning: In TensorRT-LLM testing, when adding test cases based on RCCA commands, the command format should be copied exactly as it appears in the RCCA case, even if it differs from existing tests. For example, some RCCA commands for trtllm-serve may omit the "serve" subcommand while others include it.

Applied to files:

  • tests/integration/test_lists/waives.txt
📚 Learning: 2025-08-26T09:37:10.463Z
Learnt from: jiaganc
Repo: NVIDIA/TensorRT-LLM PR: 7031
File: tensorrt_llm/bench/dataclasses/configuration.py:90-104
Timestamp: 2025-08-26T09:37:10.463Z
Learning: In TensorRT-LLM, the `get_pytorch_perf_config()` method returns `self.pytorch_config` which can contain default `cuda_graph_config` values, so `llm_args` may already have this config before the extra options processing.

Applied to files:

  • tests/unittest/llmapi/test_memory_profiling.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
📚 Learning: 2025-08-26T09:37:10.463Z
Learnt from: jiaganc
Repo: NVIDIA/TensorRT-LLM PR: 7031
File: tensorrt_llm/bench/dataclasses/configuration.py:90-104
Timestamp: 2025-08-26T09:37:10.463Z
Learning: In TensorRT-LLM's bench configuration, the `get_pytorch_perf_config()` method returns `self.pytorch_config` which is a Dict[str, Any] that can contain default values including `cuda_graph_config`, making the fallback `llm_args["cuda_graph_config"]` safe to use.

Applied to files:

  • tests/unittest/llmapi/test_memory_profiling.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
📚 Learning: 2025-08-19T12:45:11.997Z
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 7033
File: tensorrt_llm/_torch/pyexecutor/model_engine.py:0-0
Timestamp: 2025-08-19T12:45:11.997Z
Learning: In tensorrt_llm/_torch/pyexecutor/model_engine.py, DoRA (Delta Orthogonal Rank Adaptation) functionality was removed from the PyTorch flow to eliminate issues with inverted DoRA detection logic. The original is_dora condition was checking if scaling_vec_pointer == 0, which was potentially incorrect.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/py_executor_creator.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
📚 Learning: 2025-12-12T03:27:08.565Z
Learnt from: tongyuantongyu
Repo: NVIDIA/TensorRT-LLM PR: 9655
File: tensorrt_llm/_torch/pyexecutor/sampler.py:3031-3031
Timestamp: 2025-12-12T03:27:08.565Z
Learning: In files under tensorrt_llm/_torch/pyexecutor, avoid accessing torch.Tensor objects inside for-loops when iterating over requests. Convert batched tensors to Python lists beforehand using tensor.tolist(), and then iterate over those lists. This improves performance by reducing tensor-bound operations inside hot loops. Apply this pattern to similar code paths that process batches to access simple Python data structures (lists) inside loops.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/py_executor_creator.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/_torch/pyexecutor/_util.py
📚 Learning: 2025-08-20T06:56:02.889Z
Learnt from: eopXD
Repo: NVIDIA/TensorRT-LLM PR: 6768
File: cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp:577-579
Timestamp: 2025-08-20T06:56:02.889Z
Learning: In cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp, maxSequenceLength is now enforced as a non-optional argument in the BlockManager constructor, so concerns about std::nullopt defaulting to 0 are not applicable. When windowSize > maxSequenceLength, a warning should be added instead of handling optional parameter cases.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
📚 Learning: 2025-08-26T06:07:02.166Z
Learnt from: shaharmor98
Repo: NVIDIA/TensorRT-LLM PR: 7231
File: tensorrt_llm/_torch/pyexecutor/_util.py:504-509
Timestamp: 2025-08-26T06:07:02.166Z
Learning: In tensorrt_llm/_torch/pyexecutor/_util.py, when calling model_engine.set_lora_model_config(), pass model_binding_config.mlp_hidden_size directly without multiplying by mapping.tp_size, as the mlp_hidden_size from get_bindings_model_config() is already the per-TP rank value needed for LoRA weight packaging.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/_util.py
🧬 Code graph analysis (4)
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (1)
tensorrt_llm/_torch/compilation/multi_stream/auto_multi_stream.py (1)
  • Stream (89-97)
tests/unittest/_torch/executor/test_pytorch_model_engine.py (1)
tests/unittest/_torch/executor/test_resource_manager.py (1)
  • test_kv_cache_manager_with_execution_stream (767-800)
tests/unittest/_torch/executor/test_resource_manager.py (1)
tensorrt_llm/_torch/pyexecutor/resource_manager.py (5)
  • KVCacheManager (151-1256)
  • shutdown (90-91)
  • shutdown (417-418)
  • shutdown (1297-1302)
  • shutdown (1551-1552)
tensorrt_llm/_torch/pyexecutor/_util.py (1)
tensorrt_llm/_torch/pyexecutor/resource_manager.py (1)
  • KVCacheManager (151-1256)
⏰ 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 (26)
tests/integration/test_lists/waives.txt (1)

305-305: LGTM - Targeted test waiver is appropriate.

Narrowing the waiver from the entire module to the specific test_profile_kvcache test allows the new test_pyexecutor_and_kvcache_share_execution_stream test to run while keeping the problematic test skipped. Based on learnings, this follows the correct pattern for waives.txt.

tests/integration/test_lists/test-db/l0_a100.yml (1)

18-19: LGTM - Test targeting aligns with PR objectives.

Adding the new test_pyexecutor_and_kvcache_share_execution_stream test to the pre-merge A100 test suite is appropriate for validating the execution_stream synchronization feature. The inline comments clarify the purpose of each test.

tests/unittest/_torch/executor/test_resource_manager.py (2)

767-800: LGTM - Good test coverage for execution_stream propagation.

The test correctly verifies that KVCacheManager uses the provided execution_stream by comparing the underlying CUDA stream pointers. The cleanup via shutdown() is properly handled.


802-835: LGTM - Backward compatibility test is appropriate.

This test ensures that KVCacheManager creates its own stream when none is provided, maintaining backward compatibility with existing code paths.

tests/unittest/llmapi/test_memory_profiling.py (2)

6-6: LGTM - Import follows namespace convention.

The import from tensorrt_llm._torch.pyexecutor.resource_manager import ResourceManagerType correctly maintains the namespace as per coding guidelines.


81-149: LGTM - Comprehensive test for execution_stream sharing.

The test thoroughly validates that:

  1. Both PyExecutor and KVCacheManager have the execution_stream
  2. The underlying CUDA stream pointers are identical
  3. The stream objects are the exact same instance (not just equal values)

The cleanup with shutdown() and torch.cuda.empty_cache() follows the pattern of the existing test.

tensorrt_llm/_torch/pyexecutor/resource_manager.py (2)

179-179: LGTM - Optional parameter maintains backward compatibility.

The execution_stream parameter defaults to None, ensuring existing callers don't need modification.


355-373: LGTM - Proper stream initialization and propagation.

The implementation correctly:

  1. Uses the provided execution_stream or creates a new one for backward compatibility
  2. Documents the synchronization purpose with KVCacheTransferManager
  3. Passes the underlying CUDA stream pointer to BufferManager
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (4)

604-609: LGTM - Single execution stream creation for proper sharing.

Creating the execution_stream once at the top level and passing it to downstream components ensures that KVCacheManager and PyExecutor share the same CUDA stream, which is the core objective of this PR.


629-629: LGTM - Stream propagated to KvCacheCreator.

The execution_stream is correctly passed to KvCacheCreator, which will propagate it to KVCacheManager during cache manager construction.


687-687: LGTM - Stream propagated to PyExecutor instance.

The execution_stream is passed to create_py_executor_instance, ensuring PyExecutor has access to the same stream used by KVCacheManager.


748-748: LGTM - Stream consistently passed in post-estimation path.

The same execution_stream is passed when recreating the PyExecutor after KV cache estimation, maintaining consistency between the estimation and final execution paths.

tensorrt_llm/_torch/pyexecutor/py_executor.py (3)

139-153: LGTM: Execution stream initialization is well-implemented.

The execution stream is properly stored with a fallback to creating a new stream when none is provided, ensuring backward compatibility. The logging statement aids debugging.

One minor observation: the log message has a trailing period and space before the closing quote which could be cleaned up, but this is cosmetic.


260-268: LGTM: Warmup properly executes within the execution stream context.

Wrapping both model engine warmups inside the stream context ensures proper synchronization with KVCacheTransferManager operations during initialization.


2165-2173: Forward step correctly wrapped in execution stream context.

The model forward runs within the execution_stream context for proper synchronization with KV cache transfer operations.

One consideration: _kv_connector_wait_for_save is called outside the stream context (Line 2173). If this wait needs to synchronize with operations on execution_stream, ensure proper stream synchronization is handled within that method. However, this appears intentional as the wait operation may need to execute on the current stream after exiting the execution_stream context.

tests/unittest/_torch/executor/test_pytorch_model_engine.py (2)

104-142: LGTM: Function signature properly updated with execution_stream parameter.

The create_model_engine_and_kvcache helper function now accepts an optional execution_stream parameter with a default of None, maintaining backward compatibility with existing tests while enabling new stream-based testing.


485-518: LGTM: Comprehensive test for execution_stream propagation.

The test properly verifies:

  1. KVCacheManager uses the provided execution_stream
  2. Forward execution within the stream context
  3. Stream consistency after forward pass
  4. Proper cleanup via shutdown()

The test pattern aligns with the similar test in test_resource_manager.py (Lines 766-799 in relevant snippets), ensuring consistent verification across the codebase.

tensorrt_llm/_torch/pyexecutor/_util.py (9)

59-101: LGTM: KvCacheCreator properly accepts and stores execution_stream.

The execution_stream parameter is correctly added to the constructor and stored as self._execution_stream for use in KV cache manager creation.


501-515: LGTM: Function signature properly extended with execution_stream.

The _create_kv_cache_manager function now accepts the optional execution_stream parameter with a sensible default of None.


542-562: LGTM: MLA branch passes execution_stream to KV cache manager.

The MLA (Multi-Latent Attention) branch correctly propagates execution_stream to the KV cache manager constructor.


563-606: LGTM: NemotronHybrid branch passes execution_stream.

The Nemotron Hybrid cache manager branch correctly propagates execution_stream.


607-656: LGTM: Qwen3Next branch passes execution_stream.

The Qwen3Next hybrid cache manager branch correctly propagates execution_stream.


657-686: LGTM: Default KV cache manager branch passes execution_stream.

The default branch correctly propagates execution_stream to the standard KV cache manager constructor.


689-713: LGTM: create_py_executor_instance accepts execution_stream.

The function signature properly includes the optional execution_stream parameter for propagation to downstream components.


794-800: LGTM: PeftCacheManager receives execution_stream.

The PEFT cache manager is correctly initialized with the execution_stream, ensuring LoRA weight operations can synchronize with the forward pass.


840-864: LGTM: PyExecutor receives execution_stream.

The PyExecutor is correctly initialized with the execution_stream, completing the propagation chain from high-level creation down to the executor.

@SimengLiu-nv
Copy link
Collaborator Author

/bot run

Copy link
Collaborator

@thorjohnsen thorjohnsen left a comment

Choose a reason for hiding this comment

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

LGTM

@tburt-nv
Copy link
Collaborator

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #28819 [ run ] triggered by Bot. Commit: 5897f32

@SimengLiu-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #28836 [ run ] triggered by Bot. Commit: a3f3c9d

@SimengLiu-nv
Copy link
Collaborator Author

/bot kill

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29016 [ kill ] triggered by Bot. Commit: a3f3c9d

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29016 [ kill ] completed with state SUCCESS. Commit: a3f3c9d
Successfully killed previous jobs for commit a3f3c9d

@SimengLiu-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29018 [ run ] triggered by Bot. Commit: a3f3c9d

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29018 [ run ] completed with state SUCCESS. Commit: a3f3c9d
/LLM/main/L0_MergeRequest_PR pipeline #22239 completed with status: 'FAILURE'

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

Copy link
Collaborator

@eopXD eopXD left a comment

Choose a reason for hiding this comment

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

LGTM

@SimengLiu-nv
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29647 [ run ] triggered by Bot. Commit: df67e11

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29647 [ run ] completed with state DISABLED
CI server is currently disabled for scheduled maintenance. Estimated completion time: 12 PM PST on 12/23.

@SimengLiu-nv
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29979 [ run ] triggered by Bot. Commit: df67e11

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29979 [ run ] completed with state SUCCESS. Commit: df67e11
/LLM/main/L0_MergeRequest_PR pipeline #23061 completed with status: 'FAILURE'

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

… KVCacheManager, PeftCacheManager to ensure proper CUDA stream synchronization between KV cache transfer operations and model forward kernels.

Signed-off-by: SimengLiu-nv <simengl@nvidia.com>
Signed-off-by: SimengLiu-nv <simengl@nvidia.com>
Signed-off-by: SimengLiu-nv <simengl@nvidia.com>
Signed-off-by: SimengLiu-nv <simengl@nvidia.com>
@SimengLiu-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #30197 [ run ] triggered by Bot. Commit: ed5a051

@SimengLiu-nv SimengLiu-nv enabled auto-merge (squash) December 30, 2025 18:59
@tensorrt-cicd
Copy link
Collaborator

PR_Github #30197 [ run ] completed with state SUCCESS. Commit: ed5a051
/LLM/main/L0_MergeRequest_PR pipeline #23243 completed with status: 'FAILURE'

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

Signed-off-by: SimengLiu-nv <simengl@nvidia.com>
@SimengLiu-nv
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #30204 [ run ] triggered by Bot. Commit: a8aeab2

@tensorrt-cicd
Copy link
Collaborator

PR_Github #30204 [ run ] completed with state SUCCESS. Commit: a8aeab2
/LLM/main/L0_MergeRequest_PR pipeline #23249 completed with status: 'FAILURE'

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

The new function pretty_print_task will raise error when the using
custom yaml files, for example tensorrt_llm/evaluate/lm_eval_tasks/gpqa/cot_zeroshot_aa/gpqa_diamond_cot_zeroshot_aa.yaml

Signed-off-by: SimengLiu-nv <simengl@nvidia.com>
@SimengLiu-nv
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #30242 [ run ] triggered by Bot. Commit: f1fccf2

Copy link
Collaborator

@yechank-nvidia yechank-nvidia left a comment

Choose a reason for hiding this comment

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

LGTM from modeling perspective.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #30242 [ run ] completed with state SUCCESS. Commit: f1fccf2
/LLM/main/L0_MergeRequest_PR pipeline #23284 completed with status: 'SUCCESS'
Pipeline passed with automatic retried tests. Check the rerun report for details.

@SimengLiu-nv SimengLiu-nv merged commit 84d107b into NVIDIA:main Dec 31, 2025
5 checks passed
videodanchik pushed a commit to videodanchik/TensorRT-LLM that referenced this pull request Jan 14, 2026
… KVCacheManager, PeftCacheManager to ensure proper CUDA stream synchronization between KV cache transfer operations and model forward kernels. (NVIDIA#10060)

Signed-off-by: SimengLiu-nv <simengl@nvidia.com>
Signed-off-by: Daniil Kulko <kulkodaniil@gmail.com>
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.

7 participants