convert-refact-hf-to-gguf.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. #!/usr/bin/env python3
  2. # HF refact--> gguf conversion
  3. from __future__ import annotations
  4. import argparse
  5. import json
  6. import os
  7. import sys
  8. from pathlib import Path
  9. import numpy as np
  10. import torch
  11. from transformers import AutoTokenizer # type: ignore[import]
  12. if "NO_LOCAL_GGUF" not in os.environ:
  13. sys.path.insert(1, str(Path(__file__).parent / "gguf-py" / "gguf"))
  14. import gguf
  15. def bytes_to_unicode():
  16. # ref: https://github.com/openai/gpt-2/blob/master/src/encoder.py
  17. """
  18. Returns list of utf-8 byte and a corresponding list of unicode strings.
  19. The reversible bpe codes work on unicode strings.
  20. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
  21. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
  22. This is a significant percentage of your normal, say, 32K bpe vocab.
  23. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
  24. And avoids mapping to whitespace/control characters the bpe code barfs on.
  25. """
  26. bs = (
  27. list(range(ord("!"), ord("~") + 1))
  28. + list(range(ord("¡"), ord("¬") + 1))
  29. + list(range(ord("®"), ord("ÿ") + 1))
  30. )
  31. cs = bs[:]
  32. n = 0
  33. for b in range(2**8):
  34. if b not in bs:
  35. bs.append(b)
  36. cs.append(2**8 + n)
  37. n += 1
  38. return dict(zip(bs, (chr(n) for n in cs)))
  39. def count_model_parts(dir_model: Path) -> int:
  40. num_parts = 0
  41. for filename in os.listdir(dir_model):
  42. if filename.startswith("pytorch_model-"):
  43. num_parts += 1
  44. if num_parts > 0:
  45. print("gguf: found " + str(num_parts) + " model parts")
  46. return num_parts
  47. def parse_args() -> argparse.Namespace:
  48. parser = argparse.ArgumentParser(
  49. description="Convert a Refact model to a GGML compatible file"
  50. )
  51. parser.add_argument(
  52. "--vocab-only",
  53. action="store_true",
  54. help="extract only the vocab",
  55. )
  56. parser.add_argument(
  57. "--outfile",
  58. type=Path,
  59. help="path to write to; default: based on input",
  60. )
  61. parser.add_argument(
  62. "model",
  63. type=Path,
  64. help="directory containing model file, or model file itself (*.bin)",
  65. )
  66. parser.add_argument(
  67. "ftype",
  68. type=int,
  69. choices=[0, 1],
  70. default=1,
  71. nargs="?",
  72. help="output format - use 0 for float32, 1 for float16",
  73. )
  74. return parser.parse_args()
  75. args = parse_args()
  76. dir_model = args.model
  77. ftype = args.ftype
  78. if not dir_model.is_dir():
  79. print(f"Error: {args.model} is not a directory", file=sys.stderr)
  80. sys.exit(1)
  81. # possible tensor data types
  82. # ftype == 0 -> float32
  83. # ftype == 1 -> float16
  84. # map from ftype to string
  85. ftype_str = ["f32", "f16"]
  86. if args.outfile is not None:
  87. fname_out = args.outfile
  88. else:
  89. # output in the same directory as the model by default
  90. fname_out = dir_model / f"ggml-model-{ftype_str[ftype]}.gguf"
  91. print("gguf: loading model " + dir_model.name)
  92. with open(dir_model / "config.json", "r", encoding="utf-8") as f:
  93. hparams = json.load(f)
  94. if hparams["architectures"][0] != "GPTRefactForCausalLM":
  95. print("Model architecture not supported: " + hparams["architectures"][0])
  96. sys.exit(1)
  97. # get number of model parts
  98. num_parts = count_model_parts(dir_model)
  99. ARCH = gguf.MODEL_ARCH.REFACT
  100. gguf_writer = gguf.GGUFWriter(fname_out, gguf.MODEL_ARCH_NAMES[ARCH])
  101. print("gguf: get model metadata")
  102. # Get refact feed forward dimension
  103. hidden_dim = hparams["n_embd"]
  104. inner_dim = 4 * hidden_dim
  105. hidden_dim = int(2 * inner_dim / 3)
  106. multiple_of = 256
  107. ff_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
  108. block_count = hparams["n_layer"]
  109. gguf_writer.add_name("Refact")
  110. # refact uses Alibi. So this is from config.json which might be used by training.
  111. gguf_writer.add_context_length(hparams["n_positions"])
  112. gguf_writer.add_embedding_length(hparams["n_embd"])
  113. gguf_writer.add_feed_forward_length(ff_dim)
  114. gguf_writer.add_block_count(block_count)
  115. gguf_writer.add_head_count(hparams["n_head"])
  116. gguf_writer.add_head_count_kv(1)
  117. gguf_writer.add_layer_norm_rms_eps(hparams["layer_norm_epsilon"])
  118. gguf_writer.add_file_type(ftype)
  119. # TOKENIZATION
  120. print("gguf: get tokenizer metadata")
  121. tokens: list[bytearray] = []
  122. scores: list[float] = []
  123. toktypes: list[int] = []
  124. tokenizer_json_file = dir_model / "tokenizer.json"
  125. if not tokenizer_json_file.is_file():
  126. print(f"Error: Missing {tokenizer_json_file}", file=sys.stderr)
  127. sys.exit(1)
  128. # gpt2 tokenizer
  129. gguf_writer.add_tokenizer_model("gpt2")
  130. with open(tokenizer_json_file, "r", encoding="utf-8") as f:
  131. tokenizer_json = json.load(f)
  132. print("gguf: get gpt2 tokenizer vocab")
  133. # The number of tokens in tokenizer.json can differ from the expected vocab size.
  134. # This causes downstream issues with mismatched tensor sizes when running the inference
  135. vocab_size = (
  136. hparams["vocab_size"]
  137. if "vocab_size" in hparams
  138. else len(tokenizer_json["model"]["vocab"])
  139. )
  140. tokenizer = AutoTokenizer.from_pretrained(dir_model, trust_remote_code=True)
  141. reverse_vocab = {id: encoded_tok for encoded_tok, id in tokenizer.vocab.items()}
  142. byte_encoder = bytes_to_unicode()
  143. byte_decoder = {v: k for k, v in byte_encoder.items()}
  144. for i in range(vocab_size):
  145. if i in reverse_vocab:
  146. text = reverse_vocab[i]
  147. try:
  148. text = bytearray([byte_decoder[c] for c in reverse_vocab[i]])
  149. except KeyError:
  150. text = bytearray()
  151. for c in reverse_vocab[i]:
  152. if ord(c) < 256: # single byte character
  153. text.append(byte_decoder[ord(c)])
  154. else: # multibyte special token character
  155. text.extend(c.encode("utf-8"))
  156. else:
  157. print(f"Key {i} not in tokenizer vocabulary. Padding with an arbitrary token.")
  158. pad_token = f"[PAD{i}]".encode("utf8")
  159. text = bytearray(pad_token)
  160. tokens.append(text)
  161. scores.append(0.0) # dymmy
  162. toktypes.append(gguf.TokenType.NORMAL) # dummy
  163. gguf_writer.add_token_list(tokens)
  164. gguf_writer.add_token_scores(scores)
  165. gguf_writer.add_token_types(toktypes)
  166. special_vocab = gguf.SpecialVocab(dir_model, load_merges=True)
  167. special_vocab.add_to_gguf(gguf_writer)
  168. # TENSORS
  169. tensor_map = gguf.get_tensor_name_map(ARCH, block_count)
  170. # params for qkv transform
  171. n_head = hparams["n_head"]
  172. n_head_kv = 1
  173. head_dim = hparams["n_embd"] // n_head
  174. # tensor info
  175. print("gguf: get tensor metadata")
  176. if num_parts == 0:
  177. part_names = iter(("pytorch_model.bin",))
  178. else:
  179. part_names = (
  180. f"pytorch_model-{n:05}-of-{num_parts:05}.bin" for n in range(1, num_parts + 1)
  181. )
  182. for part_name in part_names:
  183. if args.vocab_only:
  184. break
  185. print("gguf: loading model part '" + part_name + "'")
  186. model_part = torch.load(dir_model / part_name, map_location="cpu")
  187. for i in range(block_count):
  188. if f"transformer.h.{i}.attn.kv.weight" in model_part:
  189. data = model_part[f"transformer.h.{i}.attn.kv.weight"]
  190. model_part[f"model.layers.{i}.self_attn.k_proj.weight"] = data[
  191. : n_head_kv * head_dim
  192. ]
  193. model_part[f"model.layers.{i}.self_attn.v_proj.weight"] = data[
  194. n_head_kv * head_dim :
  195. ]
  196. del model_part[f"transformer.h.{i}.attn.kv.weight"]
  197. if f"transformer.h.{i}.attn.q.weight" in model_part:
  198. model_part[f"model.layers.{i}.self_attn.q_proj.weight"] = model_part[
  199. f"transformer.h.{i}.attn.q.weight"
  200. ]
  201. del model_part[f"transformer.h.{i}.attn.q.weight"]
  202. if f"transformer.h.{i}.mlp.gate_up_proj.weight" in model_part:
  203. data = model_part[f"transformer.h.{i}.mlp.gate_up_proj.weight"]
  204. model_part[f"model.layers.{i}.mlp.gate_proj.weight"] = data[:ff_dim]
  205. model_part[f"model.layers.{i}.mlp.up_proj.weight"] = data[ff_dim:]
  206. del model_part[f"transformer.h.{i}.mlp.gate_up_proj.weight"]
  207. for name in model_part.keys():
  208. data = model_part[name]
  209. old_dtype = data.dtype
  210. # convert any unsupported data types to float32
  211. if data.dtype != torch.float16 and data.dtype != torch.float32:
  212. data = data.to(torch.float32)
  213. data = data.squeeze().numpy()
  214. # map tensor names
  215. new_name = tensor_map.get_name(name, try_suffixes=(".weight",))
  216. if new_name is None:
  217. print("Can not map tensor '" + name + "'")
  218. sys.exit()
  219. n_dims = len(data.shape)
  220. data_dtype = data.dtype
  221. # if f32 desired, convert any float16 to float32
  222. if ftype == 0 and data_dtype == np.float16:
  223. data = data.astype(np.float32)
  224. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  225. if ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  226. data = data.astype(np.float32)
  227. # if f16 desired, convert any float32 2-dim weight tensors to float16
  228. if (
  229. ftype == 1
  230. and data_dtype == np.float32
  231. and name.endswith(".weight")
  232. and n_dims == 2
  233. ):
  234. data = data.astype(np.float16)
  235. print(
  236. new_name
  237. + ", n_dims = "
  238. + str(n_dims)
  239. + ", "
  240. + str(old_dtype)
  241. + " --> "
  242. + str(data.dtype)
  243. )
  244. gguf_writer.add_tensor(new_name, data)
  245. print("gguf: write header")
  246. gguf_writer.write_header_to_file()
  247. print("gguf: write metadata")
  248. gguf_writer.write_kv_data_to_file()
  249. if not args.vocab_only:
  250. print("gguf: write tensors")
  251. gguf_writer.write_tensors_to_file()
  252. gguf_writer.close()
  253. print(f"gguf: model successfully exported to '{fname_out}'")
  254. print("")