PEFT适配器加载

激活单个 LoRA 模块

当我们想要在自己的模型中使用Lora方法进行微调时,可以借助PeftModel来给我们自己的模型实现lora方法。

复制代码
# 1. 创建原始模型
net_original = nn.Sequential(
    nn.Linear(10,10),
    nn.ReLU(),
    nn.Linear(10,2)
)

# 2. 用副本分别创建并保存两个适配器(不污染原始模型)
net_copy1 = copy.deepcopy(net_original)
config1 = LoraConfig(target_modules=["0"])   # 在模型的第0层添加lora模块
model1 = get_peft_model(net_copy1, config1)
model1.save_pretrained("./weights/lora_A")

net_copy2 = copy.deepcopy(net_original)
config2 = LoraConfig(target_modules=["2"])
model2 = get_peft_model(net_copy2, config2)
model2.save_pretrained("./weights/lora_B")

上述实现了自定义模型的创建和 lora 适配器的创建。

复制代码
# 3. 用干净的原始模型加载lora_A(此时基础模型无任何适配器)
model = PeftModel.from_pretrained(
    copy.deepcopy(net_original),  # 传入原始模型副本
    model_id="./weights/lora_A",
    adapter_name="task_a"
)



# 4.加载第二个适配器
model.load_adapter(
    model_id="./weights/lora_B",
    adapter_name="task_b"  # 另一个唯一名称
)

# 使用 set_adapter() 强制模型使用指定的适配器并禁用其他适配器
model.set_adapter("task_b")

这一步实现了将两个适配器加载到模型上同时激活适配器 lora_B。

同时激活多个Lora模块

PeftMixedModel 支持同时激活多个LoRA模块,实现更灵活的组合调用。

复制代码
import torch
from torch import nn
from peft import LoraConfig, get_peft_model, PeftModel, PeftMixedModel
import copy

# 1. 创建原始模型
net_original = nn.Sequential(
    nn.Linear(10,10),
    nn.ReLU(),
    nn.Linear(10,2)
)

# 2. 用副本分别创建并保存两个适配器(不污染原始模型)
net_copy1 = copy.deepcopy(net_original)
config1 = LoraConfig(target_modules=["0"])
model1 = get_peft_model(net_copy1, config1)
model1.save_pretrained("./weights/lora_A")

net_copy2 = copy.deepcopy(net_original)
config2 = LoraConfig(target_modules=["2"])
model2 = get_peft_model(net_copy2, config2)
model2.save_pretrained("./weights/lora_B")

model = PeftMixedModel.from_pretrained(
    copy.deepcopy(net_original),
    model_id="./weights/lora_A",
    adapter_name = "task_a"
)

model.load_adapter(
    model_id="./weights/lora_B",
    adapter_name="task_b"  # 另一个唯一名称
)

# 使用 set_adapter() 强制模型使用指定的适配器并禁用其他适配器
model.set_adapter(["task_a","task_b"])

print("adapter",model.active_adapter)

与上面的流程基本一致,但是模型模板改为 PeftMixedModel

相关推荐
gis分享者1 小时前
AI数字营销实测体验,GEO效果查询功能体验
人工智能·csdn·geo·数字营销·实测体验·效果查询
莱歌数字1 小时前
轻出20%性能:三维拓扑优化如何重塑无人机电子设备散热格局
人工智能·科技·制造·cae·散热
猿小猴子2 小时前
主流 AI IDE 之一的「DeepSeek-Reasonix 」介绍
人工智能·ai·deepseek·reasonix
装不满的克莱因瓶2 小时前
链式法则如何传递参数误差 —— 深入理解神经网络中的梯度传播
人工智能·python·深度学习·神经网络·数学·机器学习·ai
Anastasiozzzz2 小时前
从有限状态机到智能体图:传统 FSM 与 Agent Graph的演进
java·人工智能·python·ai
程序员cxuan7 小时前
为每个任务配一套 harness:Claude Code 里的动态工作流
人工智能
程序员cxuan7 小时前
Claude Fable 5 来了
人工智能·后端·程序员
云边云科技_云网融合7 小时前
云边云科技亮相 2026 WOD 制造业数智化博览会 云网融合赋能制造焕新
人工智能·科技·安全·制造
Σίσυφος19008 小时前
激光三角 光平面标定-多高度误差分析
人工智能·计算机视觉·平面
JS菌8 小时前
手写一个 AI Agent 全栈项目:从沙箱执行到子智能体的完整实现
前端·人工智能·后端