convert_hf_to_gguf_update.py 16 KB

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