Qubitium commited on
Commit
d69e8dd
1 Parent(s): 3c42795

Upload tiktoken.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. tiktoken.py +374 -0
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 vocab_clone
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)