glmedge-convert-image-encoder-to-gguf.py 11 KB

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