Download ppai/lora_ppai.py from AdminHugging/ppai-code: direct link, hf CLI and curl.
- Browser
- Download file 2.51 kB
-
https://huggingface.co/datasets/AdminHugging/ppai-code/resolve/main/ppai/lora_ppai.py
- Command line
-
hf download hf://datasets/AdminHugging/ppai-code/ppai/lora_ppai.py
-
curl -L -o lora_ppai.py https://huggingface.co/datasets/AdminHugging/ppai-code/resolve/main/ppai/lora_ppai.py
2.51 kB
| """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) | |