convert_hf_to_gguf_update.py 17 KB

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