Text Generation
Transformers
PyTorch
Safetensors
llama
text-generation-inference
mfromm commited on
Commit
ff88b5e
·
verified ·
1 Parent(s): d49562c

Update gptx_tokenizer.py

Browse files
Files changed (1) hide show
  1. gptx_tokenizer.py +448 -19
gptx_tokenizer.py CHANGED
@@ -1,34 +1,463 @@
1
- """
2
- This module supplies `transformers`-compatible wrappers for
3
- `GPTXTokenizer`s.
4
 
5
- The tokenizers in this do not conform to the `PreTrainedTokenizer` API,
6
- but allow for better practical usage.
7
- """
 
 
8
 
9
- from typing import List
 
 
 
 
 
10
 
11
- from gptx_tokenizer.hf_wrappers import (
12
- HFTokenizer as _HFTokenizer,
13
- SPTokenizer as _SPTokenizer,
14
- )
15
 
16
- class HFTokenizer(_HFTokenizer):
17
- # The tokenizer is ridiculously slow without this; however, this
18
- # doesn't implement all APIs of `PreTrainedTokenizer`.
19
- def encode(self, text: str, **kwargs) -> List[int]:
20
- return_tokens = kwargs.pop('return_tokens', False)
21
- return self._tok.encode(text, return_tokens=return_tokens)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
 
23
 
24
- class SPTokenizer(_SPTokenizer):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  # `is_continuation` does not work without this, but it doesn't
26
  # implement all APIs of `PreTrainedTokenizer`.
27
  def encode(self, text: str, **kwargs) -> List[int]:
28
  return_tokens = kwargs.pop('return_tokens', False)
29
  is_continuation = kwargs.pop('is_continuation', False)
30
- return self._tok.encode(
31
  text,
32
  return_tokens=return_tokens,
33
  is_continuation=is_continuation,
34
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
 
 
2
 
3
+ import json
4
+ import os
5
+ import warnings
6
+ from pathlib import Path
7
+ from typing import Any, Dict, List, Mapping, Optional, Tuple, Union
8
 
9
+ import sentencepiece as spm
10
+ import numpy as np
11
+ import torch
12
+ from huggingface_hub import hf_hub_download, list_repo_files, try_to_load_from_cache
13
+ from transformers.tokenization_utils import PreTrainedTokenizer
14
+ from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE
15
 
 
 
 
 
16
 
17
+ REPO_ID = "openGPT-X/Teuken-7B-base-v0.6"
18
+
19
+
20
+ class HFGPTXTokenizer(PreTrainedTokenizer):
21
+ """
22
+ A custom tokenizer class that extends Hugging Face's PreTrainedTokenizer.
23
+ It is specifically designed to work with SentencePiece models and integrates
24
+ with Hugging Face's tokenizer utilities.
25
+ """
26
+
27
+ model_file_glob = "*tokenizer.json"
28
+ vocab_files_names = {"tokenizer_file": "tokenizer.json"}
29
+ decode_kwargs: List[str] = []
30
+
31
+ def _encode(self, text: str, return_tokens: bool = False, is_continuation: bool = False):
32
+ """
33
+ Encode a given text using the tokenizer.
34
+
35
+ Args:
36
+ text (str): The text to encode.
37
+ return_tokens (bool): If True, returns token strings instead of token IDs.
38
+ is_continuation (bool): If True, uses a continuation tokenizer (if available).
39
+ Returns:
40
+ List[int] or List[str]: Encoded text as a list of token IDs or token strings.
41
+ """
42
+ assert self.tok is not None, "No tokenizer is currently loaded"
43
+
44
+ # Variant with additional sp processor:
45
+ tokenizer = self.continuation_tokenizer if is_continuation else self.tok
46
+
47
+ if return_tokens:
48
+ return tokenizer.encode_as_pieces(text)
49
+ else:
50
+ return tokenizer.encode(text)
51
+
52
+ def create_list_of_special_tokens(self) -> List[str]:
53
+ """
54
+ Create a list of special tokens, including the BOS, EOS, PAD, EOD tokens,
55
+ and 256 additional placeholder tokens.
56
+ Returns:
57
+ List[str]: List of special tokens.
58
+ """
59
+ return [self.bos_token, self.eos_token, self.pad_token, self.eod_token] + [
60
+ f"<placeholder_tok_{i}>" for i in range(256)
61
+ ]
62
+
63
+ def find_tokenizer_config(self, config_path: Path, repo_id: str = None) -> Optional[Path]:
64
+ if not os.path.isfile(config_path):
65
+ config_path = try_to_load_from_cache(repo_id=repo_id, filename=Path(config_path).name)
66
+ if not config_path:
67
+ config_path = self._download_config_from_hub(repo_id=repo_id)
68
+
69
+ return config_path
70
+
71
+
72
+ def instantiate_from_file_or_name(self, model_file_or_name: str, repo_id: str = None):
73
+ """
74
+ Load the tokenizer model from a file or download it from a repository.
75
+
76
+ Args:
77
+ model_file_or_name (str): Path to the model file or the model name.
78
+ repo_id (str, optional): Repository ID from which to download the model file.
79
+
80
+ Returns:
81
+ spm.SentencePieceProcessor: Loaded SentencePieceProcessor instance.
82
+
83
+ Raises:
84
+ ValueError: If repo_id is not provided when model_file_or_name is not a file.
85
+ OSError: If the model file cannot be loaded or downloaded.
86
+ """
87
+ if not os.path.isfile(model_file_or_name):
88
+ model_file_or_name = try_to_load_from_cache(repo_id=repo_id, filename=Path(model_file_or_name).name)
89
+ if not model_file_or_name:
90
+ model_file_or_name = self._download_model_from_hub(repo_id=repo_id)
91
+
92
+ try:
93
+ return spm.SentencePieceProcessor(model_file=model_file_or_name)
94
+ except Exception as e:
95
+ raise OSError(f"Failed to load tokenizer model: {str(e)}")
96
+
97
+ def _download_model_from_hub(self, repo_id: str) -> Optional[str]:
98
+ try:
99
+ # List all files in the repo
100
+ repo_files = list_repo_files(repo_id)
101
+
102
+ # Find the tokenizer model file
103
+ tokenizer_files = [f for f in repo_files if f.endswith('.model')]
104
+ if not tokenizer_files:
105
+ raise FileNotFoundError(f"No .model file found in repository {repo_id}")
106
+
107
+ # Use the first .model file found
108
+ model_file = tokenizer_files[0]
109
+ print(f"Found tokenizer model file: {model_file}")
110
+
111
+ # Download the file
112
+ model_file_or_name = hf_hub_download(repo_id=repo_id, filename=model_file)
113
+ print(f"Downloaded tokenizer model to: {model_file_or_name}")
114
+ except Exception as e:
115
+ raise OSError(f"Failed to download tokenizer model: {str(e)}")
116
+
117
+ return model_file_or_name
118
+
119
+ def _download_config_from_hub(self, repo_id: str):
120
+ if repo_id is None:
121
+ raise ValueError("repo_id must be provided if config_path is not a local file")
122
+
123
+ try:
124
+ # List all files in the repo
125
+ repo_files = list_repo_files(repo_id)
126
+
127
+ # Find the tokenizer config file
128
+ tokenizer_files = [f for f in repo_files if f.endswith('tokenizer_config.json')]
129
+ if not tokenizer_files:
130
+ raise FileNotFoundError(f"No tokenizer_config.json file found in repository {repo_id}")
131
+
132
+ # Use the first tokenizer_config.json file found
133
+ tokenizer_config_file = tokenizer_files[0]
134
+ print(f"Found tokenizer config file: {tokenizer_config_file}")
135
+
136
+ # Download the file
137
+ tokenizer_config_file_or_name = hf_hub_download(repo_id=repo_id, filename=tokenizer_config_file)
138
+ print(f"Downloaded tokenizer config file to: {tokenizer_config_file_or_name}")
139
+ return tokenizer_config_file_or_name
140
+ except Exception as e:
141
+ raise OSError(f"Failed to download tokenizer model: {str(e)}")
142
+ def __init__(
143
+ self,
144
+ model_path: Optional[str] = None,
145
+ config_path: Optional[str] = None,
146
+ **kwargs: Any,
147
+ ) -> None:
148
+ """
149
+ Initialize the tokenizer.
150
+ Args:
151
+ model_path (Optional[str]): Path to the tokenizer model file.
152
+ config_path (Optional[str]): Path to the tokenizer configuration file.
153
+ **kwargs: Additional keyword arguments passed to the superclass.
154
+ This method also ensures backward compatibility by setting
155
+ `clean_up_tokenization_spaces` to False by default.
156
+ """
157
+ # Prevent cleanup of tokenization spaces to maintain backward compatibility
158
+ self.clean_up_tokenization_spaces = kwargs.setdefault("clean_up_tokenization_spaces", False)
159
+ self.vocab = None
160
+ cp_path = kwargs.get("name_or_path", ".")
161
+ if model_path is None:
162
+ model_path = str(Path(cp_path) / self.vocab_files_names["tokenizer_file"])
163
+ self.tok = self.instantiate_from_file_or_name(model_path, repo_id=REPO_ID)
164
 
165
+ super().__init__(**kwargs)
166
 
167
+ # Specify special tokens which we know the value of.
168
+ # EOD from `tok` is used as what is called EOS in HuggingFace.
169
+ # Since there is no corresponding mapping for EOS from `tok` in
170
+ # HuggingFace, it is treated as an additional special token.
171
+ # Same for all other special tokens.
172
+
173
+
174
+ self.unk_token = "<unk>"
175
+ self.eos_token = "</s>"
176
+ self.bos_token = "<s>"
177
+ self.pad_token = "<pad>"
178
+ self.eod_token = "<eod>"
179
+
180
+ self.additional_special_tokens = self.create_list_of_special_tokens()
181
+
182
+ if config_path is None:
183
+ config_path = str(Path(cp_path) / TOKENIZER_CONFIG_FILE)
184
+
185
+ if os.path.isfile(config_path):
186
+ self.tokenizer_config = self.load_json(Path(config_path))
187
+ else: # Load from repo
188
+ self.tokenizer_config = self.load_json(Path(self.find_tokenizer_config(Path(config_path), repo_id=REPO_ID)))
189
+
190
+ @property
191
+ def vocab_size(self) -> int:
192
+ """
193
+ Get the size of the tokenizer vocabulary.
194
+ Returns:
195
+ int: The size of the vocabulary.
196
+ """
197
+ return self.tok.GetPieceSize()
198
+
199
+ def get_vocab(self) -> Dict[str, int]:
200
+ """
201
+ Get the vocabulary as a dictionary mapping token strings to their IDs.
202
+ Returns:
203
+ Dict[str, int]: Vocabulary mapping.
204
+ """
205
+ if self.vocab is None:
206
+ self.vocab = {self.tok.IdToPiece(i): i for i in range(self.vocab_size)}
207
+ return self.vocab
208
+
209
+ def _tokenize(self, text: str, **kwargs) -> List[int]:
210
+ """
211
+ Tokenize the input text.
212
+ Args:
213
+ text (str): Text to tokenize.
214
+ **kwargs: Additional keyword arguments.
215
+ Returns:
216
+ List[int]: List of token IDs.
217
+ """
218
+ return_tokens = kwargs.pop("return_tokens", True)
219
+ return self._encode(text, return_tokens=return_tokens, **kwargs)
220
+
221
+ def _convert_token_to_id(self, token: str) -> int:
222
+ """
223
+ Convert a token string to its corresponding ID.
224
+ Args:
225
+ token (str): The token to convert.
226
+ Returns:
227
+ int: The token's ID.
228
+ Raises:
229
+ ValueError: If the token is unknown and cannot be encoded to a single ID.
230
+ """
231
+ return self.tok.PieceToId(token)
232
+
233
+
234
+ def decode(
235
+ self,
236
+ token_ids: Union[List[int], List[List[int]]],
237
+ num_threads: Optional[int] = None,
238
+ skip_special_tokens: bool = False,
239
+ clean_up_tokenization_spaces: bool = False,
240
+ ) -> str:
241
+ """
242
+ Decode a list of token IDs into a string.
243
+ Args:
244
+ token_ids (Union[List[int], List[List[int]]]): List of token IDs or lists of token IDs.
245
+ num_threads (Optional[int]): Number of threads to use for decoding.
246
+ Returns:
247
+ str: Decoded string.
248
+ """
249
+ if isinstance(token_ids, torch.Tensor): # For PyTorch tensors
250
+ token_ids = token_ids.tolist()
251
+ elif isinstance(token_ids, np.ndarray): # For NumPy arrays
252
+ token_ids = token_ids.tolist()
253
+
254
+ output = self.tok.decode(input=token_ids, num_threads=num_threads)
255
+ if skip_special_tokens:
256
+ for substring in self.additional_special_tokens:
257
+ output = output.replace(substring, "")
258
+
259
+ if clean_up_tokenization_spaces:
260
+ warnings.warn(
261
+ "when cleaning up tokenization spaces, this will not behave "
262
+ "like the original `GPTXTokenizer`., Please supply "
263
+ "`clean_up_tokenization_spaces=False` for decoding."
264
+ )
265
+ output = self.clean_up_tokenization(output)
266
+
267
+ return output
268
+
269
+
270
+ def _convert_id_to_token(self, index: int) -> str:
271
+ """
272
+ Convert a token ID to its corresponding token string.
273
+ Args:
274
+ index (int): Token ID.
275
+ Returns:
276
+ str: Corresponding token string.
277
+ """
278
+ return self.tok.IdToPiece(index)
279
+
280
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
281
+ """
282
+ Convert a list of tokens into a single string.
283
+ Args:
284
+ tokens (List[str]): List of token strings.
285
+ Returns:
286
+ str: Concatenated string of tokens.
287
+ """
288
+ return self.tok.DecodePieces(tokens)
289
+
290
+ def _tok_decode(self, token_ids: List[int], **kwargs: Any) -> str:
291
+ """
292
+ Internal method to decode token IDs with additional arguments.
293
+ Args:
294
+ token_ids (List[int]): List of token IDs.
295
+ **kwargs: Additional arguments to pass to the decode method.
296
+ Returns:
297
+ str: Decoded string.
298
+ This method also issues a warning if unsupported arguments are provided.
299
+ """
300
+ passed_kwargs = {key: value for (key, value) in kwargs.items() if key in self.decode_kwargs}
301
+ if len(passed_kwargs) != len(kwargs):
302
+ warnings.warn("silently ignoring some arguments to `decode` due to missing " "support from the tokenizer.")
303
+ text = self.decode(token_ids, **passed_kwargs)
304
+ return text
305
+
306
+ def save_tokenizer(self, save_dir: str) -> None:
307
+ if not os.path.isdir(save_dir):
308
+ print(f"Vocabulary path ({save_dir}) should be a directory")
309
+ return
310
+ out_vocab_file = os.path.join(save_dir, "tokenizer.model")
311
+
312
+ # if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
313
+ # copyfile(self.vocab_file, out_vocab_file)
314
+ # elif not os.path.isfile(self.vocab_file):
315
+ with open(out_vocab_file, "wb") as f:
316
+ content_spiece_model = self.tok.serialized_model_proto()
317
+ f.write(content_spiece_model)
318
+
319
+ return (out_vocab_file,)
320
+
321
+ def _decode(
322
+ self,
323
+ token_ids: List[int],
324
+ skip_special_tokens: bool = False,
325
+ clean_up_tokenization_spaces: bool = None,
326
+ spaces_between_special_tokens: bool = True,
327
+ **kwargs: Any,
328
+ ) -> str:
329
+ text = self._tok_decode(
330
+ token_ids,
331
+ skip_special_tokens=skip_special_tokens,
332
+ spaces_between_special_tokens=spaces_between_special_tokens,
333
+ **kwargs,
334
+ )
335
+
336
+ clean_up_tokenization_spaces = (
337
+ clean_up_tokenization_spaces
338
+ if clean_up_tokenization_spaces is not None
339
+ else self.clean_up_tokenization_spaces
340
+ )
341
+ if clean_up_tokenization_spaces:
342
+ warnings.warn(
343
+ "when cleaning up tokenization spaces, this will not behave "
344
+ "like the original `GPTXTokenizer`., Please supply "
345
+ "`clean_up_tokenization_spaces=False` for decoding."
346
+ )
347
+ clean_text = self.clean_up_tokenization(text)
348
+ return clean_text
349
+ else:
350
+ return text
351
+
352
+ def save_vocabulary(
353
+ self,
354
+ save_directory: str,
355
+ filename_prefix: Optional[str] = None,
356
+ ) -> Tuple[str]:
357
+ filename_prefix = filename_prefix + "-" if filename_prefix else ""
358
+ save_directory = Path(save_directory)
359
+
360
+ self._save_tokenizer_config(save_directory, filename_prefix)
361
+ tokenizer_file_path = self._save_tokenizer(save_directory, filename_prefix)
362
+
363
+ return (tokenizer_file_path,)
364
+
365
+ def _save_tokenizer_config(
366
+ self,
367
+ save_directory: Path,
368
+ filename_prefix: str,
369
+ ) -> str:
370
+ self.save_tokenizer_config(save_directory)
371
+ old_tokenizer_config_path = save_directory / TOKENIZER_CONFIG_FILE
372
+ assert old_tokenizer_config_path.is_file(), "tokenizer config path changed"
373
+ new_tokenizer_config_path = save_directory / (filename_prefix + old_tokenizer_config_path.name)
374
+ old_tokenizer_config_path.replace(new_tokenizer_config_path)
375
+ return str(new_tokenizer_config_path)
376
+
377
+ def _find_tokenizer_files(self, save_directory: Path) -> List[Path]:
378
+ files = list(Path(save_directory).glob(self.model_file_glob))
379
+ return files
380
+
381
+ def _get_tokenizer_file(self, files: List[Path]):
382
+ assert files, "no saved tokenizer file found"
383
+ assert len(files) <= 1, "cannot handle multiple saved tokenizer files"
384
+ return files[0]
385
+
386
+ def _save_tokenizer(
387
+ self,
388
+ save_directory: Path,
389
+ filename_prefix: str,
390
+ ) -> str:
391
+ self.save_tokenizer(str(save_directory))
392
+ tokenizer_files = self._find_tokenizer_files(save_directory)
393
+ old_tokenizer_file_path = self._get_tokenizer_file(tokenizer_files)
394
+ assert old_tokenizer_file_path.is_file(), "could not access saved tokenizer file"
395
+ new_tokenizer_file_path = save_directory / (filename_prefix + self.vocab_files_names["tokenizer_file"])
396
+ old_tokenizer_file_path.replace(new_tokenizer_file_path)
397
+ return str(new_tokenizer_file_path)
398
+
399
+ def save_tokenizer_config(self, save_dir: Path) -> None:
400
+ # convert Path to str
401
+ for k in self.tokenizer_config:
402
+ if isinstance(self.tokenizer_config[k], Path):
403
+ self.tokenizer_config[k] = str(self.tokenizer_config[k])
404
+
405
+ info_file = save_dir / "tokenizer_config.json"
406
+ with info_file.open("w") as f:
407
+ json.dump(self.tokenizer_config, f, indent=4)
408
+
409
+ def load_json(self, path: Path) -> dict:
410
+ with path.open("r") as f:
411
+ return json.load(f)
412
+
413
+ class SPTokenizer(HFGPTXTokenizer):
414
+ model_file_glob = "*tokenizer.model"
415
+ vocab_files_names = {"tokenizer_file": "tokenizer.model"}
416
+ decode_kwargs = ["num_threads"]
417
  # `is_continuation` does not work without this, but it doesn't
418
  # implement all APIs of `PreTrainedTokenizer`.
419
  def encode(self, text: str, **kwargs) -> List[int]:
420
  return_tokens = kwargs.pop('return_tokens', False)
421
  is_continuation = kwargs.pop('is_continuation', False)
422
+ return self._encode(
423
  text,
424
  return_tokens=return_tokens,
425
  is_continuation=is_continuation,
426
  )
427
+
428
+ def __init__(self, *args, **kwargs):
429
+ super().__init__(*args, **kwargs)
430
+
431
+ self.eos_token = "</s>"
432
+ self.eos_token_id = 2
433
+ self.system_messages_by_lang = { # translations by deepl / google translate
434
+ "BG": "Чат между човек и асистент с изкуствен интелект. Асистентът дава полезни и учтиви отговори на въпросите на човека.", # noqa
435
+ "CS": "Chat mezi člověkem a asistentem s umělou inteligencí. Asistent poskytuje vstřícné a zdvořilé odpovědi na otázky člověka.", # noqa
436
+ "DA": "En chat mellem et menneske og en assistent med kunstig intelligens, som giver hjælpsomme og høflige svar på menneskets spørgsmål.", # noqa
437
+ "DE": "Ein Gespräch zwischen einem Menschen und einem Assistenten mit künstlicher Intelligenz. Der Assistent gibt hilfreiche und höfliche Antworten auf die Fragen des Menschen.", # noqa
438
+ "EL": "Μια συνομιλία μεταξύ ενός ανθρώπου και ενός βοηθού τεχνητής νοημοσύνης. Ο βοηθός δίνει χρήσιμες και ευγενικές απαντήσεις στις ερωτήσεις του ανθρώπου.", # noqa
439
+ "EN": "A chat between a human and an artificial intelligence assistant.The assistant gives helpful and polite answers to the human's questions.", # noqa
440
+ "ES": "Una conversación entre un humano y un asistente de inteligencia artificial. El asistente da respuestas útiles y amables a las preguntas del humano.", # noqa
441
+ "ET": "Inimese ja tehisintellekti assistendi vaheline vestlus. Assistent annab inimese küsimustele abivalmis ja viisakaid vastuseid.", # noqa
442
+ "FI": "Ihmisen ja tekoälyavustajan välinen keskustelu. Avustaja antaa avuliaita ja kohteliaita vastauksia ihmisen kysymyksiin.", # noqa
443
+ "FR": "Conversation entre un humain et un assistant doté d'une intelligence artificielle. L'assistant donne des réponses utiles et polies aux questions de l'homme.", # noqa
444
+ "GA": "Comhrá idir duine agus cúntóir hintleachta saorga. Tugann an cúntóir freagraí cabhracha dea-bh��asacha ar cheisteanna an duine.", # noqa
445
+ "HR": "Razgovor između čovjeka i pomoćnika umjetne inteligencije. Pomoćnik daje korisne i ljubazne odgovore na ljudska pitanja.", # noqa
446
+ "HU": "Egy ember és egy mesterséges intelligencia asszisztens közötti beszélgetés. Az asszisztens segítőkész és udvarias válaszokat ad az ember kérdéseire.", # noqa
447
+ "IT": "Una chat tra un umano e un assistente di intelligenza artificiale. L'assistente fornisce risposte utili ed educate alle domande dell'uomo.", # noqa
448
+ "LT": "Žmogaus ir dirbtinio intelekto asistento pokalbis. Asistentas naudingai ir mandagiai atsako į žmogaus klausimus.", # noqa
449
+ "LV": "Cilvēka un mākslīgā intelekta asistenta tērzēšana. Asistents sniedz noderīgas un pieklājīgas atbildes uz cilvēka jautājumiem.", # noqa
450
+ "MT": "Chat bejn bniedem u assistent ta' intelliġenza artifiċjali. L-assistent jagħti tweġibiet ta' għajnuna u edukat għall-mistoqsijiet tal-bniedem.", # noqa
451
+ "NL": "Een chat tussen een mens en een assistent met kunstmatige intelligentie. De assistent geeft behulpzame en beleefde antwoorden op de vragen van de mens.", # noqa
452
+ "PL": "Czat między człowiekiem a asystentem sztucznej inteligencji. Asystent udziela pomocnych i uprzejmych odpowiedzi na pytania człowieka.", # noqa
453
+ "PT": "Uma conversa entre um ser humano e um assistente de inteligência artificial. O assistente dá respostas úteis e educadas às perguntas do utilizador.", # noqa
454
+ "RO": "O conversație între un om și un asistent cu inteligență artificială. Asistentul oferă răspunsuri utile și politicoase la întrebările omului.", # noqa
455
+ "SK": "Rozhovor medzi človekom a asistentom s umelou inteligenciou. Asistent poskytuje užitočné a zdvorilé odpovede na otázky človeka.", # noqa
456
+ "SL": "Pogovor med človekom in pomočnikom z umetno inteligenco. Pomočnik človeku prijazno in vljudno odgovarja na njegova vprašanja.", # noqa
457
+ "SV": "En chatt mellan en människa och en assistent med artificiell intelligens. Assistenten ger hjälpsamma och artiga svar på människans frågor.", # noqa
458
+ }
459
+ chat_template = "{%- for message in messages %}\n{%- if (message['role']|lower == 'user') != (loop.index0 % 2 == 0) %}\n{{- raise_exception('Roles must alternate User/Assistant/User/Assistant/...') }}\n{%- endif %}\n{%-if message['role']|lower == 'user' %}\n{{- message['role']|capitalize + ': ' + message['content'] + '\\n' }}\n{%- elif message['role']|lower == 'assistant' %}\n{{- message['role']|capitalize + ': ' + message['content'] + eos_token + '\\n' }}\n{%- else %}\n{{- raise_exception('Only user and assistant roles are supported!') }}\n {%- endif %}\n{%- endfor %}{%-if add_generation_prompt %}\n{{- 'Assistant: '}}\n{%- endif %}\n"
460
+ self.chat_template = {
461
+ lang: f"System: {sys_msg}" + "{{- '\\n'}}\n" + chat_template
462
+ for lang, sys_msg in self.system_messages_by_lang.items()
463
+ }