network_oft.py 4.2 KB
Newer Older
V
v0xie 已提交
1 2
import torch
import network
3
from lyco_helpers import factorization
4
from einops import rearrange
V
v0xie 已提交
5 6 7 8


class ModuleTypeOFT(network.ModuleType):
    def create_module(self, net: network.Network, weights: network.NetworkWeights):
9
        if all(x in weights.w for x in ["oft_blocks"]) or all(x in weights.w for x in ["oft_diag"]):
V
v0xie 已提交
10 11 12 13
            return NetworkModuleOFT(net, weights)

        return None

V
v0xie 已提交
14 15
# 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
V
v0xie 已提交
16 17
class NetworkModuleOFT(network.NetworkModule):
    def __init__(self,  net: network.Network, weights: network.NetworkWeights):
V
v0xie 已提交
18

V
v0xie 已提交
19 20
        super().__init__(net, weights)

21
        self.lin_module = None
V
v0xie 已提交
22
        self.org_module: list[torch.Module] = [self.sd_module]
23

24 25 26
        # kohya-ss
        if "oft_blocks" in weights.w.keys():
            self.is_kohya = True
27
            self.oft_blocks = weights.w["oft_blocks"] # (num_blocks, block_size, block_size)
V
v0xie 已提交
28
            self.alpha = weights.w["alpha"] # alpha is constraint
29
            self.dim = self.oft_blocks.shape[0] # lora dim
V
v0xie 已提交
30
        # LyCORIS
31 32
        elif "oft_diag" in weights.w.keys():
            self.is_kohya = False
V
v0xie 已提交
33 34 35
            self.oft_blocks = weights.w["oft_diag"]
            # self.alpha is unused
            self.dim = self.oft_blocks.shape[1] # (num_blocks, block_size, block_size)
36 37 38

        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]
V
v0xie 已提交
39
        is_other_linear = type(self.sd_module) in [torch.nn.MultiheadAttention] # unsupported
40

41
        if is_linear:
V
v0xie 已提交
42
            self.out_dim = self.sd_module.out_features
43
        elif is_conv:
V
v0xie 已提交
44
            self.out_dim = self.sd_module.out_channels
V
v0xie 已提交
45 46
        elif is_other_linear:
            self.out_dim = self.sd_module.embed_dim
47 48 49

        if self.is_kohya:
            self.constraint = self.alpha * self.out_dim
V
v0xie 已提交
50 51
            self.num_blocks = self.dim
            self.block_size = self.out_dim // self.dim
52 53
        else:
            self.constraint = None
54 55
            self.block_size, self.num_blocks = factorization(self.out_dim, self.dim)

V
v0xie 已提交
56 57 58
    def calc_updown_kb(self, orig_weight, multiplier):
        oft_blocks = self.oft_blocks.to(orig_weight.device, dtype=orig_weight.dtype)
        oft_blocks = oft_blocks - oft_blocks.transpose(1, 2) # ensure skew-symmetric orthogonal matrix
V
v0xie 已提交
59

V
v0xie 已提交
60 61
        R = oft_blocks.to(orig_weight.device, dtype=orig_weight.dtype)
        R = R * multiplier + torch.eye(self.block_size, device=orig_weight.device)
V
v0xie 已提交
62

V
v0xie 已提交
63 64 65 66 67 68 69 70
        # 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) ...')
V
v0xie 已提交
71

72 73
        updown = merged_weight.to(orig_weight.device, dtype=orig_weight.dtype) - orig_weight
        output_shape = orig_weight.shape
V
v0xie 已提交
74
        return self.finalize_updown(updown, orig_weight, output_shape)
V
v0xie 已提交
75

76
    def calc_updown(self, orig_weight):
V
v0xie 已提交
77
        # if alpha is a very small number as in coft, calc_scale() will return a almost zero number so we ignore it
78
        multiplier = self.multiplier()
79
        return self.calc_updown_kb(orig_weight, multiplier)
80

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    # override to remove the multiplier/scale factor; it's already multiplied in get_weight
    def finalize_updown(self, updown, orig_weight, output_shape, ex_bias=None):
        if self.bias is not None:
            updown = updown.reshape(self.bias.shape)
            updown += self.bias.to(orig_weight.device, dtype=orig_weight.dtype)
            updown = updown.reshape(output_shape)

        if len(output_shape) == 4:
            updown = updown.reshape(output_shape)

        if orig_weight.size().numel() == updown.size().numel():
            updown = updown.reshape(orig_weight.shape)

        if ex_bias is not None:
            ex_bias = ex_bias * self.multiplier()

        return updown, ex_bias