Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
AUTOMATIC1111
GitHub Repository: AUTOMATIC1111/stable-diffusion-webui
Path: blob/master/extensions-builtin/Lora/network_lokr.py
2447 views
1
import torch
2
3
import lyco_helpers
4
import network
5
6
7
class ModuleTypeLokr(network.ModuleType):
8
def create_module(self, net: network.Network, weights: network.NetworkWeights):
9
has_1 = "lokr_w1" in weights.w or ("lokr_w1_a" in weights.w and "lokr_w1_b" in weights.w)
10
has_2 = "lokr_w2" in weights.w or ("lokr_w2_a" in weights.w and "lokr_w2_b" in weights.w)
11
if has_1 and has_2:
12
return NetworkModuleLokr(net, weights)
13
14
return None
15
16
17
def make_kron(orig_shape, w1, w2):
18
if len(w2.shape) == 4:
19
w1 = w1.unsqueeze(2).unsqueeze(2)
20
w2 = w2.contiguous()
21
return torch.kron(w1, w2).reshape(orig_shape)
22
23
24
class NetworkModuleLokr(network.NetworkModule):
25
def __init__(self, net: network.Network, weights: network.NetworkWeights):
26
super().__init__(net, weights)
27
28
self.w1 = weights.w.get("lokr_w1")
29
self.w1a = weights.w.get("lokr_w1_a")
30
self.w1b = weights.w.get("lokr_w1_b")
31
self.dim = self.w1b.shape[0] if self.w1b is not None else self.dim
32
self.w2 = weights.w.get("lokr_w2")
33
self.w2a = weights.w.get("lokr_w2_a")
34
self.w2b = weights.w.get("lokr_w2_b")
35
self.dim = self.w2b.shape[0] if self.w2b is not None else self.dim
36
self.t2 = weights.w.get("lokr_t2")
37
38
def calc_updown(self, orig_weight):
39
if self.w1 is not None:
40
w1 = self.w1.to(orig_weight.device)
41
else:
42
w1a = self.w1a.to(orig_weight.device)
43
w1b = self.w1b.to(orig_weight.device)
44
w1 = w1a @ w1b
45
46
if self.w2 is not None:
47
w2 = self.w2.to(orig_weight.device)
48
elif self.t2 is None:
49
w2a = self.w2a.to(orig_weight.device)
50
w2b = self.w2b.to(orig_weight.device)
51
w2 = w2a @ w2b
52
else:
53
t2 = self.t2.to(orig_weight.device)
54
w2a = self.w2a.to(orig_weight.device)
55
w2b = self.w2b.to(orig_weight.device)
56
w2 = lyco_helpers.make_weight_cp(t2, w2a, w2b)
57
58
output_shape = [w1.size(0) * w2.size(0), w1.size(1) * w2.size(1)]
59
if len(orig_weight.shape) == 4:
60
output_shape = orig_weight.shape
61
62
updown = make_kron(output_shape, w1, w2)
63
64
return self.finalize_updown(updown, orig_weight, output_shape)
65
66