File size: 1,378 Bytes
5f92b4e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | """Native nn.Linear LoRA adapters; base weights are frozen and preserved."""
import math
import torch
from torch import nn
from torch.nn import functional as F
class LoRALinear(nn.Module):
def __init__(self,base,rank=32,alpha=32,dropout=0.):
super().__init__();self.base=base;self.scaling=alpha/rank;self.dropout=nn.Dropout(dropout)
self.A=nn.Parameter(torch.empty(rank,base.in_features,dtype=torch.float32,device=base.weight.device))
self.B=nn.Parameter(torch.zeros(base.out_features,rank,dtype=torch.float32,device=base.weight.device));nn.init.kaiming_uniform_(self.A,a=math.sqrt(5))
self.base.requires_grad_(False)
def forward(self,x):
return self.base(x)+(F.linear(F.linear(self.dropout(x),self.A),self.B)*self.scaling).to(x.dtype)
def inject(model,rank,alpha,dropout,targets):
model.requires_grad_(False);names=[]
for name,module in list(model.named_modules()):
if isinstance(module,nn.Linear) and name.startswith('blocks.') and any(name.endswith('.'+s) for s in targets):
parent,leaf=name.rsplit('.',1);setattr(model.get_submodule(parent),leaf,LoRALinear(module,rank,alpha,dropout));names.append(name)
if not names:raise ValueError('No LoRA target modules matched')
return names
def adapter_state(model):return {n:p.detach().cpu() for n,p in model.named_parameters() if p.requires_grad}
|