File size: 1,766 Bytes
7c61ee6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Minimal LoRA for the TRELLIS.2 sparse-structure flow (frozen base weights, fp32 adapters)."""
import torch
import torch.nn as nn

TARGETS = {
    "cross": ["cross_attn.to_q", "cross_attn.to_kv", "cross_attn.to_out"],
    "cross_self": ["cross_attn.to_q", "cross_attn.to_kv", "cross_attn.to_out", "self_attn.to_qkv", "self_attn.to_out"],
}


class LoRALinear(nn.Module):
    def __init__(self, base: nn.Linear, r: int, alpha: float):
        super().__init__()
        self.base = base
        self.scale = alpha / r
        self.A = nn.Parameter(torch.randn(r, base.in_features, device=base.weight.device) / base.in_features ** 0.5)
        self.B = nn.Parameter(torch.zeros(base.out_features, r, device=base.weight.device))

    def forward(self, x):
        return self.base(x) + ((x.float() @ self.A.T) @ self.B.T * self.scale).to(x.dtype)


def apply_lora(model, targets="cross", r=16, alpha=16):
    for p in model.parameters():
        p.requires_grad = False
    names = TARGETS[targets]
    for blk in model.blocks:
        for name in names:
            parent, attr = name.split(".")
            mod = getattr(blk, parent)
            setattr(mod, attr, LoRALinear(getattr(mod, attr), r, alpha))
    return [p for n, p in model.named_parameters() if n.endswith((".A", ".B"))]


def lora_state(model):
    return {n: p.detach().cpu() for n, p in model.named_parameters() if n.endswith((".A", ".B"))}


def load_lora(model, path):
    ckpt = torch.load(path, map_location="cpu")
    apply_lora(model, ckpt["targets"], ckpt["r"], ckpt["alpha"])
    missing = set(n for n, _ in model.named_parameters() if n.endswith((".A", ".B"))) - set(ckpt["state"])
    assert not missing, missing
    model.load_state_dict(ckpt["state"], strict=False)
    return model