convert_hf_to_gguf_update.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import logging
  4. import os
  5. import pathlib
  6. import re
  7. import requests
  8. import json
  9. import shutil
  10. import argparse
  11. from hashlib import sha256
  12. from enum import IntEnum, auto
  13. from transformers import AutoTokenizer
  14. logging.basicConfig(level=logging.DEBUG)
  15. logger = logging.getLogger("convert_hf_to_gguf_update")
  16. sess = requests.Session()
  17. convert_py_pth = pathlib.Path("convert_hf_to_gguf.py")
  18. convert_py = convert_py_pth.read_text(encoding="utf-8")
  19. hf_token_pth = pathlib.Path.home() / ".cache" / "huggingface" / "token"
  20. hf_token = hf_token_pth.read_text(encoding="utf-8").strip() if hf_token_pth.exists() else None
  21. class TOKENIZER_TYPE(IntEnum):
  22. SPM = auto()
  23. BPE = auto()
  24. WPM = auto()
  25. UGM = auto()
  26. DOC_STRING = """
  27. This script downloads the tokenizer models of the specified models from Huggingface and
  28. generates the get_vocab_base_pre() function for convert_hf_to_gguf.py
  29. /!\\ It is intended to be used by contributors and is not meant to be run by end users
  30. This is necessary in order to analyze the type of pre-tokenizer used by the model and
  31. provide the necessary information to llama.cpp via the GGUF header in order to implement
  32. the same pre-tokenizer.
  33. ref: https://github.com/ggml-org/llama.cpp/pull/6920
  34. Instructions:
  35. - Add a new model to the "models" list
  36. - Run the script with your huggingface token
  37. By default, token will be read from ~/.cache/huggingface/token
  38. - The convert_hf_to_gguf.py script will have had its get_vocab_base_pre() function updated
  39. - Update llama.cpp with the new pre-tokenizer if necessary
  40. """
  41. # TODO: generate tokenizer tests for llama.cpp
  42. parser = argparse.ArgumentParser(description=DOC_STRING, formatter_class=argparse.RawTextHelpFormatter)
  43. parser.add_argument(
  44. "--full", action="store_true",
  45. help="download full list of models - make sure you have access to all of them",
  46. )
  47. parser.add_argument(
  48. "--check-missing", action="store_true",
  49. help="only check for missing pre-tokenizer hashes",
  50. )
  51. parser.add_argument(
  52. "hf_token",
  53. help="optional HF token",
  54. nargs="?",
  55. )
  56. args = parser.parse_args()
  57. hf_token = args.hf_token if args.hf_token is not None else hf_token
  58. if hf_token is None:
  59. logger.warning("HF token not found. You can provide it as an argument or set it in ~/.cache/huggingface/token")
  60. if args.check_missing and args.full:
  61. logger.warning("Downloading full list of models requested, ignoring --check-missing!")
  62. args.check_missing = False
  63. # TODO: this string has to exercise as much pre-tokenizer functionality as possible
  64. # will be updated with time - contributions welcome
  65. 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'
  66. # TODO: add models here, base models preferred
  67. models = [
  68. {"name": "llama-spm", "tokt": TOKENIZER_TYPE.SPM, "repo": "https://huggingface.co/meta-llama/Llama-2-7b-hf", },
  69. {"name": "llama-bpe", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/meta-llama/Meta-Llama-3-8B", },
  70. {"name": "phi-3", "tokt": TOKENIZER_TYPE.SPM, "repo": "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct", },
  71. {"name": "deepseek-llm", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/deepseek-ai/deepseek-llm-7b-base", },
  72. {"name": "deepseek-coder", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/deepseek-ai/deepseek-coder-6.7b-base", },
  73. {"name": "falcon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/tiiuae/falcon-7b", },
  74. {"name": "bert-bge", "tokt": TOKENIZER_TYPE.WPM, "repo": "https://huggingface.co/BAAI/bge-small-en-v1.5", },
  75. {"name": "falcon3", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/tiiuae/Falcon3-7B-Base", },
  76. {"name": "bert-bge-large", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/BAAI/bge-large-zh-v1.5", },
  77. {"name": "mpt", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/mosaicml/mpt-7b", },
  78. {"name": "starcoder", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/bigcode/starcoder2-3b", },
  79. {"name": "gpt-2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/openai-community/gpt2", },
  80. {"name": "stablelm2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/stabilityai/stablelm-2-zephyr-1_6b", },
  81. {"name": "refact", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/smallcloudai/Refact-1_6-base", },
  82. {"name": "command-r", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/CohereForAI/c4ai-command-r-v01", },
  83. {"name": "qwen2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/Qwen/Qwen1.5-7B", },
  84. {"name": "olmo", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/allenai/OLMo-1.7-7B-hf", },
  85. {"name": "dbrx", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/databricks/dbrx-base", },
  86. {"name": "jina-v1-en", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/jinaai/jina-reranker-v1-tiny-en", },
  87. {"name": "jina-v2-en", "tokt": TOKENIZER_TYPE.WPM, "repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-en", }, # WPM!
  88. {"name": "jina-v2-es", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-es", },
  89. {"name": "jina-v2-de", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-de", },
  90. {"name": "smaug-bpe", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/abacusai/Smaug-Llama-3-70B-Instruct", },
  91. {"name": "poro-chat", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/LumiOpen/Poro-34B-chat", },
  92. {"name": "jina-v2-code", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-code", },
  93. {"name": "viking", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/LumiOpen/Viking-7B", }, # Also used for Viking 13B and 33B
  94. {"name": "gemma", "tokt": TOKENIZER_TYPE.SPM, "repo": "https://huggingface.co/google/gemma-2b", },
  95. {"name": "gemma-2", "tokt": TOKENIZER_TYPE.SPM, "repo": "https://huggingface.co/google/gemma-2-9b", },
  96. {"name": "jais", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/core42/jais-13b", },
  97. {"name": "t5", "tokt": TOKENIZER_TYPE.UGM, "repo": "https://huggingface.co/google-t5/t5-small", },
  98. {"name": "codeshell", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/WisdomShell/CodeShell-7B", },
  99. {"name": "tekken", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/mistralai/Mistral-Nemo-Base-2407", },
  100. {"name": "smollm", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/HuggingFaceTB/SmolLM-135M", },
  101. {'name': "bloom", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/bigscience/bloom", },
  102. {'name': "gpt3-finnish", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/TurkuNLP/gpt3-finnish-small", },
  103. {"name": "exaone", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct", },
  104. {"name": "phi-2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/microsoft/phi-2", },
  105. {"name": "chameleon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/facebook/chameleon-7b", },
  106. {"name": "roberta-bpe", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/sentence-transformers/stsb-roberta-base"},
  107. {"name": "gigachat", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/ai-sage/GigaChat-20B-A3B-instruct"},
  108. {"name": "megrez", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/Infinigence/Megrez-3B-Instruct"},
  109. {"name": "deepseek-v3", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/deepseek-ai/DeepSeek-V3"},
  110. {"name": "deepseek-r1-qwen", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"},
  111. {"name": "gpt-4o", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/Xenova/gpt-4o", },
  112. {"name": "superbpe", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/UW/OLMo2-8B-SuperBPE-t180k", },
  113. {"name": "trillion", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/trillionlabs/Trillion-7B-preview", },
  114. {"name": "bailingmoe", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/inclusionAI/Ling-lite", },
  115. {"name": "llama4", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/meta-llama/Llama-4-Scout-17B-16E-Instruct", },
  116. {"name": "pixtral", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/mistral-community/pixtral-12b", },
  117. {"name": "seed-coder", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/ByteDance-Seed/Seed-Coder-8B-Base", },
  118. {"name": "a.x-4.0", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/skt/A.X-4.0", },
  119. {"name": "midm-2.0", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/K-intelligence/Midm-2.0-Base-Instruct", },
  120. {"name": "lfm2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/LiquidAI/LFM2-Tokenizer"},
  121. {"name": "exaone4", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/LGAI-EXAONE/EXAONE-4.0-32B", },
  122. {"name": "mellum", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/JetBrains/Mellum-4b-base", },
  123. {"name": "afmoe", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/arcee-ai/Trinity-Tokenizer", },
  124. {"name": "bailingmoe2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/inclusionAI/Ling-mini-base-2.0", },
  125. {"name": "granite-docling", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/ibm-granite/granite-docling-258M", },
  126. {"name": "minimax-m2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/MiniMaxAI/MiniMax-M2", },
  127. {"name": "kormo", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/KORMo-Team/KORMo-tokenizer", },
  128. ]
  129. # some models are known to be broken upstream, so we will skip them as exceptions
  130. pre_computed_hashes = [
  131. # chatglm-bpe has 2 hashes, why?
  132. {"name": "chatglm-bpe", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/THUDM/glm-4-9b-chat", "chkhsh": "b6e8e1518dc4305be2fe39c313ed643381c4da5db34a98f6a04c093f8afbe99b"},
  133. {"name": "chatglm-bpe", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/THUDM/glm-4-9b-chat", "chkhsh": "81d72c7348a9f0ebe86f23298d37debe0a5e71149e29bd283904c02262b27516"},
  134. {"name": "glm4", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/THUDM/glm-4-9b-hf", "chkhsh": "a1336059768a55c99a734006ffb02203cd450fed003e9a71886c88acf24fdbc2"},
  135. {"name": "glm4", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/zai-org/GLM-4.5-Air", "chkhsh": "9ca2dd618e8afaf09731a7cf6e2105b373ba6a1821559f258b272fe83e6eb902"},
  136. {"name": "minerva-7b", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/sapienzanlp/Minerva-7B-base-v1.0", "chkhsh": "1431a23e583c97432bc230bff598d103ddb5a1f89960c8f1d1051aaa944d0b35"},
  137. {"name": "hunyuan", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/tencent/Hunyuan-A13B-Instruct", "chkhsh": "7e57df22b1fe23a7b1e1c7f3dc4e3f96d43a4eb0836d0c6bdc3436d7b2f1c664"},
  138. {"name": "hunyuan-dense", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/tencent/Hunyuan-4B-Instruct", "chkhsh": "bba3b3366b646dbdded5dbc42d59598b849371afc42f7beafa914afaa5b70aa6"},
  139. # falcon-h1 series uses 4 different tokenizers across model sizes (0.5b - 34b), hence we need to define 4 different hashes
  140. {"name": "falcon-h1", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/tiiuae/Falcon-H1-0.5B-Base", "chkhsh": "a6b57017d60e6edb4d88ecc2845188e0eb333a70357e45dcc9b53964a73bbae6"},
  141. {"name": "falcon-h1", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/tiiuae/Falcon-H1-1B-Base", "chkhsh": "60476e1243776c4fb1b993dbd7a5f15ac22f83c80afdf425fa5ae01c8d44ef86"},
  142. {"name": "falcon-h1", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/tiiuae/Falcon-H1-7B-Base", "chkhsh": "3eda48b4c4dc7de733d1a8b3e3b4a85243dbbf704da2ee9d42c6beced8897896"},
  143. {"name": "falcon-h1", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/tiiuae/Falcon-H1-34B-Base", "chkhsh": "48f8e02c0359c0bbdd82f26909171fac1c18a457bb47573ed1fe3bbb2c1cfd4b"},
  144. {"name": "kimi-k2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/moonshotai/Kimi-K2-Base", "chkhsh": "81212dc7cdb7e0c1074ca62c5aeab0d43c9f52b8a737be7b12a777c953027890"},
  145. {"name": "qwen2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/Qwen/Qwen3-Embedding-0.6B", "chkhsh": "d4540891389ea895b53b399da6ac824becc30f2fba0e9ddbb98f92e55ca0e97c"},
  146. {"name": "grok-2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/alvarobartt/grok-2-tokenizer", "chkhsh": "66b8d4e19ab16c3bfd89bce5d785fb7e0155e8648708a1f42077cb9fe002c273"},
  147. ]
  148. def download_file_with_auth(url, token, save_path):
  149. headers = {"Authorization": f"Bearer {token}"} if token else None
  150. response = sess.get(url, headers=headers)
  151. response.raise_for_status()
  152. os.makedirs(os.path.dirname(save_path), exist_ok=True)
  153. with open(save_path, 'wb') as downloaded_file:
  154. downloaded_file.write(response.content)
  155. logger.info(f"File {save_path} downloaded successfully")
  156. def download_model(model):
  157. name = model["name"]
  158. repo = model["repo"]
  159. tokt = model["tokt"]
  160. os.makedirs(f"models/tokenizers/{name}", exist_ok=True)
  161. files = ["config.json", "tokenizer.json", "tokenizer_config.json"]
  162. if name == "gpt-4o":
  163. # Xenova/gpt-4o is tokenizer-only, it does not contain config.json
  164. files = ["tokenizer.json", "tokenizer_config.json"]
  165. if tokt == TOKENIZER_TYPE.SPM:
  166. files.append("tokenizer.model")
  167. if tokt == TOKENIZER_TYPE.UGM:
  168. files.append("spiece.model")
  169. if os.path.isdir(repo):
  170. # If repo is a path on the file system, copy the directory
  171. for file in files:
  172. src_path = os.path.join(repo, file)
  173. dst_path = f"models/tokenizers/{name}/{file}"
  174. if os.path.isfile(dst_path):
  175. logger.info(f"{name}: File {dst_path} already exists - skipping")
  176. continue
  177. if os.path.isfile(src_path):
  178. shutil.copy2(src_path, dst_path)
  179. logger.info(f"{name}: Copied {src_path} to {dst_path}")
  180. else:
  181. logger.warning(f"{name}: Source file {src_path} does not exist")
  182. else:
  183. # If repo is a URL, download the files
  184. for file in files:
  185. save_path = f"models/tokenizers/{name}/{file}"
  186. if os.path.isfile(save_path):
  187. logger.info(f"{name}: File {save_path} already exists - skipping")
  188. continue
  189. download_file_with_auth(f"{repo}/resolve/main/{file}", hf_token, save_path)
  190. # get list of existing models and chkhsh from the convert_hf_to_gguf.py file
  191. # returns mapping res --> chkhsh
  192. def get_existing_models(convert_py):
  193. pattern = r'if chkhsh == "([a-f0-9]{64})":\s*\n\s*.*\s*res = "([^"]+)"'
  194. matches = re.findall(pattern, convert_py)
  195. output = {}
  196. for chkhsh, res in matches:
  197. output[res] = chkhsh
  198. return output
  199. existing_models = {}
  200. all_models = models.copy()
  201. if not args.full:
  202. # Filter out models that already exist in convert_hf_to_gguf.py
  203. existing_models = get_existing_models(convert_py)
  204. all_models = models.copy()
  205. models = [model for model in all_models if model["name"] not in existing_models]
  206. if not args.check_missing:
  207. logging.info(f"Downloading {len(models)} models...")
  208. for model in models:
  209. try:
  210. download_model(model)
  211. except Exception as e:
  212. logger.error(f"Failed to download model {model['name']}. Error: {e}")
  213. # generate the source code for the convert_hf_to_gguf.py:get_vocab_base_pre() function:
  214. src_ifs = ""
  215. for model in [*pre_computed_hashes, *all_models]:
  216. name = model["name"]
  217. tokt = model["tokt"]
  218. chkhsh = model.get("chkhsh")
  219. if tokt == TOKENIZER_TYPE.SPM or tokt == TOKENIZER_TYPE.UGM:
  220. continue
  221. # create the tokenizer
  222. if chkhsh is not None:
  223. # if the model has a pre-computed hash, use it
  224. logger.info(f"Using pre-computed hash for model {name}: {chkhsh}")
  225. elif name in existing_models:
  226. # if the model already exists in convert_hf_to_gguf.py, skip compute hash
  227. chkhsh = existing_models[name]
  228. else:
  229. # otherwise, compute the hash of the tokenizer
  230. # Fail if the tokenizer folder with config does not exist or there are other download issues previously
  231. if not os.path.isfile(f"models/tokenizers/{name}/tokenizer_config.json"):
  232. raise OSError(f"Config for tokenizer {name} not found. The model may not exist or is not accessible with the provided token.")
  233. try:
  234. logger.info(f"Loading tokenizer from {f'models/tokenizers/{name}'}...")
  235. if name == "t5":
  236. tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}", use_fast=False)
  237. else:
  238. tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}")
  239. except Exception as e:
  240. raise OSError(f"Error loading tokenizer for model {name}.") from e
  241. chktok = tokenizer.encode(CHK_TXT)
  242. chkhsh = sha256(str(chktok).encode()).hexdigest()
  243. logger.info(f"model: {name}")
  244. logger.info(f"tokt: {tokt}")
  245. logger.info(f"repo: {model['repo']}")
  246. logger.info(f"chktok: {chktok}")
  247. logger.info(f"chkhsh: {chkhsh}")
  248. # print the "pre_tokenizer" content from the tokenizer.json
  249. with open(f"models/tokenizers/{name}/tokenizer.json", "r", encoding="utf-8") as f:
  250. cfg = json.load(f)
  251. normalizer = cfg["normalizer"]
  252. logger.info("normalizer: " + json.dumps(normalizer, indent=4))
  253. pre_tokenizer = cfg["pre_tokenizer"]
  254. logger.info("pre_tokenizer: " + json.dumps(pre_tokenizer, indent=4))
  255. if "ignore_merges" in cfg["model"]:
  256. logger.info("ignore_merges: " + json.dumps(cfg["model"]["ignore_merges"], indent=4))
  257. logger.info("")
  258. src_ifs += f" if chkhsh == \"{chkhsh}\":\n"
  259. src_ifs += f" # ref: {model['repo']}\n"
  260. src_ifs += f" res = \"{name}\"\n"
  261. src_func = f"""
  262. def get_vocab_base_pre(self, tokenizer) -> str:
  263. # encoding this string and hashing the resulting tokens would (hopefully) give us a unique identifier that
  264. # is specific for the BPE pre-tokenizer used by the model
  265. # we will use this unique identifier to write a "tokenizer.ggml.pre" entry in the GGUF file which we can
  266. # use in llama.cpp to implement the same pre-tokenizer
  267. chktxt = {repr(CHK_TXT)}
  268. chktok = tokenizer.encode(chktxt)
  269. chkhsh = sha256(str(chktok).encode()).hexdigest()
  270. logger.debug(f"chktok: {{chktok}}")
  271. logger.debug(f"chkhsh: {{chkhsh}}")
  272. res = None
  273. # NOTE: if you get an error here, you need to update the convert_hf_to_gguf_update.py script
  274. # or pull the latest version of the model from Huggingface
  275. # don't edit the hashes manually!
  276. {src_ifs}
  277. if res is None:
  278. logger.warning("\\n")
  279. logger.warning("**************************************************************************************")
  280. logger.warning("** WARNING: The BPE pre-tokenizer was not recognized!")
  281. logger.warning("** There are 2 possible reasons for this:")
  282. logger.warning("** - the model has not been added to convert_hf_to_gguf_update.py yet")
  283. logger.warning("** - the pre-tokenization config has changed upstream")
  284. logger.warning("** Check your model files and convert_hf_to_gguf_update.py and update them accordingly.")
  285. logger.warning("** ref: https://github.com/ggml-org/llama.cpp/pull/6920")
  286. logger.warning("**")
  287. logger.warning(f"** chkhsh: {{chkhsh}}")
  288. logger.warning("**************************************************************************************")
  289. logger.warning("\\n")
  290. raise NotImplementedError("BPE pre-tokenizer was not recognized - update get_vocab_base_pre()")
  291. logger.debug(f"tokenizer.ggml.pre: {{repr(res)}}")
  292. logger.debug(f"chkhsh: {{chkhsh}}")
  293. return res
  294. """
  295. convert_py = re.sub(
  296. r"(# Marker: Start get_vocab_base_pre)(.+?)( +# Marker: End get_vocab_base_pre)",
  297. lambda m: m.group(1) + src_func + m.group(3),
  298. convert_py,
  299. flags=re.DOTALL | re.MULTILINE,
  300. )
  301. convert_py_pth.write_text(convert_py, encoding="utf-8")
  302. logger.info("+++ convert_hf_to_gguf.py was updated")
  303. # generate tests for each tokenizer model
  304. tests = [
  305. "ied 4 ½ months",
  306. "Äpfel",
  307. "",
  308. " ",
  309. " ",
  310. " ",
  311. "\t",
  312. "\n",
  313. "\n\n",
  314. "\n\n\n",
  315. "\t\n",
  316. "Hello world",
  317. " Hello world",
  318. "Hello World",
  319. " Hello World",
  320. " Hello World!",
  321. "Hello, world!",
  322. " Hello, world!",
  323. " this is 🦙.cpp",
  324. "w048 7tuijk dsdfhu",
  325. "нещо на Български",
  326. "កាន់តែពិសេសអាចខលចេញ",
  327. "🚀 (normal) 😶‍🌫️ (multiple emojis concatenated) ✅ (only emoji that has its own token)",
  328. "Hello",
  329. " Hello",
  330. " Hello",
  331. " Hello",
  332. " Hello",
  333. " Hello\n Hello",
  334. " (",
  335. "\n =",
  336. "' era",
  337. "Hello, y'all! How are you 😁 ?我想在apple工作1314151天~",
  338. "!!!!!!",
  339. "3",
  340. "33",
  341. "333",
  342. "3333",
  343. "33333",
  344. "333333",
  345. "3333333",
  346. "33333333",
  347. "333333333",
  348. "Cửa Việt", # llama-bpe fails on this
  349. " discards",
  350. CHK_TXT,
  351. ]
  352. # write the tests to ./models/ggml-vocab-{name}.gguf.inp
  353. # the format is:
  354. #
  355. # test0
  356. # __ggml_vocab_test__
  357. # test1
  358. # __ggml_vocab_test__
  359. # ...
  360. #
  361. # with each model, encode all tests and write the results in ./models/ggml-vocab-{name}.gguf.out
  362. # for each test, write the resulting tokens on a separate line
  363. for model in models:
  364. name = model["name"]
  365. tokt = model["tokt"]
  366. # Skip if the tokenizer folder does not exist or there are other download issues previously
  367. if not os.path.exists(f"models/tokenizers/{name}"):
  368. logger.warning(f"Directory for tokenizer {name} not found. Skipping...")
  369. continue
  370. # create the tokenizer
  371. try:
  372. if name == "t5":
  373. tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}", use_fast=False)
  374. else:
  375. tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}")
  376. except (OSError, TypeError) as e:
  377. logger.error(f"Failed to load tokenizer for model {name}. Error: {e}")
  378. continue # Skip this model and continue with the next one in the loop
  379. if not os.path.exists(f"models/ggml-vocab-{name}.gguf"):
  380. logger.info(f"Skip vocab files for model {name}, no GGUF file found")
  381. continue
  382. with open(f"models/ggml-vocab-{name}.gguf.inp", "w", encoding="utf-8") as f:
  383. for text in tests:
  384. f.write(f"{text}")
  385. f.write("\n__ggml_vocab_test__\n")
  386. with open(f"models/ggml-vocab-{name}.gguf.out", "w") as f:
  387. for text in tests:
  388. res = tokenizer.encode(text, add_special_tokens=False)
  389. for r in res:
  390. f.write(f" {r}")
  391. f.write("\n")
  392. logger.info(f"Tests for {name} written in ./models/ggml-vocab-{name}.gguf.*")
  393. # generate commands for creating vocab files
  394. logger.info("\nRun the following commands to generate the vocab files for testing:\n")
  395. for model in models:
  396. name = model["name"]
  397. print(f"python3 convert_hf_to_gguf.py models/tokenizers/{name}/ --outfile models/ggml-vocab-{name}.gguf --vocab-only") # noqa: NP100
  398. logger.info("\n")