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

相关推荐
阿里云大数据AI技术1 小时前
光轮智能 × 阿里云:共建 Physical AI 云上数据、评测与持续学习基础设施
人工智能·机器学习
机器之心1 小时前
实锤了:Claude Code偷查用户,时区、中国AI实验室全是关键词
人工智能·openai
网易云信1 小时前
Cursor点燃个人开发者,企业级AI为何频频受挫?Agent工厂从提效工具到AI员工的跃迁
人工智能·开源
网易云信1 小时前
解锁触手可及的温暖:网易智企 x Wander Puffs AI 云游泡芙
人工智能
转转技术团队1 小时前
从 PRD 到可验证代码:AI 需求开发闭环实践
人工智能
机器之心2 小时前
飞书让表格变成「AI同事」加入群聊,不打开表就能用表
人工智能·openai
Bigfish_coding2 小时前
前端转agent-【python】-15 AI Agent 可观测性入门:LangFuse 链路追踪、Token 监控与 LLM 质量评估
人工智能
我唔知啊2 小时前
我把 Claude Code 拆成了一间餐厅:从一句话到一次回复,中间到底发生了什么
人工智能
Harry技术2 小时前
02 · Codex 核心概念:代理、沙箱、审批和项目说明书
人工智能