File size: 2,505 Bytes
ee15e43 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | """LoRA для PPAI: у модели сырые nn.Parameter вместо nn.Linear.
Оборачиваем веса через torch.nn.utils.parametrize — доступ к атрибуту
начинает возвращать base + B@A * scale, ничего в forward менять не нужно.
"""
from __future__ import annotations
import torch
import torch.nn as nn
TARGETS = ("wq", "wk", "wv", "wo", "w13", "w2", "s13", "s2")
class LoRADelta(nn.Module):
def __init__(self, out_f: int, in_f: int, r: int = 16, alpha: int = 32):
super().__init__()
self.A = nn.Parameter(torch.zeros(r, in_f))
self.B = nn.Parameter(torch.zeros(out_f, r))
self.scale = alpha / r
nn.init.normal_(self.A, std=1.0 / max(in_f, 1) ** 0.5)
# B = 0 -> на старте модель идентична базовой
def forward(self, W: torch.Tensor) -> torch.Tensor:
return W + (self.B @ self.A).to(W.dtype) * self.scale
def attach(model, r: int = 16, alpha: int = 32) -> int:
"""Включить LoRA. Возвращает число обучемых параметров."""
from torch.nn.utils import parametrize
for name, p in model.named_parameters():
p.requires_grad = False
n = 0
for block in model.modules():
for tgt in TARGETS:
w = getattr(block, tgt, None)
if not isinstance(w, nn.Parameter) or w.ndim != 2:
continue
parametrize.register_parametrization(block, tgt, LoRADelta(w.shape[0], w.shape[1], r, alpha))
n += 1
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"[lora] обёрнуто весов: {n} | обучаемо {trainable/1e6:.2f}M", flush=True)
return trainable
def lora_state_dict(model) -> dict:
return {k: v.detach().cpu() for k, v in model.state_dict().items() if "parametrizations" in k}
def merge_and_save(model, out_dir: str) -> None:
"""Слить base+delta в обычные веса и сохранить HF-совместимо."""
from torch.nn.utils import parametrize
for module in model.modules():
if hasattr(module, "parametrizations"):
for name in list(module.parametrizations.keys()):
parametrize.remove_parametrizations(module, name, leave_parametrized=True)
model.save_pretrained(out_dir, safe_serialization=True)
print(f"[lora] слито и сохранено: {out_dir}", flush=True)
|