Path: blob/master/extensions-builtin/Lora/lyco_helpers.py
2447 views
import torch123def make_weight_cp(t, wa, wb):4temp = torch.einsum('i j k l, j r -> i r k l', t, wb)5return torch.einsum('i j k l, i r -> r j k l', temp, wa)678def rebuild_conventional(up, down, shape, dyn_dim=None):9up = up.reshape(up.size(0), -1)10down = down.reshape(down.size(0), -1)11if dyn_dim is not None:12up = up[:, :dyn_dim]13down = down[:dyn_dim, :]14return (up @ down).reshape(shape)151617def rebuild_cp_decomposition(up, down, mid):18up = up.reshape(up.size(0), -1)19down = down.reshape(down.size(0), -1)20return torch.einsum('n m k l, i n, m j -> i j k l', mid, up, down)212223# copied from https://github.com/KohakuBlueleaf/LyCORIS/blob/dev/lycoris/modules/lokr.py24def factorization(dimension: int, factor:int=-1) -> tuple[int, int]:25'''26return a tuple of two value of input dimension decomposed by the number closest to factor27second value is higher or equal than first value.2829In LoRA with Kroneckor Product, first value is a value for weight scale.30secon value is a value for weight.3132Because of non-commutative property, A⊗B ≠ B⊗A. Meaning of two matrices is slightly different.3334examples)35factor36-1 2 4 8 16 ...37127 -> 1, 127 127 -> 1, 127 127 -> 1, 127 127 -> 1, 127 127 -> 1, 12738128 -> 8, 16 128 -> 2, 64 128 -> 4, 32 128 -> 8, 16 128 -> 8, 1639250 -> 10, 25 250 -> 2, 125 250 -> 2, 125 250 -> 5, 50 250 -> 10, 2540360 -> 8, 45 360 -> 2, 180 360 -> 4, 90 360 -> 8, 45 360 -> 12, 3041512 -> 16, 32 512 -> 2, 256 512 -> 4, 128 512 -> 8, 64 512 -> 16, 32421024 -> 32, 32 1024 -> 2, 512 1024 -> 4, 256 1024 -> 8, 128 1024 -> 16, 6443'''4445if factor > 0 and (dimension % factor) == 0:46m = factor47n = dimension // factor48if m > n:49n, m = m, n50return m, n51if factor < 0:52factor = dimension53m, n = 1, dimension54length = m + n55while m<n:56new_m = m + 157while dimension%new_m != 0:58new_m += 159new_n = dimension // new_m60if new_m + new_n > length or new_m>factor:61break62else:63m, n = new_m, new_n64if m > n:65n, m = m, n66return m, n67686970