2023-10-18 06:35:50 +00:00
|
|
|
import torch
|
|
|
|
import network
|
2024-02-08 19:55:05 +00:00
|
|
|
from lyco_helpers import factorization
|
2023-11-02 05:34:27 +00:00
|
|
|
from einops import rearrange
|
2023-10-18 06:35:50 +00:00
|
|
|
|
|
|
|
|
|
|
|
class ModuleTypeOFT(network.ModuleType):
|
|
|
|
def create_module(self, net: network.Network, weights: network.NetworkWeights):
|
2023-11-02 07:13:11 +00:00
|
|
|
if all(x in weights.w for x in ["oft_blocks"]) or all(x in weights.w for x in ["oft_diag"]):
|
2023-10-18 06:35:50 +00:00
|
|
|
return NetworkModuleOFT(net, weights)
|
|
|
|
|
|
|
|
return None
|
|
|
|
|
2023-11-16 02:28:48 +00:00
|
|
|
# Supports both kohya-ss' implementation of COFT https://github.com/kohya-ss/sd-scripts/blob/main/networks/oft.py
|
|
|
|
# and KohakuBlueleaf's implementation of OFT/COFT https://github.com/KohakuBlueleaf/LyCORIS/blob/dev/lycoris/modules/diag_oft.py
|
2023-10-18 06:35:50 +00:00
|
|
|
class NetworkModuleOFT(network.NetworkModule):
|
|
|
|
def __init__(self, net: network.Network, weights: network.NetworkWeights):
|
2023-10-18 11:16:01 +00:00
|
|
|
|
2023-10-18 06:35:50 +00:00
|
|
|
super().__init__(net, weights)
|
|
|
|
|
2023-11-02 07:13:11 +00:00
|
|
|
self.lin_module = None
|
2023-11-04 00:52:55 +00:00
|
|
|
self.org_module: list[torch.Module] = [self.sd_module]
|
2023-11-04 02:35:15 +00:00
|
|
|
|
2023-12-13 17:43:24 +00:00
|
|
|
self.scale = 1.0
|
2024-02-19 06:43:07 +00:00
|
|
|
self.is_kohya = False
|
|
|
|
self.is_boft = False
|
2023-12-13 17:43:24 +00:00
|
|
|
|
2023-11-02 07:13:11 +00:00
|
|
|
# kohya-ss
|
|
|
|
if "oft_blocks" in weights.w.keys():
|
|
|
|
self.is_kohya = True
|
2023-11-04 21:54:36 +00:00
|
|
|
self.oft_blocks = weights.w["oft_blocks"] # (num_blocks, block_size, block_size)
|
2023-11-16 02:28:48 +00:00
|
|
|
self.alpha = weights.w["alpha"] # alpha is constraint
|
2023-11-04 21:54:36 +00:00
|
|
|
self.dim = self.oft_blocks.shape[0] # lora dim
|
2024-02-09 05:58:59 +00:00
|
|
|
# LyCORIS OFT
|
2023-11-02 07:13:11 +00:00
|
|
|
elif "oft_diag" in weights.w.keys():
|
2023-11-16 02:28:48 +00:00
|
|
|
self.oft_blocks = weights.w["oft_diag"]
|
|
|
|
# self.alpha is unused
|
|
|
|
self.dim = self.oft_blocks.shape[1] # (num_blocks, block_size, block_size)
|
2023-11-02 07:13:11 +00:00
|
|
|
|
2024-02-09 05:58:59 +00:00
|
|
|
# LyCORIS BOFT
|
2024-02-08 19:55:05 +00:00
|
|
|
if weights.w["oft_diag"].dim() == 4:
|
2024-02-07 12:49:17 +00:00
|
|
|
self.is_boft = True
|
2024-02-18 06:58:41 +00:00
|
|
|
self.rescale = weights.w.get('rescale', None)
|
|
|
|
if self.rescale is not None:
|
|
|
|
self.rescale = self.rescale.reshape(-1, *[1]*(self.org_module[0].weight.dim() - 1))
|
2024-02-07 12:49:17 +00:00
|
|
|
|
2023-11-02 07:13:11 +00:00
|
|
|
is_linear = type(self.sd_module) in [torch.nn.Linear, torch.nn.modules.linear.NonDynamicallyQuantizableLinear]
|
|
|
|
is_conv = type(self.sd_module) in [torch.nn.Conv2d]
|
2023-11-16 02:28:48 +00:00
|
|
|
is_other_linear = type(self.sd_module) in [torch.nn.MultiheadAttention] # unsupported
|
2023-11-04 02:35:15 +00:00
|
|
|
|
2023-11-02 07:13:11 +00:00
|
|
|
if is_linear:
|
2023-10-18 06:35:50 +00:00
|
|
|
self.out_dim = self.sd_module.out_features
|
2023-11-02 07:13:11 +00:00
|
|
|
elif is_conv:
|
2023-10-18 06:35:50 +00:00
|
|
|
self.out_dim = self.sd_module.out_channels
|
2023-11-16 02:28:48 +00:00
|
|
|
elif is_other_linear:
|
|
|
|
self.out_dim = self.sd_module.embed_dim
|
2023-11-02 07:13:11 +00:00
|
|
|
|
|
|
|
if self.is_kohya:
|
|
|
|
self.constraint = self.alpha * self.out_dim
|
2023-11-16 02:28:48 +00:00
|
|
|
self.num_blocks = self.dim
|
|
|
|
self.block_size = self.out_dim // self.dim
|
2024-02-07 12:51:22 +00:00
|
|
|
elif self.is_boft:
|
|
|
|
self.constraint = None
|
2024-02-08 19:55:05 +00:00
|
|
|
self.boft_m = weights.w["oft_diag"].shape[0]
|
|
|
|
self.block_num = weights.w["oft_diag"].shape[1]
|
|
|
|
self.block_size = weights.w["oft_diag"].shape[2]
|
|
|
|
self.boft_b = self.block_size
|
|
|
|
#self.block_size, self.block_num = butterfly_factor(self.out_dim, self.dim)
|
2023-11-02 07:13:11 +00:00
|
|
|
else:
|
|
|
|
self.constraint = None
|
2023-11-04 21:54:36 +00:00
|
|
|
self.block_size, self.num_blocks = factorization(self.out_dim, self.dim)
|
|
|
|
|
2023-12-13 17:38:32 +00:00
|
|
|
def calc_updown(self, orig_weight):
|
2024-01-05 08:31:48 +00:00
|
|
|
oft_blocks = self.oft_blocks.to(orig_weight.device)
|
2024-01-22 10:52:34 +00:00
|
|
|
eye = torch.eye(self.block_size, device=oft_blocks.device)
|
2023-12-13 17:47:13 +00:00
|
|
|
|
2023-12-13 17:38:32 +00:00
|
|
|
if self.is_kohya:
|
|
|
|
block_Q = oft_blocks - oft_blocks.transpose(1, 2) # ensure skew-symmetric orthogonal matrix
|
|
|
|
norm_Q = torch.norm(block_Q.flatten())
|
2024-01-22 10:52:34 +00:00
|
|
|
new_norm_Q = torch.clamp(norm_Q, max=self.constraint.to(oft_blocks.device))
|
2023-12-13 17:38:32 +00:00
|
|
|
block_Q = block_Q * ((new_norm_Q + 1e-8) / (norm_Q + 1e-8))
|
2023-12-13 17:47:13 +00:00
|
|
|
oft_blocks = torch.matmul(eye + block_Q, (eye - block_Q).float().inverse())
|
2023-10-22 15:54:24 +00:00
|
|
|
|
2024-01-05 08:31:48 +00:00
|
|
|
R = oft_blocks.to(orig_weight.device)
|
2023-10-18 06:35:50 +00:00
|
|
|
|
2024-02-07 12:49:17 +00:00
|
|
|
if not self.is_boft:
|
|
|
|
# This errors out for MultiheadAttention, might need to be handled up-stream
|
|
|
|
merged_weight = rearrange(orig_weight, '(k n) ... -> k n ...', k=self.num_blocks, n=self.block_size)
|
|
|
|
merged_weight = torch.einsum(
|
|
|
|
'k n m, k n ... -> k m ...',
|
|
|
|
R,
|
|
|
|
merged_weight
|
|
|
|
)
|
|
|
|
merged_weight = rearrange(merged_weight, 'k m ... -> (k m) ...')
|
|
|
|
else:
|
2024-02-09 05:58:59 +00:00
|
|
|
# TODO: determine correct value for scale
|
2024-02-07 12:49:17 +00:00
|
|
|
scale = 1.0
|
2024-02-08 19:55:05 +00:00
|
|
|
m = self.boft_m
|
|
|
|
b = self.boft_b
|
2024-02-07 12:49:17 +00:00
|
|
|
r_b = b // 2
|
|
|
|
inp = orig_weight
|
|
|
|
for i in range(m):
|
|
|
|
bi = R[i] # b_num, b_size, b_size
|
|
|
|
if i == 0:
|
|
|
|
# Apply multiplier/scale and rescale into first weight
|
2024-02-07 12:55:11 +00:00
|
|
|
bi = bi * scale + (1 - scale) * eye
|
2024-02-07 12:49:17 +00:00
|
|
|
inp = rearrange(inp, "(c g k) ... -> (c k g) ...", g=2, k=2**i * r_b)
|
|
|
|
inp = rearrange(inp, "(d b) ... -> d b ...", b=b)
|
|
|
|
inp = torch.einsum("b i j, b j ... -> b i ...", bi, inp)
|
|
|
|
inp = rearrange(inp, "d b ... -> (d b) ...")
|
|
|
|
inp = rearrange(inp, "(c k g) ... -> (c g k) ...", g=2, k=2**i * r_b)
|
|
|
|
merged_weight = inp
|
2023-10-18 06:35:50 +00:00
|
|
|
|
2024-02-12 06:25:09 +00:00
|
|
|
# Rescale mechanism
|
|
|
|
if self.rescale is not None:
|
|
|
|
merged_weight = self.rescale.to(merged_weight) * merged_weight
|
|
|
|
|
2024-01-05 08:31:48 +00:00
|
|
|
updown = merged_weight.to(orig_weight.device) - orig_weight.to(merged_weight.dtype)
|
2023-11-04 02:35:15 +00:00
|
|
|
output_shape = orig_weight.shape
|
2023-10-18 06:35:50 +00:00
|
|
|
return self.finalize_updown(updown, orig_weight, output_shape)
|