Advertisement
Guest User

Check stable diffusion base checkpoint version

a guest
Mar 16th, 2023
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.13 KB | None | 0 0
  1. ## https://huggingface.co/JosephusCheung/ASimilarityCalculatior/blob/main/qwerty.py
  2. ## Check stable diffusion base checkpoint version:
  3. ## python qwerty.py model_to_check.ckpt model1.ckpt model2.ckpt model3.ckpt
  4.  
  5. from safetensors.torch import load_file
  6. import sys
  7. import torch
  8. from pathlib import Path
  9. import torch.nn as nn
  10. import torch.nn.functional as F
  11.  
  12. def cal_cross_attn(to_q, to_k, to_v, rand_input):
  13.     hidden_dim, embed_dim = to_q.shape
  14.     attn_to_q = nn.Linear(hidden_dim, embed_dim, bias=False)
  15.     attn_to_k = nn.Linear(hidden_dim, embed_dim, bias=False)
  16.     attn_to_v = nn.Linear(hidden_dim, embed_dim, bias=False)
  17.     attn_to_q.load_state_dict({"weight": to_q})
  18.     attn_to_k.load_state_dict({"weight": to_k})
  19.     attn_to_v.load_state_dict({"weight": to_v})
  20.    
  21.     return torch.einsum(
  22.         "ik, jk -> ik",
  23.         F.softmax(torch.einsum("ij, kj -> ik", attn_to_q(rand_input), attn_to_k(rand_input)), dim=-1),
  24.         attn_to_v(rand_input)
  25.     )
  26.  
  27. def model_hash(filename):
  28.     try:
  29.         with open(filename, "rb") as file:
  30.             import hashlib
  31.             m = hashlib.sha256()
  32.  
  33.             file.seek(0x100000)
  34.             m.update(file.read(0x10000))
  35.             return m.hexdigest()[0:8]
  36.     except FileNotFoundError:
  37.         return 'NOFILE'
  38.        
  39. def load_model(path):
  40.     if path.suffix == ".safetensors":
  41.         return load_file(path, device="cpu")
  42.     else:
  43.         ckpt = torch.load(path, map_location="cpu")
  44.         return ckpt["state_dict"] if "state_dict" in ckpt else ckpt
  45.        
  46. def eval(model, n, input):
  47.     qk = f"model.diffusion_model.output_blocks.{n}.1.transformer_blocks.0.attn1.to_q.weight"
  48.     uk = f"model.diffusion_model.output_blocks.{n}.1.transformer_blocks.0.attn1.to_k.weight"
  49.     vk = f"model.diffusion_model.output_blocks.{n}.1.transformer_blocks.0.attn1.to_v.weight"
  50.     atoq, atok, atov = model[qk], model[uk], model[vk]
  51.  
  52.     attn = cal_cross_attn(atoq, atok, atov, input)
  53.     return attn
  54.  
  55. def main():
  56.     file1 = Path(sys.argv[1])
  57.     files = sys.argv[2:]
  58.    
  59.     seed = 114514
  60.     torch.manual_seed(seed)
  61.     print(f"seed: {seed}")
  62.    
  63.     model_a = load_model(file1)
  64.    
  65.     print()
  66.     print(f"base: {file1.name} [{model_hash(file1)}]")
  67.     print()
  68.  
  69.     map_attn_a = {}
  70.     map_rand_input = {}
  71.     for n in range(3, 11):
  72.         hidden_dim, embed_dim = model_a[f"model.diffusion_model.output_blocks.{n}.1.transformer_blocks.0.attn1.to_q.weight"].shape
  73.         rand_input = torch.randn([embed_dim, hidden_dim])
  74.  
  75.         map_attn_a[n] = eval(model_a, n, rand_input)
  76.         map_rand_input[n] = rand_input
  77.        
  78.     del model_a
  79.      
  80.     for file2 in files:
  81.         file2 = Path(file2)
  82.         model_b = load_model(file2)
  83.        
  84.         sims = []
  85.         for n in range(3, 11):
  86.             attn_a = map_attn_a[n]
  87.             attn_b = eval(model_b, n, map_rand_input[n])
  88.            
  89.             sim = torch.mean(torch.cosine_similarity(attn_a, attn_b))
  90.             sims.append(sim)
  91.            
  92.         print(f"{file2} [{model_hash(file2)}] - {torch.mean(torch.stack(sims)) * 1e2:.2f}%")
  93.        
  94. if __name__ == "__main__":
  95.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement