PEFT documentation

适配器注入

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

适配器注入

借助 PEFT,你可以将可训练的适配器注入到任何 torch 模块中,从而无需依赖 PEFT 中的建模类即可使用适配器方法。此功能适用于除基于提示学习(例如 prefix tuning 或 p-tuning)以及在不同目标层之间保持共享状态的适配器之外的所有适配器。

请查看下表,了解何时应注入适配器。

优点缺点
模型会被就地修改,保留所有原始属性和方法手动编写 Hugging Face 的 from_pretrained 和 save_pretrained 实用函数来保存和加载适配器
适用于任何 torch 模块和模态无法与PeftModel提供的任何实用方法配合使用,例如禁用和合并适配器

inject_adapter_in_model 不支持在多个目标层之间共享适配器状态的 PEFT 方法。目前包括 TinyLoRA、UniLoRA、VeRA、PVeRA、VBLoRA 和 FRoD。对于这些方法,请改用 get_peft_model()。

创建新的 PEFT 模型

要执行适配器注入,请使用 inject_adapter_in_model() 方法。该方法接受 3 个参数:PEFT 配置、模型以及可选的适配器名称。如果你使用不同的适配器名称多次调用 inject_adapter_in_model(),也可以为模型附加多个适配器。

例如,要将 LoRA 适配器注入到 DummyModel 模块的 linear 子模块中:

import torch
from peft import inject_adapter_in_model, LoraConfig

class DummyModel(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.embedding = torch.nn.Embedding(10, 10)
        self.linear = torch.nn.Linear(10, 10)
        self.lm_head = torch.nn.Linear(10, 10)

    def forward(self, input_ids):
        x = self.embedding(input_ids)
        x = self.linear(x)
        x = self.lm_head(x)
        return x


lora_config = LoraConfig(
    lora_alpha=16,
    lora_dropout=0.1,
    r=64,
    bias="none",
    target_modules=["linear"],
)

model = DummyModel()
model = inject_adapter_in_model(lora_config, model)

dummy_inputs = torch.LongTensor([[0, 1, 2, 3, 4, 5, 6, 7]])
dummy_outputs = model(dummy_inputs)

打印模型以确认适配器已正确注入。

DummyModel(
  (embedding): Embedding(10, 10)
  (linear): Linear(
    in_features=10, out_features=10, bias=True
    (lora_dropout): ModuleDict(
      (default): Dropout(p=0.1, inplace=False)
    )
    (lora_A): ModuleDict(
      (default): Linear(in_features=10, out_features=64, bias=False)
    )
    (lora_B): ModuleDict(
      (default): Linear(in_features=64, out_features=10, bias=False)
    )
    (lora_embedding_A): ParameterDict()
    (lora_embedding_B): ParameterDict()
  )
  (lm_head): Linear(in_features=10, out_features=10, bias=True)
)

基于 state_dict 的注入

有时,可能存在 PEFT 适配器检查点,但由于某些原因,对应的 PEFT 配置未知。要为该检查点注入 PEFT 层,通常需要根据检查点中的 state_dict 逆向推导对应的 PEFT 配置,尤其是 target_modules 参数。这可能繁琐且容易出错。为避免这种情况,也可以调用 inject_adapter_in_model() 并将加载的 state_dict 作为参数传入:

from safetensors.torch import load_file

model = ...
state_dict = load_file(<path-to-safetensors-file>)
lora_config = LoraConfig(...)
model = inject_adapter_in_model(lora_config, model, state_dict=state_dict)

在这种情况下,PEFT 将使用 state_dict 作为参考来确定要针对哪些层,而不是使用 PEFT 配置。作为用户,你无需为此设置 PEFT 配置中确切的 target_modules。不过,你仍然需要传入正确类型的 PEFT 配置,在本例中为 LoraConfig,你可以将 target_modules 保留为 None。

请注意,这仍然只是创建未初始化的 PEFT 层,state_dict 中的值并未用于填充模型权重。要填充权重,请按照下文描述继续调用 set_peft_model_state_dict()。

⚠️ 请注意,如果 PEFT 配置中的设置与 state_dict 中发现的内容不一致,PEFT 会发出警告。如果您确定 PEFT 配置未正确指定,可以忽略该警告。

如果原始 PEFT 适配器使用的是 target_parameters 而非 target_modules,则从 state_dict 注入将无法正常工作。在这种情况下,必须使用正确的 PEFT 配置进行注入。

保存模型

如果只想保存适配器,请使用 get_peft_model_state_dict() 函数:

from peft import get_peft_model_state_dict

peft_state_dict = get_peft_model_state_dict(model)
print(peft_state_dict)

否则,model.state_dict() 将返回模型的完整状态字典。

加载模型

加载保存的 state_dict 后,可以使用 set_peft_model_state_dict() 函数将其应用:

from peft import set_peft_model_state_dict

model = DummyModel()
model = inject_adapter_in_model(lora_config, model)
outcome = set_peft_model_state_dict(model, peft_state_dict)
# check that there were no wrong keys
print(outcome.unexpected_keys)

如果注入适配器速度较慢,或者需要加载大量适配器,可以使用一种优化方法:在 meta 设备上创建一个“空”适配器,仅在调用 set_peft_model_state_dict() 时才用真实权重填充权重。为此,请将 low_cpu_mem_usage=True 同时传递给 inject_adapter_in_model() 和 set_peft_model_state_dict()。

model = DummyModel()
model = inject_adapter_in_model(lora_config, model, low_cpu_mem_usage=True)

print(model.linear.lora_A["default"].weight.device.type == "meta")  # should be True
set_peft_model_state_dict(model, peft_state_dict, low_cpu_mem_usage=True)
print(model.linear.lora_A["default"].weight.device.type == "cpu")  # should be True

要从 Hub 加载权重,可以使用底层函数 load_peft_weights():

state_dict = load_peft_weights("my-account/my-adapter-repo")

设置和加载基础权重

上述函数处理的是adapter的 state dict。在某些情况下,还需要通过 PEFT 包装器读取或写入base model的权重。这并非完全直观,因为 PEFT 会重命名目标模块的参数(例如 q_proj.weight 变为 q_proj.base_layer.weight),并添加 base model 中不存在的 adapter 参数。请使用 get_base_model_state_dict() 和 set_base_model_state_dict() 在两种命名之间进行转换:

from peft import LoraConfig, get_peft_model, get_base_model_state_dict, set_base_model_state_dict
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m")
model = get_peft_model(model, LoraConfig(target_modules="all-linear"))

# state dict with the original (pre-PEFT) key names, adapter parameters excluded
base_state_dict = get_base_model_state_dict(model)

# load a state dict with original key names into the PEFT-wrapped model
outcome = set_base_model_state_dict(model, base_state_dict, strict=False)
# check that there were no wrong keys
print(outcome.missing_keys, outcome.unexpected_keys)

此功能的主要用例是在模型已被 PEFT 包装之后加载基础权重。例如,TorchTitan 等 FSDP 训练配置会在 meta 设备上初始化模型,应用 PEFT,然后对结果进行分片。只有在分片之后才会存在实际内存,因此,其键使用原始名称的检查点必须加载到已包装的模型中。请注意,get_base_model_state_dict() 返回的是模型的实时张量,而非副本。

Update on GitHub