eson commited on
Commit
480ae5d
1 Parent(s): 814ee6b

add grok mixtral

Browse files
.gitattributes CHANGED
@@ -39,3 +39,7 @@ vocab/gemma_7b/gemma-7b/tokenizer.model filter=lfs diff=lfs merge=lfs -text
39
  vocab/gemma_7b/gemma-7b/tokenizer.json filter=lfs diff=lfs merge=lfs -text
40
  vocab/grok_1/tokenizer.model filter=lfs diff=lfs merge=lfs -text
41
  vocab/llama3/Meta-Llama-3-70B/tokenizer.json filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
39
  vocab/gemma_7b/gemma-7b/tokenizer.json filter=lfs diff=lfs merge=lfs -text
40
  vocab/grok_1/tokenizer.model filter=lfs diff=lfs merge=lfs -text
41
  vocab/llama3/Meta-Llama-3-70B/tokenizer.json filter=lfs diff=lfs merge=lfs -text
42
+ vocab/mistral_7b/Mistral-7B-v0.1/tokenizer.json filter=lfs diff=lfs merge=lfs -text
43
+ vocab/mistral_7b/Mistral-7B-v0.1/tokenizer.model filter=lfs diff=lfs merge=lfs -text
44
+ vocab/mixtral_8_7b/Mixtral-8x7B-v0.1/tokenizer.json filter=lfs diff=lfs merge=lfs -text
45
+ vocab/mixtral_8_7b/Mixtral-8x7B-v0.1/tokenizer.model filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -35,31 +35,26 @@ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-
35
  https://huggingface.co/spaces/yenniejun/tokenizers-languages
36
 
37
 
38
- ## gradio app
39
-
40
- - https://arena.lmsys.org/
41
-
42
-
43
- ## lang
44
-
45
-
46
-
47
- ## number
48
 
 
49
 
50
 
51
- ## diff
52
 
 
 
 
 
53
 
54
 
55
 
56
 
57
 
58
- ## Compress Rate
 
59
 
60
 
61
- **简介**
62
- we tokenize in cc-100
63
 
64
  | tokenizer | vocab_size | g_bytes/b_tokens | t_bytes/t_tokens | b_tokens/g_bytes |
65
  |:----------------------------|-------------:|-------------------:|-------------------:|-------------------:|
 
35
  https://huggingface.co/spaces/yenniejun/tokenizers-languages
36
 
37
 
 
 
 
 
 
 
 
 
 
 
38
 
39
+ ## Compress Rate
40
 
41
 
42
+ [cc-100](https://huggingface.co/datasets/cc100) 数据集,每个语言取1万条数据,测试不同tokenizer的压缩率。压缩率指标 `g_bytes/b_tokens`
43
 
44
+ 您可通过以下脚本进行复现
45
+ ```sh
46
+ python utils/compress_rate_util.py
47
+ ```
48
 
49
 
50
 
51
 
52
 
53
+ <details> <summary>简体中文压缩率</summary>
54
+ 在简体中文数据集 cc100-zh-Hans 计算压缩率
55
 
56
 
57
+ </details>
 
58
 
59
  | tokenizer | vocab_size | g_bytes/b_tokens | t_bytes/t_tokens | b_tokens/g_bytes |
60
  |:----------------------------|-------------:|-------------------:|-------------------:|-------------------:|
app.py CHANGED
@@ -59,7 +59,6 @@ with gr.Blocks(css="css/style.css", title="Tokenizer Arena") as demo:
59
  gr.Markdown("## Input Text")
60
  dropdown_examples = gr.Dropdown(
61
  example_types,
62
- value="Examples",
63
  type="index",
64
  show_label=False,
65
  container=False,
 
59
  gr.Markdown("## Input Text")
60
  dropdown_examples = gr.Dropdown(
61
  example_types,
 
62
  type="index",
63
  show_label=False,
64
  container=False,
config.py CHANGED
@@ -9,4 +9,12 @@ ADD_SPECIAL_TOKEN = False
9
  LAZY_IMPORT = True
10
 
11
  # DEBUG: 设置环境变量 RUST_BACKTRACE=full
12
- #
 
 
 
 
 
 
 
 
 
9
  LAZY_IMPORT = True
10
 
11
  # DEBUG: 设置环境变量 RUST_BACKTRACE=full
12
+ #
13
+
14
+ default_user_input = """\
15
+ Replace this text in the input field to see how tokenization works.
16
+ Buenos días!
17
+ 华为发布Mate60手机。
18
+ ラグビーワールドカップ2023フランス"""
19
+ default_tokenizer_type_1 = "llama3"
20
+ default_tokenizer_type_2 = "gpt4"
evaluation.md DELETED
@@ -1,5 +0,0 @@
1
-
2
-
3
- ## coverage
4
-
5
- rare characters falling back to utf-8 bytes
 
 
 
 
 
 
examples.py CHANGED
@@ -24,7 +24,7 @@ examples = {
24
  # !?。"#$%&'()*+,-/:;<=>@[\]^_`{|}~⦅⦆「」、、〃》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘’‛“”„‟…‧﹏.
25
  ["punctuation: ,.:/?+=\",。!?;【】〔〕〖〗", "gemma_7b", "llama"], # llama词典有点小
26
  ["symbol: 🦙❤❥웃유♋☮✊☏☢☚✔☑♚▢♪✈✞÷↑↓▤▥⊙■□▣▽¿─│♥❣▬▫☿Ⓐ ✋✉☣☤", "baichuan", "llama"],
27
- ["special: [PAD] [UNK] [CLS] [SEP] [MASK] "],
28
  ],
29
  "zh": [
30
  ["空格测试: 2个空格 8个空格", "llama", "chatglm2_6b"], # chatglm 有blank_n,
@@ -36,15 +36,16 @@ examples = {
36
  }
37
 
38
  more_examples = [
39
- # bert VS clue
40
  # bert系列
41
- ("bert_base_cased", "bert_base_uncased", ""), # # clue VS kplug, bert VS clue
42
- ("bert_base_cased", "clue", ""),
 
43
 
44
  # llama系列 (基于sentencepiece)
45
  ("baichuan", "baichuan2", "baichuan2支持多空格 ,多个换行\n\n\n,do not add dummy prefix as Baichuan1"),
46
  ("llama", "baichuan2", "baichuan2支持多空格 ,多个换行\n\n"),
47
  ("llama", "chinese_llama2", ""),
 
48
  ("chinese_llama", "chinese_llama2", ""),
49
 
50
  # glm系列 (基于sentencepiece)
@@ -72,7 +73,7 @@ def example_fn(example_idx):
72
  def get_more_example():
73
  import urllib.parse
74
  url_prefix = "https://huggingface.co/spaces/eson/tokenizer-arena"
75
- for tokenizer1, tokenizer2, text in more_examples:
76
  full_url = f'{url_prefix}?tokenizer1={tokenizer1}&tokenizer2={tokenizer2}&text={urllib.parse.quote(text)}'
77
  print(full_url)
78
 
 
24
  # !?。"#$%&'()*+,-/:;<=>@[\]^_`{|}~⦅⦆「」、、〃》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘’‛“”„‟…‧﹏.
25
  ["punctuation: ,.:/?+=\",。!?;【】〔〕〖〗", "gemma_7b", "llama"], # llama词典有点小
26
  ["symbol: 🦙❤❥웃유♋☮✊☏☢☚✔☑♚▢♪✈✞÷↑↓▤▥⊙■□▣▽¿─│♥❣▬▫☿Ⓐ ✋✉☣☤", "baichuan", "llama"],
27
+ # ["special: [PAD] [UNK] [CLS] [SEP] [MASK] <|endoftext|>", "", ""],
28
  ],
29
  "zh": [
30
  ["空格测试: 2个空格 8个空格", "llama", "chatglm2_6b"], # chatglm 有blank_n,
 
36
  }
37
 
38
  more_examples = [
 
39
  # bert系列
40
+ ("bert_base_cased", "bert_base_uncased", "", ""), # # clue VS kplug, bert VS clue
41
+ ("bert_base_cased", "clue", "", "增加了[]()"),
42
+ ("clue", "kplug", "", ""),
43
 
44
  # llama系列 (基于sentencepiece)
45
  ("baichuan", "baichuan2", "baichuan2支持多空格 ,多个换行\n\n\n,do not add dummy prefix as Baichuan1"),
46
  ("llama", "baichuan2", "baichuan2支持多空格 ,多个换行\n\n"),
47
  ("llama", "chinese_llama2", ""),
48
+ ("llama", "llama3", "扩充词典"),
49
  ("chinese_llama", "chinese_llama2", ""),
50
 
51
  # glm系列 (基于sentencepiece)
 
73
  def get_more_example():
74
  import urllib.parse
75
  url_prefix = "https://huggingface.co/spaces/eson/tokenizer-arena"
76
+ for tokenizer1, tokenizer2, text, comment in more_examples:
77
  full_url = f'{url_prefix}?tokenizer1={tokenizer1}&tokenizer2={tokenizer2}&text={urllib.parse.quote(text)}'
78
  print(full_url)
79
 
js/onload.js CHANGED
@@ -3,10 +3,16 @@ function() {
3
  //$("footer a")["href"] = "https://github.com/xu-song/tokenizer-arena/issues"
4
  //$("footer a").childNodes[0].textContent ="Send Feedback"
5
 
6
- document.querySelectorAll("footer a")[0].childNodes[0].textContent ="Send Feedback"; // 🤔Reporting Issues
 
 
 
 
 
7
  document.querySelectorAll("footer a")[0].href = "https://github.com/xu-song/tokenizer-arena/issues";
8
 
9
  // download button
10
 
11
  // API
 
12
  }
 
3
  //$("footer a")["href"] = "https://github.com/xu-song/tokenizer-arena/issues"
4
  //$("footer a").childNodes[0].textContent ="Send Feedback"
5
 
6
+
7
+ // <a href="https://gradio.app" class="built-with svelte-16bt5n8" target="_blank" rel="noreferrer">
8
+ // Built with Gradio <img src="http://127.0.0.1:7860/assets/logo-3707f936.svg" alt="logo" class="svelte-16bt5n8">
9
+ // </a>
10
+ console.log("nice")
11
+ document.querySelectorAll("footer a")[0].childNodes[0].textContent ="Send Feedback"; // 🤔Reporting Issues, 💬Leave comments
12
  document.querySelectorAll("footer a")[0].href = "https://github.com/xu-song/tokenizer-arena/issues";
13
 
14
  // download button
15
 
16
  // API
17
+ return 'Animation created';
18
  }
util.py CHANGED
@@ -117,14 +117,6 @@ def get_overlap_token_size(tokenizer_type_1, tokenizer_type_2):
117
  return overlap_token_size, overlap_token_size
118
 
119
 
120
- default_user_input = """Replace this text in the input field to see how tokenization works.
121
- Buenos días!
122
- 华为发布Mate60手机。
123
- ラグビーワールドカップ2023フランス"""
124
- default_tokenizer_type_1 = "llama"
125
- # default_tokenizer_type_2 = "internlm_chat_7b"
126
- default_tokenizer_type_2 = "gpt_35_turbo"
127
-
128
 
129
  def on_load(url_params, request: gr.Request):
130
  """
@@ -148,9 +140,9 @@ def on_load(url_params, request: gr.Request):
148
  # if "referer" in request.headers: # not work for huggingface-space
149
  # url_params = parse_qs(urlparse(request.headers["referer"]).query)
150
  # url_params = {k: v[0] for k, v in url_params.items() if len(v) > 0}
151
- tokenizer_type_1 = url_params.get("tokenizer1", default_tokenizer_type_1)
152
- tokenizer_type_2 = url_params.get("tokenizer2", default_tokenizer_type_2)
153
- text = url_params.get("text", default_user_input)
154
  logger.info(f"client_ip: {client_ip}; params: {url_params}")
155
  return text, tokenizer_type_1, tokenizer_type_2
156
 
 
117
  return overlap_token_size, overlap_token_size
118
 
119
 
 
 
 
 
 
 
 
 
120
 
121
  def on_load(url_params, request: gr.Request):
122
  """
 
140
  # if "referer" in request.headers: # not work for huggingface-space
141
  # url_params = parse_qs(urlparse(request.headers["referer"]).query)
142
  # url_params = {k: v[0] for k, v in url_params.items() if len(v) > 0}
143
+ tokenizer_type_1 = url_params.get("tokenizer1", config.default_tokenizer_type_1)
144
+ tokenizer_type_2 = url_params.get("tokenizer2", config.default_tokenizer_type_2)
145
+ text = url_params.get("text", config.default_user_input)
146
  logger.info(f"client_ip: {client_ip}; params: {url_params}")
147
  return text, tokenizer_type_1, tokenizer_type_2
148
 
utils/compress_rate_util.py CHANGED
@@ -99,7 +99,7 @@ def pprint(stats):
99
  table.append(columns)
100
  df = pd.DataFrame(table)
101
  # print(df.to_markdown(index=False, tablefmt='fancy_grid'))
102
- logger.info(df.to_markdown(index=False))
103
  return
104
 
105
 
@@ -167,8 +167,8 @@ def main():
167
  for lang in ["en", "zh-Hans"]:
168
  print("###" * 10 + lang)
169
 
170
- for tokenizer_name in ['llama', 'llama2', 'llama3']:
171
- # for tokenizer_name in all_tokenizers:
172
  tokenizer = load_tokener(tokenizer_name)
173
  stat = tokenize_corpus(tokenizer, lang)
174
  # ["qwen1_5_14b_chat", "gpt_35_turbo",]:
 
99
  table.append(columns)
100
  df = pd.DataFrame(table)
101
  # print(df.to_markdown(index=False, tablefmt='fancy_grid'))
102
+ logger.info("\n{df.to_markdown(index=False)}")
103
  return
104
 
105
 
 
167
  for lang in ["en", "zh-Hans"]:
168
  print("###" * 10 + lang)
169
 
170
+ # for tokenizer_name in ['llama', 'llama2', 'llama3']:
171
+ for tokenizer_name in all_tokenizers:
172
  tokenizer = load_tokener(tokenizer_name)
173
  stat = tokenize_corpus(tokenizer, lang)
174
  # ["qwen1_5_14b_chat", "gpt_35_turbo",]:
vocab/code_davinci_002/__init__.py CHANGED
@@ -1,3 +1,5 @@
1
 
 
 
2
 
3
- from vocab.text_davinci_003 import tokenizer
 
1
 
2
+ import copy
3
+ from vocab.text_davinci_003 import tokenizer as base_tokenizer
4
 
5
+ tokenizer = copy.copy(base_tokenizer)
vocab/dbrx_instruct/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ from transformers import AutoTokenizer
4
+
5
+ CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
6
+ TOKENIZER_DIR = os.path.join(CURRENT_DIR, "dbrx-instruct")
7
+ tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_DIR, trust_remote_code=True)
8
+
vocab/dbrx_instruct/dbrx-instruct/added_tokens.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "<|im_end|>": 100279,
3
+ "<|im_start|>": 100278,
4
+ "<|pad|>": 100277
5
+ }
vocab/dbrx_instruct/dbrx-instruct/special_tokens_map.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>"
5
+ ],
6
+ "bos_token": {
7
+ "content": "<|endoftext|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false
12
+ },
13
+ "eos_token": {
14
+ "content": "<|endoftext|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ },
20
+ "pad_token": {
21
+ "content": "<|pad|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false
26
+ },
27
+ "unk_token": {
28
+ "content": "<|endoftext|>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false
33
+ }
34
+ }
vocab/dbrx_instruct/dbrx-instruct/tiktoken.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dbrx tokenizer."""
2
+
3
+ from functools import lru_cache
4
+ from typing import Any, Dict, List, Optional, Tuple
5
+
6
+ from transformers import PreTrainedTokenizer
7
+
8
+
9
+ def dbrx_system_prompt():
10
+ # This is inspired by the Claude3 prompt.
11
+ # source: https://twitter.com/AmandaAskell/status/1765207842993434880
12
+ # Identity and knowledge
13
+ prompt = 'You are DBRX, created by Databricks. You were last updated in December 2023. You answer questions based on information available up to that point.\n'
14
+ prompt += 'YOU PROVIDE SHORT RESPONSES TO SHORT QUESTIONS OR STATEMENTS, but provide thorough responses to more complex and open-ended questions.\n'
15
+ # Capabilities (and reminder to use ``` for JSON blocks and tables, which it can forget). Also a reminder that it can't browse the internet or run code.
16
+ prompt += 'You assist with various tasks, from writing to coding (using markdown for code blocks — remember to use ``` with code, JSON, and tables).\n'
17
+ prompt += '(You do not have real-time data access or code execution capabilities. '
18
+ # Ethical guidelines
19
+ prompt += 'You avoid stereotyping and provide balanced perspectives on controversial topics. '
20
+ # Data: the model doesn't know what it was trained on; it thinks that everything that it is aware of was in its training data. This is a reminder that it wasn't.
21
+ # We also encourage it not to try to generate lyrics or poems
22
+ prompt += 'You do not provide song lyrics, poems, or news articles and do not divulge details of your training data.)\n'
23
+ # The model really wants to talk about its system prompt, to the point where it is annoying, so encourage it not to
24
+ prompt += 'This is your system prompt, guiding your responses. Do not reference it, just respond to the user. If you find yourself talking about this message, stop. You should be responding appropriately and usually that means not mentioning this.\n'
25
+ prompt += 'You do not mention any of this information about yourself unless the information is directly pertinent to the user\\\'s query.'.upper()
26
+ return prompt
27
+
28
+
29
+ # Taken from
30
+ # https://github.com/huggingface/transformers/blob/8aca43bdb3cb9a5020f6d57589d85679dc873b1c/src/transformers/models/gpt2/tokenization_gpt2.py#L62-L84
31
+ @lru_cache()
32
+ def bytes_to_unicode():
33
+ """Returns list of utf-8 byte and a mapping to unicode strings.
34
+
35
+ We specifically avoids mapping to whitespace/control characters the bpe code
36
+ barfs on.
37
+
38
+ The reversible bpe codes work on unicode strings. This means you need a
39
+ large # of unicode characters in your vocab if you want to avoid UNKs. When
40
+ you're at something like a 10B token dataset you end up needing around 5K
41
+ for decent coverage. This is a significant percentage of your normal, say,
42
+ 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and
43
+ unicode strings.
44
+ """
45
+ bs = (list(range(ord('!'),
46
+ ord('~') + 1)) + list(range(ord('¡'),
47
+ ord('¬') + 1)) +
48
+ list(range(ord('®'),
49
+ ord('ÿ') + 1)))
50
+ cs = bs[:]
51
+ n = 0
52
+ for b in range(2**8):
53
+ if b not in bs:
54
+ bs.append(b)
55
+ cs.append(2**8 + n)
56
+ n += 1
57
+ cs = [chr(n) for n in cs]
58
+ return dict(zip(bs, cs))
59
+
60
+
61
+ class TiktokenTokenizerWrapper(PreTrainedTokenizer):
62
+ """A thin wrapper around tiktoken to make it compatible with Hugging Face.
63
+
64
+ tokenizers.
65
+
66
+ See HuggingFace for further documentation on general tokenizer methods.
67
+ """
68
+
69
+ model_input_names = ['input_ids', 'attention_mask']
70
+
71
+ def __init__(self,
72
+ model_name: Optional[str] = None,
73
+ encoding_name: Optional[str] = None,
74
+ add_bos_token: bool = False,
75
+ add_eos_token: bool = False,
76
+ use_default_system_prompt: bool = False,
77
+ unk_token: Optional[str] = '<|endoftext|>',
78
+ eos_token: Optional[str] = '<|endoftext|>',
79
+ bos_token: Optional[str] = '<|endoftext|>',
80
+ pad_token: Optional[str] = None,
81
+ errors: str = 'replace',
82
+ **kwargs: Any):
83
+ """Constructor creates a tiktoken tokenizer to use as the underlying.
84
+
85
+ tokenizer.
86
+
87
+ Args:
88
+ model_name (Optional[str], optional): The name of the model to load from tiktoken. Defaults to None.
89
+ Either model_name or encoding_name must be set, but not both.
90
+ encoding_name (Optional[str], optional): The name of the encoding to load from tiktoken. Defaults to None.
91
+ Either model_name or encoding_name must be set, but not both.
92
+ add_bos_token (bool, optional): Whether to add bos tokens. Defaults to False.
93
+ add_eos_token (bool, optional): Whether to add eos tokens. Defaults to False.
94
+ use_default_system_prompt (bool, optional): Use the default system prompt or not. Defaults to False.
95
+ unk_token (Optional[str], optional): The unk token. Defaults to '<|endoftext|>'.
96
+ eos_token (Optional[str], optional): The eos token. Defaults to '<|endoftext|>'.
97
+ bos_token (Optional[str], optional): The bos token. Defaults to '<|endoftext|>'.
98
+ pad_token (Optional[str], optional): The pad token. Defaults to None.
99
+ errors (str, optional): Paradigm to follow when decoding bytes to UTF-8. See
100
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
101
+ Defaults to `"replace"`.
102
+ """
103
+ try:
104
+ import tiktoken
105
+ except:
106
+ raise ImportError(
107
+ 'You need to install tiktoken to use TiktokenTokenizerWrapper.')
108
+
109
+ # Workaround to make tiktokenizer picklable.
110
+ # https://github.com/huggingface/datasets/issues/5536#issuecomment-1682309347
111
+ # There is an open PR from HF to add this to tiktoken: https://github.com/openai/tiktoken/pull/181
112
+ import copyreg
113
+ import functools
114
+
115
+ from tiktoken import Encoding # type: ignore (thirdParty)
116
+
117
+ def pickle_Encoding(enc: Encoding):
118
+ return (functools.partial(Encoding,
119
+ enc.name,
120
+ pat_str=enc._pat_str,
121
+ mergeable_ranks=enc._mergeable_ranks,
122
+ special_tokens=enc._special_tokens), ())
123
+
124
+ copyreg.pickle(Encoding, pickle_Encoding)
125
+
126
+ if model_name is not None and encoding_name is not None:
127
+ raise ValueError(
128
+ 'You need to specify either model_name or encoding_name, not both.'
129
+ )
130
+
131
+ self.model_name = model_name
132
+ self.encoding_name = encoding_name
133
+
134
+ if self.model_name is not None:
135
+ self.encoding = tiktoken.encoding_for_model( # type: ignore (thirdParty)
136
+ self.model_name)
137
+ elif self.encoding_name is not None:
138
+ self.encoding = tiktoken.get_encoding( # type: ignore (thirdParty)
139
+ self.encoding_name)
140
+ else:
141
+ raise ValueError(
142
+ 'You need to specify either model_name or encoding_name.')
143
+
144
+ self.add_bos_token = add_bos_token
145
+ self.add_eos_token = add_eos_token
146
+ self.use_default_system_prompt = use_default_system_prompt
147
+
148
+ self.byte_encoder = bytes_to_unicode()
149
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
150
+ self.errors = errors
151
+
152
+ self.decoder: Dict[int, str] = {}
153
+ for i in range(self.encoding.n_vocab):
154
+ try:
155
+ self.encoding.decode_single_token_bytes(i)
156
+ except KeyError:
157
+ continue
158
+ # Taken from
159
+ # https://gist.github.com/xenova/a452a6474428de0182b17605a98631ee
160
+ decoding = ''.join([
161
+ bytes_to_unicode()[ord(char)] for char in
162
+ self.encoding.decode_single_token_bytes(i).decode('latin-1')
163
+ ])
164
+ self.decoder[i] = decoding
165
+
166
+ self.encoder: Dict[str, int] = {}
167
+ for i in range(self.encoding.n_vocab):
168
+ if i in self.decoder:
169
+ self.encoder[self.decoder[i]] = i
170
+
171
+ super().__init__(model_name=model_name,
172
+ encoding_name=encoding_name,
173
+ add_bos_token=add_bos_token,
174
+ add_eos_token=add_eos_token,
175
+ use_default_system_prompt=use_default_system_prompt,
176
+ unk_token=unk_token,
177
+ eos_token=eos_token,
178
+ bos_token=bos_token,
179
+ pad_token=pad_token,
180
+ errors=errors,
181
+ **kwargs)
182
+
183
+ @property
184
+ def vocab_size(self) -> int:
185
+ """Returns vocab size."""
186
+ return self.encoding.n_vocab
187
+
188
+ @property
189
+ def is_fast(self) -> bool:
190
+ return False
191
+
192
+ @property
193
+ def default_chat_template(self):
194
+ """Chat ML Template for User/Assistant.
195
+
196
+ Pinning default Chat ML template in case defaults change.
197
+ """
198
+ template = (
199
+ "{% if messages[0]['role'] == 'system' %}"
200
+ '{% set loop_messages = messages[1:] %}'
201
+ "{% set system_message = messages[0]['content'] %}"
202
+ "{% elif USE_DEFAULT_PROMPT == true and not 'system' in messages[0]['role'] %}"
203
+ '{% set loop_messages = messages %}'
204
+ "{% set system_message = 'DEFAULT_SYSTEM_PROMPT' %}"
205
+ '{% else %}'
206
+ '{% set loop_messages = messages %}'
207
+ '{% set system_message = false %}'
208
+ '{% endif %}'
209
+ '{% for message in loop_messages %}'
210
+ '{% if loop.index0 == 0 %}'
211
+ '{% if system_message != false %}'
212
+ "{{ '<|im_start|>system\n' + system_message.strip() + '<|im_end|>\n'}}"
213
+ '{% endif %}'
214
+ "{{ '<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' }}"
215
+ '{% else %}'
216
+ "{{ '\n' + '<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' }}"
217
+ '{% endif %}'
218
+ '{% if (add_generation_prompt == true and loop.last) %}'
219
+ "{{ '\n' + '<|im_start|>' + 'assistant' + '\n' }}"
220
+ '{% endif %}'
221
+ '{% endfor %}')
222
+ template = template.replace(
223
+ 'USE_DEFAULT_PROMPT',
224
+ 'true' if self.use_default_system_prompt else 'false')
225
+ template = template.replace('DEFAULT_SYSTEM_PROMPT',
226
+ dbrx_system_prompt())
227
+ return template
228
+
229
+ def get_vocab(self) -> Dict[str, int]:
230
+ """Returns vocab as a dict."""
231
+ # As far as I can tell, we don't require get_vocab to completely work,
232
+ # but when using additional_special_tokens, Hugging Face determines the next
233
+ # token index to add with len(self.get_vocab()) so we need the _size_ of this dictionary to be correct.
234
+ vocab_clone = self.encoder.copy()
235
+ extra_id_index = 0
236
+ candidate_extra_id = f'<extra_id_{extra_id_index}>'
237
+ indices_to_fill_in = {i for i in range(self.vocab_size)} - set(
238
+ vocab_clone.values())
239
+
240
+ # Add enough indices to make get_vocab() the right length
241
+ for index_to_add in indices_to_fill_in:
242
+ # Make sure we don't overwrite a token that already exists
243
+ while candidate_extra_id in vocab_clone:
244
+ extra_id_index += 1
245
+ candidate_extra_id = f'<extra_id_{extra_id_index}>'
246
+
247
+ # Get an index to add and add the item
248
+ vocab_clone[candidate_extra_id] = index_to_add
249
+
250
+ return dict(vocab_clone, **self.added_tokens_encoder)
251
+
252
+ def _tokenize(self, text: str) -> List[str]:
253
+ """Returns a tokenized string."""
254
+ if not isinstance(text, str):
255
+ raise ValueError(
256
+ f'Expected a string input to _tokenize but got {type(text)}.')
257
+
258
+ tokens = [
259
+ self.decoder[t]
260
+ for t in self.encoding.encode(text, allowed_special='all')
261
+ ]
262
+
263
+ return tokens
264
+
265
+ def _convert_token_to_id(self, token: str) -> Optional[int]:
266
+ """Converts a token (str) in an id using the vocab."""
267
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
268
+
269
+ def _convert_id_to_token(self, index: int) -> Optional[str]:
270
+ """Converts an index (integer) in a token (str) using the vocab."""
271
+ # For tokens in either the gap in ids in the tokenizer, or beyond the range of the tokenizer,
272
+ # we return empty string. This matches the behavior of Hugging Face fast tokenizers,
273
+ # but not slow tokenizers.
274
+ return self.decoder.get(index, '')
275
+
276
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
277
+ """Converts a sequence of tokens (string) in a single string."""
278
+ text = ''.join(tokens)
279
+ text = bytearray([self.byte_decoder[c] for c in text
280
+ ]).decode('utf-8', errors=self.errors)
281
+ return text
282
+
283
+ def build_inputs_with_special_tokens(
284
+ self,
285
+ token_ids_0: List[int],
286
+ token_ids_1: Optional[List[int]] = None) -> List[int]:
287
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
288
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
289
+
290
+ output = bos_token_id + token_ids_0 + eos_token_id
291
+
292
+ if token_ids_1 is not None:
293
+ output = output + bos_token_id + token_ids_1 + eos_token_id
294
+
295
+ return output
296
+
297
+ def get_special_tokens_mask(
298
+ self,
299
+ token_ids_0: List[int],
300
+ token_ids_1: Optional[List[int]] = None,
301
+ already_has_special_tokens: bool = False) -> List[int]:
302
+ """Retrieves sequence ids from a token list that has no special tokens.
303
+
304
+ Function copied from
305
+ https://github.com/huggingface/transformers/blob/e3a4bd2bee212a2d0fd9f03b27fe7bfc1debe42d/src/transformers/models/gpt2/tokenization_gpt2.py#L265-L295
306
+
307
+ added. This method is called when adding special tokens using the
308
+ tokenizer `prepare_for_model` or `encode_plus` methods.
309
+
310
+ Args:
311
+ token_ids_0 (`List[int]`):
312
+ List of IDs.
313
+ token_ids_1 (`List[int]`, *optional*):
314
+ Optional second list of IDs for sequence pairs.
315
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
316
+ Whether or not the token list is already formatted with special tokens for the model.
317
+
318
+ Returns:
319
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
320
+ """
321
+ if already_has_special_tokens:
322
+ return super().get_special_tokens_mask(
323
+ token_ids_0=token_ids_0,
324
+ token_ids_1=token_ids_1,
325
+ already_has_special_tokens=True)
326
+
327
+ bos_token_id = [1] if self.add_bos_token else []
328
+ eos_token_id = [1] if self.add_eos_token else []
329
+
330
+ if token_ids_1 is None:
331
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
332
+ return (bos_token_id + ([0] * len(token_ids_0)) + eos_token_id +
333
+ bos_token_id + ([0] * len(token_ids_1)) + eos_token_id)
334
+
335
+ def create_token_type_ids_from_sequences(
336
+ self,
337
+ token_ids_0: List[int],
338
+ token_ids_1: Optional[List[int]] = None) -> List[int]:
339
+ sep = [self.sep_token_id]
340
+
341
+ if token_ids_1 is None:
342
+ return len(token_ids_0 + sep) * [0]
343
+ return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
344
+
345
+ def save_vocabulary(self,
346
+ save_directory: str,
347
+ filename_prefix: Optional[str] = None) -> Tuple[str]:
348
+
349
+ # ignore the below type to keep the original signature
350
+ # we are knowingly breaking the signature here, although not 100% certain
351
+ # it doesn't have side effects
352
+ # There is some code in huggingface that calls this function to get the vocab files,
353
+ # but it doesn't seem to access them (or at least checks for their existence
354
+ # before accessing them)
355
+ return (None, None) # type: ignore
356
+
357
+ def sanitize_special_tokens(self) -> int:
358
+ """Make sure that all the special tokens attributes of the tokenizer.
359
+
360
+ (`tokenizer.mask_token`, `tokenizer.cls_token`, etc.) are in the
361
+ vocabulary.
362
+
363
+ Add the missing ones to the vocabulary if needed.
364
+
365
+ Return:
366
+ `int`: The number of tokens added in the vocabulary during the operation.
367
+ """
368
+ actual_new_tokens = []
369
+ for token in self.all_special_tokens_extended:
370
+ encoded = self.encoding.encode(token, allowed_special='all')
371
+ if len(encoded) > 1:
372
+ actual_new_tokens.append(token)
373
+
374
+ return self.add_tokens(actual_new_tokens, special_tokens=True)
vocab/dbrx_instruct/dbrx-instruct/tokenizer_config.json ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": false,
5
+ "added_tokens_decoder": {
6
+ "100257": {
7
+ "content": "<|endoftext|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "100277": {
15
+ "content": "<|pad|>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "100278": {
23
+ "content": "<|im_start|>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ },
30
+ "100279": {
31
+ "content": "<|im_end|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ }
38
+ },
39
+ "additional_special_tokens": [
40
+ "<|im_start|>",
41
+ "<|im_end|>"
42
+ ],
43
+ "auto_map": {
44
+ "AutoTokenizer": [
45
+ "tiktoken.TiktokenTokenizerWrapper",
46
+ null
47
+ ]
48
+ },
49
+ "bos_token": "<|endoftext|>",
50
+ "clean_up_tokenization_spaces": true,
51
+ "encoding_name": null,
52
+ "eos_token": "<|endoftext|>",
53
+ "errors": "replace",
54
+ "model_max_length": 1000000000000000019884624838656,
55
+ "model_name": "gpt-4",
56
+ "pad_token": "<|pad|>",
57
+ "tokenizer_class": "TiktokenTokenizerWrapper",
58
+ "unk_token": "<|endoftext|>",
59
+ "use_default_system_prompt": true
60
+ }
vocab/grok_1/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+
3
+ ## reference
4
+ https://github.com/xai-org/grok-1/blob/main/run.py
5
+
6
+ vocab_size=128 * 1024,
7
+ pad_token=0,
8
+ eos_token=2,
9
+ """
10
+
11
+
12
+ import os
13
+ import sentencepiece
14
+ from tokenizer import sptokenizer_patch
15
+
16
+ CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
17
+ MODEL_FILE = os.path.join(CURRENT_DIR, "tokenizer.model")
18
+
19
+ tokenizer = sentencepiece.SentencePieceProcessor(model_file=MODEL_FILE)
20
+
21
+ # print(tokenizer.decode([1,2,3], skip_special_tokens=True))
vocab/grok_1/tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5c69d7cbad192fa2c9d14e2a77fbfdc11597c68907b043ddb0260e3d28eddd7f
3
+ size 2229219
vocab/mistral_7b/__init__.py CHANGED
@@ -1,5 +1,13 @@
1
 
 
 
 
2
 
3
 
4
- from transformers import AutoTokenizer
5
- tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1", trust_remote_code=True)
 
 
 
 
 
 
1
 
2
+ import os
3
+ import config
4
+ from transformers import AutoTokenizer
5
 
6
 
7
+
8
+ if config.USE_REMOTE:
9
+ tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1", trust_remote_code=True)
10
+ else:
11
+ CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
12
+ TOKENIZER_DIR = os.path.join(CURRENT_DIR, "Mistral-7B-v0.1")
13
+ tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_DIR, trust_remote_code=True)
vocab/mixtral_8_7b/Mixtral-8x7B-v0.1/special_tokens_map.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<s>",
3
+ "eos_token": "</s>",
4
+ "unk_token": "<unk>"
5
+ }
vocab/mixtral_8_7b/Mixtral-8x7B-v0.1/tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc4f0bd70b3709312d9d1d9e5ba674794b6bc5abc17429897a540f93882f25fc
3
+ size 1795303
vocab/mixtral_8_7b/Mixtral-8x7B-v0.1/tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dadfd56d766715c61d2ef780a525ab43b8e6da4de6865bda3d95fdef5e134055
3
+ size 493443
vocab/mixtral_8_7b/Mixtral-8x7B-v0.1/tokenizer_config.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<s>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ }
29
+ },
30
+ "additional_special_tokens": [],
31
+ "bos_token": "<s>",
32
+ "clean_up_tokenization_spaces": false,
33
+ "eos_token": "</s>",
34
+ "legacy": true,
35
+ "model_max_length": 1000000000000000019884624838656,
36
+ "pad_token": null,
37
+ "sp_model_kwargs": {},
38
+ "spaces_between_special_tokens": false,
39
+ "tokenizer_class": "LlamaTokenizer",
40
+ "unk_token": "<unk>",
41
+ "use_default_system_prompt": false
42
+ }
vocab/mixtral_8_7b/__init__.py CHANGED
@@ -1,2 +1,14 @@
 
 
 
 
1
  from transformers import AutoTokenizer
2
- tokenizer = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-v0.1", trust_remote_code=True)
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ import os
4
+ import config
5
  from transformers import AutoTokenizer
6
+
7
+
8
+ if config.USE_REMOTE:
9
+ tokenizer = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-v0.1", trust_remote_code=True)
10
+ else:
11
+ CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
12
+ TOKENIZER_DIR = os.path.join(CURRENT_DIR, "Mixtral-8x7B-v0.1")
13
+ tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_DIR, trust_remote_code=True)
14
+
vocab/text_davinci_003/__init__.py CHANGED
@@ -18,7 +18,6 @@ import tiktoken
18
  import tokenizer.tiktoken_patch
19
 
20
  tokenizer = tiktoken.encoding_for_model('text-davinci-003')
21
- tokenizer.vocab_size = tokenizer.n_vocab
22
 
23
  tokenizer.comments = ""
24
  tokenizer.reversible = True
 
18
  import tokenizer.tiktoken_patch
19
 
20
  tokenizer = tiktoken.encoding_for_model('text-davinci-003')
 
21
 
22
  tokenizer.comments = ""
23
  tokenizer.reversible = True