Implementation:AI4Finance Foundation FinGPT convert linear layer to lora
| Knowledge Sources | |
|---|---|
| Domains | Deep_Learning, Parameter_Efficient_Finetuning |
| Last Updated | 2026-10-18 00:00 GMT |
Overview
Concrete tool for injecting custom LoRA adapters into linear layers by module name pattern provided by the FinGPT RAG training utilities.
Description
The convert_linear_layer_to_lora function replaces `nn.Linear` modules whose names contain a specified pattern with `LinearLayer_LoRA` modules. Unlike the PEFT library's `get_peft_model`, this custom implementation directly replaces linear layers with LoRA-adapted versions that add `lora_dropout(x) @ lora_right_weight @ lora_left_weight * lora_scaling` during training (disabled in eval mode).
The related only_optimize_lora_parameters function freezes all parameters except `lora_right_weight` and `lora_left_weight`, enabling memory-efficient training.
Usage
Import this function when you need custom LoRA injection in DeepSpeed training:
- DeepSpeed SFT with LoRA: Replacing linear layers matching a name pattern.
- Custom LoRA implementation: Using DeepSpeed-native LoRA rather than PEFT.
Code Reference
Source Location
- Repository: FinGPT
- File: fingpt/FinGPT_RAG/instruct-FinGPT/training/utils/module/lora.py
- Lines: L89-104 (convert_linear_layer_to_lora), L13-87 (LinearLayer_LoRA), L134-141 (only_optimize_lora_parameters)
Signature
def convert_linear_layer_to_lora(
model: nn.Module,
part_module_name: str,
lora_dim: int = 0,
lora_scaling: int = 1,
lora_droppout: int = 0,
) -> nn.Module
def only_optimize_lora_parameters(
model: nn.Module,
) -> nn.Module
Import
from utils.module.lora import convert_linear_layer_to_lora, only_optimize_lora_parameters
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| model | nn.Module | Yes | Base model to inject LoRA into |
| part_module_name | str | Yes | Module name pattern to match (e.g., "q_proj") |
| lora_dim | int | No | LoRA rank (0 disables LoRA, default 0) |
| lora_scaling | int | No | LoRA scaling factor (default 1) |
| lora_droppout | int | No | LoRA dropout rate (default 0) |
Outputs
| Name | Type | Description |
|---|---|---|
| return value | nn.Module | Model with LinearLayer_LoRA modules replacing matching Linear layers |
Usage Examples
Inject LoRA into Model
from utils.module.lora import convert_linear_layer_to_lora, only_optimize_lora_parameters
# Inject LoRA into all linear layers containing "q_proj" in their name
model = convert_linear_layer_to_lora(
model,
part_module_name="q_proj",
lora_dim=8,
lora_scaling=1,
lora_droppout=0,
)
# Freeze all non-LoRA parameters
model = only_optimize_lora_parameters(model)
Related Pages
Implements Principle
- Principle:AI4Finance_Foundation_FinGPT_DeepSpeed_Supervised_Finetuning
- Principle:AI4Finance_Foundation_FinGPT_LoRA_Fine_Tuning