convert-image-encoder-to-gguf.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. import argparse
  2. import os
  3. import json
  4. import torch
  5. import numpy as np
  6. from gguf import *
  7. from transformers import CLIPModel, CLIPProcessor, CLIPVisionModel
  8. TEXT = "clip.text"
  9. VISION = "clip.vision"
  10. def k(raw_key: str, arch: str) -> str:
  11. return raw_key.format(arch=arch)
  12. def should_skip_tensor(name: str, has_text: bool, has_vision: bool, has_llava: bool) -> bool:
  13. if name in (
  14. "logit_scale",
  15. "text_model.embeddings.position_ids",
  16. "vision_model.embeddings.position_ids",
  17. ):
  18. return True
  19. if has_llava and name in ["visual_projection.weight", "vision_model.post_layernorm.weight", "vision_model.post_layernorm.bias"]:
  20. return True
  21. if name.startswith("v") and not has_vision:
  22. return True
  23. if name.startswith("t") and not has_text:
  24. return True
  25. return False
  26. def get_tensor_name(name: str) -> str:
  27. if "projection" in name:
  28. return name
  29. if "mm_projector" in name:
  30. return name.replace("model.mm_projector", "mm")
  31. return name.replace("text_model", "t").replace("vision_model", "v").replace("encoder.layers", "blk").replace("embeddings.", "").replace("_proj", "").replace("self_attn.", "attn_").replace("layer_norm", "ln").replace("layernorm", "ln").replace("mlp.fc1", "ffn_down").replace("mlp.fc2", "ffn_up").replace("embedding", "embd").replace("final", "post").replace("layrnorm", "ln")
  32. def bytes_to_unicode():
  33. """
  34. Returns list of utf-8 byte and a corresponding list of unicode strings.
  35. The reversible bpe codes work on unicode strings.
  36. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
  37. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
  38. This is a significant percentage of your normal, say, 32K bpe vocab.
  39. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
  40. And avoids mapping to whitespace/control characters the bpe code barfs on.
  41. """
  42. bs = (
  43. list(range(ord("!"), ord("~") + 1))
  44. + list(range(ord("¡"), ord("¬") + 1))
  45. + list(range(ord("®"), ord("ÿ") + 1))
  46. )
  47. cs = bs[:]
  48. n = 0
  49. for b in range(2**8):
  50. if b not in bs:
  51. bs.append(b)
  52. cs.append(2**8 + n)
  53. n += 1
  54. cs = [chr(n) for n in cs]
  55. return dict(zip(bs, cs))
  56. ap = argparse.ArgumentParser(prog="convert_hf_to_gguf.py")
  57. ap.add_argument("-m", "--model-dir", help="Path to model directory cloned from HF Hub", required=True)
  58. ap.add_argument("--use-f32", action="store_true", default=False, help="Use f32 instead of f16")
  59. ap.add_argument("--text-only", action="store_true", required=False,
  60. help="Save a text-only model. It can't be used to encode images")
  61. ap.add_argument("--vision-only", action="store_true", required=False,
  62. help="Save a vision-only model. It can't be used to encode texts")
  63. ap.add_argument("--clip_model_is_vision", action="store_true", required=False,
  64. help="The clip model is a pure vision model (ShareGPT4V vision extract for example)")
  65. ap.add_argument("--llava-projector", help="Path to llava.projector file. If specified, save an image encoder for LLaVA models.")
  66. ap.add_argument("--image-mean", nargs=3, type=float, required=False, help="Override image mean values")
  67. ap.add_argument("--image-std", nargs=3, type=float, required=False, help="Override image std values")
  68. ap.add_argument("-o", "--output-dir", help="Directory to save GGUF files. Default is the original model directory", default=None)
  69. # Example --image_mean 0.48145466 0.4578275 0.40821073 --image_std 0.26862954 0.26130258 0.27577711
  70. default_image_mean = [0.48145466, 0.4578275, 0.40821073]
  71. default_image_std = [0.26862954, 0.26130258, 0.27577711]
  72. ap.add_argument('--image_mean', type=float, nargs='+', help='Mean of the images for normalization (overrides processor) ', default=None)
  73. ap.add_argument('--image_std', type=float, nargs='+', help='Standard deviation of the images for normalization (overrides processor)', default=None)
  74. # with proper
  75. args = ap.parse_args()
  76. if args.text_only and args.vision_only:
  77. print("--text-only and --image-only arguments cannot be specified at the same time.")
  78. exit(1)
  79. if args.use_f32:
  80. print("WARNING: Weights for the convolution op is always saved in f16, as the convolution op in GGML does not support 32-bit kernel weights yet.")
  81. # output in the same directory as the model if output_dir is None
  82. dir_model = args.model_dir
  83. if args.clip_model_is_vision:
  84. vocab = None
  85. tokens = None
  86. else:
  87. with open(dir_model + "/vocab.json", "r", encoding="utf-8") as f:
  88. vocab = json.load(f)
  89. tokens = [key for key in vocab]
  90. with open(dir_model + "/config.json", "r", encoding="utf-8") as f:
  91. config = json.load(f)
  92. if args.clip_model_is_vision:
  93. v_hparams = config
  94. t_hparams = None
  95. else:
  96. v_hparams = config["vision_config"]
  97. t_hparams = config["text_config"]
  98. # possible data types
  99. # ftype == 0 -> float32
  100. # ftype == 1 -> float16
  101. #
  102. # map from ftype to string
  103. ftype_str = ["f32", "f16"]
  104. ftype = 1
  105. if args.use_f32:
  106. ftype = 0
  107. if args.clip_model_is_vision:
  108. model = CLIPVisionModel.from_pretrained(dir_model)
  109. processor = None
  110. else:
  111. model = CLIPModel.from_pretrained(dir_model)
  112. processor = CLIPProcessor.from_pretrained(dir_model)
  113. fname_middle = None
  114. has_text_encoder = True
  115. has_vision_encoder = True
  116. has_llava_projector = False
  117. if args.text_only:
  118. fname_middle = "text-"
  119. has_vision_encoder = False
  120. elif args.llava_projector is not None:
  121. fname_middle = "mmproj-"
  122. has_text_encoder = False
  123. has_llava_projector = True
  124. elif args.vision_only:
  125. fname_middle = "vision-"
  126. has_text_encoder = False
  127. else:
  128. fname_middle = ""
  129. output_dir = args.output_dir if args.output_dir is not None else dir_model
  130. os.makedirs(output_dir, exist_ok=True)
  131. output_prefix = os.path.basename(output_dir).replace("ggml_", "")
  132. fname_out = os.path.join(output_dir, f"{fname_middle}model-{ftype_str[ftype]}.gguf")
  133. fout = GGUFWriter(path=fname_out, arch="clip")
  134. fout.add_bool("clip.has_text_encoder", has_text_encoder)
  135. fout.add_bool("clip.has_vision_encoder", has_vision_encoder)
  136. fout.add_bool("clip.has_llava_projector", has_llava_projector)
  137. fout.add_file_type(ftype)
  138. model_name = config["_name_or_path"] if "_name_or_path" in config else os.path.basename(dir_model)
  139. fout.add_name(model_name)
  140. if args.text_only:
  141. fout.add_description("text-only CLIP model")
  142. elif args.vision_only and not has_llava_projector:
  143. fout.add_description("vision-only CLIP model")
  144. elif has_llava_projector:
  145. fout.add_description("image encoder for LLaVA")
  146. else:
  147. fout.add_description("two-tower CLIP model")
  148. if has_text_encoder:
  149. # text_model hparams
  150. fout.add_uint32(k(KEY_CONTEXT_LENGTH, TEXT), t_hparams["max_position_embeddings"])
  151. fout.add_uint32(k(KEY_EMBEDDING_LENGTH, TEXT), t_hparams["hidden_size"])
  152. fout.add_uint32(k(KEY_FEED_FORWARD_LENGTH, TEXT), t_hparams["intermediate_size"])
  153. fout.add_uint32("clip.text.projection_dim", t_hparams.get("projection_dim", config["projection_dim"]))
  154. fout.add_uint32(k(KEY_ATTENTION_HEAD_COUNT, TEXT), t_hparams["num_attention_heads"])
  155. fout.add_float32(k(KEY_ATTENTION_LAYERNORM_EPS, TEXT), t_hparams["layer_norm_eps"])
  156. fout.add_uint32(k(KEY_BLOCK_COUNT, TEXT), t_hparams["num_hidden_layers"])
  157. fout.add_token_list(tokens)
  158. if has_vision_encoder:
  159. # vision_model hparams
  160. fout.add_uint32("clip.vision.image_size", v_hparams["image_size"])
  161. fout.add_uint32("clip.vision.patch_size", v_hparams["patch_size"])
  162. fout.add_uint32(k(KEY_EMBEDDING_LENGTH, VISION), v_hparams["hidden_size"])
  163. fout.add_uint32(k(KEY_FEED_FORWARD_LENGTH, VISION), v_hparams["intermediate_size"])
  164. fout.add_uint32("clip.vision.projection_dim", v_hparams.get("projection_dim", config["projection_dim"]))
  165. fout.add_uint32(k(KEY_ATTENTION_HEAD_COUNT, VISION), v_hparams["num_attention_heads"])
  166. fout.add_float32(k(KEY_ATTENTION_LAYERNORM_EPS, VISION), v_hparams["layer_norm_eps"])
  167. block_count = v_hparams["num_hidden_layers"] - 1 if has_llava_projector else v_hparams["num_hidden_layers"]
  168. fout.add_uint32(k(KEY_BLOCK_COUNT, VISION), block_count)
  169. if processor is not None:
  170. image_mean = processor.image_processor.image_mean if args.image_mean is None or args.image_mean == default_image_mean else args.image_mean
  171. image_std = processor.image_processor.image_std if args.image_std is None or args.image_std == default_image_std else args.image_std
  172. else:
  173. image_mean = args.image_mean if args.image_mean is not None else default_image_mean
  174. image_std = args.image_std if args.image_std is not None else default_image_std
  175. fout.add_array("clip.vision.image_mean", image_mean)
  176. fout.add_array("clip.vision.image_std", image_std)
  177. use_gelu = v_hparams["hidden_act"] == "gelu"
  178. fout.add_bool("clip.use_gelu", use_gelu)
  179. if has_llava_projector:
  180. model.vision_model.encoder.layers.pop(-1)
  181. projector = torch.load(args.llava_projector)
  182. for name, data in projector.items():
  183. name = get_tensor_name(name)
  184. if data.ndim == 2:
  185. data = data.squeeze().numpy().astype(np.float16)
  186. else:
  187. data = data.squeeze().numpy().astype(np.float32)
  188. fout.add_tensor(name, data)
  189. print("Projector tensors added\n")
  190. state_dict = model.state_dict()
  191. for name, data in state_dict.items():
  192. if should_skip_tensor(name, has_text_encoder, has_vision_encoder, has_llava_projector):
  193. # we don't need this
  194. print(f"skipping parameter: {name}")
  195. continue
  196. name = get_tensor_name(name)
  197. data = data.squeeze().numpy()
  198. n_dims = len(data.shape)
  199. # ftype == 0 -> float32, ftype == 1 -> float16
  200. ftype_cur = 0
  201. if n_dims == 4:
  202. print(f"tensor {name} is always saved in f16")
  203. data = data.astype(np.float16)
  204. ftype_cur = 1
  205. elif ftype == 1:
  206. if name[-7:] == ".weight" and n_dims == 2:
  207. print(" Converting to float16")
  208. data = data.astype(np.float16)
  209. ftype_cur = 1
  210. else:
  211. print(" Converting to float32")
  212. data = data.astype(np.float32)
  213. ftype_cur = 0
  214. else:
  215. if data.dtype != np.float32:
  216. print(" Converting to float32")
  217. data = data.astype(np.float32)
  218. ftype_cur = 0
  219. print(f"{name} - {ftype_str[ftype_cur]} - shape = {data.shape}")
  220. fout.add_tensor(name, data)
  221. fout.write_header_to_file()
  222. fout.write_kv_data_to_file()
  223. fout.write_tensors_to_file()
  224. fout.close()
  225. print("Done. Output file: " + fname_out)