LoRA 和 DoRA 代码笔记

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

LoRA

在这里插入图片描述
LoRA初始化时,A使用正态分布,B使用0.

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的参数。

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的参数

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相同。
在这里插入图片描述

在这里插入图片描述

#训练时
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)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
LORA(Long Range)和Zigbee是两种不同的无线通信协议,适用于不同的物联网应用场景。它们在代码实现上有以下区别。 首先,在数据传输的方式上,LORA采用的是频移键控(FSK)调制技术,而Zigbee采用的是直接序列扩频(DSSS)调制技术。这使得它们在传输距离、传输速率和功耗上有所差异。LORA可以实现更长的通信距离,但传输速率相对较低,适用于低传输需求的长距离通信场景。而Zigbee适用于相对短距离的传输,但通信速率较高。 其次,LORA和Zigbee在网络拓扑结构上也有差异。LORA通常采用星型或者点对点的网络结构,其中一个集中式的LORA网关连接多个节点设备。而Zigbee则更适用于形成星状、网状或者多跳的网络拓扑结构,具有较强的自组织和自修复能力。 另外,对于代码实现部分,LORA通常使用C++或者类似的高级语言进行开发,开发者需要根据硬件设备的特点自行实现协议栈和物理层代码。而Zigbee则有其自身的通信协议栈,开发者可以基于其提供的标准库进行开发,简化了开发流程。 总结而言,LORA和Zigbee是两种不同的无线通信协议,在代码实现上有差异。LORA适用于长距离、低传输需求的场景,通信距离远,但速率较低;而Zigbee适用于短距离的传输,速率较高,具备自组织和自修复能力。开发者需要根据具体的应用需求选择合适的通信协议和相应的代码实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值