"""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