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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. if not token.startswith("hf_"):
  44. logger.info("Huggingface token seems invalid")
  45. logger.info("Usage: python convert-hf-to-gguf-update.py <huggingface_token>")
  46. sys.exit(1)
  47. else:
  48. logger.info("Usage: python convert-hf-to-gguf-update.py <huggingface_token>")
  49. sys.exit(1)
  50. # TODO: add models here, base models preferred
  51. models = [
  52. {"name": "llama-spm", "tokt": TOKENIZER_TYPE.SPM, "repo": "https://huggingface.co/meta-llama/Llama-2-7b-hf", },
  53. {"name": "llama-bpe", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/meta-llama/Meta-Llama-3-8B", },
  54. {"name": "phi-3", "tokt": TOKENIZER_TYPE.SPM, "repo": "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct", },
  55. {"name": "deepseek-llm", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/deepseek-ai/deepseek-llm-7b-base", },
  56. {"name": "deepseek-coder", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/deepseek-ai/deepseek-coder-6.7b-base", },
  57. {"name": "falcon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/tiiuae/falcon-7b", },
  58. {"name": "bert-bge", "tokt": TOKENIZER_TYPE.WPM, "repo": "https://huggingface.co/BAAI/bge-small-en-v1.5", },
  59. {"name": "mpt", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/mosaicml/mpt-7b", },
  60. {"name": "starcoder", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/bigcode/starcoder2-3b", },
  61. {"name": "gpt-2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/openai-community/gpt2", },
  62. {"name": "refact", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/smallcloudai/Refact-1_6-base", },
  63. {"name": "command-r", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/CohereForAI/c4ai-command-r-v01", },
  64. {"name": "qwen2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/Qwen/Qwen1.5-7B", },
  65. {"name": "olmo", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/allenai/OLMo-1.7-7B-hf", },
  66. {"name": "dbrx", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/databricks/dbrx-base", },
  67. {"name": "jina-en", "tokt": TOKENIZER_TYPE.WPM, "repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-en", }, # WPM!
  68. {"name": "jina-es", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-es", },
  69. {"name": "jina-de", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-de", },
  70. ]
  71. # make directory "models/tokenizers" if it doesn't exist
  72. if not os.path.exists("models/tokenizers"):
  73. os.makedirs("models/tokenizers")
  74. def download_file_with_auth(url, token, save_path):
  75. headers = {"Authorization": f"Bearer {token}"}
  76. response = requests.get(url, headers=headers)
  77. if response.status_code == 200:
  78. with open(save_path, 'wb') as f:
  79. f.write(response.content)
  80. logger.info(f"File {save_path} downloaded successfully")
  81. else:
  82. logger.info(f"Failed to download file. Status code: {response.status_code}")
  83. # download the tokenizer models
  84. for model in models:
  85. name = model["name"]
  86. repo = model["repo"]
  87. tokt = model["tokt"]
  88. if not os.path.exists(f"models/tokenizers/{name}"):
  89. os.makedirs(f"models/tokenizers/{name}")
  90. else:
  91. logger.info(f"Directory models/tokenizers/{name} already exists - skipping")
  92. continue
  93. logger.info(f"Downloading {name} to models/tokenizers/{name}")
  94. url = f"{repo}/raw/main/config.json"
  95. save_path = f"models/tokenizers/{name}/config.json"
  96. download_file_with_auth(url, token, save_path)
  97. url = f"{repo}/raw/main/tokenizer.json"
  98. save_path = f"models/tokenizers/{name}/tokenizer.json"
  99. download_file_with_auth(url, token, save_path)
  100. # if downloaded file is less than 1KB, we likely need to download an LFS instead
  101. if os.path.getsize(save_path) < 1024:
  102. # remove the file
  103. os.remove(save_path)
  104. url = f"{repo}/resolve/main/tokenizer.json"
  105. save_path = f"models/tokenizers/{name}/tokenizer.json"
  106. download_file_with_auth(url, token, save_path)
  107. if tokt == TOKENIZER_TYPE.SPM:
  108. url = f"{repo}/resolve/main/tokenizer.model"
  109. save_path = f"models/tokenizers/{name}/tokenizer.model"
  110. download_file_with_auth(url, token, save_path)
  111. url = f"{repo}/raw/main/tokenizer_config.json"
  112. save_path = f"models/tokenizers/{name}/tokenizer_config.json"
  113. download_file_with_auth(url, token, save_path)
  114. # generate the source code for the convert-hf-to-gguf.py:get_vocab_base_pre() function:
  115. # TODO: auto-update convert-hf-to-gguf.py with the generated function
  116. src_ifs = ""
  117. for model in models:
  118. name = model["name"]
  119. tokt = model["tokt"]
  120. if tokt == TOKENIZER_TYPE.SPM:
  121. continue
  122. # Skip if the tokenizer folder does not exist or there are other download issues previously
  123. if not os.path.exists(f"models/tokenizers/{name}"):
  124. logger.warning(f"Directory for tokenizer {name} not found. Skipping...")
  125. continue
  126. # create the tokenizer
  127. try:
  128. tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}")
  129. except OSError as e:
  130. logger.error(f"Error loading tokenizer for model {name}. The model may not exist or is not accessible with the provided token. Error: {e}")
  131. continue # Skip to the next model if the tokenizer can't be loaded
  132. chktok = tokenizer.encode(chktxt)
  133. chkhsh = sha256(str(chktok).encode()).hexdigest()
  134. logger.info(f"model: {name}")
  135. logger.info(f"tokt: {tokt}")
  136. logger.info(f"repo: {model['repo']}")
  137. logger.info(f"chktok: {chktok}")
  138. logger.info(f"chkhsh: {chkhsh}")
  139. # print the "pre_tokenizer" content from the tokenizer.json
  140. with open(f"models/tokenizers/{name}/tokenizer.json", "r", encoding="utf-8") as f:
  141. cfg = json.load(f)
  142. normalizer = cfg["normalizer"]
  143. logger.info("normalizer: " + json.dumps(normalizer, indent=4))
  144. pre_tokenizer = cfg["pre_tokenizer"]
  145. logger.info("pre_tokenizer: " + json.dumps(pre_tokenizer, indent=4))
  146. if "ignore_merges" in cfg["model"]:
  147. logger.info("ignore_merges: " + json.dumps(cfg["model"]["ignore_merges"], indent=4))
  148. logger.info("")
  149. src_ifs += f" if chkhsh == \"{chkhsh}\":\n"
  150. src_ifs += f" # ref: {model['repo']}\n"
  151. src_ifs += f" res = \"{name}\"\n"
  152. src_func = f"""
  153. def get_vocab_base_pre(self, tokenizer) -> str:
  154. # encoding this string and hashing the resulting tokens would (hopefully) give us a unique identifier that
  155. # is specific for the BPE pre-tokenizer used by the model
  156. # we will use this unique identifier to write a "tokenizer.ggml.pre" entry in the GGUF file which we can
  157. # use in llama.cpp to implement the same pre-tokenizer
  158. chktxt = {repr(chktxt)}
  159. chktok = tokenizer.encode(chktxt)
  160. chkhsh = sha256(str(chktok).encode()).hexdigest()
  161. logger.debug(f"chktok: {{chktok}}")
  162. logger.debug(f"chkhsh: {{chkhsh}}")
  163. res = None
  164. # NOTE: if you get an error here, you need to update the convert-hf-to-gguf-update.py script
  165. # or pull the latest version of the model from Huggingface
  166. # don't edit the hashes manually!
  167. {src_ifs}
  168. if res is None:
  169. logger.warning("\\n")
  170. logger.warning("**************************************************************************************")
  171. logger.warning("** WARNING: The BPE pre-tokenizer was not recognized!")
  172. logger.warning("** There are 2 possible reasons for this:")
  173. logger.warning("** - the model has not been added to convert-hf-to-gguf-update.py yet")
  174. logger.warning("** - the pre-tokenization config has changed upstream")
  175. logger.warning("** Check your model files and convert-hf-to-gguf-update.py and update them accordingly.")
  176. logger.warning("** ref: https://github.com/ggerganov/llama.cpp/pull/6920")
  177. logger.warning("**")
  178. logger.warning(f"** chkhsh: {{chkhsh}}")
  179. logger.warning("**************************************************************************************")
  180. logger.warning("\\n")
  181. raise NotImplementedError("BPE pre-tokenizer was not recognized - update get_vocab_base_pre()")
  182. logger.debug(f"tokenizer.ggml.pre: {{repr(res)}}")
  183. logger.debug(f"chkhsh: {{chkhsh}}")
  184. return res
  185. """
  186. print(src_func) # noqa: NP100
  187. logger.info("\n")
  188. logger.info("!!! Copy-paste the function above into convert-hf-to-gguf.py !!!")
  189. logger.info("\n")
  190. # generate tests for each tokenizer model
  191. tests = [
  192. "ied 4 ½ months",
  193. "Führer",
  194. "",
  195. " ",
  196. " ",
  197. " ",
  198. "\t",
  199. "\n",
  200. "\n\n",
  201. "\n\n\n",
  202. "\t\n",
  203. "Hello world",
  204. " Hello world",
  205. "Hello World",
  206. " Hello World",
  207. " Hello World!",
  208. "Hello, world!",
  209. " Hello, world!",
  210. " this is 🦙.cpp",
  211. "w048 7tuijk dsdfhu",
  212. "нещо на Български",
  213. "កាន់តែពិសេសអាចខលចេញ",
  214. "🚀 (normal) 😶‍🌫️ (multiple emojis concatenated) ✅ (only emoji that has its own token)",
  215. "Hello",
  216. " Hello",
  217. " Hello",
  218. " Hello",
  219. " Hello",
  220. " Hello\n Hello",
  221. " (",
  222. "\n =",
  223. "' era",
  224. "Hello, y'all! How are you 😁 ?我想在apple工作1314151天~",
  225. "3",
  226. "33",
  227. "333",
  228. "3333",
  229. "33333",
  230. "333333",
  231. "3333333",
  232. "33333333",
  233. "333333333",
  234. # "Cửa Việt", # llama-bpe fails on this
  235. chktxt,
  236. ]
  237. # write the tests to ./models/ggml-vocab-{name}.gguf.inp
  238. # the format is:
  239. #
  240. # test0
  241. # __ggml_vocab_test__
  242. # test1
  243. # __ggml_vocab_test__
  244. # ...
  245. #
  246. # with each model, encode all tests and write the results in ./models/ggml-vocab-{name}.gguf.out
  247. # for each test, write the resulting tokens on a separate line
  248. for model in models:
  249. name = model["name"]
  250. tokt = model["tokt"]
  251. # Skip if the tokenizer folder does not exist or there are other download issues previously
  252. if not os.path.exists(f"models/tokenizers/{name}"):
  253. logger.warning(f"Directory for tokenizer {name} not found. Skipping...")
  254. continue
  255. # create the tokenizer
  256. try:
  257. tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}")
  258. except OSError as e:
  259. logger.error(f"Failed to load tokenizer for model {name}. Error: {e}")
  260. continue # Skip this model and continue with the next one in the loop
  261. with open(f"models/ggml-vocab-{name}.gguf.inp", "w", encoding="utf-8") as f:
  262. for text in tests:
  263. f.write(f"{text}")
  264. f.write("\n__ggml_vocab_test__\n")
  265. with open(f"models/ggml-vocab-{name}.gguf.out", "w") as f:
  266. for text in tests:
  267. res = tokenizer.encode(text, add_special_tokens=False)
  268. for r in res:
  269. f.write(f" {r}")
  270. f.write("\n")
  271. logger.info(f"Tests for {name} written in ./models/ggml-vocab-{name}.gguf.*")
  272. # generate commands for creating vocab files
  273. logger.info("\nRun the following commands to generate the vocab files for testing:\n")
  274. for model in models:
  275. name = model["name"]
  276. print(f"python3 convert-hf-to-gguf.py models/tokenizers/{name}/ --outfile models/ggml-vocab-{name}.gguf --vocab-only") # noqa: NP100
  277. logger.info("\n")