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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-instruct-commercial-v0.4"
|
18 |
+
|
19 |
+
class HFGPTXTokenizer(PreTrainedTokenizer):
|
20 |
+
"""
|
21 |
+
A custom tokenizer class that extends Hugging Face's PreTrainedTokenizer.
|
22 |
+
It is specifically designed to work with SentencePiece models and integrates
|
23 |
+
with Hugging Face's tokenizer utilities.
|
24 |
+
"""
|
25 |
+
|
26 |
+
model_file_glob = "*tokenizer.json"
|
27 |
+
vocab_files_names = {"tokenizer_file": "tokenizer.json"}
|
28 |
+
decode_kwargs: List[str] = []
|
29 |
+
|
30 |
+
def _encode(self, text: str, return_tokens: bool = False, is_continuation: bool = False):
|
31 |
+
"""
|
32 |
+
Encode a given text using the tokenizer.
|
33 |
+
|
34 |
+
Args:
|
35 |
+
text (str): The text to encode.
|
36 |
+
return_tokens (bool): If True, returns token strings instead of token IDs.
|
37 |
+
is_continuation (bool): If True, uses a continuation tokenizer (if available).
|
38 |
+
Returns:
|
39 |
+
List[int] or List[str]: Encoded text as a list of token IDs or token strings.
|
40 |
+
"""
|
41 |
+
assert self.tok is not None, "No tokenizer is currently loaded"
|
42 |
+
|
43 |
+
# Variant with additional sp processor:
|
44 |
+
tokenizer = self.continuation_tokenizer if is_continuation else self.tok
|
45 |
+
|
46 |
+
if return_tokens:
|
47 |
+
return tokenizer.encode_as_pieces(text)
|
48 |
+
else:
|
49 |
+
return tokenizer.encode(text)
|
50 |
+
|
51 |
+
def create_list_of_special_tokens(self) -> List[str]:
|
52 |
+
"""
|
53 |
+
Create a list of special tokens, including the BOS, EOS, PAD, EOD tokens,
|
54 |
+
and 256 additional placeholder tokens.
|
55 |
+
Returns:
|
56 |
+
List[str]: List of special tokens.
|
57 |
+
"""
|
58 |
+
return [self.bos_token, self.eos_token, self.pad_token, self.eod_token] + [
|
59 |
+
f"<placeholder_tok_{i}>" for i in range(256)
|
60 |
+
]
|
61 |
+
|
62 |
+
def find_tokenizer_config(self, config_path: Path, repo_id: str = None) -> Optional[Path]:
|
63 |
+
if not os.path.isfile(config_path):
|
64 |
+
config_path = try_to_load_from_cache(repo_id=repo_id, filename=Path(config_path).name)
|
65 |
+
if not config_path:
|
66 |
+
config_path = self._download_config_from_hub(repo_id=repo_id)
|
67 |
+
|
68 |
+
return config_path
|
69 |
+
|
70 |
+
|
71 |
+
def instantiate_from_file_or_name(self, model_file_or_name: str, repo_id: str = None):
|
72 |
+
"""
|
73 |
+
Load the tokenizer model from a file or download it from a repository.
|
74 |
+
|
75 |
+
Args:
|
76 |
+
model_file_or_name (str): Path to the model file or the model name.
|
77 |
+
repo_id (str, optional): Repository ID from which to download the model file.
|
78 |
+
|
79 |
+
Returns:
|
80 |
+
spm.SentencePieceProcessor: Loaded SentencePieceProcessor instance.
|
81 |
+
|
82 |
+
Raises:
|
83 |
+
ValueError: If repo_id is not provided when model_file_or_name is not a file.
|
84 |
+
OSError: If the model file cannot be loaded or downloaded.
|
85 |
+
"""
|
86 |
+
if not os.path.isfile(model_file_or_name):
|
87 |
+
model_file_or_name = try_to_load_from_cache(repo_id=repo_id, filename=Path(model_file_or_name).name)
|
88 |
+
if not model_file_or_name:
|
89 |
+
model_file_or_name = self._download_model_from_hub(repo_id=repo_id)
|
90 |
+
|
91 |
+
try:
|
92 |
+
return spm.SentencePieceProcessor(model_file=model_file_or_name)
|
93 |
+
except Exception as e:
|
94 |
+
raise OSError(f"Failed to load tokenizer model: {str(e)}")
|
95 |
+
|
96 |
+
def _download_model_from_hub(self, repo_id: str) -> Optional[str]:
|
97 |
+
try:
|
98 |
+
# List all files in the repo
|
99 |
+
repo_files = list_repo_files(repo_id)
|
100 |
+
|
101 |
+
# Find the tokenizer model file
|
102 |
+
tokenizer_files = [f for f in repo_files if f.endswith('.model')]
|
103 |
+
if not tokenizer_files:
|
104 |
+
raise FileNotFoundError(f"No .model file found in repository {repo_id}")
|
105 |
+
|
106 |
+
# Use the first .model file found
|
107 |
+
model_file = tokenizer_files[0]
|
108 |
+
print(f"Found tokenizer model file: {model_file}")
|
109 |
+
|
110 |
+
# Download the file
|
111 |
+
model_file_or_name = hf_hub_download(repo_id=repo_id, filename=model_file)
|
112 |
+
print(f"Downloaded tokenizer model to: {model_file_or_name}")
|
113 |
+
except Exception as e:
|
114 |
+
raise OSError(f"Failed to download tokenizer model: {str(e)}")
|
115 |
+
|
116 |
+
return model_file_or_name
|
117 |
+
|
118 |
+
def _download_config_from_hub(self, repo_id: str):
|
119 |
+
if repo_id is None:
|
120 |
+
raise ValueError("repo_id must be provided if config_path is not a local file")
|
121 |
+
|
122 |
+
try:
|
123 |
+
# List all files in the repo
|
124 |
+
repo_files = list_repo_files(repo_id)
|
125 |
+
|
126 |
+
# Find the tokenizer config file
|
127 |
+
tokenizer_files = [f for f in repo_files if f.endswith('tokenizer_config.json')]
|
128 |
+
if not tokenizer_files:
|
129 |
+
raise FileNotFoundError(f"No tokenizer_config.json file found in repository {repo_id}")
|
130 |
+
|
131 |
+
# Use the first tokenizer_config.json file found
|
132 |
+
tokenizer_config_file = tokenizer_files[0]
|
133 |
+
print(f"Found tokenizer config file: {tokenizer_config_file}")
|
134 |
+
|
135 |
+
# Download the file
|
136 |
+
tokenizer_config_file_or_name = hf_hub_download(repo_id=repo_id, filename=tokenizer_config_file)
|
137 |
+
print(f"Downloaded tokenizer config file to: {tokenizer_config_file_or_name}")
|
138 |
+
return tokenizer_config_file_or_name
|
139 |
+
except Exception as e:
|
140 |
+
raise OSError(f"Failed to download tokenizer model: {str(e)}")
|
141 |
+
def __init__(
|
142 |
+
self,
|
143 |
+
model_path: Optional[str] = None,
|
144 |
+
config_path: Optional[str] = None,
|
145 |
+
**kwargs: Any,
|
146 |
+
) -> None:
|
147 |
+
"""
|
148 |
+
Initialize the tokenizer.
|
149 |
+
Args:
|
150 |
+
model_path (Optional[str]): Path to the tokenizer model file.
|
151 |
+
config_path (Optional[str]): Path to the tokenizer configuration file.
|
152 |
+
**kwargs: Additional keyword arguments passed to the superclass.
|
153 |
+
This method also ensures backward compatibility by setting
|
154 |
+
`clean_up_tokenization_spaces` to False by default.
|
155 |
+
"""
|
156 |
+
# Prevent cleanup of tokenization spaces to maintain backward compatibility
|
157 |
+
self.clean_up_tokenization_spaces = kwargs.setdefault("clean_up_tokenization_spaces", False)
|
158 |
+
self.vocab = None
|
159 |
+
cp_path = kwargs.get("name_or_path", ".")
|
160 |
+
if model_path is None:
|
161 |
+
model_path = str(Path(cp_path) / self.vocab_files_names["tokenizer_file"])
|
162 |
+
self.tok = self.instantiate_from_file_or_name(model_path, repo_id=REPO_ID)
|
163 |
+
|
164 |
+
super().__init__(**kwargs)
|
165 |
+
|
166 |
+
# Specify special tokens which we know the value of.
|
167 |
+
# EOD from `tok` is used as what is called EOS in HuggingFace.
|
168 |
+
# Since there is no corresponding mapping for EOS from `tok` in
|
169 |
+
# HuggingFace, it is treated as an additional special token.
|
170 |
+
# Same for all other special tokens.
|
171 |
+
|
172 |
+
|
173 |
+
self.unk_token = "<unk>"
|
174 |
+
self.eos_token = "</s>"
|
175 |
+
self.bos_token = "<s>"
|
176 |
+
self.pad_token = "<pad>"
|
177 |
+
self.eod_token = "<eod>"
|
178 |
+
|
179 |
+
self.additional_special_tokens = self.create_list_of_special_tokens()
|
180 |
+
|
181 |
+
if config_path is None:
|
182 |
+
config_path = str(Path(cp_path) / TOKENIZER_CONFIG_FILE)
|
183 |
+
|
184 |
+
if os.path.isfile(config_path):
|
185 |
+
self.tokenizer_config = self.load_json(Path(config_path))
|
186 |
+
else: # Load from repo
|
187 |
+
self.tokenizer_config = self.load_json(Path(self.find_tokenizer_config(Path(config_path), repo_id=REPO_ID)))
|
188 |
+
|
189 |
+
@property
|
190 |
+
def vocab_size(self) -> int:
|
191 |
+
"""
|
192 |
+
Get the size of the tokenizer vocabulary.
|
193 |
+
Returns:
|
194 |
+
int: The size of the vocabulary.
|
195 |
+
"""
|
196 |
+
return self.tok.GetPieceSize()
|
197 |
+
|
198 |
+
def get_vocab(self) -> Dict[str, int]:
|
199 |
+
"""
|
200 |
+
Get the vocabulary as a dictionary mapping token strings to their IDs.
|
201 |
+
Returns:
|
202 |
+
Dict[str, int]: Vocabulary mapping.
|
203 |
+
"""
|
204 |
+
if self.vocab is None:
|
205 |
+
self.vocab = {self.tok.IdToPiece(i): i for i in range(self.vocab_size)}
|
206 |
+
return self.vocab
|
207 |
+
|
208 |
+
def _tokenize(self, text: str, **kwargs) -> List[int]:
|
209 |
+
"""
|
210 |
+
Tokenize the input text.
|
211 |
+
Args:
|
212 |
+
text (str): Text to tokenize.
|
213 |
+
**kwargs: Additional keyword arguments.
|
214 |
+
Returns:
|
215 |
+
List[int]: List of token IDs.
|
216 |
+
"""
|
217 |
+
return_tokens = kwargs.pop("return_tokens", True)
|
218 |
+
return self._encode(text, return_tokens=return_tokens, **kwargs)
|
219 |
+
|
220 |
+
def _convert_token_to_id(self, token: str) -> int:
|
221 |
+
"""
|
222 |
+
Convert a token string to its corresponding ID.
|
223 |
+
Args:
|
224 |
+
token (str): The token to convert.
|
225 |
+
Returns:
|
226 |
+
int: The token's ID.
|
227 |
+
Raises:
|
228 |
+
ValueError: If the token is unknown and cannot be encoded to a single ID.
|
229 |
+
"""
|
230 |
+
return self.tok.PieceToId(token)
|
231 |
+
|
232 |
+
|
233 |
+
def decode(
|
234 |
+
self,
|
235 |
+
token_ids: Union[List[int], List[List[int]]],
|
236 |
+
num_threads: Optional[int] = None,
|
237 |
+
skip_special_tokens: bool = False,
|
238 |
+
clean_up_tokenization_spaces: bool = False,
|
239 |
+
) -> str:
|
240 |
+
"""
|
241 |
+
Decode a list of token IDs into a string.
|
242 |
+
Args:
|
243 |
+
token_ids (Union[List[int], List[List[int]]]): List of token IDs or lists of token IDs.
|
244 |
+
num_threads (Optional[int]): Number of threads to use for decoding.
|
245 |
+
Returns:
|
246 |
+
str: Decoded string.
|
247 |
+
"""
|
248 |
+
if isinstance(token_ids, torch.Tensor): # For PyTorch tensors
|
249 |
+
token_ids = token_ids.tolist()
|
250 |
+
elif isinstance(token_ids, np.ndarray): # For NumPy arrays
|
251 |
+
token_ids = token_ids.tolist()
|
252 |
+
|
253 |
+
output = self.tok.decode(input=token_ids, num_threads=num_threads)
|
254 |
+
if skip_special_tokens:
|
255 |
+
for substring in self.additional_special_tokens:
|
256 |
+
output = output.replace(substring, "")
|
257 |
+
|
258 |
+
if clean_up_tokenization_spaces:
|
259 |
+
warnings.warn(
|
260 |
+
"when cleaning up tokenization spaces, this will not behave "
|
261 |
+
"like the original `GPTXTokenizer`., Please supply "
|
262 |
+
"`clean_up_tokenization_spaces=False` for decoding."
|
263 |
+
)
|
264 |
+
output = self.clean_up_tokenization(output)
|
265 |
+
|
266 |
+
return output
|
267 |
+
|
268 |
+
|
269 |
+
def _convert_id_to_token(self, index: int) -> str:
|
270 |
+
"""
|
271 |
+
Convert a token ID to its corresponding token string.
|
272 |
+
Args:
|
273 |
+
index (int): Token ID.
|
274 |
+
Returns:
|
275 |
+
str: Corresponding token string.
|
276 |
+
"""
|
277 |
+
return self.tok.IdToPiece(index)
|
278 |
+
|
279 |
+
def convert_tokens_to_string(self, tokens: List[str]) -> str:
|
280 |
+
"""
|
281 |
+
Convert a list of tokens into a single string.
|
282 |
+
Args:
|
283 |
+
tokens (List[str]): List of token strings.
|
284 |
+
Returns:
|
285 |
+
str: Concatenated string of tokens.
|
286 |
+
"""
|
287 |
+
return self.tok.DecodePieces(tokens)
|
288 |
+
|
289 |
+
def _tok_decode(self, token_ids: List[int], **kwargs: Any) -> str:
|
290 |
+
"""
|
291 |
+
Internal method to decode token IDs with additional arguments.
|
292 |
+
Args:
|
293 |
+
token_ids (List[int]): List of token IDs.
|
294 |
+
**kwargs: Additional arguments to pass to the decode method.
|
295 |
+
Returns:
|
296 |
+
str: Decoded string.
|
297 |
+
This method also issues a warning if unsupported arguments are provided.
|
298 |
+
"""
|
299 |
+
passed_kwargs = {key: value for (key, value) in kwargs.items() if key in self.decode_kwargs}
|
300 |
+
if len(passed_kwargs) != len(kwargs):
|
301 |
+
warnings.warn("silently ignoring some arguments to `decode` due to missing " "support from the tokenizer.")
|
302 |
+
text = self.decode(token_ids, **passed_kwargs)
|
303 |
+
return text
|
304 |
+
|
305 |
+
def save_tokenizer(self, save_dir: str) -> None:
|
306 |
+
if not os.path.isdir(save_dir):
|
307 |
+
print(f"Vocabulary path ({save_dir}) should be a directory")
|
308 |
+
return
|
309 |
+
out_vocab_file = os.path.join(save_dir, "tokenizer.model")
|
310 |
+
|
311 |
+
# if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
312 |
+
# copyfile(self.vocab_file, out_vocab_file)
|
313 |
+
# elif not os.path.isfile(self.vocab_file):
|
314 |
+
with open(out_vocab_file, "wb") as f:
|
315 |
+
content_spiece_model = self.tok.serialized_model_proto()
|
316 |
+
f.write(content_spiece_model)
|
317 |
+
|
318 |
+
return (out_vocab_file,)
|
319 |
+
|
320 |
+
def _decode(
|
321 |
+
self,
|
322 |
+
token_ids: List[int],
|
323 |
+
skip_special_tokens: bool = False,
|
324 |
+
clean_up_tokenization_spaces: bool = None,
|
325 |
+
spaces_between_special_tokens: bool = True,
|
326 |
+
**kwargs: Any,
|
327 |
+
) -> str:
|
328 |
+
text = self._tok_decode(
|
329 |
+
token_ids,
|
330 |
+
skip_special_tokens=skip_special_tokens,
|
331 |
+
spaces_between_special_tokens=spaces_between_special_tokens,
|
332 |
+
**kwargs,
|
333 |
+
)
|
334 |
+
|
335 |
+
clean_up_tokenization_spaces = (
|
336 |
+
clean_up_tokenization_spaces
|
337 |
+
if clean_up_tokenization_spaces is not None
|
338 |
+
else self.clean_up_tokenization_spaces
|
339 |
+
)
|
340 |
+
if clean_up_tokenization_spaces:
|
341 |
+
warnings.warn(
|
342 |
+
"when cleaning up tokenization spaces, this will not behave "
|
343 |
+
"like the original `GPTXTokenizer`., Please supply "
|
344 |
+
"`clean_up_tokenization_spaces=False` for decoding."
|
345 |
+
)
|
346 |
+
clean_text = self.clean_up_tokenization(text)
|
347 |
+
return clean_text
|
348 |
+
else:
|
349 |
+
return text
|
350 |
+
|
351 |
+
def save_vocabulary(
|
352 |
+
self,
|
353 |
+
save_directory: str,
|
354 |
+
filename_prefix: Optional[str] = None,
|
355 |
+
) -> Tuple[str]:
|
356 |
+
filename_prefix = filename_prefix + "-" if filename_prefix else ""
|
357 |
+
save_directory = Path(save_directory)
|
358 |
+
|
359 |
+
self._save_tokenizer_config(save_directory, filename_prefix)
|
360 |
+
tokenizer_file_path = self._save_tokenizer(save_directory, filename_prefix)
|
361 |
+
|
362 |
+
return (tokenizer_file_path,)
|
363 |
+
|
364 |
+
def _save_tokenizer_config(
|
365 |
+
self,
|
366 |
+
save_directory: Path,
|
367 |
+
filename_prefix: str,
|
368 |
+
) -> str:
|
369 |
+
self.save_tokenizer_config(save_directory)
|
370 |
+
old_tokenizer_config_path = save_directory / TOKENIZER_CONFIG_FILE
|
371 |
+
assert old_tokenizer_config_path.is_file(), "tokenizer config path changed"
|
372 |
+
new_tokenizer_config_path = save_directory / (filename_prefix + old_tokenizer_config_path.name)
|
373 |
+
old_tokenizer_config_path.replace(new_tokenizer_config_path)
|
374 |
+
return str(new_tokenizer_config_path)
|
375 |
+
|
376 |
+
def _find_tokenizer_files(self, save_directory: Path) -> List[Path]:
|
377 |
+
files = list(Path(save_directory).glob(self.model_file_glob))
|
378 |
+
return files
|
379 |
+
|
380 |
+
def _get_tokenizer_file(self, files: List[Path]):
|
381 |
+
assert files, "no saved tokenizer file found"
|
382 |
+
assert len(files) <= 1, "cannot handle multiple saved tokenizer files"
|
383 |
+
return files[0]
|
384 |
+
|
385 |
+
def _save_tokenizer(
|
386 |
+
self,
|
387 |
+
save_directory: Path,
|
388 |
+
filename_prefix: str,
|
389 |
+
) -> str:
|
390 |
+
self.save_tokenizer(str(save_directory))
|
391 |
+
tokenizer_files = self._find_tokenizer_files(save_directory)
|
392 |
+
old_tokenizer_file_path = self._get_tokenizer_file(tokenizer_files)
|
393 |
+
assert old_tokenizer_file_path.is_file(), "could not access saved tokenizer file"
|
394 |
+
new_tokenizer_file_path = save_directory / (filename_prefix + self.vocab_files_names["tokenizer_file"])
|
395 |
+
old_tokenizer_file_path.replace(new_tokenizer_file_path)
|
396 |
+
return str(new_tokenizer_file_path)
|
397 |
+
|
398 |
+
def save_tokenizer_config(self, save_dir: Path) -> None:
|
399 |
+
# convert Path to str
|
400 |
+
for k in self.tokenizer_config:
|
401 |
+
if isinstance(self.tokenizer_config[k], Path):
|
402 |
+
self.tokenizer_config[k] = str(self.tokenizer_config[k])
|
403 |
+
|
404 |
+
info_file = save_dir / "tokenizer_config.json"
|
405 |
+
with info_file.open("w") as f:
|
406 |
+
json.dump(self.tokenizer_config, f, indent=4)
|
407 |
+
|
408 |
+
def load_json(self, path: Path) -> dict:
|
409 |
+
with path.open("r") as f:
|
410 |
+
return json.load(f)
|
411 |
+
|
412 |
+
class SPTokenizer(HFGPTXTokenizer):
|
413 |
+
model_file_glob = "*tokenizer.model"
|
414 |
+
vocab_files_names = {"tokenizer_file": "tokenizer.model"}
|
415 |
+
decode_kwargs = ["num_threads"]
|
416 |
+
# `is_continuation` does not work without this, but it doesn't
|
417 |
+
# implement all APIs of `PreTrainedTokenizer`.
|
418 |
+
def encode(self, text: str, **kwargs) -> List[int]:
|
419 |
+
return_tokens = kwargs.pop('return_tokens', False)
|
420 |
+
is_continuation = kwargs.pop('is_continuation', False)
|
421 |
+
return self._encode(
|
422 |
+
text,
|
423 |
+
return_tokens=return_tokens,
|
424 |
+
is_continuation=is_continuation,
|
425 |
+
)
|
426 |
+
|
427 |
+
def __init__(self, *args, **kwargs):
|
428 |
+
super().__init__(*args, **kwargs)
|
429 |
+
|
430 |
+
self.eos_token = "</s>"
|
431 |
+
self.eos_token_id = 2
|
432 |
+
self.system_messages_by_lang = { # translations by deepl / google translate
|
433 |
+
"BG": "Чат между човек и асистент с изкуствен интелект. Асистентът дава полезни и учтиви отговори на въпросите на човека.", # noqa
|
434 |
+
"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
|
435 |
+
"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
|
436 |
+
"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
|
437 |
+
"EL": "Μια συνομιλία μεταξύ ενός ανθρώπου και ενός βοηθού τεχνητής νοημοσύνης. Ο βοηθός δίνει χρήσιμες και ευγενικές απαντήσεις στις ερωτήσεις του ανθρώπου.", # noqa
|
438 |
+
"EN": "A chat between a human and an artificial intelligence assistant.The assistant gives helpful and polite answers to the human's questions.", # noqa
|
439 |
+
"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
|
440 |
+
"ET": "Inimese ja tehisintellekti assistendi vaheline vestlus. Assistent annab inimese küsimustele abivalmis ja viisakaid vastuseid.", # noqa
|
441 |
+
"FI": "Ihmisen ja tekoälyavustajan välinen keskustelu. Avustaja antaa avuliaita ja kohteliaita vastauksia ihmisen kysymyksiin.", # noqa
|
442 |
+
"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
|
443 |
+
"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
|
444 |
+
"HR": "Razgovor između čovjeka i pomoćnika umjetne inteligencije. Pomoćnik daje korisne i ljubazne odgovore na ljudska pitanja.", # noqa
|
445 |
+
"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
|
446 |
+
"IT": "Una chat tra un umano e un assistente di intelligenza artificiale. L'assistente fornisce risposte utili ed educate alle domande dell'uomo.", # noqa
|
447 |
+
"LT": "Žmogaus ir dirbtinio intelekto asistento pokalbis. Asistentas naudingai ir mandagiai atsako į žmogaus klausimus.", # noqa
|
448 |
+
"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
|
449 |
+
"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
|
450 |
+
"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
|
451 |
+
"PL": "Czat między człowiekiem a asystentem sztucznej inteligencji. Asystent udziela pomocnych i uprzejmych odpowiedzi na pytania człowieka.", # noqa
|
452 |
+
"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
|
453 |
+
"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
|
454 |
+
"SK": "Rozhovor medzi človekom a asistentom s umelou inteligenciou. Asistent poskytuje užitočné a zdvorilé odpovede na otázky človeka.", # noqa
|
455 |
+
"SL": "Pogovor med človekom in pomočnikom z umetno inteligenco. Pomočnik človeku prijazno in vljudno odgovarja na njegova vprašanja.", # noqa
|
456 |
+
"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
|
457 |
+
}
|
458 |
+
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"
|
459 |
+
self.chat_template = {
|
460 |
+
lang: f"System: {sys_msg}" + "{{- '\\n'}}\n" + chat_template
|
461 |
+
for lang, sys_msg in self.system_messages_by_lang.items()
|
462 |
+
}
|
463 |
+
self.chat_template['default'] = f"System: {self.system_messages_by_lang['EN']}" + "{{- '\\n'}}\n" + chat_template
|