Add self-contained base-model CPT, SFT, RL and checkpoint averaging notebook tutorials
5f92b4e verified Download tutorials/runtime/lora.py from SlayerLab/Slayer1B-1.09: direct link, hf CLI and curl.
- Browser
- Download file 1.38 kB
-
https://huggingface.co/SlayerLab/Slayer1B-1.09/resolve/main/tutorials/runtime/lora.py
- Command line
-
hf download hf://SlayerLab/Slayer1B-1.09/tutorials/runtime/lora.py
-
curl -L -o lora.py https://huggingface.co/SlayerLab/Slayer1B-1.09/resolve/main/tutorials/runtime/lora.py
1.38 kB
| """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} | |