bigdl-core-cpp 2.1.0b20240820.post1__py3-none-win_amd64.whl → 2.2.0b20250217.post0__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. bigdl/cpp/{convert-hf-to-gguf.py → convert_hf_to_gguf.py} +908 -140
  2. bigdl/cpp/convert_hf_to_gguf_update.py +376 -0
  3. bigdl/cpp/convert_llama_ggml_to_gguf.py +450 -0
  4. bigdl/cpp/convert_lora_to_gguf.py +433 -0
  5. bigdl/cpp/gguf-py/gguf/__init__.py +1 -1
  6. bigdl/cpp/gguf-py/gguf/constants.py +414 -89
  7. bigdl/cpp/gguf-py/gguf/gguf.py +1 -1
  8. bigdl/cpp/gguf-py/gguf/gguf_reader.py +5 -6
  9. bigdl/cpp/gguf-py/gguf/gguf_writer.py +77 -14
  10. bigdl/cpp/gguf-py/gguf/lazy.py +3 -1
  11. bigdl/cpp/gguf-py/gguf/metadata.py +195 -76
  12. bigdl/cpp/gguf-py/gguf/quants.py +1210 -64
  13. bigdl/cpp/gguf-py/gguf/tensor_mapping.py +156 -34
  14. bigdl/cpp/gguf-py/gguf/utility.py +1 -1
  15. bigdl/cpp/gguf-py/gguf/vocab.py +325 -3
  16. bigdl/cpp/libs/common.lib +0 -0
  17. bigdl/cpp/libs/ggml-base.dll +0 -0
  18. bigdl/cpp/libs/ggml-cpu.dll +0 -0
  19. bigdl/cpp/libs/ggml-sycl.dll +0 -0
  20. bigdl/cpp/libs/ggml.dll +0 -0
  21. bigdl/cpp/libs/libc++.dll +0 -0
  22. bigdl/cpp/libs/llama-batched.exe +0 -0
  23. bigdl/cpp/libs/llama-bench.exe +0 -0
  24. bigdl/cpp/libs/llama-cli.exe +0 -0
  25. bigdl/cpp/libs/llama-embedding.exe +0 -0
  26. bigdl/cpp/libs/llama-gguf.exe +0 -0
  27. bigdl/cpp/libs/llama-llava-cli.exe +0 -0
  28. bigdl/cpp/libs/llama-lookup.exe +0 -0
  29. bigdl/cpp/libs/llama-ls-sycl-device.exe +0 -0
  30. bigdl/cpp/libs/llama-minicpmv-cli.exe +0 -0
  31. bigdl/cpp/libs/llama-perplexity.exe +0 -0
  32. bigdl/cpp/libs/llama-quantize.exe +0 -0
  33. bigdl/cpp/libs/llama-server.exe +0 -0
  34. bigdl/cpp/libs/llama-simple.exe +0 -0
  35. bigdl/cpp/libs/llama-speculative.exe +0 -0
  36. bigdl/cpp/libs/llama-tokenize.exe +0 -0
  37. bigdl/cpp/libs/llama.dll +0 -0
  38. bigdl/cpp/libs/llava_shared.dll +0 -0
  39. bigdl/cpp/libs/ollama-ggml-base.dll +0 -0
  40. bigdl/cpp/libs/ollama-ggml-cpu.dll +0 -0
  41. bigdl/cpp/libs/ollama-ggml-sycl.dll +0 -0
  42. bigdl/cpp/libs/ollama-lib.exe +0 -0
  43. bigdl/cpp/libs/ollama.exe +0 -0
  44. bigdl/cpp/libs/ollama_ggml.dll +0 -0
  45. bigdl/cpp/libs/ollama_llama.dll +0 -0
  46. bigdl/cpp/libs/ollama_llava_shared.dll +0 -0
  47. {bigdl_core_cpp-2.1.0b20240820.post1.data → bigdl_core_cpp-2.2.0b20250217.post0.data}/scripts/init-llama-cpp.bat +7 -2
  48. bigdl_core_cpp-2.2.0b20250217.post0.data/scripts/init-ollama.bat +16 -0
  49. {bigdl_core_cpp-2.1.0b20240820.post1.dist-info → bigdl_core_cpp-2.2.0b20250217.post0.dist-info}/METADATA +9 -5
  50. bigdl_core_cpp-2.2.0b20250217.post0.dist-info/RECORD +56 -0
  51. {bigdl_core_cpp-2.1.0b20240820.post1.dist-info → bigdl_core_cpp-2.2.0b20250217.post0.dist-info}/WHEEL +1 -1
  52. bigdl/cpp/convert.py +0 -1714
  53. bigdl/cpp/libs/baby-llama.exe +0 -0
  54. bigdl/cpp/libs/batched-bench.exe +0 -0
  55. bigdl/cpp/libs/batched.exe +0 -0
  56. bigdl/cpp/libs/beam-search.exe +0 -0
  57. bigdl/cpp/libs/benchmark.exe +0 -0
  58. bigdl/cpp/libs/convert-llama2c-to-ggml.exe +0 -0
  59. bigdl/cpp/libs/dist/windows-amd64/ollama_runners/cpu/ollama_llama_server.exe +0 -0
  60. bigdl/cpp/libs/dist/windows-amd64/ollama_runners/cpu_avx/ollama_llama_server.exe +0 -0
  61. bigdl/cpp/libs/dist/windows-amd64/ollama_runners/cpu_avx2/ollama_llama_server.exe +0 -0
  62. bigdl/cpp/libs/embedding.exe +0 -0
  63. bigdl/cpp/libs/export-lora.exe +0 -0
  64. bigdl/cpp/libs/finetune.exe +0 -0
  65. bigdl/cpp/libs/ggml_shared.dll +0 -0
  66. bigdl/cpp/libs/gguf.exe +0 -0
  67. bigdl/cpp/libs/gritlm.exe +0 -0
  68. bigdl/cpp/libs/imatrix.exe +0 -0
  69. bigdl/cpp/libs/infill.exe +0 -0
  70. bigdl/cpp/libs/llava-cli.exe +0 -0
  71. bigdl/cpp/libs/lookahead.exe +0 -0
  72. bigdl/cpp/libs/lookup.exe +0 -0
  73. bigdl/cpp/libs/ls-sycl-device.exe +0 -0
  74. bigdl/cpp/libs/main.exe +0 -0
  75. bigdl/cpp/libs/parallel.exe +0 -0
  76. bigdl/cpp/libs/passkey.exe +0 -0
  77. bigdl/cpp/libs/perplexity.exe +0 -0
  78. bigdl/cpp/libs/q8dot.exe +0 -0
  79. bigdl/cpp/libs/quantize-stats.exe +0 -0
  80. bigdl/cpp/libs/quantize.exe +0 -0
  81. bigdl/cpp/libs/save-load-state.exe +0 -0
  82. bigdl/cpp/libs/server.exe +0 -0
  83. bigdl/cpp/libs/simple.exe +0 -0
  84. bigdl/cpp/libs/speculative.exe +0 -0
  85. bigdl/cpp/libs/tokenize.exe +0 -0
  86. bigdl/cpp/libs/train-text-from-scratch.exe +0 -0
  87. bigdl/cpp/libs/vdot.exe +0 -0
  88. bigdl_core_cpp-2.1.0b20240820.post1.data/scripts/init-ollama.bat +0 -13
  89. bigdl_core_cpp-2.1.0b20240820.post1.dist-info/RECORD +0 -63
  90. {bigdl_core_cpp-2.1.0b20240820.post1.data → bigdl_core_cpp-2.2.0b20250217.post0.data}/scripts/init-llama-cpp.ps1 +0 -0
  91. {bigdl_core_cpp-2.1.0b20240820.post1.dist-info → bigdl_core_cpp-2.2.0b20250217.post0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,376 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ # This script downloads the tokenizer models of the specified models from Huggingface and
5
+ # generates the get_vocab_base_pre() function for convert_hf_to_gguf.py
6
+ #
7
+ # This is necessary in order to analyze the type of pre-tokenizer used by the model and
8
+ # provide the necessary information to llama.cpp via the GGUF header in order to implement
9
+ # the same pre-tokenizer.
10
+ #
11
+ # ref: https://github.com/ggerganov/llama.cpp/pull/6920
12
+ #
13
+ # Instructions:
14
+ #
15
+ # - Add a new model to the "models" list
16
+ # - Run the script with your huggingface token:
17
+ #
18
+ # python3 convert_hf_to_gguf_update.py <huggingface_token>
19
+ #
20
+ # - The convert_hf_to_gguf.py script will have had its get_vocab_base_pre() function updated
21
+ # - Update llama.cpp with the new pre-tokenizer if necessary
22
+ #
23
+ # TODO: generate tokenizer tests for llama.cpp
24
+ #
25
+
26
+ import logging
27
+ import os
28
+ import pathlib
29
+ import re
30
+
31
+ import requests
32
+ import sys
33
+ import json
34
+ import shutil
35
+
36
+ from hashlib import sha256
37
+ from enum import IntEnum, auto
38
+ from transformers import AutoTokenizer
39
+
40
+ logging.basicConfig(level=logging.DEBUG)
41
+ logger = logging.getLogger("convert_hf_to_gguf_update")
42
+ sess = requests.Session()
43
+
44
+
45
+ class TOKENIZER_TYPE(IntEnum):
46
+ SPM = auto()
47
+ BPE = auto()
48
+ WPM = auto()
49
+ UGM = auto()
50
+
51
+
52
+ # TODO: this string has to exercise as much pre-tokenizer functionality as possible
53
+ # will be updated with time - contributions welcome
54
+ 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'
55
+
56
+ if len(sys.argv) == 2:
57
+ token = sys.argv[1]
58
+ if not token.startswith("hf_"):
59
+ logger.info("Huggingface token seems invalid")
60
+ logger.info("Usage: python convert_hf_to_gguf_update.py <huggingface_token>")
61
+ sys.exit(1)
62
+ else:
63
+ logger.info("Usage: python convert_hf_to_gguf_update.py <huggingface_token>")
64
+ sys.exit(1)
65
+
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": "bert-bge-large", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/BAAI/bge-large-zh-v1.5", },
76
+ {"name": "mpt", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/mosaicml/mpt-7b", },
77
+ {"name": "starcoder", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/bigcode/starcoder2-3b", },
78
+ {"name": "gpt-2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/openai-community/gpt2", },
79
+ {"name": "stablelm2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/stabilityai/stablelm-2-zephyr-1_6b", },
80
+ {"name": "refact", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/smallcloudai/Refact-1_6-base", },
81
+ {"name": "command-r", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/CohereForAI/c4ai-command-r-v01", },
82
+ {"name": "qwen2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/Qwen/Qwen1.5-7B", },
83
+ {"name": "olmo", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/allenai/OLMo-1.7-7B-hf", },
84
+ {"name": "dbrx", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/databricks/dbrx-base", },
85
+ {"name": "jina-v1-en", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/jinaai/jina-reranker-v1-tiny-en", },
86
+ {"name": "jina-v2-en", "tokt": TOKENIZER_TYPE.WPM, "repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-en", }, # WPM!
87
+ {"name": "jina-v2-es", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-es", },
88
+ {"name": "jina-v2-de", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-de", },
89
+ {"name": "smaug-bpe", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/abacusai/Smaug-Llama-3-70B-Instruct", },
90
+ {"name": "poro-chat", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/LumiOpen/Poro-34B-chat", },
91
+ {"name": "jina-v2-code", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/jinaai/jina-embeddings-v2-base-code", },
92
+ {"name": "viking", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/LumiOpen/Viking-7B", }, # Also used for Viking 13B and 33B
93
+ {"name": "gemma", "tokt": TOKENIZER_TYPE.SPM, "repo": "https://huggingface.co/google/gemma-2b", },
94
+ {"name": "gemma-2", "tokt": TOKENIZER_TYPE.SPM, "repo": "https://huggingface.co/google/gemma-2-9b", },
95
+ {"name": "jais", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/core42/jais-13b", },
96
+ {"name": "t5", "tokt": TOKENIZER_TYPE.UGM, "repo": "https://huggingface.co/google-t5/t5-small", },
97
+ {"name": "codeshell", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/WisdomShell/CodeShell-7B", },
98
+ {"name": "tekken", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/mistralai/Mistral-Nemo-Base-2407", },
99
+ {"name": "smollm", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/HuggingFaceTB/SmolLM-135M", },
100
+ {'name': "bloom", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/bigscience/bloom", },
101
+ {'name': "gpt3-finnish", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/TurkuNLP/gpt3-finnish-small", },
102
+ {"name": "exaone", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct", },
103
+ {"name": "phi-2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/microsoft/phi-2", },
104
+ {"name": "chameleon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/facebook/chameleon-7b", },
105
+ {"name": "minerva-7b", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/sapienzanlp/Minerva-7B-base-v1.0", },
106
+ {"name": "roberta-bpe", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/sentence-transformers/stsb-roberta-base"},
107
+ ]
108
+
109
+
110
+ def download_file_with_auth(url, token, save_path):
111
+ headers = {"Authorization": f"Bearer {token}"}
112
+ response = sess.get(url, headers=headers)
113
+ response.raise_for_status()
114
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
115
+ with open(save_path, 'wb') as downloaded_file:
116
+ downloaded_file.write(response.content)
117
+ logger.info(f"File {save_path} downloaded successfully")
118
+
119
+
120
+ def download_model(model):
121
+ name = model["name"]
122
+ repo = model["repo"]
123
+ tokt = model["tokt"]
124
+
125
+ os.makedirs(f"models/tokenizers/{name}", exist_ok=True)
126
+
127
+ files = ["config.json", "tokenizer.json", "tokenizer_config.json"]
128
+
129
+ if tokt == TOKENIZER_TYPE.SPM:
130
+ files.append("tokenizer.model")
131
+
132
+ if tokt == TOKENIZER_TYPE.UGM:
133
+ files.append("spiece.model")
134
+
135
+ if os.path.isdir(repo):
136
+ # If repo is a path on the file system, copy the directory
137
+ for file in files:
138
+ src_path = os.path.join(repo, file)
139
+ dst_path = f"models/tokenizers/{name}/{file}"
140
+ if os.path.isfile(dst_path):
141
+ logger.info(f"{name}: File {dst_path} already exists - skipping")
142
+ continue
143
+ if os.path.isfile(src_path):
144
+ shutil.copy2(src_path, dst_path)
145
+ logger.info(f"{name}: Copied {src_path} to {dst_path}")
146
+ else:
147
+ logger.warning(f"{name}: Source file {src_path} does not exist")
148
+ else:
149
+ # If repo is a URL, download the files
150
+ for file in files:
151
+ save_path = f"models/tokenizers/{name}/{file}"
152
+ if os.path.isfile(save_path):
153
+ logger.info(f"{name}: File {save_path} already exists - skipping")
154
+ continue
155
+ download_file_with_auth(f"{repo}/resolve/main/{file}", token, save_path)
156
+
157
+
158
+ for model in models:
159
+ try:
160
+ download_model(model)
161
+ except Exception as e:
162
+ logger.error(f"Failed to download model {model['name']}. Error: {e}")
163
+
164
+
165
+ # generate the source code for the convert_hf_to_gguf.py:get_vocab_base_pre() function:
166
+
167
+ src_ifs = ""
168
+ for model in models:
169
+ name = model["name"]
170
+ tokt = model["tokt"]
171
+
172
+ if tokt == TOKENIZER_TYPE.SPM or tokt == TOKENIZER_TYPE.UGM:
173
+ continue
174
+
175
+ # Skip if the tokenizer folder does not exist or there are other download issues previously
176
+ if not os.path.exists(f"models/tokenizers/{name}"):
177
+ logger.warning(f"Directory for tokenizer {name} not found. Skipping...")
178
+ continue
179
+
180
+ # create the tokenizer
181
+ try:
182
+ if name == "t5":
183
+ tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}", use_fast=False)
184
+ else:
185
+ tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}")
186
+ except OSError as e:
187
+ logger.error(f"Error loading tokenizer for model {name}. The model may not exist or is not accessible with the provided token. Error: {e}")
188
+ continue # Skip to the next model if the tokenizer can't be loaded
189
+
190
+ chktok = tokenizer.encode(CHK_TXT)
191
+ chkhsh = sha256(str(chktok).encode()).hexdigest()
192
+
193
+ logger.info(f"model: {name}")
194
+ logger.info(f"tokt: {tokt}")
195
+ logger.info(f"repo: {model['repo']}")
196
+ logger.info(f"chktok: {chktok}")
197
+ logger.info(f"chkhsh: {chkhsh}")
198
+
199
+ # print the "pre_tokenizer" content from the tokenizer.json
200
+ with open(f"models/tokenizers/{name}/tokenizer.json", "r", encoding="utf-8") as f:
201
+ cfg = json.load(f)
202
+ normalizer = cfg["normalizer"]
203
+ logger.info("normalizer: " + json.dumps(normalizer, indent=4))
204
+ pre_tokenizer = cfg["pre_tokenizer"]
205
+ logger.info("pre_tokenizer: " + json.dumps(pre_tokenizer, indent=4))
206
+ if "ignore_merges" in cfg["model"]:
207
+ logger.info("ignore_merges: " + json.dumps(cfg["model"]["ignore_merges"], indent=4))
208
+
209
+ logger.info("")
210
+
211
+ src_ifs += f" if chkhsh == \"{chkhsh}\":\n"
212
+ src_ifs += f" # ref: {model['repo']}\n"
213
+ src_ifs += f" res = \"{name}\"\n"
214
+
215
+ src_func = f"""
216
+ def get_vocab_base_pre(self, tokenizer) -> str:
217
+ # encoding this string and hashing the resulting tokens would (hopefully) give us a unique identifier that
218
+ # is specific for the BPE pre-tokenizer used by the model
219
+ # we will use this unique identifier to write a "tokenizer.ggml.pre" entry in the GGUF file which we can
220
+ # use in llama.cpp to implement the same pre-tokenizer
221
+
222
+ chktxt = {repr(CHK_TXT)}
223
+
224
+ chktok = tokenizer.encode(chktxt)
225
+ chkhsh = sha256(str(chktok).encode()).hexdigest()
226
+
227
+ logger.debug(f"chktok: {{chktok}}")
228
+ logger.debug(f"chkhsh: {{chkhsh}}")
229
+
230
+ res = None
231
+
232
+ # NOTE: if you get an error here, you need to update the convert_hf_to_gguf_update.py script
233
+ # or pull the latest version of the model from Huggingface
234
+ # don't edit the hashes manually!
235
+ {src_ifs}
236
+ if res is None:
237
+ logger.warning("\\n")
238
+ logger.warning("**************************************************************************************")
239
+ logger.warning("** WARNING: The BPE pre-tokenizer was not recognized!")
240
+ logger.warning("** There are 2 possible reasons for this:")
241
+ logger.warning("** - the model has not been added to convert_hf_to_gguf_update.py yet")
242
+ logger.warning("** - the pre-tokenization config has changed upstream")
243
+ logger.warning("** Check your model files and convert_hf_to_gguf_update.py and update them accordingly.")
244
+ logger.warning("** ref: https://github.com/ggerganov/llama.cpp/pull/6920")
245
+ logger.warning("**")
246
+ logger.warning(f"** chkhsh: {{chkhsh}}")
247
+ logger.warning("**************************************************************************************")
248
+ logger.warning("\\n")
249
+ raise NotImplementedError("BPE pre-tokenizer was not recognized - update get_vocab_base_pre()")
250
+
251
+ logger.debug(f"tokenizer.ggml.pre: {{repr(res)}}")
252
+ logger.debug(f"chkhsh: {{chkhsh}}")
253
+
254
+ return res
255
+ """
256
+
257
+ convert_py_pth = pathlib.Path("convert_hf_to_gguf.py")
258
+ convert_py = convert_py_pth.read_text(encoding="utf-8")
259
+ convert_py = re.sub(
260
+ r"(# Marker: Start get_vocab_base_pre)(.+?)( +# Marker: End get_vocab_base_pre)",
261
+ lambda m: m.group(1) + src_func + m.group(3),
262
+ convert_py,
263
+ flags=re.DOTALL | re.MULTILINE,
264
+ )
265
+
266
+ convert_py_pth.write_text(convert_py, encoding="utf-8")
267
+
268
+ logger.info("+++ convert_hf_to_gguf.py was updated")
269
+
270
+ # generate tests for each tokenizer model
271
+
272
+ tests = [
273
+ "ied 4 ½ months",
274
+ "Führer",
275
+ "",
276
+ " ",
277
+ " ",
278
+ " ",
279
+ "\t",
280
+ "\n",
281
+ "\n\n",
282
+ "\n\n\n",
283
+ "\t\n",
284
+ "Hello world",
285
+ " Hello world",
286
+ "Hello World",
287
+ " Hello World",
288
+ " Hello World!",
289
+ "Hello, world!",
290
+ " Hello, world!",
291
+ " this is 🦙.cpp",
292
+ "w048 7tuijk dsdfhu",
293
+ "нещо на Български",
294
+ "កាន់តែពិសេសអាចខលចេញ",
295
+ "🚀 (normal) 😶‍🌫️ (multiple emojis concatenated) ✅ (only emoji that has its own token)",
296
+ "Hello",
297
+ " Hello",
298
+ " Hello",
299
+ " Hello",
300
+ " Hello",
301
+ " Hello\n Hello",
302
+ " (",
303
+ "\n =",
304
+ "' era",
305
+ "Hello, y'all! How are you 😁 ?我想在apple工作1314151天~",
306
+ "!!!!!!",
307
+ "3",
308
+ "33",
309
+ "333",
310
+ "3333",
311
+ "33333",
312
+ "333333",
313
+ "3333333",
314
+ "33333333",
315
+ "333333333",
316
+ "Cửa Việt", # llama-bpe fails on this
317
+ " discards",
318
+ CHK_TXT,
319
+ ]
320
+
321
+ # write the tests to ./models/ggml-vocab-{name}.gguf.inp
322
+ # the format is:
323
+ #
324
+ # test0
325
+ # __ggml_vocab_test__
326
+ # test1
327
+ # __ggml_vocab_test__
328
+ # ...
329
+ #
330
+
331
+ # with each model, encode all tests and write the results in ./models/ggml-vocab-{name}.gguf.out
332
+ # for each test, write the resulting tokens on a separate line
333
+
334
+ for model in models:
335
+ name = model["name"]
336
+ tokt = model["tokt"]
337
+
338
+ # Skip if the tokenizer folder does not exist or there are other download issues previously
339
+ if not os.path.exists(f"models/tokenizers/{name}"):
340
+ logger.warning(f"Directory for tokenizer {name} not found. Skipping...")
341
+ continue
342
+
343
+ # create the tokenizer
344
+ try:
345
+ if name == "t5":
346
+ tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}", use_fast=False)
347
+ else:
348
+ tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}")
349
+ except OSError as e:
350
+ logger.error(f"Failed to load tokenizer for model {name}. Error: {e}")
351
+ continue # Skip this model and continue with the next one in the loop
352
+
353
+ with open(f"models/ggml-vocab-{name}.gguf.inp", "w", encoding="utf-8") as f:
354
+ for text in tests:
355
+ f.write(f"{text}")
356
+ f.write("\n__ggml_vocab_test__\n")
357
+
358
+ with open(f"models/ggml-vocab-{name}.gguf.out", "w") as f:
359
+ for text in tests:
360
+ res = tokenizer.encode(text, add_special_tokens=False)
361
+ for r in res:
362
+ f.write(f" {r}")
363
+ f.write("\n")
364
+
365
+ logger.info(f"Tests for {name} written in ./models/ggml-vocab-{name}.gguf.*")
366
+
367
+ # generate commands for creating vocab files
368
+
369
+ logger.info("\nRun the following commands to generate the vocab files for testing:\n")
370
+
371
+ for model in models:
372
+ name = model["name"]
373
+
374
+ print(f"python3 convert_hf_to_gguf.py models/tokenizers/{name}/ --outfile models/ggml-vocab-{name}.gguf --vocab-only") # noqa: NP100
375
+
376
+ logger.info("\n")