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

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