convert_image_encoder_to_gguf.py 14 KB

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