导入包
import torch
from torch import nn
from peft import LoraConfig, get_peft_model, PeftModel
自定义简单模型
net1 = nn.Sequential(
nn.Linear(10, 10),
nn.ReLU(),
nn.Linear(10, 2)
)
PEFT 配置文件、创建模型
配置文件和预制模型的区别在于,预制模型有默认的target_modules值,而自定义模型没有,因此我们需要明确指定。
config = LoraConfig(target_modules=["0"])
model = get_peft_model(net1, config)
多适配器加载与切换
我们为2个适配器分别命名为 "loraA" 和 "loraB",这允许我们在同一个主模型中加载多个适配器,并通过适配器名称(激活)在推理时选择使用哪个适配器。
创建模型
netAll = nn.Sequential(
nn.Linear(10, 10),
nn.ReLU(),
nn.Linear(10, 2)
)
配器1
configA1 = LoraConfig(target_modules=["0"])
modelA1 = get_peft_model(netAll, configA1)
modelA1.save_pretrained("./loraA")
配器2
configA2 = LoraConfig(target_modules=["2"])
modelA2 = get_peft_model(netAll, configA2)
modelA2.save_pretrained("./loraB")
加载与切换
加载基本模型
netAll2 = nn.Sequential(
nn.Linear(10, 10),
nn.ReLU(),
nn.Linear(10, 2)
)
加载配器1
model2 = PeftModel.from_pretrained(netAll2, model_id="./loraA/", adapter_name="loraA")
加载配器2
model2.load_adapter("./loraB/", adapter_name="loraB")
# 查看当前适配器
model2.active_adapter
切换适配器
model2.set_adapter("loraB")
禁用适配器
某些时候我们需要得到原始模型的输出,这时候就需要考虑禁用已有模型中的适配器。
激活适配器A
model2.set_adapter("loraA")
禁用loraA
with model2.disable_adapter():
print(model2(torch.arange(0, 10).view(1, 10).float()))