LoRA 和 DoRA 代码笔记

Improving LoRA: Implementing Weight-Decomposed Low-Rank Adaptation (DoRA) from Scratch

LoRA

LoRA初始化时,A使用正态分布,B使用0.

python 复制代码
class LoRALayer(nn.Module):
    def __init__(self, in_dim, out_dim, rank, alpha):
        super().__init__()
        std_dev = 1 / torch.sqrt(torch.tensor(rank).float())
        self.A = nn.Parameter(torch.randn(in_dim, rank) * std_dev)
        self.B = nn.Parameter(torch.zeros(rank, out_dim))
        self.alpha = alpha

    def forward(self, x):
        x = self.alpha * (x @ self.A @ self.B)
        return x


class LinearWithLoRA(nn.Module):
    def __init__(self, linear, rank, alpha):
        super().__init__()
        self.linear = linear
        self.lora = LoRALayer(
            linear.in_features, linear.out_features, rank, alpha
        )

    def forward(self, x):
        return self.linear(x) + self.lora(x)

在训练的时候,使用LinearWithLoRA 替换Linear层,并且freeze Linear的参数,只训练lora的参数。

python 复制代码
model_lora = copy.deepcopy(model_pretrained)

model_lora.layers[0] = LinearWithLoRA(model_lora.layers[0], rank=4, alpha=8)

freeze_linear_layers(model_lora)

#然后就可以正常训练了

freeze Linear的参数

python 复制代码
def freeze_linear_layers(model):
    for child in model.children():
        if isinstance(child, nn.Linear):
            for param in child.parameters():
                param.requires_grad = False
        else:
            # Recursively freeze linear layers in children modules
            freeze_linear_layers(child)

DoRA (Weight-Decomposed Low-Rank Adaptation)

权重weight矩阵W,可以分为 模向量m(magnitude vector)和方向矩阵V(directional matrix)。

把LoRA加入到方向矩阵V中,然后再和m计算出新的权重W。

使用方法和LoRA相同。

python 复制代码
#训练时
class LinearWithDoRA(nn.Module):
    def __init__(self, linear, rank, alpha):
        super().__init__()
        self.linear = linear
        self.lora = LoRALayer(linear.in_features, linear.out_features, rank, alpha)
        self.m = nn.Parameter(torch.ones(1, linear.out_features))

    def forward(self, x):
        linear_output = self.linear(x)
        lora_output = self.lora(x)
        lora_output_norm = lora_output / (lora_output.norm(p=2, dim=1, keepdim=True) + 1e-9)
        dora_modification = self.m * lora_output_norm
        return linear_output + dora_modification

#合并时
# Code inspired by https://github.com/catid/dora/blob/main/dora.py
class LinearWithDoRAMerged(nn.Module):
    def __init__(self, linear, rank, alpha):
        super().__init__()
        self.linear = linear
        self.lora = LoRALayer(
            linear.in_features, linear.out_features, rank, alpha
        )
        
        self.m = nn.Parameter(
            self.linear.weight.norm(p=2, dim=0, keepdim=True))

    def forward(self, x):
        lora = self.lora.A @ self.lora.B
        numerator = self.linear.weight + self.lora.alpha*lora.T
        denominator = numerator.norm(p=2, dim=0, keepdim=True)
        directional_component = numerator / denominator
        new_weight = self.m * directional_component
        return F.linear(x, new_weight, self.linear.bias)
相关推荐
小途软件8 小时前
基于图像生成的虚拟现实体验
java·人工智能·pytorch·python·深度学习·语言模型
Byron Loong9 小时前
【Python】Pytorch是个什么包
开发语言·pytorch·python
彼岸花苏陌10 小时前
conda安装gpu版本的pytorch
人工智能·pytorch·conda
Mr.Lee jack10 小时前
【torch.compile】PyTorch FX IR 与 Inductor IR 融合策略深度剖析
人工智能·pytorch·python
Rabbit_QL10 小时前
【Pytorch使用】Sequential、ModuleList 与 ModuleDict 的设计与取舍
人工智能·pytorch·python
DP+GISer12 小时前
03基于pytorch的深度学习遥感地物分类全流程实战教程(包含遥感深度学习数据集制作与大图预测)-实践篇-使用公开数据集进行深度学习遥感地物分类
人工智能·pytorch·python·深度学习·图像分割·遥感·地物分类
Francek Chen13 小时前
【自然语言处理】应用05:自然语言推断:使用注意力
人工智能·pytorch·深度学习·神经网络·自然语言处理
DP+GISer13 小时前
04基于pytorch的深度学习遥感地物分类全流程实战教程(包含遥感深度学习数据集制作与大图预测)-实践篇-使用自己的数据集进行深度学习遥感地物分类
pytorch·python·深度学习·图像分割·遥感·数据集制作·地物分类
kimi-22213 小时前
Accelerate 是由 Hugging Face 开发的一个轻量级 Python 库,旨在让 PyTorch 的分布式训练变得极其简单
pytorch·分布式·python
于本淡14 小时前
深度学习框架:PyTorch与MXNet性能解析与实战对比
pytorch·深度学习·mxnet