convert-hf-to-gguf-update.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. #!/usr/bin/env python3
  2. # This script downloads the tokenizer models of the specified models from Huggingface and
  3. # generates the get_vocab_base_pre() function for convert-hf-to-gguf.py
  4. #
  5. # This is necessary in order to analyze the type of pre-tokenizer used by the model and
  6. # provide the necessary information to llama.cpp via the GGUF header in order to implement
  7. # the same pre-tokenizer.
  8. #
  9. # ref: https://github.com/ggerganov/llama.cpp/pull/6920
  10. #
  11. # Instructions:
  12. #
  13. # - Add a new model to the "models" list
  14. # - Run the script with your huggingface token:
  15. #
  16. # python3 convert-hf-to-gguf-update.py <huggingface_token>
  17. #
  18. # - Copy-paste the generated get_vocab_base_pre() function into convert-hf-to-gguf.py
  19. # - Update llama.cpp with the new pre-tokenizer if necessary
  20. #
  21. # TODO: generate tokenizer tests for llama.cpp
  22. # TODO: automate the update of convert-hf-to-gguf.py
  23. #
  24. import logging
  25. import os
  26. import requests
  27. import sys
  28. import json
  29. from hashlib import sha256
  30. from enum import IntEnum, auto
  31. from transformers import AutoTokenizer
  32. logging.basicConfig(level=logging.DEBUG)
  33. logger = logging.getLogger("convert-hf-to-gguf-update")
  34. class TOKENIZER_TYPE(IntEnum):
  35. SPM = auto()
  36. BPE = auto()
  37. WPM = auto()
  38. # TODO: this string has to exercise as much pre-tokenizer functionality as possible
  39. # will be updated with time - contributions welcome
  40. chktxt = '\n \n\n \n\n\n \t \t\t \t\n \n \n \n \n🚀 (normal) 😶‍🌫️ (multiple emojis concatenated) ✅ 🦙🦙 3 33 333 3333 33333 333333 3333333 33333333 3.3 3..3 3...3 កាន់តែពិសេសអាច😁 ?我想在apple工作1314151天~ ------======= нещо на Български \'\'\'\'\'\'```````\"\"\"\"......!!!!!!?????? I\'ve been \'told he\'s there, \'RE you sure? \'M not sure I\'ll make it, \'D you like some tea? We\'Ve a\'lL'
  41. if len(sys.argv) == 2:
  42. token = sys.argv[1]
  43. else:
  44. logger.info("Usage: python convert-hf-to-gguf-update.py <huggingface_token>")
  45. sys.exit(1)
  46. # TODO: add models here, base models preferred
  47. models = [
  48. {"name": "llama-spm", "tokt": TOKENIZER_TYPE.SPM, "repo": "https://huggingface.co/meta-llama/Llama-2-7b-hf", },
  49. {"name": "llama-bpe", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/meta-llama/Meta-Llama-3-8B", },
  50. {"name": "phi-3", "tokt": TOKENIZER_TYPE.SPM, "repo": "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct", },
  51. {"name": "deepseek-llm", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/deepseek-ai/deepseek-llm-7b-base", },
  52. {"name": "deepseek-coder", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/deepseek-ai/deepseek-coder-6.7b-base", },
  53. {"name": "falcon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/tiiuae/falcon-7b", },
  54. {"name": "bert-bge", "tokt": TOKENIZER_TYPE.WPM, "repo": "https://huggingface.co/BAAI/bge-small-en-v1.5", },
  55. {"name": "mpt", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/mosaicml/mpt-7b", },
  56. {"name": "starcoder", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/bigcode/starcoder2-3b", },
  57. {"name": "gpt-2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/openai-community/gpt2", },
  58. {"name": "refact", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/smallcloudai/Refact-1_6-base", },
  59. {"name": "command-r", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/CohereForAI/c4ai-command-r-v01", },
  60. {"name": "qwen2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/Qwen/Qwen1.5-7B", },
  61. {"name": "olmo", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/allenai/OLMo-1.7-7B-hf", },
  62. {"name": "dbrx", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/databricks/dbrx-base", },
  63. ]
  64. # make directory "models/tokenizers" if it doesn't exist
  65. if not os.path.exists("models/tokenizers"):
  66. os.makedirs("models/tokenizers")
  67. def download_file_with_auth(url, token, save_path):
  68. headers = {"Authorization": f"Bearer {token}"}
  69. response = requests.get(url, headers=headers)
  70. if response.status_code == 200:
  71. with open(save_path, 'wb') as f:
  72. f.write(response.content)
  73. logger.info(f"File {save_path} downloaded successfully")
  74. else:
  75. logger.info(f"Failed to download file. Status code: {response.status_code}")
  76. # download the tokenizer models
  77. for model in models:
  78. name = model["name"]
  79. repo = model["repo"]
  80. tokt = model["tokt"]
  81. if not os.path.exists(f"models/tokenizers/{name}"):
  82. os.makedirs(f"models/tokenizers/{name}")
  83. else:
  84. logger.info(f"Directory models/tokenizers/{name} already exists - skipping")
  85. continue
  86. logger.info(f"Downloading {name} to models/tokenizers/{name}")
  87. url = f"{repo}/raw/main/config.json"
  88. save_path = f"models/tokenizers/{name}/config.json"
  89. download_file_with_auth(url, token, save_path)
  90. url = f"{repo}/raw/main/tokenizer.json"
  91. save_path = f"models/tokenizers/{name}/tokenizer.json"
  92. download_file_with_auth(url, token, save_path)
  93. # if downloaded file is less than 1KB, we likely need to download an LFS instead
  94. if os.path.getsize(save_path) < 1024:
  95. # remove the file
  96. os.remove(save_path)
  97. url = f"{repo}/resolve/main/tokenizer.json"
  98. save_path = f"models/tokenizers/{name}/tokenizer.json"
  99. download_file_with_auth(url, token, save_path)
  100. if tokt == TOKENIZER_TYPE.SPM:
  101. url = f"{repo}/resolve/main/tokenizer.model"
  102. save_path = f"models/tokenizers/{name}/tokenizer.model"
  103. download_file_with_auth(url, token, save_path)
  104. url = f"{repo}/raw/main/tokenizer_config.json"
  105. save_path = f"models/tokenizers/{name}/tokenizer_config.json"
  106. download_file_with_auth(url, token, save_path)
  107. # generate the source code for the convert-hf-to-gguf.py:get_vocab_base_pre() function:
  108. # TODO: auto-update convert-hf-to-gguf.py with the generated function
  109. src_ifs = ""
  110. for model in models:
  111. name = model["name"]
  112. tokt = model["tokt"]
  113. if tokt == TOKENIZER_TYPE.SPM:
  114. continue
  115. # create the tokenizer
  116. tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}")
  117. chktok = tokenizer.encode(chktxt)
  118. chkhsh = sha256(str(chktok).encode()).hexdigest()
  119. logger.info(f"model: {name}")
  120. logger.info(f"tokt: {tokt}")
  121. logger.info(f"repo: {model['repo']}")
  122. logger.info(f"chktok: {chktok}")
  123. logger.info(f"chkhsh: {chkhsh}")
  124. # print the "pre_tokenizer" content from the tokenizer.json
  125. with open(f"models/tokenizers/{name}/tokenizer.json", "r", encoding="utf-8") as f:
  126. cfg = json.load(f)
  127. normalizer = cfg["normalizer"]
  128. logger.info("normalizer: " + json.dumps(normalizer, indent=4))
  129. pre_tokenizer = cfg["pre_tokenizer"]
  130. logger.info("pre_tokenizer: " + json.dumps(pre_tokenizer, indent=4))
  131. logger.info("")
  132. src_ifs += f" if chkhsh == \"{chkhsh}\":\n"
  133. src_ifs += f" # ref: {model['repo']}\n"
  134. src_ifs += f" res = \"{name}\"\n"
  135. src_func = f"""
  136. def get_vocab_base_pre(self, tokenizer) -> str:
  137. # encoding this string and hashing the resulting tokens would (hopefully) give us a unique identifier that
  138. # is specific for the BPE pre-tokenizer used by the model
  139. # we will use this unique identifier to write a "tokenizer.ggml.pre" entry in the GGUF file which we can
  140. # use in llama.cpp to implement the same pre-tokenizer
  141. chktxt = {repr(chktxt)}
  142. chktok = tokenizer.encode(chktxt)
  143. chkhsh = sha256(str(chktok).encode()).hexdigest()
  144. logger.debug(f"chktok: {{chktok}}")
  145. logger.debug(f"chkhsh: {{chkhsh}}")
  146. res = None
  147. # NOTE: if you get an error here, you need to update the convert-hf-to-gguf-update.py script
  148. # or pull the latest version of the model from Huggingface
  149. # don't edit the hashes manually!
  150. {src_ifs}
  151. if res is None:
  152. logger.warning("\\n")
  153. logger.warning("**************************************************************************************")
  154. logger.warning("** WARNING: The BPE pre-tokenizer was not recognized!")
  155. logger.warning("** There are 2 possible reasons for this:")
  156. logger.warning("** - the model has not been added to convert-hf-to-gguf-update.py yet")
  157. logger.warning("** - the pre-tokenization config has changed upstream")
  158. logger.warning("** Check your model files and convert-hf-to-gguf-update.py and update them accordingly.")
  159. logger.warning("** ref: https://github.com/ggerganov/llama.cpp/pull/6920")
  160. logger.warning("**")
  161. logger.warning(f"** chkhsh: {{chkhsh}}")
  162. logger.warning("**************************************************************************************")
  163. logger.warning("\\n")
  164. raise NotImplementedError("BPE pre-tokenizer was not recognized - update get_vocab_base_pre()")
  165. logger.debug(f"tokenizer.ggml.pre: {{repr(res)}}")
  166. logger.debug(f"chkhsh: {{chkhsh}}")
  167. return res
  168. """
  169. print(src_func) # noqa: NP100
  170. logger.info("\n")
  171. logger.info("!!! Copy-paste the function above into convert-hf-to-gguf.py !!!")
  172. logger.info("\n")
  173. # generate tests for each tokenizer model
  174. tests = [
  175. "ied 4 ½ months",
  176. "Führer",
  177. "",
  178. " ",
  179. " ",
  180. " ",
  181. "\t",
  182. "\n",
  183. "\n\n",
  184. "\n\n\n",
  185. "\t\n",
  186. "Hello world",
  187. " Hello world",
  188. "Hello World",
  189. " Hello World",
  190. " Hello World!",
  191. "Hello, world!",
  192. " Hello, world!",
  193. " this is 🦙.cpp",
  194. "w048 7tuijk dsdfhu",
  195. "нещо на Български",
  196. "កាន់តែពិសេសអាចខលចេញ",
  197. "🚀 (normal) 😶‍🌫️ (multiple emojis concatenated) ✅ (only emoji that has its own token)",
  198. "Hello",
  199. " Hello",
  200. " Hello",
  201. " Hello",
  202. " Hello",
  203. " Hello\n Hello",
  204. " (",
  205. "\n =",
  206. "' era",
  207. "Hello, y'all! How are you 😁 ?我想在apple工作1314151天~",
  208. "3",
  209. "33",
  210. "333",
  211. "3333",
  212. "33333",
  213. "333333",
  214. "3333333",
  215. "33333333",
  216. "333333333",
  217. chktxt,
  218. ]
  219. # write the tests to ./models/ggml-vocab-{name}.gguf.inp
  220. # the format is:
  221. #
  222. # test0
  223. # __ggml_vocab_test__
  224. # test1
  225. # __ggml_vocab_test__
  226. # ...
  227. #
  228. # with each model, encode all tests and write the results in ./models/ggml-vocab-{name}.gguf.out
  229. # for each test, write the resulting tokens on a separate line
  230. for model in models:
  231. name = model["name"]
  232. tokt = model["tokt"]
  233. # create the tokenizer
  234. tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}")
  235. with open(f"models/ggml-vocab-{name}.gguf.inp", "w", encoding="utf-8") as f:
  236. for text in tests:
  237. f.write(f"{text}")
  238. f.write("\n__ggml_vocab_test__\n")
  239. with open(f"models/ggml-vocab-{name}.gguf.out", "w") as f:
  240. for text in tests:
  241. res = tokenizer.encode(text, add_special_tokens=False)
  242. for r in res:
  243. f.write(f" {r}")
  244. f.write("\n")
  245. logger.info(f"Tests for {name} written in ./models/ggml-vocab-{name}.gguf.*")
  246. # generate commands for creating vocab files
  247. logger.info("\nRun the following commands to generate the vocab files for testing:\n")
  248. for model in models:
  249. name = model["name"]
  250. print(f"python3 convert-hf-to-gguf.py models/tokenizers/{name}/ --outfile models/ggml-vocab-{name}.gguf --vocab-only") # noqa: NP100
  251. logger.info("\n")