Guest User

SD15 Safetensor VAE Fix

a guest
Oct 8th, 2024
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | Software | 0 0
  1. # sd15 repairs checkpoints with vae errors
  2. # based on https://github.com/huggingface/diffusers/issues/4790
  3. # tested on https://civitai.com/models/146136
  4. # use with Easy Diffusion:
  5. # 1. Open the Developer Console
  6. # 2. python /path/to/script.py -i /path/to/checkpoint.safetensors -o /path/to/fixed_checkpoint.safetensors
  7.  
  8. import argparse
  9. from safetensors import safe_open
  10. from safetensors.torch import save_file
  11. from pathlib import Path
  12.  
  13. def fix_diffusers_model_conversion(load_path, save_path):
  14. # load original
  15. tensors = {}
  16. with safe_open(load_path, framework="pt") as f:
  17. for key in f.keys():
  18. tensors[key] = f.get_tensor(key)
  19. # migrate
  20. new_tensors = {}
  21. for k, v in tensors.items():
  22. new_key = k
  23. # only fix the vae
  24. if 'first_stage_model.' in k:
  25. # migrate q, k, v keys
  26. new_key = new_key.replace('.to_q.weight', '.q.weight')
  27. new_key = new_key.replace('.to_q.bias', '.q.bias')
  28. new_key = new_key.replace('.to_k.weight', '.k.weight')
  29. new_key = new_key.replace('.to_k.bias', '.k.bias')
  30. new_key = new_key.replace('.to_v.weight', '.v.weight')
  31. new_key = new_key.replace('.to_v.bias', '.v.bias')
  32. new_tensors[new_key] = v
  33. # save
  34. save_file(new_tensors, save_path)
  35.  
  36. # get the cli arguments
  37. parser = argparse.ArgumentParser()
  38. parser.add_argument('-i', '--input', required=True, help='Broken checkpoint path')
  39. parser.add_argument('-o', '--output', required=True, help='Path for newly fixed checkpoint')
  40. args = parser.parse_args()
  41.  
  42. # check the input file exists and the output file does not
  43. input_file = Path(args.input)
  44. output_file = Path(args.output)
  45.  
  46. if input_file.is_file() and not output_file.is_file():
  47. print("Attempting to fix checkpoint...")
  48. fix_diffusers_model_conversion(args.input, args.output)
  49. else:
  50. print("Invalid command line. Use -h for help.")
  51.  
Advertisement
Add Comment
Please, Sign In to add comment