convert-falcon-hf-to-gguf.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. #!/usr/bin/env python3
  2. # HF falcon--> gguf conversion
  3. import gguf
  4. import os
  5. import sys
  6. import struct
  7. import json
  8. import numpy as np
  9. import torch
  10. from typing import Any, List
  11. from pathlib import Path
  12. from transformers import AutoTokenizer
  13. def bytes_to_unicode():
  14. # ref: https://github.com/openai/gpt-2/blob/master/src/encoder.py
  15. """
  16. Returns list of utf-8 byte and a corresponding list of unicode strings.
  17. The reversible bpe codes work on unicode strings.
  18. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
  19. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
  20. This is a significant percentage of your normal, say, 32K bpe vocab.
  21. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
  22. And avoids mapping to whitespace/control characters the bpe code barfs on.
  23. """
  24. bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
  25. cs = bs[:]
  26. n = 0
  27. for b in range(2**8):
  28. if b not in bs:
  29. bs.append(b)
  30. cs.append(2**8+n)
  31. n += 1
  32. cs = [chr(n) for n in cs]
  33. return dict(zip(bs, cs))
  34. def count_model_parts(dir_model: str) -> int:
  35. num_parts = 0
  36. for filename in os.listdir(dir_model):
  37. if filename.startswith("pytorch_model-"):
  38. num_parts += 1
  39. if num_parts > 0:
  40. print("gguf: found " + str(num_parts) + " model parts")
  41. return num_parts
  42. if len(sys.argv) < 3:
  43. print("Usage: convert-h5-to-ggml.py dir-model ftype\n")
  44. print(" ftype == 0 -> float32")
  45. print(" ftype == 1 -> float16")
  46. sys.exit(1)
  47. # output in the same directory as the model
  48. dir_model = sys.argv[1]
  49. last_dir = os.path.basename(os.path.normpath(dir_model))
  50. # possible tensor data types
  51. # ftype == 0 -> float32
  52. # ftype == 1 -> float16
  53. # map from ftype to string
  54. ftype_str = ["f32", "f16"]
  55. ftype = 1
  56. if len(sys.argv) > 2:
  57. ftype = int(sys.argv[2])
  58. if ftype < 0 or ftype > 1:
  59. print("Invalid ftype: " + str(ftype))
  60. sys.exit(1)
  61. fname_out = sys.argv[1] + "/ggml-model-" + ftype_str[ftype] + ".gguf"
  62. print("gguf: loading model "+last_dir)
  63. with open(dir_model + "/config.json", "r", encoding="utf-8") as f:
  64. hparams = json.load(f)
  65. if hparams["architectures"][0] != "RWForCausalLM":
  66. print("Model architecture not supported: " + hparams["architectures"][0])
  67. sys.exit()
  68. # get number of model parts
  69. num_parts = count_model_parts(dir_model)
  70. ARCH=gguf.MODEL_ARCH.FALCON
  71. gguf_writer = gguf.GGUFWriter(fname_out, gguf.MODEL_ARCH_NAMES[ARCH])
  72. print("gguf: get model metadata")
  73. block_count = hparams["n_layer"]
  74. gguf_writer.add_name("Falcon")
  75. gguf_writer.add_context_length(2048) # not in config.json
  76. gguf_writer.add_tensor_data_layout("jploski") # qkv tensor transform
  77. gguf_writer.add_embedding_length(hparams["hidden_size"])
  78. gguf_writer.add_feed_forward_length(4 * hparams["hidden_size"])
  79. gguf_writer.add_block_count(block_count)
  80. gguf_writer.add_head_count(hparams["n_head"])
  81. if "n_head_kv" in hparams:
  82. gguf_writer.add_head_count_kv(hparams["n_head_kv"])
  83. else:
  84. gguf_writer.add_head_count_kv(1)
  85. gguf_writer.add_layer_norm_eps(hparams["layer_norm_epsilon"])
  86. gguf_writer.add_file_type(ftype)
  87. # TOKENIZATION
  88. print("gguf: get tokenizer metadata")
  89. tokens: List[str] = []
  90. scores: List[float] = []
  91. toktypes: List[int] = []
  92. merges: List[str] = []
  93. if Path(dir_model + "/tokenizer.json").is_file():
  94. # gpt2 tokenizer
  95. gguf_writer.add_tokenizer_model("gpt2")
  96. print("gguf: get gpt2 tokenizer merges")
  97. with open(dir_model + "/tokenizer.json", "r", encoding="utf-8") as f:
  98. tokenizer_json = json.load(f)
  99. merges = tokenizer_json["model"]["merges"]
  100. gguf_writer.add_token_merges(merges)
  101. print("gguf: get gpt2 tokenizer vocab")
  102. vocab_size = len(tokenizer_json["model"]["vocab"])
  103. # ref: https://github.com/cmp-nct/ggllm.cpp/blob/master/falcon_convert.py
  104. tokenizer = AutoTokenizer.from_pretrained(dir_model)
  105. reverse_vocab = {id: encoded_tok for encoded_tok, id in tokenizer.vocab.items()}
  106. byte_encoder = bytes_to_unicode()
  107. byte_decoder = {v: k for k, v in byte_encoder.items()}
  108. for i in range(vocab_size):
  109. if i in reverse_vocab:
  110. try:
  111. text = bytearray([byte_decoder[c] for c in reverse_vocab[i]])
  112. except KeyError:
  113. text = bytearray()
  114. for c in reverse_vocab[i]:
  115. if ord(c) < 256: # single byte character
  116. text.append(byte_decoder[ord(c)])
  117. else: # multibyte special token character
  118. text.extend(c.encode('utf-8'))
  119. else:
  120. print(f"Key {i} not in tokenizer vocabulary. Padding with an arbitrary token.")
  121. pad_token = f"[PAD{i}]".encode("utf8")
  122. text = bytearray(pad_token)
  123. tokens.append(text)
  124. scores.append(0.0) # dymmy
  125. toktypes.append(gguf.TokenType.NORMAL) # dummy
  126. gguf_writer.add_token_list(tokens)
  127. gguf_writer.add_token_scores(scores)
  128. gguf_writer.add_token_types(toktypes)
  129. print("gguf: get special token ids")
  130. # Look for special tokens in config.json
  131. if "bos_token_id" in hparams and hparams["bos_token_id"] != None:
  132. gguf_writer.add_bos_token_id(hparams["bos_token_id"])
  133. if "eos_token_id" in hparams and hparams["eos_token_id"] != None:
  134. gguf_writer.add_eos_token_id(hparams["eos_token_id"])
  135. if "unk_token_id" in hparams and hparams["unk_token_id"] != None:
  136. gguf_writer.add_unk_token_id(hparams["unk_token_id"])
  137. if "sep_token_id" in hparams and hparams["sep_token_id"] != None:
  138. gguf_writer.add_sep_token_id(hparams["sep_token_id"])
  139. if "pad_token_id" in hparams and hparams["pad_token_id"] != None:
  140. gguf_writer.add_pad_token_id(hparams["pad_token_id"])
  141. # TENSORS
  142. tensor_map = gguf.get_tensor_name_map(ARCH,block_count)
  143. # params for qkv transform
  144. n_head = hparams["n_head"]
  145. n_head_kv = hparams["n_head_kv"] if "n_head_kv" in hparams else 1
  146. head_dim = hparams["hidden_size"] // n_head
  147. # tensor info
  148. print("gguf: get tensor metadata")
  149. if num_parts == 0:
  150. part_names = ("pytorch_model.bin",)
  151. else:
  152. part_names = (
  153. f"pytorch_model-{n:05}-of-{num_parts:05}.bin" for n in range(1, num_parts + 1)
  154. )
  155. for part_name in part_names:
  156. print("gguf: loading model part '" + part_name + "'")
  157. model_part = torch.load(f"{dir_model}/{part_name}", map_location="cpu")
  158. for name in model_part.keys():
  159. data = model_part[name]
  160. old_dtype = data.dtype
  161. # convert any unsupported data types to float32
  162. if data.dtype != torch.float16 and data.dtype != torch.float32:
  163. data = data.to(torch.float32)
  164. # QKV tensor transform
  165. # The original query_key_value tensor contains n_head_kv "kv groups",
  166. # each consisting of n_head/n_head_kv query weights followed by one key
  167. # and one value weight (shared by all query heads in the kv group).
  168. # This layout makes it a big pain to work with in GGML.
  169. # So we rearrange them here,, so that we have n_head query weights
  170. # followed by n_head_kv key weights followed by n_head_kv value weights,
  171. # in contiguous fashion.
  172. # ref: https://github.com/jploski/ggml/blob/falcon40b/examples/falcon/convert-hf-to-ggml.py
  173. if "query_key_value" in name:
  174. qkv = data.view(n_head_kv, n_head // n_head_kv + 2, head_dim, head_dim * n_head)
  175. q = qkv[:, :-2 ].reshape(n_head * head_dim, head_dim * n_head)
  176. k = qkv[:, [-2]].reshape(n_head_kv * head_dim, head_dim * n_head)
  177. v = qkv[:, [-1]].reshape(n_head_kv * head_dim, head_dim * n_head)
  178. data = torch.cat((q,k,v)).reshape_as(data)
  179. data = data.squeeze().numpy()
  180. # map tensor names
  181. if name.endswith(".weight") and name[:-7] in tensor_map:
  182. name = tensor_map[name[:-7]] + ".weight"
  183. elif name.endswith(".bias") and name[:-5] in tensor_map:
  184. name = tensor_map[name[:-5]] + ".bias"
  185. else:
  186. print("Can not map tensor '" + name + "'")
  187. sys.exit()
  188. n_dims = len(data.shape)
  189. data_dtype = data.dtype
  190. # if f32 desired, convert any float16 to float32
  191. if ftype == 0 and data_dtype == np.float16:
  192. data = data.astype(np.float32)
  193. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  194. if ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  195. data = data.astype(np.float32)
  196. # if f16 desired, convert any float32 2-dim weight tensors to float16
  197. if ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  198. data = data.astype(np.float16)
  199. print(name + ", n_dims = " + str(n_dims) + ", " + str(old_dtype) + " --> " + str(data.dtype))
  200. gguf_writer.add_tensor(name, data)
  201. print("gguf: write header")
  202. gguf_writer.write_header_to_file()
  203. print("gguf: write metadata")
  204. gguf_writer.write_kv_data_to_file()
  205. print("gguf: write tensors")
  206. gguf_writer.write_tensors_to_file()
  207. gguf_writer.close()
  208. print("gguf: model successfully exported to '" + fname_out + "'")
  209. print("")