Guest User

Untitled

a guest
Aug 10th, 2023
894
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.14 KB | None | 0 0
  1. # Script for converting a HF Diffusers saved pipeline to a Stable Diffusion checkpoint.
  2. # *Only* converts the UNet, VAE, and Text Encoder.
  3. # Does not convert optimizer state or any other thing.
  4.  
  5. import argparse
  6. import os.path as osp
  7. import re
  8.  
  9. import torch
  10. from safetensors.torch import load_file, save_file
  11.  
  12.  
  13. # =================#
  14. # UNet Conversion #
  15. # =================#
  16.  
  17. unet_conversion_map = [
  18.     # (stable-diffusion, HF Diffusers)
  19.     ("time_embed.0.weight", "time_embedding.linear_1.weight"),
  20.     ("time_embed.0.bias", "time_embedding.linear_1.bias"),
  21.     ("time_embed.2.weight", "time_embedding.linear_2.weight"),
  22.     ("time_embed.2.bias", "time_embedding.linear_2.bias"),
  23.     ("input_blocks.0.0.weight", "conv_in.weight"),
  24.     ("input_blocks.0.0.bias", "conv_in.bias"),
  25.     ("out.0.weight", "conv_norm_out.weight"),
  26.     ("out.0.bias", "conv_norm_out.bias"),
  27.     ("out.2.weight", "conv_out.weight"),
  28.     ("out.2.bias", "conv_out.bias"),
  29. ]
  30.  
  31. unet_conversion_map_resnet = [
  32.     # (stable-diffusion, HF Diffusers)
  33.     ("in_layers.0", "norm1"),
  34.     ("in_layers.2", "conv1"),
  35.     ("out_layers.0", "norm2"),
  36.     ("out_layers.3", "conv2"),
  37.     ("emb_layers.1", "time_emb_proj"),
  38.     ("skip_connection", "conv_shortcut"),
  39. ]
  40.  
  41. unet_conversion_map_layer = []
  42. # hardcoded number of downblocks and resnets/attentions...
  43. # would need smarter logic for other networks.
  44. for i in range(4):
  45.     # loop over downblocks/upblocks
  46.  
  47.     for j in range(2):
  48.         # loop over resnets/attentions for downblocks
  49.         hf_down_res_prefix = f"down_blocks.{i}.resnets.{j}."
  50.         sd_down_res_prefix = f"input_blocks.{3*i + j + 1}.0."
  51.         unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))
  52.  
  53.         if i < 3:
  54.             # no attention layers in down_blocks.3
  55.             hf_down_atn_prefix = f"down_blocks.{i}.attentions.{j}."
  56.             sd_down_atn_prefix = f"input_blocks.{3*i + j + 1}.1."
  57.             unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))
  58.  
  59.     for j in range(3):
  60.         # loop over resnets/attentions for upblocks
  61.         hf_up_res_prefix = f"up_blocks.{i}.resnets.{j}."
  62.         sd_up_res_prefix = f"output_blocks.{3*i + j}.0."
  63.         unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))
  64.  
  65.         if i > 0:
  66.             # no attention layers in up_blocks.0
  67.             hf_up_atn_prefix = f"up_blocks.{i}.attentions.{j}."
  68.             sd_up_atn_prefix = f"output_blocks.{3*i + j}.1."
  69.             unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))
  70.  
  71.     if i < 3:
  72.         # no downsample in down_blocks.3
  73.         hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0.conv."
  74.         sd_downsample_prefix = f"input_blocks.{3*(i+1)}.0.op."
  75.         unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))
  76.  
  77.         # no upsample in up_blocks.3
  78.         hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
  79.         sd_upsample_prefix = f"output_blocks.{3*i + 2}.{1 if i == 0 else 2}."
  80.         unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))
  81.  
  82. hf_mid_atn_prefix = "mid_block.attentions.0."
  83. sd_mid_atn_prefix = "middle_block.1."
  84. unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))
  85.  
  86. for j in range(2):
  87.     hf_mid_res_prefix = f"mid_block.resnets.{j}."
  88.     sd_mid_res_prefix = f"middle_block.{2*j}."
  89.     unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))
  90.  
  91.  
  92. def convert_unet_state_dict(unet_state_dict):
  93.     # buyer beware: this is a *brittle* function,
  94.     # and correct output requires that all of these pieces interact in
  95.     # the exact order in which I have arranged them.
  96.     mapping = {k: k for k in unet_state_dict.keys()}
  97.     for sd_name, hf_name in unet_conversion_map:
  98.         mapping[hf_name] = sd_name
  99.     for k, v in mapping.items():
  100.         if "resnets" in k:
  101.             for sd_part, hf_part in unet_conversion_map_resnet:
  102.                 v = v.replace(hf_part, sd_part)
  103.             mapping[k] = v
  104.     for k, v in mapping.items():
  105.         for sd_part, hf_part in unet_conversion_map_layer:
  106.             v = v.replace(hf_part, sd_part)
  107.         mapping[k] = v
  108.     new_state_dict = {v: unet_state_dict[k] for k, v in mapping.items()}
  109.     return new_state_dict
  110.  
  111.  
  112. # ================#
  113. # VAE Conversion #
  114. # ================#
  115.  
  116. vae_conversion_map = [
  117.     # (stable-diffusion, HF Diffusers)
  118.     ("nin_shortcut", "conv_shortcut"),
  119.     ("norm_out", "conv_norm_out"),
  120.     ("mid.attn_1.", "mid_block.attentions.0."),
  121. ]
  122.  
  123. for i in range(4):
  124.     # down_blocks have two resnets
  125.     for j in range(2):
  126.         hf_down_prefix = f"encoder.down_blocks.{i}.resnets.{j}."
  127.         sd_down_prefix = f"encoder.down.{i}.block.{j}."
  128.         vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
  129.  
  130.     if i < 3:
  131.         hf_downsample_prefix = f"down_blocks.{i}.downsamplers.0."
  132.         sd_downsample_prefix = f"down.{i}.downsample."
  133.         vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
  134.  
  135.         hf_upsample_prefix = f"up_blocks.{i}.upsamplers.0."
  136.         sd_upsample_prefix = f"up.{3-i}.upsample."
  137.         vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
  138.  
  139.     # up_blocks have three resnets
  140.     # also, up blocks in hf are numbered in reverse from sd
  141.     for j in range(3):
  142.         hf_up_prefix = f"decoder.up_blocks.{i}.resnets.{j}."
  143.         sd_up_prefix = f"decoder.up.{3-i}.block.{j}."
  144.         vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
  145.  
  146. # this part accounts for mid blocks in both the encoder and the decoder
  147. for i in range(2):
  148.     hf_mid_res_prefix = f"mid_block.resnets.{i}."
  149.     sd_mid_res_prefix = f"mid.block_{i+1}."
  150.     vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
  151.  
  152.  
  153. vae_conversion_map_attn = [
  154.     # (stable-diffusion, HF Diffusers)
  155.     ("norm.", "group_norm."),
  156.     ("q.", "query."),
  157.     ("k.", "key."),
  158.     ("v.", "value."),
  159.     ("proj_out.", "proj_attn."),
  160. ]
  161.  
  162.  
  163. def reshape_weight_for_sd(w):
  164.     # convert HF linear weights to SD conv2d weights
  165.     return w.reshape(*w.shape, 1, 1)
  166.  
  167.  
  168. def convert_vae_state_dict(vae_state_dict):
  169.     mapping = {k: k for k in vae_state_dict.keys()}
  170.     for k, v in mapping.items():
  171.         for sd_part, hf_part in vae_conversion_map:
  172.             v = v.replace(hf_part, sd_part)
  173.         mapping[k] = v
  174.     for k, v in mapping.items():
  175.         if "attentions" in k:
  176.             for sd_part, hf_part in vae_conversion_map_attn:
  177.                 v = v.replace(hf_part, sd_part)
  178.             mapping[k] = v
  179.     new_state_dict = {v: vae_state_dict[k] for k, v in mapping.items()}
  180.     weights_to_convert = ["q", "k", "v", "proj_out"]
  181.     for k, v in new_state_dict.items():
  182.         for weight_name in weights_to_convert:
  183.             if f"mid.attn_1.{weight_name}.weight" in k:
  184.                 print(f"Reshaping {k} for SD format")
  185.                 new_state_dict[k] = reshape_weight_for_sd(v)
  186.     return new_state_dict
  187.  
  188.  
  189. # =========================#
  190. # Text Encoder Conversion #
  191. # =========================#
  192.  
  193.  
  194. textenc_conversion_lst = [
  195.     # (stable-diffusion, HF Diffusers)
  196.     ("resblocks.", "text_model.encoder.layers."),
  197.     ("ln_1", "layer_norm1"),
  198.     ("ln_2", "layer_norm2"),
  199.     (".c_fc.", ".fc1."),
  200.     (".c_proj.", ".fc2."),
  201.     (".attn", ".self_attn"),
  202.     ("ln_final.", "transformer.text_model.final_layer_norm."),
  203.     ("token_embedding.weight", "transformer.text_model.embeddings.token_embedding.weight"),
  204.     ("positional_embedding", "transformer.text_model.embeddings.position_embedding.weight"),
  205. ]
  206. protected = {re.escape(x[1]): x[0] for x in textenc_conversion_lst}
  207. textenc_pattern = re.compile("|".join(protected.keys()))
  208.  
  209. # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
  210. code2idx = {"q": 0, "k": 1, "v": 2}
  211.  
  212.  
  213. def convert_text_enc_state_dict_v20(text_enc_dict):
  214.     new_state_dict = {}
  215.     capture_qkv_weight = {}
  216.     capture_qkv_bias = {}
  217.     for k, v in text_enc_dict.items():
  218.         if (
  219.             k.endswith(".self_attn.q_proj.weight")
  220.             or k.endswith(".self_attn.k_proj.weight")
  221.             or k.endswith(".self_attn.v_proj.weight")
  222.         ):
  223.             k_pre = k[: -len(".q_proj.weight")]
  224.             k_code = k[-len("q_proj.weight")]
  225.             if k_pre not in capture_qkv_weight:
  226.                 capture_qkv_weight[k_pre] = [None, None, None]
  227.             capture_qkv_weight[k_pre][code2idx[k_code]] = v
  228.             continue
  229.  
  230.         if (
  231.             k.endswith(".self_attn.q_proj.bias")
  232.             or k.endswith(".self_attn.k_proj.bias")
  233.             or k.endswith(".self_attn.v_proj.bias")
  234.         ):
  235.             k_pre = k[: -len(".q_proj.bias")]
  236.             k_code = k[-len("q_proj.bias")]
  237.             if k_pre not in capture_qkv_bias:
  238.                 capture_qkv_bias[k_pre] = [None, None, None]
  239.             capture_qkv_bias[k_pre][code2idx[k_code]] = v
  240.             continue
  241.  
  242.         relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k)
  243.         new_state_dict[relabelled_key] = v
  244.  
  245.     for k_pre, tensors in capture_qkv_weight.items():
  246.         if None in tensors:
  247.             raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
  248.         relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
  249.         new_state_dict[relabelled_key + ".in_proj_weight"] = torch.cat(tensors)
  250.  
  251.     for k_pre, tensors in capture_qkv_bias.items():
  252.         if None in tensors:
  253.             raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing")
  254.         relabelled_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], k_pre)
  255.         new_state_dict[relabelled_key + ".in_proj_bias"] = torch.cat(tensors)
  256.  
  257.     return new_state_dict
  258.  
  259.  
  260. def convert_text_enc_state_dict(text_enc_dict):
  261.     return text_enc_dict
  262.  
  263.  
  264. if __name__ == "__main__":
  265.     parser = argparse.ArgumentParser()
  266.  
  267.     parser.add_argument("--model_path", default=None, type=str, required=True, help="Path to the model to convert.")
  268.     parser.add_argument("--checkpoint_path", default=None, type=str, required=True, help="Path to the output model.")
  269.     parser.add_argument("--half", action="store_true", help="Save weights in half precision.")
  270.     parser.add_argument(
  271.         "--use_safetensors", action="store_true", help="Save weights use safetensors, default is ckpt."
  272.     )
  273.  
  274.     args = parser.parse_args()
  275.  
  276.     assert args.model_path is not None, "Must provide a model path!"
  277.  
  278.     assert args.checkpoint_path is not None, "Must provide a checkpoint path!"
  279.  
  280.     # Path for safetensors
  281.     unet_path = osp.join(args.model_path, "unet", "diffusion_pytorch_model.safetensors")
  282.     #vae_path = osp.join(args.model_path, "vae", "diffusion_pytorch_model.safetensors")
  283.     #text_enc_path = osp.join(args.model_path, "text_encoder", "model.safetensors")
  284.  
  285.     # Load models from safetensors if it exists, if it doesn't pytorch
  286.     if osp.exists(unet_path):
  287.         unet_state_dict = load_file(unet_path, device="cpu")
  288.     else:
  289.         unet_path = osp.join(args.model_path, "unet", "diffusion_pytorch_model.bin")
  290.         unet_state_dict = torch.load(unet_path, map_location="cpu")
  291.  
  292.     #if osp.exists(vae_path):
  293.     #    vae_state_dict = load_file(vae_path, device="cpu")
  294.     #else:
  295.     #    vae_path = osp.join(args.model_path, "vae", "diffusion_pytorch_model.bin")
  296.     #    vae_state_dict = torch.load(vae_path, map_location="cpu")
  297.  
  298.     #if osp.exists(text_enc_path):
  299.     #    text_enc_dict = load_file(text_enc_path, device="cpu")
  300.     #else:
  301.     #    text_enc_path = osp.join(args.model_path, "text_encoder", "pytorch_model.bin")
  302.     #    text_enc_dict = torch.load(text_enc_path, map_location="cpu")
  303.  
  304.     # Convert the UNet model
  305.     #unet_state_dict = convert_unet_state_dict(unet_state_dict)
  306.     #unet_state_dict = {"model.diffusion_model." + k: v for k, v in unet_state_dict.items()}
  307.  
  308.     # Convert the VAE model
  309.     #vae_state_dict = convert_vae_state_dict(vae_state_dict)
  310.     #vae_state_dict = {"first_stage_model." + k: v for k, v in vae_state_dict.items()}
  311.  
  312.     # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper
  313.     #is_v20_model = "text_model.encoder.layers.22.layer_norm2.bias" in text_enc_dict
  314.     is_v20_model = True
  315.  
  316.     #if is_v20_model:
  317.         # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm
  318.         #text_enc_dict = {"transformer." + k: v for k, v in text_enc_dict.items()}
  319.         #text_enc_dict = convert_text_enc_state_dict_v20(text_enc_dict)
  320.         #text_enc_dict = {"cond_stage_model.model." + k: v for k, v in text_enc_dict.items()}
  321.     #else:
  322.         #text_enc_dict = convert_text_enc_state_dict(text_enc_dict)
  323.         #text_enc_dict = {"cond_stage_model.transformer." + k: v for k, v in text_enc_dict.items()}
  324.  
  325.     # Put together new checkpoint
  326.     state_dict = {**unet_state_dict}
  327.     if args.half:
  328.         state_dict = {k: v.half() for k, v in state_dict.items()}
  329.  
  330.     if args.use_safetensors:
  331.         save_file(state_dict, args.checkpoint_path)
  332.     else:
  333.         state_dict = {"state_dict": state_dict}
  334.         torch.save(state_dict, args.checkpoint_path)
Advertisement
Add Comment
Please, Sign In to add comment