-
Notifications
You must be signed in to change notification settings - Fork 1.9k
[TRTLLM-7346][fix] Improve performance of PyTorchModelEngine._get_lora_params_from_requests #7203
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
…a_params_from_requests (NVIDIA#7033) Signed-off-by: Amit Zuker <[email protected]>
📝 WalkthroughWalkthroughRemoves the is_dora field from LoRA parameter handling across runtime and tests, updates internal LoRA parameter collection/merge structures in model_engine, simplifies LoraLayer forward by dropping an unused flag read, and adds a precise Optional[List[TaskLayerModuleConfig]] type annotation in LlmRequest. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Req as LlmRequest
participant Eng as ModelEngine
participant Lay as LoraLayer
participant Kern as lora_grouped_gemm
Note over Req,Eng: LoRA params per request are keyed by (request_id, layer_id, module_id)<br/>containing adapter_size and weight_pointers only
Req->>Eng: submit request (LoRA configs)
Eng->>Eng: Collect per-request LoRA module entries
Eng->>Eng: Merge across requests per (layer_id, module_id)<br/>• append adapter_size<br/>• extend weight_pointers<br/>• insert zeros when missing
Eng->>Lay: Provide lora_params {adapter_size, weight_pointers}
Lay->>Lay: Determine active modules, lora_ranks
Lay->>Kern: lora_grouped_gemm(weight_pointers, ranks)
Kern-->>Lay: LoRA outputs
Lay-->>Eng: Combined outputs (zeros for inactive modules when needed)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
|
/bot run |
|
PR_Github #16413 [ run ] triggered by Bot |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (8)
tensorrt_llm/_torch/pyexecutor/llm_request.py (2)
1-1: Add NVIDIA copyright header.Per repo guidelines, prepend the NVIDIA copyright header (current year) to all source files.
320-323: Type annotation for py_lora_task_layer_module_configs looks good; consider deferring the runtime import.Fully-qualified annotation is precise. If you want to avoid importing the bindings module chain at runtime when the class is defined, gate the import for type checkers and keep the annotation as a forward reference.
Example:
+from typing import TYPE_CHECKING, Optional +if TYPE_CHECKING: + from tensorrt_llm.bindings.internal.runtime import TaskLayerModuleConfig @@ - self.py_lora_task_layer_module_configs: list[ - tensorrt_llm.bindings.internal.runtime. - TaskLayerModuleConfig] | None = None + self.py_lora_task_layer_module_configs: Optional[list["TaskLayerModuleConfig"]] = NoneThis keeps startup cost minimal, helps static type checkers, and avoids accidental import-time side effects.
tensorrt_llm/_torch/pyexecutor/model_engine.py (6)
1-1: Add NVIDIA copyright header.Per repo guidelines, prepend the NVIDIA copyright header (current year) to all source files.
1996-2000: Per-module container init is correct; consider preallocating for fewer resizes.Initializing empty lists works but leads to repeated list growth in the subsequent merge. Since the batch size (number of requests) is known, preallocating per-module arrays can reduce Python list reallocations in hot paths.
Optional approach: allocate adapter_size as [0] * num_requests and weight_pointers as [0] * (3 * num_requests), then fill by request index. I’ve sketched a full refactor below in a later comment.
2019-2021: Alignment for requests without LoRA configs is correct; micro-optimization available.Appending a 0 and [0,0,0] per request preserves alignment. If this function appears on flame graphs, consider the preallocation pattern mentioned earlier to avoid repeated list concatenations for each (layer, module) across requests.
2042-2046: Tensor materialization: prefer explicit dtype via torch.tensor for clarity.Functionally identical, but torch.tensor(..., dtype=...) reads clearer than class constructors and avoids accidental device surprises.
- current_lora_params['adapter_size'] = torch.IntTensor( - current_lora_params['adapter_size']) - current_lora_params['weight_pointers'] = torch.LongTensor( - current_lora_params['weight_pointers']) + current_lora_params['adapter_size'] = torch.tensor( + current_lora_params['adapter_size'], dtype=torch.int32) + current_lora_params['weight_pointers'] = torch.tensor( + current_lora_params['weight_pointers'], dtype=torch.int64)
1964-2053: Optional: one-pass, preallocated build to reduce Python overhead in hot path.If profiling shows this function on the critical path, here’s a drop-in refactor that:
- Preallocates per-module arrays sized by the number of requests.
- Fills slots by request index in a single pass.
- Eliminates tmp_lora_params and most list concatenations.
@@ def _get_lora_params_from_requests(self, - lora_params = {} - tmp_lora_params = {} - request_list = scheduled_requests.context_requests + scheduled_requests.generation_requests + lora_params: dict = {} + request_list = scheduled_requests.context_requests + scheduled_requests.generation_requests + num_requests = len(request_list) @@ - # trace all requests to get the union set of the lora params - for request in request_list: - if request.py_lora_task_layer_module_configs is None: - continue - - for module in request.py_lora_task_layer_module_configs: - module_id = module.module_id - layer_id = module.layer_id - - if layer_id not in lora_params: - lora_params[layer_id] = {} - if module_id not in lora_params[layer_id]: - lora_params[layer_id][module_id] = { - 'adapter_size': [], - 'weight_pointers': [], - } - - scaling_vec_pointer = module.scaling_vec_pointer - if scaling_vec_pointer is None: - scaling_vec_pointer = 0 - tmp_lora_params[(request.py_request_id, layer_id, - module_id)] = { - 'adapter_size': [module.adapter_size], - 'weight_pointers': [ - module.weights_in_pointer, - module.weights_out_pointer, - scaling_vec_pointer - ], - } + # First pass: discover union of (layer_id, module_id) and preallocate + for request in request_list: + modules = request.py_lora_task_layer_module_configs + if not modules: + continue + for module in modules: + layer_id, module_id = module.layer_id, module.module_id + layer_map = lora_params.setdefault(layer_id, {}) + if module_id not in layer_map: + layer_map[module_id] = { + 'adapter_size': [0] * num_requests, + 'weight_pointers': [0] * (3 * num_requests), + } @@ - for request in request_list: - # Need to set default values for this case - if request.py_lora_task_layer_module_configs is None: - for layer_id in lora_params: - for module_id in lora_params[layer_id]: - current_lora_params = lora_params[layer_id][module_id] - current_lora_params['adapter_size'].append(0) - current_lora_params['weight_pointers'] += [0, 0, 0] - else: - for layer_id in lora_params: - for module_id in lora_params[layer_id]: - current_tmp_lora_params = tmp_lora_params.get( - (request.py_request_id, layer_id, module_id), None) - current_lora_params = lora_params[layer_id][module_id] - if current_tmp_lora_params is None: - current_lora_params['adapter_size'].append(0) - current_lora_params['weight_pointers'] += [0, 0, 0] - else: - current_lora_params[ - 'adapter_size'] += current_tmp_lora_params[ - 'adapter_size'] - current_lora_params[ - 'weight_pointers'] += current_tmp_lora_params[ - 'weight_pointers'] + # Second pass: fill preallocated slots by request index + for req_idx, request in enumerate(request_list): + modules = request.py_lora_task_layer_module_configs + if not modules: + continue # leave zeros + for module in modules: + layer_id, module_id = module.layer_id, module.module_id + cur = lora_params[layer_id][module_id] + cur['adapter_size'][req_idx] = int(module.adapter_size) + base = 3 * req_idx + cur['weight_pointers'][base + 0] = int(module.weights_in_pointer) + cur['weight_pointers'][base + 1] = int(module.weights_out_pointer) + cur['weight_pointers'][base + 2] = int(module.scaling_vec_pointer or 0) @@ - for layer_id in lora_params: - for module_id in lora_params[layer_id]: - current_lora_params = lora_params[layer_id][module_id] - current_lora_params['adapter_size'] = torch.IntTensor( - current_lora_params['adapter_size']) - current_lora_params['weight_pointers'] = torch.LongTensor( - current_lora_params['weight_pointers']) + for layer_id in lora_params: + for module_id in lora_params[layer_id]: + cur = lora_params[layer_id][module_id] + cur['adapter_size'] = torch.tensor(cur['adapter_size'], dtype=torch.int32) + cur['weight_pointers'] = torch.tensor(cur['weight_pointers'], dtype=torch.int64)This should be a drop-in replacement with equivalent output while reducing Python-side overhead.
If you’d like, I can push this variant as a follow-up patch and run a quick microbenchmark on representative batches to quantify the win.
2026-2038: Uselist.extend()for clearer and marginally faster list concatenationThe merge logic is sound, but switching from
+=toextend()makes it explicit that you’re appending one list onto another and avoids creating a temporary list. The None-coercion note is purely defensive—there’s no evidence in the Python binding thatweights_in_pointerorweights_out_pointercan ever beNone(they’re initialized from native pointers), so you can safely ignore it unless future changes introduce optional pointers.• Replace in tensorrt_llm/_torch/pyexecutor/model_engine.py (lines 2026–2038):
- current_lora_params['adapter_size'] += current_tmp_lora_params['adapter_size'] - current_lora_params['weight_pointers'] += current_tmp_lora_params['weight_pointers'] + current_lora_params['adapter_size'].extend(current_tmp_lora_params['adapter_size']) + current_lora_params['weight_pointers'].extend(current_tmp_lora_params['weight_pointers'])
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (4)
tensorrt_llm/_torch/peft/lora/layer.py(0 hunks)tensorrt_llm/_torch/pyexecutor/llm_request.py(1 hunks)tensorrt_llm/_torch/pyexecutor/model_engine.py(1 hunks)tests/unittest/_torch/modules/tests_lora_modules/test_lora_attention_pytorch_flow_vs_trt.py(0 hunks)
💤 Files with no reviewable changes (2)
- tests/unittest/_torch/modules/tests_lora_modules/test_lora_attention_pytorch_flow_vs_trt.py
- tensorrt_llm/_torch/peft/lora/layer.py
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.py: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else
Files:
tensorrt_llm/_torch/pyexecutor/llm_request.pytensorrt_llm/_torch/pyexecutor/model_engine.py
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Prepend NVIDIA copyright header (current year) to all source files
Files:
tensorrt_llm/_torch/pyexecutor/llm_request.pytensorrt_llm/_torch/pyexecutor/model_engine.py
🧠 Learnings (3)
📓 Common learnings
Learnt from: amitz-nv
PR: NVIDIA/TensorRT-LLM#7033
File: tensorrt_llm/_torch/pyexecutor/model_engine.py:2086-2092
Timestamp: 2025-08-19T12:45:35.429Z
Learning: DoRA (Delta Orthogonal Rank Adaptation) functionality has been removed from the PyTorch flow in tensorrt_llm/_torch/pyexecutor/model_engine.py. The is_dora field is computed but not used downstream in the PyTorch flow, so converting it to a tensor would be wasteful overhead.
📚 Learning: 2025-08-19T12:45:11.997Z
Learnt from: amitz-nv
PR: NVIDIA/TensorRT-LLM#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/model_engine.py
📚 Learning: 2025-08-19T12:45:35.429Z
Learnt from: amitz-nv
PR: NVIDIA/TensorRT-LLM#7033
File: tensorrt_llm/_torch/pyexecutor/model_engine.py:2086-2092
Timestamp: 2025-08-19T12:45:35.429Z
Learning: DoRA (Delta Orthogonal Rank Adaptation) functionality has been removed from the PyTorch flow in tensorrt_llm/_torch/pyexecutor/model_engine.py. The is_dora field is computed but not used downstream in the PyTorch flow, so converting it to a tensor would be wasteful overhead.
Applied to files:
tensorrt_llm/_torch/pyexecutor/model_engine.py
⏰ 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 (2)
tensorrt_llm/_torch/pyexecutor/model_engine.py (2)
2048-2052: Attaching host_request_types/prompt_lens_cpu/num_seqs is consistent with prior contract.This retains the public surface used by downstream consumers while dropping is_dora. LGTM.
2001-2012: LoRA scaling_vec_pointer fallback validated—no further changes neededThe PyTorch executor’s LoRA path correctly defaults
scaling_vec_pointerto 0 and downstream code intensorrt_llm/_torch/peft/lora/layer.pyonly inspectsadapter_sizeandweight_pointers(nois_dorareferences). The remainingis_dorachecks reside exclusively in the pure-Python fallback (tensorrt_llm/lora_manager.py), so this change does not impact the PyTorch flow.
shaharmor98
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM
|
PR_Github #16413 [ run ] completed with state |
…a_params_from_requests (NVIDIA#7203) Signed-off-by: Amit Zuker <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
…a_params_from_requests (NVIDIA#7203) Signed-off-by: Amit Zuker <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
…a_params_from_requests (NVIDIA#7203) Signed-off-by: Amit Zuker <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
…a_params_from_requests (NVIDIA#7203) Signed-off-by: Amit Zuker <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
…a_params_from_requests (NVIDIA#7203) Signed-off-by: Amit Zuker <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
…a_params_from_requests (NVIDIA#7203) Signed-off-by: Amit Zuker <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
…a_params_from_requests (NVIDIA#7203) Signed-off-by: Amit Zuker <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
…a_params_from_requests (NVIDIA#7203) Signed-off-by: Amit Zuker <[email protected]> Signed-off-by: Wangshanshan <[email protected]>
Description
Cherrypick from
mainof merge commit a1e03af of PR #7033Test 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 thestage-listparameter to access the appropriate container environment. Note: Does NOT update GitHub check status.For guidance on mapping tests to stage names, see
docs/source/reference/ci-overview.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip testing for latest commit on pull request.
--comment "Reason for skipping build/test"is required. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.reuse-pipeline
reuse-pipelineReuse a previous pipeline to validate current commit. This action will also kill all currently running builds associated with the pull request. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.
Summary by CodeRabbit
No user-facing changes; behavior remains consistent while maintainability and consistency are improved.