1
0

convert_hf_to_gguf_update.py 15 KB

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