Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
AUTOMATIC1111
GitHub Repository: AUTOMATIC1111/stable-diffusion-webui
Path: blob/master/extensions-builtin/Lora/lyco_helpers.py
2447 views
1
import torch
2
3
4
def make_weight_cp(t, wa, wb):
5
temp = torch.einsum('i j k l, j r -> i r k l', t, wb)
6
return torch.einsum('i j k l, i r -> r j k l', temp, wa)
7
8
9
def rebuild_conventional(up, down, shape, dyn_dim=None):
10
up = up.reshape(up.size(0), -1)
11
down = down.reshape(down.size(0), -1)
12
if dyn_dim is not None:
13
up = up[:, :dyn_dim]
14
down = down[:dyn_dim, :]
15
return (up @ down).reshape(shape)
16
17
18
def rebuild_cp_decomposition(up, down, mid):
19
up = up.reshape(up.size(0), -1)
20
down = down.reshape(down.size(0), -1)
21
return torch.einsum('n m k l, i n, m j -> i j k l', mid, up, down)
22
23
24
# copied from https://github.com/KohakuBlueleaf/LyCORIS/blob/dev/lycoris/modules/lokr.py
25
def factorization(dimension: int, factor:int=-1) -> tuple[int, int]:
26
'''
27
return a tuple of two value of input dimension decomposed by the number closest to factor
28
second value is higher or equal than first value.
29
30
In LoRA with Kroneckor Product, first value is a value for weight scale.
31
secon value is a value for weight.
32
33
Because of non-commutative property, A⊗B ≠ B⊗A. Meaning of two matrices is slightly different.
34
35
examples)
36
factor
37
-1 2 4 8 16 ...
38
127 -> 1, 127 127 -> 1, 127 127 -> 1, 127 127 -> 1, 127 127 -> 1, 127
39
128 -> 8, 16 128 -> 2, 64 128 -> 4, 32 128 -> 8, 16 128 -> 8, 16
40
250 -> 10, 25 250 -> 2, 125 250 -> 2, 125 250 -> 5, 50 250 -> 10, 25
41
360 -> 8, 45 360 -> 2, 180 360 -> 4, 90 360 -> 8, 45 360 -> 12, 30
42
512 -> 16, 32 512 -> 2, 256 512 -> 4, 128 512 -> 8, 64 512 -> 16, 32
43
1024 -> 32, 32 1024 -> 2, 512 1024 -> 4, 256 1024 -> 8, 128 1024 -> 16, 64
44
'''
45
46
if factor > 0 and (dimension % factor) == 0:
47
m = factor
48
n = dimension // factor
49
if m > n:
50
n, m = m, n
51
return m, n
52
if factor < 0:
53
factor = dimension
54
m, n = 1, dimension
55
length = m + n
56
while m<n:
57
new_m = m + 1
58
while dimension%new_m != 0:
59
new_m += 1
60
new_n = dimension // new_m
61
if new_m + new_n > length or new_m>factor:
62
break
63
else:
64
m, n = new_m, new_n
65
if m > n:
66
n, m = m, n
67
return m, n
68
69
70