minicpmv-convert-image-encoder-to-gguf.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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.models.idefics2.modeling_idefics2 import Idefics2VisionTransformer, Idefics2VisionConfig
  9. TEXT = "clip.text"
  10. VISION = "clip.vision"
  11. def add_key_str(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_minicpmv: 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_minicpmv and name in ["visual_projection.weight"]:
  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("--minicpmv-projector", help="Path to minicpmv.projector file. If specified, save an image encoder for MiniCPM-V 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. # possible data types
  97. # ftype == 0 -> float32
  98. # ftype == 1 -> float16
  99. #
  100. # map from ftype to string
  101. ftype_str = ["f32", "f16"]
  102. ftype = 1
  103. if args.use_f32:
  104. ftype = 0
  105. # if args.clip_model_is_vision or args.clip_model_is_openclip:
  106. # model = CLIPVisionModel.from_pretrained(dir_model)
  107. # processor = None
  108. # else:
  109. # model = CLIPModel.from_pretrained(dir_model)
  110. # processor = CLIPProcessor.from_pretrained(dir_model)
  111. default_vision_config = {
  112. "hidden_size": 1152,
  113. "image_size": 980,
  114. "intermediate_size": 4304,
  115. "model_type": "idefics2",
  116. "num_attention_heads": 16,
  117. "num_hidden_layers": 27,
  118. "patch_size": 14,
  119. }
  120. vision_config = Idefics2VisionConfig(**default_vision_config)
  121. model = Idefics2VisionTransformer(vision_config)
  122. processor = None
  123. # if model.attn_pool is not None:
  124. # model.attn_pool = torch.nn.Identity()
  125. # model.blocks = model.blocks[:-1]
  126. model.load_state_dict(torch.load(os.path.join(dir_model, "minicpmv.clip")))
  127. fname_middle = None
  128. has_text_encoder = True
  129. has_vision_encoder = True
  130. has_minicpmv_projector = False
  131. if args.text_only:
  132. fname_middle = "text-"
  133. has_vision_encoder = False
  134. elif args.minicpmv_projector is not None:
  135. fname_middle = "mmproj-"
  136. has_text_encoder = False
  137. has_minicpmv_projector = True
  138. elif args.vision_only:
  139. fname_middle = "vision-"
  140. has_text_encoder = False
  141. else:
  142. fname_middle = ""
  143. output_dir = args.output_dir if args.output_dir is not None else dir_model
  144. os.makedirs(output_dir, exist_ok=True)
  145. output_prefix = os.path.basename(output_dir).replace("ggml_", "")
  146. fname_out = os.path.join(output_dir, f"{fname_middle}model-{ftype_str[ftype]}.gguf")
  147. fout = GGUFWriter(path=fname_out, arch="clip")
  148. fout.add_bool("clip.has_text_encoder", has_text_encoder)
  149. fout.add_bool("clip.has_vision_encoder", has_vision_encoder)
  150. fout.add_bool("clip.has_minicpmv_projector", has_minicpmv_projector)
  151. fout.add_file_type(ftype)
  152. if args.text_only:
  153. fout.add_description("text-only CLIP model")
  154. elif args.vision_only and not has_minicpmv_projector:
  155. fout.add_description("vision-only CLIP model")
  156. elif has_minicpmv_projector:
  157. fout.add_description("image encoder for MiniCPM-V")
  158. # add projector type
  159. fout.add_string("clip.projector_type", "resampler")
  160. else:
  161. fout.add_description("two-tower CLIP model")
  162. if has_vision_encoder:
  163. # vision_model hparams
  164. fout.add_uint32("clip.vision.image_size", 448)
  165. fout.add_uint32("clip.vision.patch_size", 14)
  166. fout.add_uint32(add_key_str(KEY_EMBEDDING_LENGTH, VISION), 1152)
  167. fout.add_uint32(add_key_str(KEY_FEED_FORWARD_LENGTH, VISION), 4304)
  168. fout.add_uint32("clip.vision.projection_dim", 0)
  169. fout.add_uint32(add_key_str(KEY_ATTENTION_HEAD_COUNT, VISION), 16)
  170. fout.add_float32(add_key_str(KEY_ATTENTION_LAYERNORM_EPS, VISION), 1e-6)
  171. block_count = 26
  172. fout.add_uint32(add_key_str(KEY_BLOCK_COUNT, VISION), block_count)
  173. if processor is not None:
  174. image_mean = processor.image_processor.image_mean if args.image_mean is None or args.image_mean == default_image_mean else args.image_mean
  175. image_std = processor.image_processor.image_std if args.image_std is None or args.image_std == default_image_std else args.image_std
  176. else:
  177. image_mean = args.image_mean if args.image_mean is not None else default_image_mean
  178. image_std = args.image_std if args.image_std is not None else default_image_std
  179. fout.add_array("clip.vision.image_mean", image_mean)
  180. fout.add_array("clip.vision.image_std", image_std)
  181. use_gelu = True
  182. fout.add_bool("clip.use_gelu", use_gelu)
  183. def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
  184. """
  185. embed_dim: output dimension for each position
  186. pos: a list of positions to be encoded: size (M,)
  187. out: (M, D)
  188. """
  189. assert embed_dim % 2 == 0
  190. omega = np.arange(embed_dim // 2, dtype=np.float32)
  191. omega /= embed_dim / 2.
  192. omega = 1. / 10000 ** omega # (D/2,)
  193. pos = pos.reshape(-1) # (M,)
  194. out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
  195. emb_sin = np.sin(out) # (M, D/2)
  196. emb_cos = np.cos(out) # (M, D/2)
  197. emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
  198. return emb
  199. def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
  200. assert embed_dim % 2 == 0
  201. # use half of dimensions to encode grid_h
  202. emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
  203. emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
  204. emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
  205. return emb
  206. # https://github.com/facebookresearch/mae/blob/efb2a8062c206524e35e47d04501ed4f544c0ae8/util/pos_embed.py#L20
  207. def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
  208. """
  209. grid_size: int of the grid height and width
  210. return:
  211. pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
  212. """
  213. if isinstance(grid_size, int):
  214. grid_h_size, grid_w_size = grid_size, grid_size
  215. else:
  216. grid_h_size, grid_w_size = grid_size[0], grid_size[1]
  217. grid_h = np.arange(grid_h_size, dtype=np.float32)
  218. grid_w = np.arange(grid_w_size, dtype=np.float32)
  219. grid = np.meshgrid(grid_w, grid_h) # here w goes first
  220. grid = np.stack(grid, axis=0)
  221. grid = grid.reshape([2, 1, grid_h_size, grid_w_size])
  222. pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
  223. if cls_token:
  224. pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
  225. return pos_embed
  226. def _replace_name_resampler(s, v):
  227. if re.match("resampler.pos_embed", s):
  228. return {
  229. s: v,
  230. re.sub("pos_embed", "pos_embed_k", s): torch.from_numpy(get_2d_sincos_pos_embed(4096, (70, 70))),
  231. }
  232. if re.match("resampler.proj", s):
  233. return {
  234. re.sub("proj", "pos_embed_k", s): torch.from_numpy(get_2d_sincos_pos_embed(4096, (70, 70))),
  235. re.sub("proj", "proj.weight", s): v.transpose(-1, -2).contiguous(),
  236. }
  237. if re.match("resampler.attn.in_proj_.*", s):
  238. return {
  239. re.sub("attn.in_proj_", "attn.q.", s): v.chunk(3, dim=0)[0],
  240. re.sub("attn.in_proj_", "attn.k.", s): v.chunk(3, dim=0)[1],
  241. re.sub("attn.in_proj_", "attn.v.", s): v.chunk(3, dim=0)[2],
  242. }
  243. return {s: v}
  244. if has_minicpmv_projector:
  245. projector = torch.load(args.minicpmv_projector)
  246. new_state_dict = {}
  247. for k, v in projector.items():
  248. kvs = _replace_name_resampler(k, v)
  249. for nk, nv in kvs.items():
  250. new_state_dict[nk] = nv
  251. projector = new_state_dict
  252. ftype_cur = 0
  253. for name, data in projector.items():
  254. name = get_tensor_name(name)
  255. data = data.squeeze().numpy()
  256. n_dims = len(data.shape)
  257. if ftype == 1:
  258. if name[-7:] == ".weight" and n_dims == 2:
  259. print(" Converting to float16")
  260. data = data.astype(np.float16)
  261. ftype_cur = 1
  262. else:
  263. print(" Converting to float32")
  264. data = data.astype(np.float32)
  265. ftype_cur = 0
  266. else:
  267. if data.dtype != np.float32:
  268. print(" Converting to float32")
  269. data = data.astype(np.float32)
  270. ftype_cur = 0
  271. fout.add_tensor(name, data)
  272. print(f"{name} - {ftype_str[ftype_cur]} - shape = {data.shape}")
  273. print("Projector tensors added\n")
  274. def _replace_name(s, v):
  275. s = "vision_model." + s
  276. if re.match("vision_model.embeddings.position_embedding", s):
  277. v = v.unsqueeze(0)
  278. return {s: v}
  279. return {s: v}
  280. state_dict = model.state_dict()
  281. new_state_dict = {}
  282. for k, v in state_dict.items():
  283. kvs = _replace_name(k, v)
  284. for nk, nv in kvs.items():
  285. new_state_dict[nk] = nv
  286. state_dict = new_state_dict
  287. for name, data in state_dict.items():
  288. if should_skip_tensor(name, has_text_encoder, has_vision_encoder, has_minicpmv_projector):
  289. # we don't need this
  290. print(f"skipping parameter: {name}")
  291. continue
  292. name = get_tensor_name(name)
  293. data = data.squeeze().numpy()
  294. n_dims = len(data.shape)
  295. # ftype == 0 -> float32, ftype == 1 -> float16
  296. ftype_cur = 0
  297. if n_dims == 4:
  298. print(f"tensor {name} is always saved in f16")
  299. data = data.astype(np.float16)
  300. ftype_cur = 1
  301. elif ftype == 1:
  302. if name[-7:] == ".weight" and n_dims == 2:
  303. print(" Converting to float16")
  304. data = data.astype(np.float16)
  305. ftype_cur = 1
  306. else:
  307. print(" Converting to float32")
  308. data = data.astype(np.float32)
  309. ftype_cur = 0
  310. else:
  311. if data.dtype != np.float32:
  312. print(" Converting to float32")
  313. data = data.astype(np.float32)
  314. ftype_cur = 0
  315. print(f"{name} - {ftype_str[ftype_cur]} - shape = {data.shape}")
  316. fout.add_tensor(name, data)
  317. fout.write_header_to_file()
  318. fout.write_kv_data_to_file()
  319. fout.write_tensors_to_file()
  320. fout.close()
  321. print("Done. Output file: " + fname_out)