LayTextLLM commited on
Commit
c4e2a3d
1 Parent(s): 7d75019

Upload tokenizer

Browse files
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "unk_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenization_llama.py ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ """Tokenization classes for LLaMA."""
22
+ import os
23
+ from shutil import copyfile
24
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
25
+
26
+ import sentencepiece as spm
27
+
28
+ from transformers.convert_slow_tokenizer import import_protobuf
29
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
30
+ from transformers.utils import logging
31
+
32
+
33
+ if TYPE_CHECKING:
34
+ from transformers.tokenization_utils_base import TextInput
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
39
+
40
+ PRETRAINED_VOCAB_FILES_MAP = {
41
+ "vocab_file": {
42
+ "hf-internal-testing/llama-tokenizer": "https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model",
43
+ },
44
+ "tokenizer_file": {
45
+ "hf-internal-testing/llama-tokenizer": "https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json",
46
+ },
47
+ }
48
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
49
+ "hf-internal-testing/llama-tokenizer": 2048,
50
+ }
51
+ SPIECE_UNDERLINE = "▁"
52
+
53
+ B_INST, E_INST = "[INST]", "[/INST]"
54
+ B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
55
+
56
+ # fmt: off
57
+ DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your \
58
+ answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
59
+ that your responses are socially unbiased and positive in nature.
60
+
61
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not \
62
+ correct. If you don't know the answer to a question, please don't share false information."""
63
+ # fmt: on
64
+
65
+
66
+ class LlamaTokenizer(PreTrainedTokenizer):
67
+ """
68
+ Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is
69
+ no padding token in the original model.
70
+
71
+ Args:
72
+ vocab_file (`str`):
73
+ Path to the vocabulary file.
74
+ unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"`):
75
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
76
+ token instead.
77
+ bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<s>"`):
78
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
79
+ eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"</s>"`):
80
+ The end of sequence token.
81
+ pad_token (`str` or `tokenizers.AddedToken`, *optional*):
82
+ A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
83
+ attention mechanisms or loss computation.
84
+ sp_model_kwargs (`Dict[str, Any]`, `Optional`, *optional*):
85
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
86
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
87
+ to set:
88
+
89
+ - `enable_sampling`: Enable subword regularization.
90
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
91
+
92
+ - `nbest_size = {0,1}`: No sampling is performed.
93
+ - `nbest_size > 1`: samples from the nbest_size results.
94
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
95
+ using forward-filtering-and-backward-sampling algorithm.
96
+
97
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
98
+ BPE-dropout.
99
+
100
+ add_bos_token (`bool`, *optional*, defaults to `True`):
101
+ Whether or not to add an `bos_token` at the start of sequences.
102
+ add_eos_token (`bool`, *optional*, defaults to `False`):
103
+ Whether or not to add an `eos_token` at the end of sequences.
104
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
105
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
106
+ extra spaces.
107
+ use_default_system_prompt (`bool`, *optional*, defaults to `False`):
108
+ Whether or not the default system prompt for Llama should be used.
109
+ spaces_between_special_tokens (`bool`, *optional*, defaults to `False`):
110
+ Whether or not to add spaces between special tokens.
111
+ legacy (`bool`, *optional*):
112
+ Whether or not the `legacy` behavior of the tokenizer should be used. Legacy is before the merge of #24622
113
+ and #25224 which includes fixes to properly handle tokens that appear after special tokens. A simple
114
+ example:
115
+
116
+ - `legacy=True`:
117
+ ```python
118
+ >>> from transformers import T5Tokenizer
119
+
120
+ >>> tokenizer = T5Tokenizer.from_pretrained("t5-base", legacy=True)
121
+ >>> tokenizer.encode("Hello <extra_id_0>.")
122
+ [8774, 32099, 3, 5, 1]
123
+ ```
124
+ - `legacy=False`:
125
+ ```python
126
+ >>> from transformers import T5Tokenizer
127
+
128
+ >>> tokenizer = T5Tokenizer.from_pretrained("t5-base", legacy=False)
129
+ >>> tokenizer.encode("Hello <extra_id_0>.") # the extra space `[3]` is no longer here
130
+ [8774, 32099, 5, 1]
131
+ ```
132
+ Checkout the [pull request](https://github.com/huggingface/transformers/pull/24565) for more details.
133
+
134
+ """
135
+
136
+ vocab_files_names = VOCAB_FILES_NAMES
137
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
138
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
139
+ model_input_names = ["input_ids", "attention_mask"]
140
+
141
+ def __init__(
142
+ self,
143
+ vocab_file,
144
+ unk_token="<unk>",
145
+ bos_token="<s>",
146
+ eos_token="</s>",
147
+ pad_token=None,
148
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
149
+ add_bos_token=True,
150
+ add_eos_token=False,
151
+ clean_up_tokenization_spaces=False,
152
+ use_default_system_prompt=False,
153
+ spaces_between_special_tokens=False,
154
+ legacy=None,
155
+ **kwargs,
156
+ ):
157
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
158
+ bos_token = AddedToken(bos_token, normalized=False, special=True) if isinstance(bos_token, str) else bos_token
159
+ eos_token = AddedToken(eos_token, normalized=False, special=True) if isinstance(eos_token, str) else eos_token
160
+ unk_token = AddedToken(unk_token, normalized=False, special=True) if isinstance(unk_token, str) else unk_token
161
+ pad_token = AddedToken(pad_token, normalized=False, special=True) if isinstance(pad_token, str) else pad_token
162
+
163
+ if legacy is None:
164
+ logger.warning_once(
165
+ f"You are using the default legacy behaviour of the {self.__class__}. This is"
166
+ " expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you."
167
+ " If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it"
168
+ " means, and thoroughly read the reason why this was added as explained in"
169
+ " https://github.com/huggingface/transformers/pull/24565"
170
+ )
171
+ legacy = True
172
+
173
+ self.legacy = legacy
174
+ self.vocab_file = vocab_file
175
+ self.add_bos_token = add_bos_token
176
+ self.add_eos_token = add_eos_token
177
+ self.use_default_system_prompt = use_default_system_prompt
178
+ self.sp_model = self.get_spm_processor(kwargs.pop("from_slow", False))
179
+
180
+ super().__init__(
181
+ bos_token=bos_token,
182
+ eos_token=eos_token,
183
+ unk_token=unk_token,
184
+ pad_token=pad_token,
185
+ add_bos_token=add_bos_token,
186
+ add_eos_token=add_eos_token,
187
+ sp_model_kwargs=self.sp_model_kwargs,
188
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
189
+ use_default_system_prompt=use_default_system_prompt,
190
+ spaces_between_special_tokens=spaces_between_special_tokens,
191
+ legacy=legacy,
192
+ **kwargs,
193
+ )
194
+
195
+ @property
196
+ def unk_token_length(self):
197
+ return len(self.sp_model.encode(str(self.unk_token)))
198
+
199
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_spm_processor
200
+ def get_spm_processor(self, from_slow=False):
201
+ tokenizer = spm.SentencePieceProcessor(**self.sp_model_kwargs)
202
+ if self.legacy or from_slow: # no dependency on protobuf
203
+ tokenizer.Load(self.vocab_file)
204
+ return tokenizer
205
+
206
+ with open(self.vocab_file, "rb") as f:
207
+ sp_model = f.read()
208
+ model_pb2 = import_protobuf(f"The new behaviour of {self.__class__.__name__} (with `self.legacy = False`)")
209
+ model = model_pb2.ModelProto.FromString(sp_model)
210
+ normalizer_spec = model_pb2.NormalizerSpec()
211
+ normalizer_spec.add_dummy_prefix = False
212
+ model.normalizer_spec.MergeFrom(normalizer_spec)
213
+ sp_model = model.SerializeToString()
214
+ tokenizer.LoadFromSerializedProto(sp_model)
215
+ return tokenizer
216
+
217
+ def __getstate__(self):
218
+ state = self.__dict__.copy()
219
+ state["sp_model"] = None
220
+ state["sp_model_proto"] = self.sp_model.serialized_model_proto()
221
+ return state
222
+
223
+ def __setstate__(self, d):
224
+ self.__dict__ = d
225
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
226
+ self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
227
+
228
+ @property
229
+ def vocab_size(self):
230
+ """Returns vocab size"""
231
+ return self.sp_model.get_piece_size()
232
+
233
+ def get_vocab(self):
234
+ """Returns vocab as a dict"""
235
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
236
+ vocab.update(self.added_tokens_encoder)
237
+ return vocab
238
+
239
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.tokenize
240
+ def tokenize(self, text: "TextInput", add_special_tokens=False, **kwargs) -> List[str]:
241
+ """
242
+ Converts a string to a list of tokens. If `self.legacy` is set to `False`, a prefix token is added unless the
243
+ first token is special.
244
+ """
245
+ if self.legacy or len(text) == 0:
246
+ return super().tokenize(text, **kwargs)
247
+
248
+ tokens = super().tokenize(SPIECE_UNDERLINE + text.replace(SPIECE_UNDERLINE, " "), **kwargs)
249
+
250
+ if len(tokens) > 1 and tokens[0] == SPIECE_UNDERLINE and tokens[1] in self.all_special_tokens:
251
+ tokens = tokens[1:]
252
+ return tokens
253
+
254
+ # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer._tokenize
255
+ def _tokenize(self, text, **kwargs):
256
+ """
257
+ Returns a tokenized string.
258
+
259
+ We de-activated the `add_dummy_prefix` option, thus the sentencepiece internals will always strip any
260
+ SPIECE_UNDERLINE. For example: `self.sp_model.encode(f"{SPIECE_UNDERLINE}Hey", out_type = str)` will give
261
+ `['H', 'e', 'y']` instead of `['▁He', 'y']`. Thus we always encode `f"{unk_token}text"` and strip the
262
+ `unk_token`. Here is an example with `unk_token = "<unk>"` and `unk_token_length = 4`.
263
+ `self.tokenizer.sp_model.encode("<unk> Hey", out_type = str)[4:]`.
264
+ """
265
+ tokens = self.sp_model.encode(text, out_type=str)
266
+ if self.legacy or not text.startswith((SPIECE_UNDERLINE, " ")):
267
+ return tokens
268
+
269
+ # 1. Encode string + prefix ex: "<unk> Hey"
270
+ tokens = self.sp_model.encode(self.unk_token + text, out_type=str)
271
+ # 2. Remove self.unk_token from ['<','unk','>', '▁Hey']
272
+ return tokens[self.unk_token_length :] if len(tokens) >= self.unk_token_length else tokens
273
+
274
+ def _convert_token_to_id(self, token):
275
+ """Converts a token (str) in an id using the vocab."""
276
+ return self.sp_model.piece_to_id(token)
277
+
278
+ def _convert_id_to_token(self, index):
279
+ """Converts an index (integer) in a token (str) using the vocab."""
280
+ token = self.sp_model.IdToPiece(index)
281
+ return token
282
+
283
+ def convert_tokens_to_string(self, tokens):
284
+ """Converts a sequence of tokens (string) in a single string."""
285
+ # since we manually add the prefix space, we have to remove it when decoding
286
+ if tokens[0].startswith(SPIECE_UNDERLINE):
287
+ tokens[0] = tokens[0][1:]
288
+
289
+ current_sub_tokens = []
290
+ out_string = ""
291
+ prev_is_special = False
292
+ for i, token in enumerate(tokens):
293
+ # make sure that special tokens are not decoded using sentencepiece model
294
+ if token in self.all_special_tokens:
295
+ if not prev_is_special and i != 0 and self.legacy:
296
+ out_string += " "
297
+ out_string += self.sp_model.decode(current_sub_tokens) + token
298
+ prev_is_special = True
299
+ current_sub_tokens = []
300
+ else:
301
+ current_sub_tokens.append(token)
302
+ prev_is_special = False
303
+ out_string += self.sp_model.decode(current_sub_tokens)
304
+ return out_string
305
+
306
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
307
+ """
308
+ Save the vocabulary and special tokens file to a directory.
309
+
310
+ Args:
311
+ save_directory (`str`):
312
+ The directory in which to save the vocabulary.
313
+
314
+ Returns:
315
+ `Tuple(str)`: Paths to the files saved.
316
+ """
317
+ if not os.path.isdir(save_directory):
318
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
319
+ return
320
+ out_vocab_file = os.path.join(
321
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
322
+ )
323
+
324
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
325
+ copyfile(self.vocab_file, out_vocab_file)
326
+ elif not os.path.isfile(self.vocab_file):
327
+ with open(out_vocab_file, "wb") as fi:
328
+ content_spiece_model = self.sp_model.serialized_model_proto()
329
+ fi.write(content_spiece_model)
330
+
331
+ return (out_vocab_file,)
332
+
333
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
334
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
335
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
336
+
337
+ output = bos_token_id + token_ids_0 + eos_token_id
338
+
339
+ if token_ids_1 is not None:
340
+ output = output + bos_token_id + token_ids_1 + eos_token_id
341
+
342
+ return output
343
+
344
+ def get_special_tokens_mask(
345
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
346
+ ) -> List[int]:
347
+ """
348
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
349
+ special tokens using the tokenizer `prepare_for_model` method.
350
+
351
+ Args:
352
+ token_ids_0 (`List[int]`):
353
+ List of IDs.
354
+ token_ids_1 (`List[int]`, *optional*):
355
+ Optional second list of IDs for sequence pairs.
356
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
357
+ Whether or not the token list is already formatted with special tokens for the model.
358
+
359
+ Returns:
360
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
361
+ """
362
+ if already_has_special_tokens:
363
+ return super().get_special_tokens_mask(
364
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
365
+ )
366
+
367
+ bos_token_id = [1] if self.add_bos_token else []
368
+ eos_token_id = [1] if self.add_eos_token else []
369
+
370
+ if token_ids_1 is None:
371
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
372
+ return (
373
+ bos_token_id
374
+ + ([0] * len(token_ids_0))
375
+ + eos_token_id
376
+ + bos_token_id
377
+ + ([0] * len(token_ids_1))
378
+ + eos_token_id
379
+ )
380
+
381
+ def create_token_type_ids_from_sequences(
382
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
383
+ ) -> List[int]:
384
+ """
385
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
386
+ sequence pair mask has the following format:
387
+
388
+ ```
389
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
390
+ | first sequence | second sequence |
391
+ ```
392
+
393
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
394
+
395
+ Args:
396
+ token_ids_0 (`List[int]`):
397
+ List of ids.
398
+ token_ids_1 (`List[int]`, *optional*):
399
+ Optional second list of IDs for sequence pairs.
400
+
401
+ Returns:
402
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
403
+ """
404
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
405
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
406
+
407
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
408
+
409
+ if token_ids_1 is not None:
410
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
411
+
412
+ return output
413
+
414
+ @property
415
+ def default_chat_template(self):
416
+ """
417
+ LLaMA uses [INST] and [/INST] to indicate user messages, and <<SYS>> and <</SYS>> to indicate system messages.
418
+ Assistant messages do not have special tokens, because LLaMA chat models are generally trained with strict
419
+ user/assistant/user/assistant message ordering, and so assistant messages can be identified from the ordering
420
+ rather than needing special tokens. The system message is partly 'embedded' in the first user message, which
421
+ results in an unusual token ordering when it is present. This template should definitely be changed if you wish
422
+ to fine-tune a model with more flexible role ordering!
423
+
424
+ The output should look something like:
425
+
426
+ <bos>[INST] B_SYS SystemPrompt E_SYS Prompt [/INST] Answer <eos><bos>[INST] Prompt [/INST] Answer <eos>
427
+ <bos>[INST] Prompt [/INST]
428
+
429
+ The reference for this chat template is [this code
430
+ snippet](https://github.com/facebookresearch/llama/blob/556949fdfb72da27c2f4a40b7f0e4cf0b8153a28/llama/generation.py#L320-L362)
431
+ in the original repository.
432
+ """
433
+ logger.warning_once(
434
+ "\nNo chat template is defined for this tokenizer - using the default template "
435
+ f"for the {self.__class__.__name__} class. If the default is not appropriate for "
436
+ "your model, please set `tokenizer.chat_template` to an appropriate template. "
437
+ "See https://huggingface.co/docs/transformers/main/chat_templating for more information.\n"
438
+ )
439
+ template = (
440
+ "{% if messages[0]['role'] == 'system' %}"
441
+ "{% set loop_messages = messages[1:] %}" # Extract system message if it's present
442
+ "{% set system_message = messages[0]['content'] %}"
443
+ "{% elif USE_DEFAULT_PROMPT == true and not '<<SYS>>' in messages[0]['content'] %}"
444
+ "{% set loop_messages = messages %}" # Or use the default system message if the flag is set
445
+ "{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}"
446
+ "{% else %}"
447
+ "{% set loop_messages = messages %}"
448
+ "{% set system_message = false %}"
449
+ "{% endif %}"
450
+ "{% for message in loop_messages %}" # Loop over all non-system messages
451
+ "{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}"
452
+ "{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}"
453
+ "{% endif %}"
454
+ "{% if loop.index0 == 0 and system_message != false %}" # Embed system message in first message
455
+ "{% set content = '<<SYS>>\\n' + system_message + '\\n<</SYS>>\\n\\n' + message['content'] %}"
456
+ "{% else %}"
457
+ "{% set content = message['content'] %}"
458
+ "{% endif %}"
459
+ "{% if message['role'] == 'user' %}" # After all of that, handle messages/roles in a fairly normal way
460
+ "{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}"
461
+ "{% elif message['role'] == 'system' %}"
462
+ "{{ '<<SYS>>\\n' + content.strip() + '\\n<</SYS>>\\n\\n' }}"
463
+ "{% elif message['role'] == 'assistant' %}"
464
+ "{{ ' ' + content.strip() + ' ' + eos_token }}"
465
+ "{% endif %}"
466
+ "{% endfor %}"
467
+ )
468
+ template = template.replace("USE_DEFAULT_PROMPT", "true" if self.use_default_system_prompt else "false")
469
+ default_message = DEFAULT_SYSTEM_PROMPT.replace("\n", "\\n").replace("'", "\\'")
470
+ template = template.replace("DEFAULT_SYSTEM_MESSAGE", default_message)
471
+
472
+ return template
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
tokenizer_config.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "auto_map": {
31
+ "AutoTokenizer": [
32
+ "tokenization_llama.LlamaTokenizer",
33
+ null
34
+ ]
35
+ },
36
+ "bos_token": "<s>",
37
+ "clean_up_tokenization_spaces": false,
38
+ "eos_token": "</s>",
39
+ "legacy": false,
40
+ "model_max_length": 1000000000000000019884624838656,
41
+ "pad_token": null,
42
+ "padding_side": "left",
43
+ "sp_model_kwargs": {},
44
+ "spaces_between_special_tokens": false,
45
+ "tokenizer_class": "LlamaTokenizer",
46
+ "unk_token": "<unk>",
47
+ "use_default_system_prompt": false
48
+ }