type
status
date
slug
summary
tags
category
icon
password
记录 PEFT 库中,使用 inject_adapter_in_model 对模型添加 LoRA 适配器的源码分析过程
 

一、inject_adapter_in_model 入口

notion image
重点是在最后三行, PEFT_TYPE_TO_TUNER_MAPPING 是根据 config 类型,选择对应的 Model
notion image
要做 LoRA 微调的时候传入的 peft_config 就是一个 LoraConfig,其 peft_type 就是 “LORA”
notion image
最后从 LoraModel 的实例中返回其 model ,而 LoraModel 类的初始化入参就只有原始的 model 和一个 peft_config,adapter_name 是用户自定义的,默认为 ‘default’;
所以重点是 LoraModel 类初始化时是如何对 model 进行改造的,下面看下这部分。
 

二、LoraModel

notion image
初始化就是直接调用其父类 BaseTuner 的初始化
notion image
其重点就是在 self.inject_adapter ,其主要流程如下
notion image
self._create_and_replace 是实现在子类 LoraModel 中,其代码如下
notion image
接下来重点看看如何创建新的 module 以及这个 new_module 是如何工作的
_create_new_module
notion image
接下来看看 Linear 是如何初始化和 forward 的
notion image
其中 nn.Linear 是 torch 里面的模块,而 LoraLayer 是 peft 中 Embedding, Conv2d, Linear 的通用父类,在 LoraLayer 会初始化它们共用的一些参数
notion image
self.update_layer 会进一步设置 Linear自己的参数
notion image
 
看一眼 Linear 是怎么 forward
notion image
值得一提的是 scaling 是配置值除了 r 的:self.scaling[adapter_name] = lora_alpha / r