Skip to content

Conversation

@amitz-nv
Copy link
Collaborator

@amitz-nv amitz-nv commented Sep 29, 2025

Description

The bug: Generated output of LoRA adapters with fused modules (such as "attn_qkv" or "mlp_gate_up") with TP>1 was bad.

The cause: The TP split logic of fused LoRA adapter modules was wrong - instead of splitting each "sub-module" weight (e.g. in "attn_qkv" split Wq by TP size, and do the same for Wk and Wv) between the different ranks, the concatenation of the "sub-modules" was split (WqWkWv was split by TP size).

The fix: First split the concatenation to the "sub-modules", then split each one by the TP rank, and then concatenate the interleaved parts. e.g. for "attn_qkv" - convert W=torch.cat([Wq, Wk, Wv]) to W=torch.chat([Wq_rank0, Wk_rank0, Wv_rank0, ..., Wq_rankN, Wk_rankN, Wv_rankN]) where N=TP size.

Notes:

  • This bug and this fix also apply for TRT-python flow.
  • There's no TRT-python test of this fix because the test uses Phi-3 model and Phi-3-mini-4k-instruct-ru-lora adapter, as that's the only public LoRA adapter I found that uses fused attention QKV and fused MLP gate up, and Phi-3 doesn't work well on TRT-python with TP>1 as reported in https://nvbugspro.nvidia.com/bug/5393849

Test Coverage

  • tests/unittest/llmapi/test_llm_multi_gpu_pytorch.py::test_phi3_lora_fused_modules_output_on_tp2_identical_to_tp1

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

  • 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.

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.

Summary by CodeRabbit

  • New Features
    • Improved LoRA support with explicit runtime mapping and model configuration, enabling better multi-GPU and pipeline/tensor parallel integration.
    • Added handling for fused QKV and MLP up-projection modules in LoRA adapters for broader model compatibility.
  • Bug Fixes
    • Ensures LoRA fused-module outputs are consistent across tensor parallel sizes (e.g., TP1 vs TP2).
  • Tests
    • Added end-to-end tests validating identical outputs for LoRA fused modules across TP settings and expanded utilities for LoRA adapter loading.

@amitz-nv amitz-nv self-assigned this Sep 29, 2025
@amitz-nv amitz-nv requested review from a team as code owners September 29, 2025 13:06
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 29, 2025

📝 Walkthrough

Walkthrough

Refactors LoRA management to require explicit Mapping and Python-side ModelConfig, replacing runtime_mapping usage. Introduces ModelConfig.from_model_config_cpp conversion and ModelConfigCpp alias. Updates PEFT/KV cache managers’ signatures, exposes PeftCacheManager.get_lora_manager, adjusts call sites (executors/model runners), extends default module mapping, and adds TP1/TP2 fused-LoRA tests.

Changes

Cohort / File(s) Summary
LoRA manager core refactor
tensorrt_llm/lora_manager.py
LoraManager now requires keyword-only mapping and model_config; removes runtime_mapping across loaders; adds TP interleaving for fused weights (attn_qkv, mlp_gate_up); updates rank/experts handling; stores mapping/model_config; imports itertools.
Runtime model config bridging
tensorrt_llm/runtime/generation.py, tensorrt_llm/runtime/model_runner_cpp.py
Adds ModelConfig.from_model_config_cpp(mapping) to build Python config from C++; introduces alias ModelConfigPython in model_runner_cpp and uses it for conversions; updates dtype import.
PEFT/resource manager API updates
tensorrt_llm/_torch/pyexecutor/resource_manager.py
Replaces public ModelConfig with ModelConfigCpp in KVCacheManager and PeftCacheManager signatures; initializes LoraManager with Mapping and ModelConfigPython.from_model_config_cpp; adds PeftCacheManager.get_lora_manager(); removes runtime_mapping usage in add_request_peft.
Executor/model runners call-site updates
tensorrt_llm/executor/worker.py, tensorrt_llm/runtime/model_runner.py, tensorrt_llm/runtime/enc_dec_model_runner.py
Construct LoraManager with mapping and model_config; remove runtime_mapping parameter from load_from_* calls; use peft_cache_manager.get_lora_manager() instead of cpp_peft_cache_manager injection.
Default LoRA module mapping
tensorrt_llm/lora_helper.py
Adds "attn_qkv" → "qkv_proj" to default TRT-LLM↔HF module mapping.
Tests for fused LoRA and TP parity
tests/unittest/llmapi/lora_test_utils.py, tests/unittest/llmapi/test_llm_multi_gpu_pytorch.py
New utilities to run RU LoRA adapter with fused modules and compare TP=1 vs TP=2 outputs; adds test invoking the check.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor App
  participant Worker as executor/worker.py
  participant PeftMgr as PeftCacheManager
  participant LoraMgr as LoraManager
  participant CppCfg as ModelConfigCpp
  participant PyCfg as ModelConfigPython

  App->>Worker: start / load model (+llm_args)
  Worker->>Worker: derive Mapping from llm_args (or default)
  Worker->>PeftMgr: (optional) init with model_config: CppCfg
  note over PeftMgr: Build mapping\nPyCfg = ModelConfigPython.from_model_config_cpp(CppCfg, mapping)
  PeftMgr->>LoraMgr: __init__(mapping, model_config=PyCfg)
  Worker->>LoraMgr: load_from_ckpt(model_dirs, model_config=PyCfg)
  note over LoraMgr: Uses internal mapping/model_config\n(no runtime_mapping param)
Loading
sequenceDiagram
  autonumber
  actor App
  participant Runner as runtime/model_runner.py
  participant LoraMgr as LoraManager
  participant PyCfg as ModelConfig (Python)
  participant Engine as TRT-LLM Engine

  App->>Runner: from_engine(..., runtime_mapping, model_config=PyCfg)
  Runner->>LoraMgr: __init__(mapping=runtime_mapping, model_config=PyCfg)
  Runner->>LoraMgr: load_from_ckpt(paths, model_config=PyCfg)
  LoraMgr->>Engine: provide interleaved weights (attn_qkv, mlp_gate_up)
Loading
sequenceDiagram
  autonumber
  participant RunnerCPP as runtime/model_runner_cpp.py
  participant CppCfg as ModelConfigCpp
  participant PyCfg as ModelConfigPython
  participant LoraMgr as LoraManager

  RunnerCPP->>PyCfg: from_model_config_cpp(CppCfg, mapping)
  RunnerCPP->>LoraMgr: __init__(mapping, model_config=PyCfg)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • shaharmor98
  • tomeras91
  • nv-guomingz
  • Superjomn

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 48.28% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title directly identifies the main change—correcting fused LoRA adapter weight splitting in both PyTorch and TRT-Python flows when tensor-parallel size exceeds one—and thus accurately summarizes the pull request’s core intent. It references the precise component and condition being addressed without veering into unrelated details. Although it includes a URL and a “[fix]” tag, the phrasing remains focused on the substantive change.
Description Check ✅ Passed The pull request description includes all required sections defined in the template, including a clear ## Description, a corresponding ## Test Coverage listing relevant tests, a ## PR Checklist, and the GitHub Bot Help text, fulfilling the repository’s description requirements.
✨ 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: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
tensorrt_llm/runtime/enc_dec_model_runner.py (1)

1-1: Missing NVIDIA Apache-2.0 header

This source file lacks the required NVIDIA header. Please add it to comply with project policy. Apply at file top:

+# SPDX-FileCopyrightText: Copyright (c) 2022-2025 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.

As per coding guidelines.

tensorrt_llm/lora_manager.py (1)

821-859: NeMo path misses fused-module TP interleaving

For NeMo adapters (attn_qkv), t_out is the fused [WqWkWv]. With TP>1 we must interleave per-rank chunks as done in the HF path; otherwise outputs diverge across TP>1 vs TP=1.

  • Either lift interleave_fused_lora_weights_for_tp to a module/class helper and reuse here, or duplicate the small logic locally.
  • Minimal insertion after t_out is read (when lora_module == "attn_qkv"):
                         t_in = all_lora_weights[layer_idx]["in"]
                         t_out = all_lora_weights[layer_idx]["out"]
+                        # Interleave fused QKV across TP ranks
+                        tp_size = self._mapping.tp_size
+                        if tp_size > 1:
+                            rank_dim = 0  # fused concatenation is along out_dim
+                            q_size = self._model_config.head_size * self._model_config.num_heads
+                            kv_size = self._model_config.head_size * self._model_config.num_kv_heads
+                            expected = q_size + 2 * kv_size
+                            if t_out.shape[rank_dim] != expected:
+                                raise ValueError(
+                                    f"NeMo attn_qkv fused dim mismatch: expected {expected}, got {t_out.shape[rank_dim]}"
+                                )
+                            interleaved = interleave_fused_lora_weights_for_tp(
+                                t_out, rank_dim, tp_size, [q_size, kv_size, kv_size]
+                            )
+                            t_out = torch.cat(interleaved, dim=rank_dim)

If you prefer not to duplicate, extract interleave_fused_lora_weights_for_tp to a @staticmethod on LoraManager and call it from both loaders.

🧹 Nitpick comments (6)
tests/unittest/llmapi/test_llm_multi_gpu_pytorch.py (1)

8-8: Mark the new fused‑LoRA test as requiring 2 GPUs

The test internally runs TP=2; add gpu2 mark to avoid scheduling on single‑GPU CI.

 @pytest.mark.gpu2
 def test_llama_7b_lora_tp2():
@@
 
-
-def test_lora_fused_modules_output_on_tp2_identical_to_tp1() -> None:
+@pytest.mark.gpu2
+def test_lora_fused_modules_output_on_tp2_identical_to_tp1() -> None:
     check_lora_fused_modules_output_tp2_identical_to_tp1(
         LLM,
         # Disable CUDA graph
         # TODO: remove this once we have a proper fix for CUDA graph in LoRA
         cuda_graph_config=None)

Based on learnings.

Also applies to: 62-67

tests/unittest/llmapi/lora_test_utils.py (1)

1-1: Add NVIDIA Apache-2.0 SPDX header

Per coding guidelines, prepend the SPDX header with current year to .py files.

+# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
 import json
tensorrt_llm/executor/worker.py (1)

199-207: TRT‑python: Mapping() defaults to tp_size=1 — emit a clear runtime warning

This matches the PR note, but it’s easy to miss at runtime. Add a warning when LoRA plugin is enabled and we fall back to a default Mapping so users don’t assume TP>1 fused‑LoRA is correct in TRT‑python.

-                mapping = Mapping(
-                ) if self.llm_args is None else self.llm_args.parallel_config.to_mapping(
-                )
+                mapping = (Mapping()
+                           if self.llm_args is None
+                           else self.llm_args.parallel_config.to_mapping())
+                if self.llm_args is None:
+                    logger.warning(
+                        "LoRA: TRT‑python flow instantiated LoraManager with a default Mapping (tp_size=1). "
+                        "Fused modules with TP>1 will not split correctly in this flow."
+                    )
tensorrt_llm/lora_manager.py (1)

1-36: Coding guideline nit: headers and imports

  • Files lack the NVIDIA Apache-2.0 header. If the repo enforces it, add it in a follow-up.
  • Import style directly imports classes; repo already uses this widely, but guidelines prefer module namespaces. Optional cleanup.
tensorrt_llm/_torch/pyexecutor/resource_manager.py (2)

1134-1144: LoraManager construction with Mapping + ModelConfigPython: OK; add minor guard

Wiring Mapping from WorldConfig and passing ModelConfigPython.from_model_config_cpp(...) is the right direction. Consider validating world_config.tensor_parallelism > 0 and consistency with model_config (e.g., hidden_size % tp_size == 0) at construction to fail fast on misconfig.


1-20: Python version compatibility (typing)

This file uses list[...] and | unions, which require Python 3.9/3.10+. If 3.8 must be supported (per guidelines), switch to typing.List / Optional[...] or add from future import annotations at module top.

📜 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 a0d489a and 9483228.

📒 Files selected for processing (10)
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py (8 hunks)
  • tensorrt_llm/executor/worker.py (3 hunks)
  • tensorrt_llm/lora_helper.py (1 hunks)
  • tensorrt_llm/lora_manager.py (5 hunks)
  • tensorrt_llm/runtime/enc_dec_model_runner.py (2 hunks)
  • tensorrt_llm/runtime/generation.py (2 hunks)
  • tensorrt_llm/runtime/model_runner.py (2 hunks)
  • tensorrt_llm/runtime/model_runner_cpp.py (2 hunks)
  • tests/unittest/llmapi/lora_test_utils.py (1 hunks)
  • tests/unittest/llmapi/test_llm_multi_gpu_pytorch.py (2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Use only spaces, no tabs; indent with 4 spaces.

Files:

  • tensorrt_llm/runtime/model_runner.py
  • tests/unittest/llmapi/test_llm_multi_gpu_pytorch.py
  • tensorrt_llm/runtime/enc_dec_model_runner.py
  • tensorrt_llm/lora_helper.py
  • tensorrt_llm/executor/worker.py
  • tensorrt_llm/runtime/model_runner_cpp.py
  • tensorrt_llm/lora_manager.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
  • tests/unittest/llmapi/lora_test_utils.py
  • tensorrt_llm/runtime/generation.py
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+.
Indent Python code with 4 spaces; do not use tabs.
Maintain module namespace when importing; prefer 'from package.subpackage import foo' then 'foo.SomeClass()' instead of importing the class directly.
Python filenames should be snake_case (e.g., some_file.py).
Python classes use PascalCase names.
Functions and methods use snake_case names.
Local variables use snake_case; prefix 'k' for variables that start with a number (e.g., k_99th_percentile).
Global variables use upper SNAKE_CASE prefixed with 'G' (e.g., G_MY_GLOBAL).
Constants use upper SNAKE_CASE (e.g., MY_CONSTANT).
Avoid shadowing variables from an outer scope.
Initialize all externally visible members of a class in the constructor.
Prefer docstrings for interfaces that may be used outside a file; comments for in-function or file-local interfaces.
Use Google-style docstrings for classes and functions (Sphinx-parsable).
Document attributes and variables inline so they render under the class/function docstring.
Avoid reflection when a simpler, explicit approach suffices (e.g., avoid dict(**locals()) patterns).
In try/except, catch the most specific exceptions possible.
For duck-typing try/except, keep the try body minimal and use else for the main logic.

Files:

  • tensorrt_llm/runtime/model_runner.py
  • tests/unittest/llmapi/test_llm_multi_gpu_pytorch.py
  • tensorrt_llm/runtime/enc_dec_model_runner.py
  • tensorrt_llm/lora_helper.py
  • tensorrt_llm/executor/worker.py
  • tensorrt_llm/runtime/model_runner_cpp.py
  • tensorrt_llm/lora_manager.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
  • tests/unittest/llmapi/lora_test_utils.py
  • tensorrt_llm/runtime/generation.py
**/*.{cpp,cxx,cc,h,hpp,hh,hxx,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Prepend the NVIDIA Apache-2.0 copyright header with current year to the top of all source files (e.g., .cpp, .h, .cu, .py).

Files:

  • tensorrt_llm/runtime/model_runner.py
  • tests/unittest/llmapi/test_llm_multi_gpu_pytorch.py
  • tensorrt_llm/runtime/enc_dec_model_runner.py
  • tensorrt_llm/lora_helper.py
  • tensorrt_llm/executor/worker.py
  • tensorrt_llm/runtime/model_runner_cpp.py
  • tensorrt_llm/lora_manager.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
  • tests/unittest/llmapi/lora_test_utils.py
  • tensorrt_llm/runtime/generation.py
🧠 Learnings (7)
📓 Common learnings
Learnt from: shaharmor98
PR: NVIDIA/TensorRT-LLM#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.
📚 Learning: 2025-08-26T06:07:02.166Z
Learnt from: shaharmor98
PR: NVIDIA/TensorRT-LLM#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/runtime/model_runner.py
  • tensorrt_llm/runtime/enc_dec_model_runner.py
  • tensorrt_llm/executor/worker.py
  • tensorrt_llm/lora_manager.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.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_multi_gpu_pytorch.py
📚 Learning: 2025-09-09T09:40:45.658Z
Learnt from: fredricz-20070104
PR: NVIDIA/TensorRT-LLM#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/unittest/llmapi/test_llm_multi_gpu_pytorch.py
📚 Learning: 2025-08-06T13:58:07.506Z
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_multi_gpu_pytorch.py
📚 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
📚 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/executor/worker.py
🧬 Code graph analysis (9)
tensorrt_llm/runtime/model_runner.py (1)
tensorrt_llm/lora_manager.py (1)
  • LoraManager (640-1260)
tests/unittest/llmapi/test_llm_multi_gpu_pytorch.py (2)
tests/unittest/llmapi/lora_test_utils.py (1)
  • check_lora_fused_modules_output_tp2_identical_to_tp1 (51-65)
tensorrt_llm/llmapi/llm.py (1)
  • LLM (1022-1038)
tensorrt_llm/runtime/enc_dec_model_runner.py (2)
tensorrt_llm/lora_manager.py (1)
  • LoraManager (640-1260)
tensorrt_llm/runtime/model_runner.py (1)
  • mapping (821-822)
tensorrt_llm/executor/worker.py (4)
tensorrt_llm/mapping.py (1)
  • Mapping (32-519)
tensorrt_llm/llmapi/llm_args.py (1)
  • to_mapping (283-296)
tensorrt_llm/lora_manager.py (1)
  • LoraManager (640-1260)
tensorrt_llm/_torch/pyexecutor/resource_manager.py (1)
  • get_lora_manager (1145-1146)
tensorrt_llm/runtime/model_runner_cpp.py (2)
tensorrt_llm/runtime/generation.py (2)
  • ModelConfig (608-685)
  • from_model_config_cpp (657-685)
tensorrt_llm/lora_manager.py (1)
  • LoraManager (640-1260)
tensorrt_llm/lora_manager.py (2)
tensorrt_llm/mapping.py (1)
  • Mapping (32-519)
tensorrt_llm/_torch/pyexecutor/resource_manager.py (1)
  • PeftCacheManager (1092-1210)
tensorrt_llm/_torch/pyexecutor/resource_manager.py (2)
tensorrt_llm/runtime/generation.py (2)
  • ModelConfig (608-685)
  • from_model_config_cpp (657-685)
tensorrt_llm/lora_manager.py (1)
  • LoraManager (640-1260)
tests/unittest/llmapi/lora_test_utils.py (2)
tensorrt_llm/llmapi/llm.py (1)
  • BaseLLM (107-739)
tensorrt_llm/executor/request.py (1)
  • LoRARequest (24-53)
tensorrt_llm/runtime/generation.py (2)
tensorrt_llm/_utils.py (3)
  • binding_to_str_dtype (200-203)
  • dtype (951-952)
  • dtype (959-969)
tensorrt_llm/mapping.py (1)
  • pp_rank (346-348)
🪛 Ruff (0.13.1)
tests/unittest/llmapi/lora_test_utils.py

29-29: Unused noqa directive (non-enabled: D205)

Remove unused noqa directive

(RUF100)


56-56: Unused noqa directive (non-enabled: D205)

Remove unused noqa directive

(RUF100)

🔇 Additional comments (12)
tensorrt_llm/lora_helper.py (1)

49-49: Good addition; verify cross-attn fused coverage

Adding "attn_qkv"→"qkv_proj" matches the fused QKV path. Do we also need a mapping for any fused cross-attention variant (e.g., "cross_attn_qkv") if supported by some checkpoints? If not applicable, ignore.

tensorrt_llm/runtime/enc_dec_model_runner.py (1)

177-180: Correctly binding LoraManager to mapping/model_config

Passing mapping and model_config at construction is the right direction and consistent with updated APIs. Please confirm encoder/decoder components load the intended LoRA targets (esp. for fused modules).

Also applies to: 202-205

tensorrt_llm/runtime/model_runner.py (1)

614-616: LGTM: LoraManager now bound to mapping/model_config

Instantiation aligns with the new API; checkpoint loading calls are correctly updated (no runtime_mapping arg).

Also applies to: 723-725

tensorrt_llm/runtime/model_runner_cpp.py (2)

35-37: Import alias is clear and narrows public surface

Using ModelConfig as ModelConfigPython improves clarity between bindings vs Python config.


281-286: Constructing LoraManager with mapping + converted ModelConfigPython

This matches the C++ flow. Please confirm ModelConfigPython.from_model_config_cpp supplies head_size/num_heads/num_kv_heads used by fused QKV split before calling load_from_ckpt; the per‑adapter loading later uses the full runtime ModelConfig, so we’re covered for lora_target_modules.

tensorrt_llm/executor/worker.py (1)

211-219: PyTorch path uses ResourceManager-provisioned LoraManager

Good change—centralizes mapping/model_config and avoids signature drift with cpp_peft_cache_manager.

tensorrt_llm/lora_manager.py (3)

1080-1083: Rank dimension selection LGTM

Using rank_dim = 1 for MoE (stacked [experts, out, rank]) and 0 otherwise aligns the split dimension for t_out and the rank dimension for t_in.
Please confirm MoE LoRA shapes always follow [num_experts, out, rank] / [num_experts, rank, in]. If not, add an explicit shape check.


664-669: Constructor changes: mapping/model_config wiring looks correct

Accepting Mapping and Python-side ModelConfig up-front simplifies downstream TP logic and removes runtime_mapping ambiguity.

Also applies to: 714-716


1025-1033: Zero-filling missing q/k/v modules: verify interaction with fused targets

When lora_target_modules contains a fused name (e.g., attn_qkv), we also extend with separate q/k/v here. Ensure downstream consumers don't double-emit both fused and unfused inputs for the same layer/module to CPP. If both are present, prefer one convention.

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

15-16: ModelConfig aliasing and import: OK

Introducing ModelConfigPython and ModelConfigCpp aliases clarifies Python vs C++ config usage.

Also applies to: 35-36


1145-1146: Accessor get_lora_manager(): OK

Simple, needed by callers.


1157-1164: Ensure request.lora_config is set when loading a new adapter

Comment notes CPP requires both config and weights or neither. In the “not cached” path you set request.lora_weights but do not set request.lora_config. Confirm that the CPP side permits weights-only here or that request.lora_config is populated elsewhere before add_request_peft. If not, populate it from self._lora_manager.cpp_lora_config[uid] similarly to weights.

             elif request.lora_weights is None and request.py_lora_path:
                 self._lora_manager.load_from_ckpt(
                     [request.py_lora_path],
                     model_config=self._lora_model_config,
                     uids=[request.lora_task_id],
                     ckpt_source=self._lora_config.lora_ckpt_source)
                 request.lora_weights = self._lora_manager.cpp_lora_weights[
                     request.lora_task_id]
+                request.lora_config = self._lora_manager.cpp_lora_config[
+                    request.lora_task_id]

Also applies to: 1165-1171

@amitz-nv amitz-nv force-pushed the dev-fix-lora-fused-modules-weights branch from 9483228 to ddac0c7 Compare September 29, 2025 15:06
@amitz-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20279 [ run ] triggered by Bot

@amitz-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20282 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20279 [ run ] completed with state ABORTED
LLM/main/L0_MergeRequest_PR #15291 (Blue Ocean) completed with status: ABORTED

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20282 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #15293 completed with status: 'FAILURE'

@amitz-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20362 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20362 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #15361 completed with status: 'FAILURE'

@amitz-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20372 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20372 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #15367 completed with status: 'FAILURE'

@amitz-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20385 [ run ] triggered by Bot

@amitz-nv amitz-nv changed the title [https://nvbugs/5510879][fix] Fix pytorch flow fused LoRA adapter modules weight split with TP>1 [https://nvbugs/5510879][fix] Fix pytorch & TRT-python flows fused LoRA adapter modules weight split with TP>1 Sep 30, 2025
@amitz-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20393 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20385 [ run ] completed with state ABORTED
LLM/main/L0_MergeRequest_PR #15380 (Blue Ocean) completed with status: ABORTED

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20393 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #15387 completed with status: 'FAILURE'

… from LoraManager load methods to its constructor, remove other TP references in load_from_model_dir as until now it always received default mapping with TP=1 as CPP expects to work on full non-split weights

Signed-off-by: Amit Zuker <[email protected]>
…ction, add support for LorA fused attn QKV, pass ModelConfig to LoraManager ctor for fused QKV LoRA adapter support

Signed-off-by: Amit Zuker <[email protected]>
Signed-off-by: Amit Zuker <[email protected]>
…ch flow, minor fixes & improvements

Signed-off-by: Amit Zuker <[email protected]>
Signed-off-by: Amit Zuker <[email protected]>
Signed-off-by: Amit Zuker <[email protected]>
… function, pass cpp_peft_cache_manager to LoraManager creation, add 'phi3' to relevant test names

Signed-off-by: Amit Zuker <[email protected]>
Signed-off-by: Amit Zuker <[email protected]>
@amitz-nv amitz-nv force-pushed the dev-fix-lora-fused-modules-weights branch from 2857625 to 30e6fb5 Compare October 12, 2025 07:02
@amitz-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21087 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21087 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #15936 completed with status: 'FAILURE'

@amitz-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #21089 [ run ] triggered by Bot

@amitz-nv amitz-nv enabled auto-merge (squash) October 12, 2025 17:12
@tensorrt-cicd
Copy link
Collaborator

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

@amitz-nv amitz-nv merged commit fac47e2 into NVIDIA:main Oct 12, 2025
5 checks passed
amitz-nv added a commit to amitz-nv/TensorRT-LLM that referenced this pull request Oct 13, 2025
…RA adapter modules weight split with TP>1 (NVIDIA#8063)

Signed-off-by: Amit Zuker <[email protected]>
amitz-nv added a commit to amitz-nv/TensorRT-LLM that referenced this pull request Oct 13, 2025
…RA adapter modules weight split with TP>1 (NVIDIA#8063)

Signed-off-by: Amit Zuker <[email protected]>
amitz-nv added a commit to amitz-nv/TensorRT-LLM that referenced this pull request Oct 15, 2025
…RA adapter modules weight split with TP>1 (NVIDIA#8063)

Signed-off-by: Amit Zuker <[email protected]>
yufeiwu-nv pushed a commit to yufeiwu-nv/TensorRT-LLM that referenced this pull request Oct 24, 2025
…RA adapter modules weight split with TP>1 (NVIDIA#8063)

Signed-off-by: Amit Zuker <[email protected]>
Signed-off-by: yufeiwu-nv <[email protected]>
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.

4 participants