Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
AUTOMATIC1111
GitHub Repository: AUTOMATIC1111/stable-diffusion-webui
Path: blob/master/extensions-builtin/Lora/network_oft.py
2447 views
1
import torch
2
import network
3
from einops import rearrange
4
5
6
class ModuleTypeOFT(network.ModuleType):
7
def create_module(self, net: network.Network, weights: network.NetworkWeights):
8
if all(x in weights.w for x in ["oft_blocks"]) or all(x in weights.w for x in ["oft_diag"]):
9
return NetworkModuleOFT(net, weights)
10
11
return None
12
13
# Supports both kohya-ss' implementation of COFT https://github.com/kohya-ss/sd-scripts/blob/main/networks/oft.py
14
# and KohakuBlueleaf's implementation of OFT/COFT https://github.com/KohakuBlueleaf/LyCORIS/blob/dev/lycoris/modules/diag_oft.py
15
class NetworkModuleOFT(network.NetworkModule):
16
def __init__(self, net: network.Network, weights: network.NetworkWeights):
17
18
super().__init__(net, weights)
19
20
self.lin_module = None
21
self.org_module: list[torch.Module] = [self.sd_module]
22
23
self.scale = 1.0
24
self.is_R = False
25
self.is_boft = False
26
27
# kohya-ss/New LyCORIS OFT/BOFT
28
if "oft_blocks" in weights.w.keys():
29
self.oft_blocks = weights.w["oft_blocks"] # (num_blocks, block_size, block_size)
30
self.alpha = weights.w.get("alpha", None) # alpha is constraint
31
self.dim = self.oft_blocks.shape[0] # lora dim
32
# Old LyCORIS OFT
33
elif "oft_diag" in weights.w.keys():
34
self.is_R = True
35
self.oft_blocks = weights.w["oft_diag"]
36
# self.alpha is unused
37
self.dim = self.oft_blocks.shape[1] # (num_blocks, block_size, block_size)
38
39
is_linear = type(self.sd_module) in [torch.nn.Linear, torch.nn.modules.linear.NonDynamicallyQuantizableLinear]
40
is_conv = type(self.sd_module) in [torch.nn.Conv2d]
41
is_other_linear = type(self.sd_module) in [torch.nn.MultiheadAttention] # unsupported
42
43
if is_linear:
44
self.out_dim = self.sd_module.out_features
45
elif is_conv:
46
self.out_dim = self.sd_module.out_channels
47
elif is_other_linear:
48
self.out_dim = self.sd_module.embed_dim
49
50
# LyCORIS BOFT
51
if self.oft_blocks.dim() == 4:
52
self.is_boft = True
53
self.rescale = weights.w.get('rescale', None)
54
if self.rescale is not None and not is_other_linear:
55
self.rescale = self.rescale.reshape(-1, *[1]*(self.org_module[0].weight.dim() - 1))
56
57
self.num_blocks = self.dim
58
self.block_size = self.out_dim // self.dim
59
self.constraint = (0 if self.alpha is None else self.alpha) * self.out_dim
60
if self.is_R:
61
self.constraint = None
62
self.block_size = self.dim
63
self.num_blocks = self.out_dim // self.dim
64
elif self.is_boft:
65
self.boft_m = self.oft_blocks.shape[0]
66
self.num_blocks = self.oft_blocks.shape[1]
67
self.block_size = self.oft_blocks.shape[2]
68
self.boft_b = self.block_size
69
70
def calc_updown(self, orig_weight):
71
oft_blocks = self.oft_blocks.to(orig_weight.device)
72
eye = torch.eye(self.block_size, device=oft_blocks.device)
73
74
if not self.is_R:
75
block_Q = oft_blocks - oft_blocks.transpose(-1, -2) # ensure skew-symmetric orthogonal matrix
76
if self.constraint != 0:
77
norm_Q = torch.norm(block_Q.flatten())
78
new_norm_Q = torch.clamp(norm_Q, max=self.constraint.to(oft_blocks.device))
79
block_Q = block_Q * ((new_norm_Q + 1e-8) / (norm_Q + 1e-8))
80
oft_blocks = torch.matmul(eye + block_Q, (eye - block_Q).float().inverse())
81
82
R = oft_blocks.to(orig_weight.device)
83
84
if not self.is_boft:
85
# This errors out for MultiheadAttention, might need to be handled up-stream
86
merged_weight = rearrange(orig_weight, '(k n) ... -> k n ...', k=self.num_blocks, n=self.block_size)
87
merged_weight = torch.einsum(
88
'k n m, k n ... -> k m ...',
89
R,
90
merged_weight
91
)
92
merged_weight = rearrange(merged_weight, 'k m ... -> (k m) ...')
93
else:
94
# TODO: determine correct value for scale
95
scale = 1.0
96
m = self.boft_m
97
b = self.boft_b
98
r_b = b // 2
99
inp = orig_weight
100
for i in range(m):
101
bi = R[i] # b_num, b_size, b_size
102
if i == 0:
103
# Apply multiplier/scale and rescale into first weight
104
bi = bi * scale + (1 - scale) * eye
105
inp = rearrange(inp, "(c g k) ... -> (c k g) ...", g=2, k=2**i * r_b)
106
inp = rearrange(inp, "(d b) ... -> d b ...", b=b)
107
inp = torch.einsum("b i j, b j ... -> b i ...", bi, inp)
108
inp = rearrange(inp, "d b ... -> (d b) ...")
109
inp = rearrange(inp, "(c k g) ... -> (c g k) ...", g=2, k=2**i * r_b)
110
merged_weight = inp
111
112
# Rescale mechanism
113
if self.rescale is not None:
114
merged_weight = self.rescale.to(merged_weight) * merged_weight
115
116
updown = merged_weight.to(orig_weight.device) - orig_weight.to(merged_weight.dtype)
117
output_shape = orig_weight.shape
118
return self.finalize_updown(updown, orig_weight, output_shape)
119
120