network_oft.py 3.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import torch
  2. import network
  3. from lyco_helpers import factorization
  4. from einops import rearrange
  5. class ModuleTypeOFT(network.ModuleType):
  6. def create_module(self, net: network.Network, weights: network.NetworkWeights):
  7. if all(x in weights.w for x in ["oft_blocks"]) or all(x in weights.w for x in ["oft_diag"]):
  8. return NetworkModuleOFT(net, weights)
  9. return None
  10. # Supports both kohya-ss' implementation of COFT https://github.com/kohya-ss/sd-scripts/blob/main/networks/oft.py
  11. # and KohakuBlueleaf's implementation of OFT/COFT https://github.com/KohakuBlueleaf/LyCORIS/blob/dev/lycoris/modules/diag_oft.py
  12. class NetworkModuleOFT(network.NetworkModule):
  13. def __init__(self, net: network.Network, weights: network.NetworkWeights):
  14. super().__init__(net, weights)
  15. self.lin_module = None
  16. self.org_module: list[torch.Module] = [self.sd_module]
  17. self.scale = 1.0
  18. # kohya-ss
  19. if "oft_blocks" in weights.w.keys():
  20. self.is_kohya = True
  21. self.oft_blocks = weights.w["oft_blocks"] # (num_blocks, block_size, block_size)
  22. self.alpha = weights.w["alpha"] # alpha is constraint
  23. self.dim = self.oft_blocks.shape[0] # lora dim
  24. # LyCORIS
  25. elif "oft_diag" in weights.w.keys():
  26. self.is_kohya = False
  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. if self.is_kohya:
  40. self.constraint = self.alpha * self.out_dim
  41. self.num_blocks = self.dim
  42. self.block_size = self.out_dim // self.dim
  43. else:
  44. self.constraint = None
  45. self.block_size, self.num_blocks = factorization(self.out_dim, self.dim)
  46. def calc_updown(self, orig_weight):
  47. oft_blocks = self.oft_blocks.to(orig_weight.device)
  48. eye = torch.eye(self.block_size, device=oft_blocks.device)
  49. if self.is_kohya:
  50. block_Q = oft_blocks - oft_blocks.transpose(1, 2) # ensure skew-symmetric orthogonal matrix
  51. norm_Q = torch.norm(block_Q.flatten())
  52. new_norm_Q = torch.clamp(norm_Q, max=self.constraint.to(oft_blocks.device))
  53. block_Q = block_Q * ((new_norm_Q + 1e-8) / (norm_Q + 1e-8))
  54. oft_blocks = torch.matmul(eye + block_Q, (eye - block_Q).float().inverse())
  55. R = oft_blocks.to(orig_weight.device)
  56. # This errors out for MultiheadAttention, might need to be handled up-stream
  57. merged_weight = rearrange(orig_weight, '(k n) ... -> k n ...', k=self.num_blocks, n=self.block_size)
  58. merged_weight = torch.einsum(
  59. 'k n m, k n ... -> k m ...',
  60. R,
  61. merged_weight
  62. )
  63. merged_weight = rearrange(merged_weight, 'k m ... -> (k m) ...')
  64. updown = merged_weight.to(orig_weight.device) - orig_weight.to(merged_weight.dtype)
  65. output_shape = orig_weight.shape
  66. return self.finalize_updown(updown, orig_weight, output_shape)