Skip to content

Conversation

@shaharmor98
Copy link
Collaborator

@shaharmor98 shaharmor98 commented Aug 7, 2025

Summary by CodeRabbit

  • New Features

    • LoRA (Low-Rank Adaptation) support added—LoRA-aware CUDA graph execution, adapter management, and prefetching.
    • Engine/executor can load and apply LoRA adapters for generation.
  • Tests

    • Added tests validating LoRA + CUDA graph behavior (single and multiple requests).
  • Bug Fixes

    • Improved handling and errors for unsupported LoRA request combinations.
  • Chores

    • Devcontainer: disabled local Hugging Face cache mount.

Description

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.

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.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 7, 2025

📝 Walkthrough

Walkthrough

Adds LoRA integration into the PyTorch execution stack: new LoraManager wiring, prefetching, LoRA-aware warmup and CUDA-graph construction/forward paths, propagation of lora_params through resource manager and CUDA graph runner, LoRA-related request fields, and unit tests for LoRA + CUDA graph.

Changes

Cohort / File(s) Change Summary
Model engine — LoRA wiring
tensorrt_llm/_torch/pyexecutor/model_engine.py
Adds lora_manager, prefetch state, set_lora_manager, prefetch_lora_dirs; threads LoRA through warmup, _maybe_get_cuda_graph (now accepts resource_manager), and forward; computes and returns lora_params to be passed into input preparation and CUDA graph runner.
CUDA graph runner — accept lora_params
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
Extends DecodingCUDAGraphRunner.__init__ to accept optional lora_params and includes lora_params in inputs during CUDA graph capture.
Executor init & accessor
tensorrt_llm/_torch/pyexecutor/py_executor.py
Calls set_lora_manager and prefetch_lora_dirs during initialization; adds get_lora_manager() to expose engine LoraManager.
Resource manager — request and cache access
tensorrt_llm/_torch/pyexecutor/resource_manager.py
KVCacheManager.add_dummy_requests accepts optional lora_request and attaches LoRA task/weights/config to dummy LlmRequest; adds get_lora_manager() on KVCacheManager and PeftCacheManager.
Worker LoRA init refactor
tensorrt_llm/executor/worker.py
Uses engine.get_lora_manager() for LoRA initialization instead of manually constructing from resource manager; keeps adapter config retrieval.
Lora manager enhancements
tensorrt_llm/lora_manager.py
Adds lora_request field to LoraConfig; LoraManager stores optional _cpp_peft_cache_manager with set_cpp_peft_cache_manager(); is_adapter_in_cpu_cache consults cache manager if set.
Tests — LoRA + CUDA graph
tests/unittest/llmapi/test_llm_pytorch.py
Adds three tests covering LoRA adapter(s) with and without CUDA graph (single and multiple requests) using CudaGraphConfig.
Devcontainer config
.devcontainer/docker-compose.yml
Disabled local HuggingFace cache mount by commenting out the HF volume mapping.

Sequence Diagram(s)

sequenceDiagram
    participant PyExecutor
    participant PyTorchModelEngine
    participant LoraManager
    participant ResourceManager
    participant DecodingCUDAGraphRunner

    PyExecutor->>PyTorchModelEngine: set_lora_manager(resource_manager)
    PyExecutor->>PyTorchModelEngine: prefetch_lora_dirs()
    PyExecutor->>PyTorchModelEngine: forward(scheduled_requests, resource_manager)
    PyTorchModelEngine->>PyTorchModelEngine: _maybe_get_cuda_graph(batch, resource_manager)
    alt LoRA prefetched
        PyTorchModelEngine->>LoraManager: build per-request LoraConfig(s)
        PyTorchModelEngine->>ResourceManager: request PEFT cache actions
        PyTorchModelEngine->>DecodingCUDAGraphRunner: construct with lora_params
    else No LoRA
        PyTorchModelEngine->>DecodingCUDAGraphRunner: construct without lora_params
    end
    DecodingCUDAGraphRunner->>DecodingCUDAGraphRunner: capture(inputs including lora_params?)
    DecodingCUDAGraphRunner->>PyTorchModelEngine: execute graph / return outputs
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Possibly related PRs

Suggested reviewers

  • Naveassaf
  • QiJune
  • byshiue
  • Wanli-Jiang
  • amitz-nv
  • pcastonguay
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • 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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 7

🔭 Outside diff range comments (1)
tensorrt_llm/_torch/pyexecutor/py_executor.py (1)

1-1: Add required NVIDIA copyright header.

According to the coding guidelines, all TensorRT-LLM source files should contain an NVIDIA copyright header that includes the current year.

Add the copyright header at the top of the file:

+# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
 import dataclasses
🧹 Nitpick comments (3)
tensorrt_llm/lora_manager.py (1)

244-244: Address the TODO comment for the lora_request field.

The field is marked with "TODO smor fix" which suggests this is temporary implementation. Consider clarifying:

  1. What specific type should replace Optional[List[Any]]?
  2. What is the intended purpose of this field?
  3. When will this TODO be addressed?

Apply this diff to improve the TODO comment:

-    lora_request: Optional[List[Any]] = None  # TODO smor fix
+    lora_request: Optional[List[Any]] = None  # TODO: Define proper type and document purpose
tensorrt_llm/_torch/pyexecutor/resource_manager.py (2)

403-403: Add type annotation for consistency.

The lora_request parameter lacks a type annotation, which is inconsistent with other parameters in the method signature. Consider adding an appropriate type hint.

-        lora_request=None,
+        lora_request: Optional["LoraRequest"] = None,

428-432: Address the TODO comment and consider error handling.

The TODO comment indicates incomplete functionality for handling multiple adapters. Consider:

  1. Clarifying the design for multiple request IDs with LoRA adapters
  2. Adding error handling for missing attributes on lora_request

Would you like me to help design a solution for handling multiple LoRA adapters or create an issue to track this limitation?

 if lora_request is not None:
-    # TODO smor currently work with single adapter only, not sure how this should work with request ids
-    lora_task_id = lora_request.task_id
-    lora_weights = lora_request.weights
-    lora_config = lora_request.config
+    # TODO smor currently work with single adapter only, not sure how this should work with request ids
+    try:
+        lora_task_id = lora_request.task_id
+        lora_weights = lora_request.weights
+        lora_config = lora_request.config
+    except AttributeError as e:
+        raise ValueError(f"Invalid lora_request object, missing attribute: {e}")
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8207d5f and 38e1bac.

📒 Files selected for processing (7)
  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (3 hunks)
  • tensorrt_llm/_torch/pyexecutor/model_engine.py (9 hunks)
  • tensorrt_llm/_torch/pyexecutor/py_executor.py (2 hunks)
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py (2 hunks)
  • tensorrt_llm/executor/worker.py (1 hunks)
  • tensorrt_llm/lora_manager.py (3 hunks)
  • tests/unittest/llmapi/test_llm_pytorch.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.py: Python code 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 Python class in the constructor.
For interfaces that may be used outside a Python file, prefer docstrings over comments.
Comments in Python 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.
Attributes and variables in Python can be documented inline; attribute docstrings will be rendered under the class docstring.
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/executor/worker.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
  • tests/unittest/llmapi/test_llm_pytorch.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
  • tensorrt_llm/lora_manager.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.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/executor/worker.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
  • tests/unittest/llmapi/test_llm_pytorch.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
  • tensorrt_llm/lora_manager.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
🧠 Learnings (6)
📓 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.
📚 Learning: in tensorrt_llm/executor/worker.py, the lora adapter cache optimization logic that checks `is_adapte...
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.

Applied to files:

  • tensorrt_llm/executor/worker.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
  • tensorrt_llm/lora_manager.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
📚 Learning: in tensorrt-llm testing, it's common to have both cli flow tests (test_cli_flow.py) and pytorch api ...
Learnt from: moraxu
PR: NVIDIA/TensorRT-LLM#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/unittest/llmapi/test_llm_pytorch.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
📚 Learning: in tensorrt-llm, test files (files under tests/ directories) do not require nvidia copyright headers...
Learnt from: galagam
PR: NVIDIA/TensorRT-LLM#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/unittest/llmapi/test_llm_pytorch.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
📚 Learning: in tensorrt-llm, examples directory can have different dependency versions than the root requirement...
Learnt from: yibinl-nvidia
PR: NVIDIA/TensorRT-LLM#6506
File: examples/models/core/mixtral/requirements.txt:3-3
Timestamp: 2025-08-01T15:14:45.673Z
Learning: In TensorRT-LLM, examples directory can have different dependency versions than the root requirements.txt file. Version conflicts between root and examples dependencies are acceptable because examples are designed to be standalone and self-contained.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/model_engine.py
📚 Learning: in tensorrt-llm's multimodal processing pipeline, shared tensor recovery using `from_shared_tensor()...
Learnt from: yechank-nvidia
PR: NVIDIA/TensorRT-LLM#6254
File: tensorrt_llm/_torch/pyexecutor/model_engine.py:1201-1204
Timestamp: 2025-07-22T09:22:14.726Z
Learning: In TensorRT-LLM's multimodal processing pipeline, shared tensor recovery using `from_shared_tensor()` is only needed during the context phase. Generation requests reuse the already-recovered tensor data and only need to call `strip_for_generation()` to remove unnecessary multimodal data while preserving the recovered tensors. This avoids redundant tensor recovery operations during generation.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/model_engine.py
🔇 Additional comments (12)
tensorrt_llm/_torch/pyexecutor/py_executor.py (2)

214-216: LGTM - LoRA manager setup looks correct.

The integration of LoRA manager setup in the constructor is properly placed after self.send_handles initialization and before self.inflight_req_ids. This follows the logical flow of setting up LoRA support early in the initialization process.


280-281: LGTM - Simple getter method for LoRA manager.

The getter method follows Python naming conventions and provides clean access to the model engine's LoRA manager. This enables external components to retrieve the LoRA manager without exposing the internal model engine structure.

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

37-37: LGTM - Clean parameter addition.

The optional lora_params parameter is properly typed and follows the existing pattern for optional metadata parameters.


72-72: LGTM - Consistent attribute assignment.

The instance attribute assignment follows the same pattern as other metadata attributes like attn_metadata and spec_metadata.


95-96: LGTM - Proper conditional inclusion.

The conditional addition of lora_params to the inputs dictionary is implemented correctly, only adding it when present. This ensures backward compatibility and avoids unnecessary dictionary entries.

tensorrt_llm/executor/worker.py (1)

164-170: Approve the refactoring to use engine.get_lora_manager().

The change simplifies LoRA manager access by delegating to the engine layer instead of manually constructing it from resource manager components. This aligns well with the broader integration approach where the PyExecutor manages LoRA initialization.

The commented-out code shows the previous complex construction pattern, which is good for reference during the transition.

tensorrt_llm/lora_manager.py (3)

11-11: LGTM - Proper type import.

Adding Any to the type imports is necessary for the new lora_request field type annotation.


751-751: LGTM - Proper attribute initialization.

The _cpp_peft_cache_manager attribute is properly initialized as a private attribute with correct type annotation.


753-756: LGTM - Clean setter method.

The set_cpp_peft_cache_manager method provides a clean interface for external setup of the PEFT cache manager. This design allows the LoraManager to be constructed without the cache manager and have it set later during initialization.

Note: Based on retrieved learnings, there are known race condition issues with LoRA adapter cache optimization logic. While this method itself looks correct, ensure that the broader integration properly handles the known race condition limitations.

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

424-427: LGTM!

Clean initialization of LoRA-related variables with descriptive names following Python conventions.


441-444: LGTM!

The LoRA parameters are correctly passed to the LlmRequest constructor with consistent formatting and naming.

tensorrt_llm/_torch/pyexecutor/model_engine.py (1)

2230-2231: LGTM! Proper parameter passing for LoRA support

The addition of resource_manager parameter to _maybe_get_cuda_graph is correct and necessary for accessing the PEFT cache manager for LoRA support.

Comment on lines 295 to 299
self.lora_prefetch_requests_list = None # TODO smor - fix "LoRARequest" import
if lora_config is not None and lora_config.lora_request is not None:
self.lora_prefetch_requests_list = lora_config.lora_request
self.has_lora_prefetched = False

Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Address the TODO comment and add proper type hints

The TODO comment indicates an unresolved import issue for "LoRARequest". This should be resolved before merging. Additionally, consider adding proper type hints for better code maintainability.

# Fix the import and add proper type hints
from typing import List, Optional
from tensorrt_llm.lora_manager import LoraRequest  # Add this import

# Then update the attribute declaration
self.lora_prefetch_requests_list: Optional[List[LoraRequest]] = None

🏁 Script executed:

#!/bin/bash
# Search for LoraRequest usage in model_engine.py
echo "Checking imports and usages of LoraRequest/LoRARequest in tensorrt_llm/_torch/pyexecutor/model_engine.py"
rg -n 'LoraRequest' tensorrt_llm/_torch/pyexecutor/model_engine.py || echo "No LoraRequest occurrences"
rg -n 'LoRARequest' tensorrt_llm/_torch/pyexecutor/model_engine.py || echo "No LoRARequest occurrences"

# Search for class definition of LoraRequest anywhere in the repo
echo "Looking for class LoraRequest definitions"
rg -n 'class LoraRequest' -n .

# Search for any lora_manager module file
echo "Locating lora_manager.py"
fd --extension py lora_manager.py || echo "lora_manager.py not found"

# Search for references to lora_manager in imports
echo "Searching for imports of lora_manager"
rg -n 'lora_manager' -n .

Length of output: 10643


🏁 Script executed:

#!/bin/bash
echo "Displaying LoraConfig class definition and initializer context"
rg -n 'class LoraConfig' tensorrt_llm/lora_manager.py -A20

echo -e "\nSearching for 'lora_request' occurrences in LoraConfig"
rg -n 'lora_request' -n tensorrt_llm/lora_manager.py -A5

Length of output: 1509


#!/bin/bash
# List all function definitions in lora_manager.py with context
echo "Function definitions in tensorrt_llm/lora_manager.py"
rg -n '^def ' tensorrt_llm/lora_manager.py -A2

Refine LoRA request type and remove stale TODO

The current TODO to “fix LoRARequest import” should be replaced by using the existing LoraModelConfig type, and both the engine’s prefetch list and the LoraConfig field should be annotated accordingly.

• In tensorrt_llm/_torch/pyexecutor/model_engine.py init:

  • Remove the # TODO smor comment.
  • Add proper imports and type hints for LoraModelConfig.
  • Change
    self.lora_prefetch_requests_list = None  # TODO smor - fix "LoRARequest" import
    to something like:
    from typing import Optional, List
    from tensorrt_llm.lora_manager import LoraModelConfig
    
    self.lora_prefetch_requests_list: Optional[List[LoraModelConfig]] = None

• In tensorrt_llm/lora_manager.py in the LoraConfig dataclass:

  • Remove the # TODO smor fix comment.
  • Update the field’s type from Optional[List[Any]] to Optional[List[LoraModelConfig]], e.g.:
    from typing import Optional, List
    # add forward‐reference import if needed: from __future__ import annotations
    
    @dataclass
    class LoraConfig(DictConversion):
        …
        lora_request: Optional[List[LoraModelConfig]] = None

This aligns the code with the actual adapter configuration type and restores maintainable type safety.

🤖 Prompt for AI Agents
In tensorrt_llm/_torch/pyexecutor/model_engine.py around lines 295 to 299,
remove the TODO comment about fixing the "LoRARequest" import and instead import
LoraModelConfig properly along with typing imports Optional and List. Then,
annotate self.lora_prefetch_requests_list as Optional[List[LoraModelConfig]]
instead of None without type. In tensorrt_llm/lora_manager.py, update the
LoraConfig dataclass by removing the TODO comment and changing the lora_request
field type from Optional[List[Any]] to Optional[List[LoraModelConfig]], adding
necessary imports and forward references if needed to ensure correct type
hinting and maintainability.

Signed-off-by: Shahar Mor <[email protected]>
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: 2

🔭 Outside diff range comments (2)
tensorrt_llm/executor/worker.py (1)

162-168: Add a fail-fast guard for missing LoRA manager in PyTorch Worker

Ensure that when using the PyTorch backend with LoRA, we check that engine.get_lora_manager() actually returns a manager (rather than letting an obscure attribute error or downstream NPE occur).

tensorrt_llm/executor/worker.py:

         if getattr(executor_config, "backend", "") == "pytorch" and lora_config is not None:
-            self._lora_manager = self.engine.get_lora_manager()
+            # fail fast if the PyExecutor didn’t register a PeftCacheManager
+            try:
+                self._lora_manager = self.engine.get_lora_manager()
+            except AttributeError:
+                raise RuntimeError(
+                    "LoRA manager not available on PyExecutor – "
+                    "ensure PeftCacheManager is registered before Worker initialization."
+                )
+            assert self._lora_manager is not None, (
+                "LoRA manager is None; verify that a PeftCacheManager was created in the PyExecutor."
+            )
             lora_model_config = self.engine.model_engine.lora_model_config
             assert lora_model_config is not None
             self._lora_model_config = lora_model_config

Points to verify and address:

  • PyExecutor sets the manager via model_engine.set_lora_manager(self.resource_manager) (py_executor.py:214)
  • ResourceManagerType.PEFT_CACHE_MANAGER must be added into resource_manager (resource_manager.py) so that set_lora_manager actually produces a valid lora_manager
  • The existing race in is_adapter_in_cpu_cache() (worker.py 375–384) remains; consider adding a regression test to ensure this change doesn’t exacerbate it.
tests/unittest/llmapi/test_llm_pytorch.py (1)

848-885: Remove commented code, add cleanup, and guard memory (multi-request CUDA graph test)

  • Remove the commented-out cuda_graph_config line and ensure cleanup.
  • Apply GPU memory gating for stability.
+@skip_gpu_memory_less_than_40gb
 def test_lora_graph_multiple_requests():
@@
-    llm = LLM(
-        model=f"{llm_models_root()}/llama-models/llama-7b-hf",
-        lora_config=lora_config,
-        #   cuda_graph_config=None)
-        cuda_graph_config=CudaGraphConfig(max_batch_size=2))
+    llm = LLM(
+        model=f"{llm_models_root()}/llama-models/llama-7b-hf",
+        lora_config=lora_config,
+        cuda_graph_config=CudaGraphConfig(max_batch_size=2))
@@
-    outputs = llm.generate(prompts, sampling_params, lora_request=lora_requests)
-
-    print(f"lora output 0: {outputs[0].outputs[0].text}")
-    print(f"ref  output 0: {references[0]}")
-    print(f"lora output 1: {outputs[1].outputs[0].text}")
-    print(f"ref  output 1: {references[1]}")
-    assert similar(outputs[0].outputs[0].text, references[0])
-    assert similar(outputs[1].outputs[0].text, references[1])
+    try:
+        outputs = llm.generate(prompts, sampling_params, lora_request=lora_requests)
+        print(f"lora output 0: {outputs[0].outputs[0].text}")
+        print(f"ref  output 0: {references[0]}")
+        print(f"lora output 1: {outputs[1].outputs[0].text}")
+        print(f"ref  output 1: {references[1]}")
+        assert similar(outputs[0].outputs[0].text, references[0])
+        assert similar(outputs[1].outputs[0].text, references[1])
+    finally:
+        llm.shutdown()
♻️ Duplicate comments (2)
tests/unittest/llmapi/test_llm_pytorch.py (1)

788-817: Stabilize test and ensure cleanup for LoRA + CUDA graph (parametrized case)

  • Add GPU memory guard for 7B + LoRA.
  • Ensure LLM is closed to prevent resource leaks.
-@pytest.mark.parametrize("cuda_graph_config",
-                         [None, CudaGraphConfig(max_batch_size=1)])
-def test_lora_dir_with_graph(cuda_graph_config):
+@skip_gpu_memory_less_than_40gb
+@pytest.mark.parametrize("cuda_graph_config", [None, CudaGraphConfig(max_batch_size=1)])
+def test_lora_dir_with_graph(cuda_graph_config):
@@
-    llm = LLM(model=f"{llm_models_root()}/llama-models/llama-7b-hf",
-              lora_config=lora_config,
-              cuda_graph_config=cuda_graph_config)
+    llm = LLM(model=f"{llm_models_root()}/llama-models/llama-7b-hf",
+              lora_config=lora_config,
+              cuda_graph_config=cuda_graph_config)
@@
-    outputs = llm.generate(prompts, sampling_params, lora_request=lora_request)
-
-    assert similar(outputs[0].outputs[0].text, references[0])
-    print(f"lora output: {outputs[0].outputs[0].text}")
-    print(f"ref  output: {references[0]}")
+    try:
+        outputs = llm.generate(prompts, sampling_params, lora_request=lora_request)
+        assert similar(outputs[0].outputs[0].text, references[0])
+        print(f"lora output: {outputs[0].outputs[0].text}")
+        print(f"ref  output: {references[0]}")
+    finally:
+        llm.shutdown()
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)

458-476: prefetch_lora_dirs: guard manager, pass mapping, and handle failures

Avoid None deref and silent failures; respect distributed mapping.

     def set_lora_manager(self, resource_manager: ResourceManager):
         peft_cache_manager = resource_manager.get_resource_manager(
             ResourceManagerType.PEFT_CACHE_MANAGER)
         if peft_cache_manager is not None:
             self.lora_manager = peft_cache_manager.get_lora_manager()

     def prefetch_lora_dirs(self):
-        if self.lora_prefetch_requests_list is None:
+        if self.lora_prefetch_requests_list is None:
             return
-
-        for request in self.lora_prefetch_requests_list:
-            self.lora_manager.load_from_ckpt(
-                [request.path],
-                model_config=self.lora_model_config,
-                runtime_mapping=None,
-                uids=[request.adapter_id])
-
-        self.has_lora_prefetched = True
+        if self.lora_manager is None or self.lora_model_config is None:
+            logger.warning("LoRA manager/model config not initialized; skipping prefetch.")
+            return
+        try:
+            for request in self.lora_prefetch_requests_list:
+                self.lora_manager.load_from_ckpt(
+                    [request.path],
+                    model_config=self.lora_model_config,
+                    runtime_mapping=self.mapping,
+                    uids=[request.adapter_id])
+            self.has_lora_prefetched = True
+        except Exception as e:
+            logger.error(f"LoRA prefetch failed for {getattr(request, 'path', '<unknown>')}: {e}")
+            raise
🧹 Nitpick comments (10)
.devcontainer/docker-compose.yml (1)

26-26: Make HF cache mount configurable instead of hard-disabling it

Commenting out the HuggingFace cache mount may slow down development (extra downloads). Prefer a flag-driven mount to keep opt-in behavior.

Consider:

 volumes:
   - ${SOURCE_DIR}:/workspaces/tensorrt_llm
-  #- ${LOCAL_HF_HOME}:/huggingface  # HF cache
+  ${ENABLE_HF_CACHE:-0}:
+    - ${LOCAL_HF_HOME}:/huggingface  # HF cache

And document:

  • Set ENABLE_HF_CACHE=1 and LOCAL_HF_HOME to enable cache mount.
tensorrt_llm/_torch/pyexecutor/resource_manager.py (2)

388-405: Tighten type hints and naming for LoRA warmup injection

The new parameter is loosely typed and named ambiguously. Use the binding type and a clearer name to improve readability and tooling.

-    def add_dummy_requests(
+    def add_dummy_requests(
             self,
             request_ids: List[int],
@@
-            max_beam_width: int = 1,
-            lora_request: Optional[List] = None,  # TODO smor fill type hint
+            max_beam_width: int = 1,
+            lora_configs: Optional[list["tensorrt_llm.bindings.executor.LoraConfig"]] = None,
     ):

And update references below from lora_request -> lora_configs accordingly.

Additional change outside this hunk (top of file or near other binding aliases) to help static typing:

# Add near other binding aliases:
# LoraConfigCpp = tensorrt_llm.bindings.executor.LoraConfig

424-436: Index-based LoRA assignment: add a defensive check

Indexing lora list by i assumes request_ids and lora entries align. Add a small guard to avoid subtle misalignment.

-            if lora_request is not None and i < len(lora_request):
+            if lora_configs is not None and i < len(lora_configs):
                 # TODO smor currently work with single adapter only, not sure how this should work with request ids
-                lora_task_id = lora_request[i].task_id
-                lora_weights = lora_request[i].weights
-                lora_config = lora_request[i].config
+                cfg = lora_configs[i]
+                lora_task_id = cfg.task_id
+                lora_weights = cfg.weights
+                lora_config = cfg.config

Optionally assert that len(lora_configs) equals len(request_ids) for warmup batches where LoRA is expected for all.

tensorrt_llm/_torch/pyexecutor/model_engine.py (7)

291-299: Initialize and type LoRA prefetch fields; remove TODOs

Add explicit types and defaults; keep comments concise.

-        self.lora_manager: Optional[LoraManager] = None
-        self.lora_prefetch_requests_list = None
-        # TODO smor- do we want to get the request inside the lora config?
-        # TODO smor- what happens if you get target modules?
-        # TODO smor- answer and guard against this
-        if lora_config is not None and lora_config.lora_request is not None:
-            self.lora_prefetch_requests_list = lora_config.lora_request
-            self.has_lora_prefetched = False
+        self.lora_manager: Optional[LoraManager] = None
+        self.lora_prefetch_requests_list: Optional[list] = None  # Optional[List[LoRARequest]] if you add a runtime-safe type
+        self.has_lora_prefetched: bool = False
+        if lora_config is not None and lora_config.lora_request is not None:
+            self.lora_prefetch_requests_list = lora_config.lora_request

If you want stricter typing without import cycles, wrap typing imports with TYPE_CHECKING.


535-564: Warmup: replace print debugging and clarify UID selection

  • Remove prints; use logger at debug level if needed.
  • UID selection cycles if batch_size > available adapters; add a short comment to document the behavior.
-            if self.has_lora_prefetched:
-                print(
-                    "SMOR, model engine, maybe get cuda graph, processing lora_params"
-                )
+            if self.has_lora_prefetched:
                 from tensorrt_llm.bindings import executor as tllm
@@
-                # Create LoRA configs for each request in the batch
-                # IMPORTANT: Match request_id to the corresponding LoRA UID
+                # Build one LoRA config per request; cycle UIDs if fewer adapters are prefetched than batch size.
                 for request_id in range(batch_size):
-                    # Use request_id as the LoRA UID (assuming they should match)
-                    # This ensures request 0 uses LoRA UID 0, request 1 uses LoRA UID 1, etc.
                     uid = available_uids[request_id % len(available_uids)]

722-775: Remove TODO noise and stabilize autotuner warmup

  • Strip “TODO SMOR ...” comments.
  • If get_autotune_warmup_request is not LoRA-aware, consider gating it or documenting.

No code diff required; just remove the TODO noise and, if needed, add a short note: “Autotuner warmup not LoRA-aware yet; acceptable since capture happens in CUDA graph warmup.”


816-824: Remove debug print and vague “fails here” comment

These should not be in production; replace with logger.debug if needed.

-                        print("SMOR, model engine, begore forward")
-                        # from IPython import embed
-                        # embed()
@@
-                        torch.cuda.synchronize()  # fails here
+                        torch.cuda.synchronize()

1290-1292: Inputs: remove debug prints and pass lora_params cleanly

  • Accepting lora_params is good; remove print side-effects.
-            cache_indirection_buffer: Optional[torch.Tensor] = None,
-            lora_params: Optional[dict] = None):
+            cache_indirection_buffer: Optional[torch.Tensor] = None,
+            lora_params: Optional[dict] = None):
@@
-        if lora_params is None:
-            lora_params = self._get_lora_params_from_requests(
-                scheduled_requests, attn_metadata)
+        if lora_params is None:
+            lora_params = self._get_lora_params_from_requests(scheduled_requests, attn_metadata)
@@
-        if bool(lora_params):
-            print("SMOR, model engine, before setting lora_params")
-            # from IPython import embed
-            # embed()
-            inputs['lora_params'] = lora_params
+        if bool(lora_params):
+            inputs['lora_params'] = lora_params

Also applies to: 1644-1647, 1671-1675


2258-2276: Forward: thread lora_params from CUDA graph runner to input prep: LGTM

Propagation is correct. Minor nit: you can reduce the else branch by initializing lora_params = None upfront.


2084-2091: Remove debug prints in lora params extraction

Keep this helper silent; printing here is noisy.

-        if len(request_list) == 2:
-            print(
-                "SMOR, after getting request_list in get lora params from requests, check for some order reversal"
-            )
-            # from IPython import embed
-            # embed()
-            # request_list = request_list[::-1]
+        # If needed, add a targeted debug log here with logger.debug(...)
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 38e1bac and ad1101a.

📒 Files selected for processing (6)
  • .devcontainer/docker-compose.yml (1 hunks)
  • tensorrt_llm/_torch/pyexecutor/model_engine.py (17 hunks)
  • tensorrt_llm/_torch/pyexecutor/py_executor.py (2 hunks)
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py (3 hunks)
  • tensorrt_llm/executor/worker.py (1 hunks)
  • tests/unittest/llmapi/test_llm_pytorch.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.py: Python code 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 Python class in the constructor.
For interfaces that may be used outside a Python file, prefer docstrings over comments.
Comments in Python 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.
Attributes and variables in Python can be documented inline; attribute docstrings will be rendered under the class docstring.
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/executor/worker.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
  • tests/unittest/llmapi/test_llm_pytorch.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.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/executor/worker.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
  • tests/unittest/llmapi/test_llm_pytorch.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
🧠 Learnings (2)
📚 Learning: 2025-07-17T09:01:27.402Z
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.

Applied to files:

  • tensorrt_llm/executor/worker.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
📚 Learning: 2025-07-28T17:06:08.621Z
Learnt from: moraxu
PR: NVIDIA/TensorRT-LLM#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/unittest/llmapi/test_llm_pytorch.py
🧬 Code Graph Analysis (3)
tensorrt_llm/executor/worker.py (2)
tensorrt_llm/_torch/pyexecutor/py_executor.py (1)
  • get_lora_manager (279-280)
tensorrt_llm/_torch/pyexecutor/resource_manager.py (1)
  • get_lora_manager (1262-1264)
tensorrt_llm/_torch/pyexecutor/resource_manager.py (11)
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
  • use_mrope (478-486)
tensorrt_llm/_torch/models/modeling_phi4mm.py (2)
  • lora_request (267-288)
  • lora_config (244-264)
tensorrt_llm/lora_manager.py (1)
  • lora_weights (1216-1217)
tensorrt_llm/_torch/models/modeling_utils.py (1)
  • config (494-495)
tensorrt_llm/_torch/models/modeling_vila.py (1)
  • config (250-251)
tests/unittest/_torch/test_pytorch_model_engine.py (1)
  • config (49-50)
tensorrt_llm/_torch/pyexecutor/llm_request.py (1)
  • LlmRequest (265-396)
tensorrt_llm/executor/result.py (1)
  • request_id (462-463)
tensorrt_llm/runtime/generation.py (1)
  • SamplingConfig (655-704)
tensorrt_llm/sampling_params.py (1)
  • _get_sampling_config (405-435)
tensorrt_llm/_torch/pyexecutor/py_executor.py (1)
  • get_lora_manager (279-280)
tests/unittest/llmapi/test_llm_pytorch.py (5)
tensorrt_llm/llmapi/llm_args.py (2)
  • CudaGraphConfig (106-163)
  • PeftCacheConfig (791-857)
tensorrt_llm/executor/request.py (1)
  • LoRARequest (24-53)
tensorrt_llm/lora_manager.py (1)
  • LoraConfig (236-253)
tensorrt_llm/llmapi/llm.py (2)
  • LLM (1102-1118)
  • generate (226-304)
tests/unittest/utils/util.py (1)
  • similar (365-367)
🪛 Ruff (0.12.2)
tensorrt_llm/_torch/pyexecutor/resource_manager.py

430-430: Line too long (142 > 120)

(E501)

tensorrt_llm/_torch/pyexecutor/model_engine.py

585-585: Line too long (130 > 120)

(E501)


763-763: Line too long (133 > 120)

(E501)

🔇 Additional comments (5)
tensorrt_llm/_torch/pyexecutor/resource_manager.py (2)

445-447: Plumbing LoRA fields through LlmRequest: LGTM

Passing lora_task_id/weights/config through to LlmRequest aligns with PeftCacheManager expectations. No issues.


1262-1265: Accessor for LoRA manager on PeftCacheManager: LGTM

Public get_lora_manager() is useful and consistent with PyExecutor usage. Good assertion too.

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

573-585: Pass LoRA configs into dummy short-requests: LGTM

Short requests receive corresponding LoRA configs. Looks correct.


593-606: Use LoRA config for max-length dummy request: LGTM

Selecting the last LoRA config for the max token request is fine for capture shape purposes.


2188-2209: _prepare_inputs(): signature and threading of lora_params: LGTM

Extending the signature and passing lora_params into TP inputs is clean. No concerns.

Comment on lines +1004 to 1005
resource_manager: Optional[ResourceManager] = None
) -> Optional[DecodingCUDAGraphRunner]:
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

CUDA-graph + LoRA: avoid hard errors; use public API and return None gracefully

  • Don’t raise ValueError for mixed context/generation; return None to fall back to eager.
  • Use peft_cache_manager.ensure_batch instead of peft_cache_manager.impl.ensure_batch.
  • Keep lora_params prepared, but avoid fatal exits.
-    def _maybe_get_cuda_graph(
+    def _maybe_get_cuda_graph(
         self,
         batch: ScheduledRequests,
-        resource_manager: Optional[ResourceManager] = None
+        resource_manager: Optional[ResourceManager] = None
     ) -> Optional[DecodingCUDAGraphRunner]:
@@
-        if self.has_lora_prefetched:
+        if self.has_lora_prefetched:
             peft_cache_manager = resource_manager.get_resource_manager(
                 ResourceManagerType.PEFT_CACHE_MANAGER)
 
             context_requests = batch.context_requests
             generation_requests = batch.generation_requests
 
-            if len(context_requests) > 0 and len(generation_requests) > 0:
-                raise ValueError(
-                    "SMOR, non empty context and generation requests isn't tested yet"
-                )
-
-            if len(context_requests) > 0:
-                raise ValueError("SMOR, context requests isn't tested yet")
+            # Currently only pure generation batches are supported for CUDA graph capture with LoRA.
+            if len(context_requests) > 0:
+                logger.debug("CUDA graph + LoRA: context batches not supported for capture yet; skipping graph.")
+                return None
 
             for generation_request in generation_requests:
                 peft_cache_manager.add_request_peft(generation_request)
 
-            py_lora_task_layer_module_configs = peft_cache_manager.impl.ensure_batch(
-                context_requests, generation_requests, False)
+            py_lora_task_layer_module_configs = peft_cache_manager.ensure_batch(
+                context_requests, generation_requests, False)
@@
-            lora_params = self._get_lora_params_from_requests(
-                batch, attn_metadata)
+            lora_params = self._get_lora_params_from_requests(batch, attn_metadata)
@@
-        self._cuda_graphs[batch_size][draft_len] = DecodingCUDAGraphRunner(
-            num_sequences_in_batch, "cuda", attn_metadata, spec_metadata,
-            self.use_mrope, lora_params)
+        self._cuda_graphs[batch_size][draft_len] = DecodingCUDAGraphRunner(
+            num_sequences_in_batch, "cuda", attn_metadata, spec_metadata, self.use_mrope, lora_params
+        )

Also applies to: 1051-1083, 1088-1091

🤖 Prompt for AI Agents
In tensorrt_llm/_torch/pyexecutor/model_engine.py around lines 1004-1005 (and
similarly at 1051-1083 and 1088-1091), change the behaviour so CUDA-graph + LoRA
conflicts do not raise a ValueError but instead return None to let the caller
fall back to eager execution; replace direct calls to
peft_cache_manager.impl.ensure_batch with the public API
peft_cache_manager.ensure_batch; continue preparing lora_params as before but
remove any fatal exits or exceptions so the function exits gracefully by
returning None when mixed context/generation or incompatible conditions are
detected.

Comment on lines +819 to +846
def test_lora_graph_single_request():
lora_req = LoRARequest(
"task-0", 0, f"{llm_models_root()}/llama-models/luotuo-lora-7b-0.1")

lora_config = LoraConfig(
lora_dir=[f"{llm_models_root()}/llama-models/luotuo-lora-7b-0.1"],
max_lora_rank=8,
lora_request=[lora_req])

llm = LLM(model=f"{llm_models_root()}/llama-models/llama-7b-hf",
lora_config=lora_config,
cuda_graph_config=CudaGraphConfig(max_batch_size=1))

prompts = [
"美国的首都在哪里? \n答案:",
]
references = [
"美国的首都是华盛顿。\n\n美国的",
]
sampling_params = SamplingParams(max_tokens=20)
lora_request = [lora_req]

outputs = llm.generate(prompts, sampling_params, lora_request=lora_request)

assert similar(outputs[0].outputs[0].text, references[0])
print(f"lora output: {outputs[0].outputs[0].text}")
print(f"ref output: {references[0]}")

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure resource cleanup and add GPU guard (single-request CUDA graph test)

Mirror the cleanup and gating done in the parametrized test.

+@skip_gpu_memory_less_than_40gb
 def test_lora_graph_single_request():
@@
-    llm = LLM(model=f"{llm_models_root()}/llama-models/llama-7b-hf",
-              lora_config=lora_config,
-              cuda_graph_config=CudaGraphConfig(max_batch_size=1))
+    llm = LLM(model=f"{llm_models_root()}/llama-models/llama-7b-hf",
+              lora_config=lora_config,
+              cuda_graph_config=CudaGraphConfig(max_batch_size=1))
@@
-    outputs = llm.generate(prompts, sampling_params, lora_request=lora_request)
-
-    assert similar(outputs[0].outputs[0].text, references[0])
-    print(f"lora output: {outputs[0].outputs[0].text}")
-    print(f"ref  output: {references[0]}")
+    try:
+        outputs = llm.generate(prompts, sampling_params, lora_request=lora_request)
+        assert similar(outputs[0].outputs[0].text, references[0])
+        print(f"lora output: {outputs[0].outputs[0].text}")
+        print(f"ref  output: {references[0]}")
+    finally:
+        llm.shutdown()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def test_lora_graph_single_request():
lora_req = LoRARequest(
"task-0", 0, f"{llm_models_root()}/llama-models/luotuo-lora-7b-0.1")
lora_config = LoraConfig(
lora_dir=[f"{llm_models_root()}/llama-models/luotuo-lora-7b-0.1"],
max_lora_rank=8,
lora_request=[lora_req])
llm = LLM(model=f"{llm_models_root()}/llama-models/llama-7b-hf",
lora_config=lora_config,
cuda_graph_config=CudaGraphConfig(max_batch_size=1))
prompts = [
"美国的首都在哪里? \n答案:",
]
references = [
"美国的首都是华盛顿。\n\n美国的",
]
sampling_params = SamplingParams(max_tokens=20)
lora_request = [lora_req]
outputs = llm.generate(prompts, sampling_params, lora_request=lora_request)
assert similar(outputs[0].outputs[0].text, references[0])
print(f"lora output: {outputs[0].outputs[0].text}")
print(f"ref output: {references[0]}")
@skip_gpu_memory_less_than_40gb
def test_lora_graph_single_request():
lora_req = LoRARequest(
"task-0", 0, f"{llm_models_root()}/llama-models/luotuo-lora-7b-0.1")
lora_config = LoraConfig(
lora_dir=[f"{llm_models_root()}/llama-models/luotuo-lora-7b-0.1"],
max_lora_rank=8,
lora_request=[lora_req])
llm = LLM(model=f"{llm_models_root()}/llama-models/llama-7b-hf",
lora_config=lora_config,
cuda_graph_config=CudaGraphConfig(max_batch_size=1))
prompts = [
"美国的首都在哪里? \n答案:",
]
references = [
"美国的首都是华盛顿。\n\n美国的",
]
sampling_params = SamplingParams(max_tokens=20)
lora_request = [lora_req]
try:
outputs = llm.generate(prompts, sampling_params, lora_request=lora_request)
assert similar(outputs[0].outputs[0].text, references[0])
print(f"lora output: {outputs[0].outputs[0].text}")
print(f"ref output: {references[0]}")
finally:
llm.shutdown()
🤖 Prompt for AI Agents
In tests/unittest/llmapi/test_llm_pytorch.py around lines 819 to 846, the
single-request CUDA-graph LoRA test lacks the GPU availability guard and
resource cleanup used by the parametrized test; wrap the test logic so it only
runs when CUDA is available (skip or return when not), and at the end mirror the
cleanup: call the LLM shutdown/close method, synchronize the GPU, and free GPU
memory (e.g., torch.cuda.synchronize() and torch.cuda.empty_cache()) so CUDA
graphs and model resources are released after the test.

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.

1 participant