network_oft.py 5.1 KB

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