LoRA微调模型结构可训参数和配置详解
背景
上一篇主要整理了一些关于LoRA的知识点总结,本文则主要从以下几方面继续学习分析LoRA微调策略。上篇 LoRA常见知识点。
测试内容和代码
1、构建一个简单的两层线性网络,加relu
激活函数,在第一层Linear中使用LoRA策略,打印看下模型结构。复习Lora在第一层Linear网络的结构,即在第一层旁增加Lora策略。
2、打印原始网络结构中可训练的参数和LoRA策略下的参数量。
3、LoraConfig类的一些参数解释。
整体代码如下:
import torch
import torch.nn as nn
from peft import get_peft_model, LoraConfig
# 定义基础模型
class SimpleMLP(nn.Module):
def __init__(self):
super(SimpleMLP, self).__init__()
self.fc1 = nn.Linear(10, 20)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(20, 2)
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
def count_parameters(model):
"""计算可训练的参数"""
for name, param in model.named_parameters():
if param.requires_grad:
# 打印具体的参数名称和形状
print(f"{
name}: {
param.size()}")
# 可训练参数总量
return sum(p.numel(