-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[TRTLLM-6825][fix] Update lora for phi4-mm #7149
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
[TRTLLM-6825][fix] Update lora for phi4-mm #7149
Conversation
|
Warning Rate limit exceeded@Wanli-Jiang has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 9 minutes and 34 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (7)
📝 WalkthroughWalkthroughAdds a configurable flag to control swapping of Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Caller as Caller (tests/app)
participant Util as _util.create_py_executor_instance
participant Engine as PyTorchModelEngine
participant RM as ResourceManager/PeftCacheManager
participant LM as LoraManager
participant MC as LoraModelConfig
Caller->>Util: build engine with lora_config
Util->>Engine: set_lora_model_config(targets, map, swap_flag)
Engine->>MC: LoraModelConfig(..., swap_flag)
Engine-->>Util: configured
Util->>RM: init PeftCacheManager(with MC)
RM->>LM: load_from_hf(..., model_config=MC)
LM->>LM: preprocess_lora_weights(lora_model, MC)
alt swap_flag == True
note right of LM #DFF2BF: perform swap of gate_up_proj.lora_B.weight
else swap_flag == False
note right of LM #FFD6D6: skip swap
end
LM-->>RM: lora weights loaded
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
✨ 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
|
f4adb25 to
78dc18b
Compare
|
/bot run |
|
PR_Github #16136 [ 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
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
tensorrt_llm/lora_helper.py (1)
82-103: Duplicate LoraConfig class defined in two modules — unify to a single type to avoid runtime confusion.Having
LoraConfigin bothtensorrt_llm.lora_managerandtensorrt_llm.lora_helperis error-prone (type checks, serialization, defaults can diverge). Prefer a single canonical class, and re-export it from helpers for convenience.Apply this minimal aliasing to remove the duplicate definition and re-use the manager’s class:
-from dataclasses import dataclass, field -from typing import Dict, List, Optional - -from ._utils import DictConversion +from dataclasses import dataclass, field +from typing import Dict, List, Optional + +from ._utils import DictConversion +from .lora_manager import LoraConfig as _ManagerLoraConfig @@ -@dataclass -class LoraConfig(DictConversion): - lora_dir: List[str] = field(default_factory=list) - lora_ckpt_source: str = "hf" - max_lora_rank: int = 64 - lora_target_modules: List[str] = field(default_factory=list) - trtllm_modules_to_hf_modules: Dict[str, str] = field(default_factory=dict) - max_loras: Optional[int] = None - max_cpu_loras: Optional[int] = None - swap_gate_up_proj_lora_b_weight: bool = True - - def __post_init__(self): - assert self.lora_ckpt_source in [ - "hf", "nemo" - ], (f"lora_ckpt_source must be one of 'hf' or 'nemo', got {self.lora_ckpt_source}" - ) - - @property - def missing_qkv_modules(self) -> List[str]: - return get_missing_qkv_modules_from_lora_modules( - self.lora_target_modules) +# Re-export the canonical LoraConfig to avoid duplication and divergence. +LoraConfig = _ManagerLoraConfigIf keeping a helper-only facade is required for public API stability, re-exporting preserves import paths (e.g.,
from tensorrt_llm.lora_helper import LoraConfig) without duplicating implementation.
🧹 Nitpick comments (5)
tensorrt_llm/lora_manager.py (1)
1031-1042: Make the swap robust: avoid mutating dict during iteration, assert even rows, and drop unnecessary clone.
- Mutating
lora_model[key]while iteratinglora_model.items()can be fragile. Iterate over a materialized list instead.- Assert row count is even before splitting; otherwise a silent half-split can corrupt weights.
- The extra
.clone()is not needed;torch.catallocates a fresh tensor.Apply this diff to harden the preprocessing:
- def preprocess_lora_weights(lora_model, model_config): - # Swap weights of gate_up_proj - if getattr(model_config, "swap_gate_up_proj_lora_b_weight", True): - for key, value in lora_model.items(): - if "gate_up_proj.lora_B.weight" in key: - original_weights = value.contiguous().clone() - half_split = original_weights.shape[0] // 2 - first_half = original_weights[:half_split, :] - second_half = original_weights[half_split:, :] - value = torch.cat((second_half, first_half), dim=0) - lora_model[key] = value - return lora_model + def preprocess_lora_weights(lora_model, model_config): + # Swap rows for gate_up_proj.lora_B.weight (gate | up ordering) + if getattr(model_config, "swap_gate_up_proj_lora_b_weight", True): + for key, value in list(lora_model.items()): + if "gate_up_proj.lora_B.weight" in key: + w = value.contiguous() + rows = w.shape[0] + assert rows % 2 == 0, ( + f"Expected even row count for {key}, got {rows}" + ) + half = rows // 2 + first_half = w[:half, :] + second_half = w[half:, :] + swapped = torch.cat((second_half, first_half), dim=0) + lora_model[key] = swapped + return lora_modeltensorrt_llm/lora_helper.py (3)
1-15: Update SPDX year range to include 2025.Repo guideline says to prepend NVIDIA copyright header (current year). Please bump to 2025.
Apply:
-# SPDX-FileCopyrightText: Copyright (c) 2022-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-FileCopyrightText: Copyright (c) 2022-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
22-41: Avoid duplicating “missing QKV” logic; reuse the manager’s single source of truth.This function mirrors
LoraManager.get_missing_qkv_modules. Maintaining two implementations risks divergence.Consider importing and delegating:
-from typing import Dict, List, Optional +from typing import Dict, List, Optional +from .lora_manager import LoraManager @@ -def get_missing_qkv_modules_from_lora_modules( - lora_target_modules: List[str]) -> List[str]: +def get_missing_qkv_modules_from_lora_modules( + lora_target_modules: List[str]) -> List[str]: @@ - missing_qkv_modules = [] - if any(x in lora_target_modules for x in ["attn_q", "attn_k", "attn_v"]): - for lora_module in ["attn_q", "attn_k", "attn_v"]: - if lora_module not in lora_target_modules: - missing_qkv_modules.append(lora_module) - if any(x in lora_target_modules - for x in ["cross_attn_q", "cross_attn_k", "cross_attn_v"]): - for lora_module in ["cross_attn_q", "cross_attn_k", "cross_attn_v"]: - if lora_module not in lora_target_modules: - missing_qkv_modules.append(lora_module) - return missing_qkv_modules + return LoraManager.get_missing_qkv_modules(lora_target_modules)
43-59: De-duplicate default module mapping; import from a single location.A second copy of the TRT-LLM↔HF mapping is hard to keep in sync (e.g., new modules like
mlp_gate_up). Prefer re-exporting the mapping fromlora_manager.py.For example:
-from ._utils import DictConversion +from ._utils import DictConversion +from .lora_manager import get_default_trtllm_modules_to_hf_modules as _default_map @@ -def get_default_trtllm_modules_to_hf_modules(): - """Get default mapping from TensorRT-LLM module names to HuggingFace module names.""" - return { - "attn_q": "q_proj", - "attn_k": "k_proj", - "attn_v": "v_proj", - "attn_dense": "o_proj", - "mlp_h_to_4h": "gate_proj", - "mlp_4h_to_h": "down_proj", - "mlp_gate": "up_proj", - "mlp_gate_up": "gate_up_proj", - "moe_h_to_4h": "w1", - "moe_4h_to_h": "w2", - "moe_gate": "w3", - "moe_router": "gate", - } +def get_default_trtllm_modules_to_hf_modules(): + """Get default mapping from TensorRT-LLM module names to HuggingFace module names.""" + return _default_map()tensorrt_llm/_torch/models/modeling_phi4mm.py (1)
265-286: LoRA requests per modality — LGTM with a minor suggestion.The static helper returns consistent
LoRARequests for image/audio modalities. Minor nit: use_for the throwaway loop variable.Apply:
- ) for i in range(num_requests) + ) for _ in range(num_requests)
📜 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 (8)
tensorrt_llm/_torch/models/modeling_phi4mm.py(1 hunks)tensorrt_llm/_torch/pyexecutor/_util.py(1 hunks)tensorrt_llm/_torch/pyexecutor/model_engine.py(1 hunks)tensorrt_llm/_torch/pyexecutor/resource_manager.py(1 hunks)tensorrt_llm/lora_helper.py(1 hunks)tensorrt_llm/lora_manager.py(4 hunks)tests/integration/defs/perf/pytorch_model_config.py(1 hunks)tests/integration/defs/test_e2e.py(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
- tensorrt_llm/_torch/pyexecutor/model_engine.py
- tensorrt_llm/_torch/pyexecutor/_util.py
- tensorrt_llm/_torch/pyexecutor/resource_manager.py
- tests/integration/defs/perf/pytorch_model_config.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/lora_manager.pytensorrt_llm/lora_helper.pytests/integration/defs/test_e2e.pytensorrt_llm/_torch/models/modeling_phi4mm.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/lora_manager.pytensorrt_llm/lora_helper.pytests/integration/defs/test_e2e.pytensorrt_llm/_torch/models/modeling_phi4mm.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 (7)
tensorrt_llm/lora_manager.py (2)
1053-1053: HF LoRA path preprocess hook — LGTM.The guarded call to
preprocess_lora_weights(lora_model, model_config)keeps HF-loading compatible across models while allowing Phi4MM to disable swapping.
244-244: swap_gate_up_proj_lora_b_weight flag fully propagated and verified
All instantiations, defaults, mappings, and tests correctly include or reference the newswap_gate_up_proj_lora_b_weightflag. No missing call sites or mappings were found.tensorrt_llm/lora_helper.py (1)
61-80: LoRA dispatcher wrapper — LGTM.The thin wrapper keeps call sites simple and preserves the existing public API.
tests/integration/defs/test_e2e.py (2)
2489-2491: Updated image expected keywords for Phi4MM — LGTM.The new tokens reflect the revised LoRA targets/mappings and match the updated modality behavior.
2497-2498: Updated image_audio expected keywords for Phi4MM — LGTM.Consistent with the modality handling changes.
tensorrt_llm/_torch/models/modeling_phi4mm.py (2)
259-261: Disable swap of gate_up_proj.lora_B.weight for Phi4MM — correct model-specific override.Default is True globally; Phi4MM sets it to False here, which matches the intended accuracy fix.
246-257: ✅ Confirmed mlp_gate_up registration and mapping
The LoRA target modules and mappings inmodeling_phi4mm.pycorrectly use"mlp_gate_up"→"gate_up_proj", and we’ve verified thatLORA_MODULE_IDSinlora_manager.pyincludes
"mlp_gate_up": 18No further changes needed.
78dc18b to
c4791f9
Compare
Signed-off-by: Wanli Jiang <[email protected]>
c4791f9 to
7e4974b
Compare
|
/bot run |
|
PR_Github #16139 [ run ] triggered by Bot |
|
PR_Github #16136 [ run ] completed with state |
|
PR_Github #16139 [ run ] completed with state |
|
/bot run |
|
PR_Github #16171 [ run ] triggered by Bot |
|
PR_Github #16171 [ run ] completed with state |
Signed-off-by: Wanli Jiang <[email protected]>
This PR is copied from #6817, which can fix the accuracy issue in phi4-mm when using LoRA.
Summary by CodeRabbit
New Features
Tests
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 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.