convert_hf_to_gguf_update.py 16 KB

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