Kekulanus commited on
Commit
305f1e7
·
verified ·
1 Parent(s): 9ae90c4

Upload tokenization_iquestcoder.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. tokenization_iquestcoder.py +553 -0
tokenization_iquestcoder.py ADDED
@@ -0,0 +1,553 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # IQuest NVFP4 Quantized Model - Official Architecture
2
+ """Tokenization classes for IQuestCoder."""
3
+
4
+ import os
5
+ from shutil import copyfile
6
+ from typing import Any, Dict, List, Optional, Tuple, Union
7
+
8
+ import sentencepiece as spm
9
+
10
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
11
+ from transformers.utils import logging
12
+
13
+
14
+ logger = logging.get_logger(__name__)
15
+
16
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
17
+
18
+ PRETRAINED_VOCAB_FILES_MAP = {
19
+ "vocab_file": {},
20
+ "tokenizer_file": {},
21
+ }
22
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
23
+
24
+
25
+
26
+ class IQuestCoderTokenizer(PreTrainedTokenizer):
27
+
28
+ vocab_files_names = VOCAB_FILES_NAMES
29
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
30
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
31
+ model_input_names = ["input_ids", "attention_mask"]
32
+
33
+ def __init__(
34
+ self,
35
+ vocab_file,
36
+ unk_token="<unk>",
37
+ bos_token="<s>",
38
+ eos_token="</s>",
39
+ pad_token=None,
40
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
41
+ add_bos_token=True,
42
+ add_eos_token=False,
43
+ clean_up_tokenization_spaces=False,
44
+ add_prefix_space=False,
45
+ legacy=None,
46
+ use_default_system_prompt=False,
47
+ chat_template=None,
48
+ **kwargs,
49
+ ):
50
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
51
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
52
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
53
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
54
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
55
+
56
+ # Legacy behavior handling
57
+ if legacy is None:
58
+ logger.warning_once(
59
+ f"You are using the default legacy behaviour of the {self.__class__.__name__}. This is"
60
+ " expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you."
61
+ " If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it"
62
+ " means, and thoroughly read the reason why this was added as explained in"
63
+ " https://github.com/huggingface/transformers/pull/24565"
64
+ )
65
+ legacy = True
66
+
67
+ self.legacy = legacy
68
+ self.vocab_file = vocab_file
69
+ self.add_bos_token = add_bos_token
70
+ self.add_eos_token = add_eos_token
71
+ self.add_prefix_space = add_prefix_space
72
+ self.use_default_system_prompt = use_default_system_prompt
73
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
74
+ self.sp_model.Load(vocab_file)
75
+
76
+
77
+
78
+ super().__init__(
79
+ bos_token=bos_token,
80
+ eos_token=eos_token,
81
+ unk_token=unk_token,
82
+ pad_token=pad_token,
83
+ add_bos_token=add_bos_token,
84
+ add_eos_token=add_eos_token,
85
+ sp_model_kwargs=self.sp_model_kwargs,
86
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
87
+ add_prefix_space=add_prefix_space,
88
+ legacy=legacy,
89
+ use_default_system_prompt=use_default_system_prompt,
90
+ chat_template=chat_template,
91
+ **kwargs,
92
+ )
93
+
94
+ def __getstate__(self):
95
+ state = self.__dict__.copy()
96
+ state["sp_model"] = None
97
+ return state
98
+
99
+ def __setstate__(self, d):
100
+ self.__dict__ = d
101
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
102
+ self.sp_model.Load(self.vocab_file)
103
+
104
+ @property
105
+ def vocab_size(self) -> int:
106
+ """Returns the vocabulary size."""
107
+ return self.sp_model.get_piece_size()
108
+
109
+ def get_vocab(self) -> Dict[str, int]:
110
+ """Returns the vocabulary as a dictionary of token to index."""
111
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
112
+ vocab.update(self.added_tokens_encoder)
113
+ return vocab
114
+
115
+ def _tokenize(self, text: str) -> List[str]:
116
+ """
117
+ Tokenize a string.
118
+
119
+ Args:
120
+ text (`str`): The text to tokenize.
121
+
122
+ Returns:
123
+ `List[str]`: The list of tokens.
124
+ """
125
+ if self.add_prefix_space:
126
+ text = " " + text
127
+
128
+ if self.legacy:
129
+ return self.sp_model.encode(text, out_type=str)
130
+
131
+ # Non-legacy behavior: handle special tokens properly
132
+ return self.sp_model.encode(text, out_type=str)
133
+
134
+ def _convert_token_to_id(self, token: str) -> int:
135
+ """Converts a token (str) to an id using the vocab."""
136
+ return self.sp_model.piece_to_id(token)
137
+
138
+ def _convert_id_to_token(self, index: int) -> str:
139
+ """Converts an index (integer) to a token (str) using the vocab."""
140
+ token = self.sp_model.IdToPiece(index)
141
+ return token
142
+
143
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
144
+ """
145
+ Converts a sequence of tokens (strings) to a single string.
146
+
147
+ This method handles special tokens separately to ensure they are not
148
+ decoded using the SentencePiece model.
149
+
150
+ Args:
151
+ tokens (`List[str]`): The list of tokens to convert.
152
+
153
+ Returns:
154
+ `str`: The decoded string.
155
+ """
156
+ current_sub_tokens = []
157
+ out_string = ""
158
+ prev_is_special = False
159
+ for i, token in enumerate(tokens):
160
+ # make sure that special tokens are not decoded using sentencepiece model
161
+ if token in self.all_special_tokens:
162
+ if not prev_is_special and i != 0:
163
+ out_string += " "
164
+ out_string += self.sp_model.decode(current_sub_tokens) + token
165
+ prev_is_special = True
166
+ current_sub_tokens = []
167
+ else:
168
+ current_sub_tokens.append(token)
169
+ prev_is_special = False
170
+ out_string += self.sp_model.decode(current_sub_tokens)
171
+ return out_string
172
+
173
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
174
+ """
175
+ Save the vocabulary and special tokens file to a directory.
176
+
177
+ Args:
178
+ save_directory (`str`):
179
+ The directory in which to save the vocabulary.
180
+ filename_prefix (`str`, *optional*):
181
+ An optional prefix to add to the named of the saved files.
182
+
183
+ Returns:
184
+ `Tuple(str)`: Paths to the files saved.
185
+ """
186
+ if not os.path.isdir(save_directory):
187
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
188
+ return
189
+ out_vocab_file = os.path.join(
190
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
191
+ )
192
+
193
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
194
+ copyfile(self.vocab_file, out_vocab_file)
195
+ elif not os.path.isfile(self.vocab_file):
196
+ with open(out_vocab_file, "wb") as fi:
197
+ content_spiece_model = self.sp_model.serialized_model_proto()
198
+ fi.write(content_spiece_model)
199
+
200
+ return (out_vocab_file,)
201
+
202
+ def build_inputs_with_special_tokens(
203
+ self,
204
+ token_ids_0: List[int],
205
+ token_ids_1: Optional[List[int]] = None
206
+ ) -> List[int]:
207
+ """
208
+ Build model inputs from a sequence or a pair of sequences for sequence classification tasks by concatenating
209
+ and adding special tokens.
210
+
211
+ An IQuestCoder sequence has the following format:
212
+
213
+ - single sequence: `<s> X </s>` (if add_eos_token is True) or `<s> X` (default)
214
+ - pair of sequences: `<s> A </s> <s> B </s>` (if add_eos_token is True) or `<s> A <s> B` (default)
215
+
216
+ Args:
217
+ token_ids_0 (`List[int]`):
218
+ List of IDs to which the special tokens will be added.
219
+ token_ids_1 (`List[int]`, *optional*):
220
+ Optional second list of IDs for sequence pairs.
221
+
222
+ Returns:
223
+ `List[int]`: List of input IDs with the appropriate special tokens.
224
+ """
225
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
226
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
227
+
228
+ output = bos_token_id + token_ids_0 + eos_token_id
229
+
230
+ if token_ids_1 is not None:
231
+ output = output + bos_token_id + token_ids_1 + eos_token_id
232
+
233
+ return output
234
+
235
+ def get_special_tokens_mask(
236
+ self,
237
+ token_ids_0: List[int],
238
+ token_ids_1: Optional[List[int]] = None,
239
+ already_has_special_tokens: bool = False
240
+ ) -> List[int]:
241
+ """
242
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
243
+ special tokens using the tokenizer `prepare_for_model` method.
244
+
245
+ Args:
246
+ token_ids_0 (`List[int]`):
247
+ List of IDs.
248
+ token_ids_1 (`List[int]`, *optional*):
249
+ Optional second list of IDs for sequence pairs.
250
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
251
+ Whether or not the token list is already formatted with special tokens for the model.
252
+
253
+ Returns:
254
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
255
+ """
256
+ if already_has_special_tokens:
257
+ return super().get_special_tokens_mask(
258
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
259
+ )
260
+
261
+ bos_token_id = [1] if self.add_bos_token else []
262
+ eos_token_id = [1] if self.add_eos_token else []
263
+
264
+ if token_ids_1 is None:
265
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
266
+ return (
267
+ bos_token_id
268
+ + ([0] * len(token_ids_0))
269
+ + eos_token_id
270
+ + bos_token_id
271
+ + ([0] * len(token_ids_1))
272
+ + eos_token_id
273
+ )
274
+
275
+ def create_token_type_ids_from_sequences(
276
+ self,
277
+ token_ids_0: List[int],
278
+ token_ids_1: Optional[List[int]] = None
279
+ ) -> List[int]:
280
+ """
281
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task.
282
+
283
+ An IQuestCoder sequence pair mask has the following format:
284
+
285
+ ```
286
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
287
+ | first sequence | second sequence |
288
+ ```
289
+
290
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
291
+
292
+ Args:
293
+ token_ids_0 (`List[int]`):
294
+ List of IDs.
295
+ token_ids_1 (`List[int]`, *optional*):
296
+ Optional second list of IDs for sequence pairs.
297
+
298
+ Returns:
299
+ `List[int]`: List of token type IDs according to the given sequence(s).
300
+ """
301
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
302
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
303
+
304
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
305
+
306
+ if token_ids_1 is not None:
307
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
308
+
309
+ return output
310
+
311
+ @property
312
+ def default_chat_template(self) -> str:
313
+ """
314
+ Returns the default chat template for IQuestCoder.
315
+
316
+ This template formats conversations with system, user, and assistant roles.
317
+ """
318
+ return DEFAULT_CHAT_TEMPLATE
319
+
320
+ def apply_chat_template(
321
+ self,
322
+ conversation: Union[List[Dict[str, str]], "Conversation"],
323
+ chat_template: Optional[str] = None,
324
+ add_generation_prompt: bool = False,
325
+ tokenize: bool = True,
326
+ padding: bool = False,
327
+ truncation: bool = False,
328
+ max_length: Optional[int] = None,
329
+ return_tensors: Optional[str] = None,
330
+ return_dict: bool = False,
331
+ **tokenizer_kwargs,
332
+ ):
333
+ """
334
+ Apply a chat template to format a conversation.
335
+
336
+ Args:
337
+ conversation (`List[Dict[str, str]]` or `Conversation`):
338
+ A list of dicts with "role" and "content" keys, representing the conversation history.
339
+ chat_template (`str`, *optional*):
340
+ A Jinja template to use for formatting. If not provided, the tokenizer's default will be used.
341
+ add_generation_prompt (`bool`, *optional*, defaults to `False`):
342
+ Whether to add a generation prompt at the end for the assistant to continue.
343
+ tokenize (`bool`, *optional*, defaults to `True`):
344
+ Whether to tokenize the output. If `False`, returns a string.
345
+ padding (`bool`, *optional*, defaults to `False`):
346
+ Whether to pad sequences.
347
+ truncation (`bool`, *optional*, defaults to `False`):
348
+ Whether to truncate sequences.
349
+ max_length (`int`, *optional*):
350
+ Maximum length of the output.
351
+ return_tensors (`str`, *optional*):
352
+ The type of tensors to return ("pt", "tf", "np", or None).
353
+ return_dict (`bool`, *optional*, defaults to `False`):
354
+ Whether to return a dictionary with additional information.
355
+ **tokenizer_kwargs:
356
+ Additional keyword arguments passed to the tokenizer.
357
+
358
+ Returns:
359
+ `Union[str, List[int], BatchEncoding]`: The formatted (and optionally tokenized) conversation.
360
+
361
+ Example:
362
+ ```python
363
+ >>> tokenizer = IQuestCoderTokenizer.from_pretrained("path/to/model")
364
+ >>> conversation = [
365
+ ... {"role": "system", "content": "You are a helpful assistant."},
366
+ ... {"role": "user", "content": "Hello!"},
367
+ ... {"role": "assistant", "content": "Hi there! How can I help you today?"},
368
+ ... {"role": "user", "content": "What's the weather like?"},
369
+ ... ]
370
+ >>> tokenizer.apply_chat_template(conversation, add_generation_prompt=True, tokenize=False)
371
+ '<|system|>\\nYou are a helpful assistant.\\n</|system|><|user|>\\nHello!\\n</|user|>...'
372
+ ```
373
+ """
374
+ # Use parent class implementation with our template
375
+ return super().apply_chat_template(
376
+ conversation,
377
+ chat_template=chat_template,
378
+ add_generation_prompt=add_generation_prompt,
379
+ tokenize=tokenize,
380
+ padding=padding,
381
+ truncation=truncation,
382
+ max_length=max_length,
383
+ return_tensors=return_tensors,
384
+ return_dict=return_dict,
385
+ **tokenizer_kwargs,
386
+ )
387
+
388
+
389
+ # Try to import and create Fast tokenizer version
390
+ try:
391
+ from transformers import PreTrainedTokenizerFast
392
+ from tokenizers import Tokenizer, decoders, models, normalizers, pre_tokenizers, processors
393
+
394
+ class IQuestCoderTokenizerFast(PreTrainedTokenizerFast):
395
+ """
396
+ Construct a "fast" IQuestCoder tokenizer (backed by HuggingFace's *tokenizers* library).
397
+
398
+ This is a fast implementation of [`IQuestCoderTokenizer`] using the 🤗 Tokenizers library.
399
+
400
+ Args:
401
+ vocab_file (`str`, *optional*):
402
+ Path to the vocabulary file (SentencePiece model).
403
+ tokenizer_file (`str`, *optional*):
404
+ Path to a tokenizer JSON file.
405
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
406
+ The unknown token.
407
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
408
+ The beginning of sequence token.
409
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
410
+ The end of sequence token.
411
+ pad_token (`str`, *optional*):
412
+ The token used for padding.
413
+ add_bos_token (`bool`, *optional*, defaults to `True`):
414
+ Whether to add a BOS token at the start of sequences.
415
+ add_eos_token (`bool`, *optional*, defaults to `False`):
416
+ Whether to add an EOS token at the end of sequences.
417
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
418
+ Whether to add an initial space to the input.
419
+ use_default_system_prompt (`bool`, *optional*, defaults to `False`):
420
+ Whether to use the default system prompt.
421
+ chat_template (`str`, *optional*):
422
+ A Jinja template for formatting conversations.
423
+
424
+ Example:
425
+ ```python
426
+ >>> from tokenization_iquestcoder import IQuestCoderTokenizerFast
427
+
428
+ >>> tokenizer = IQuestCoderTokenizerFast.from_pretrained("path/to/model")
429
+ >>> tokenizer.encode("Hello, world!")
430
+ [1, 15043, 29892, 3186, 29991]
431
+ ```
432
+ """
433
+
434
+ vocab_files_names = VOCAB_FILES_NAMES
435
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
436
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
437
+ model_input_names = ["input_ids", "attention_mask"]
438
+ slow_tokenizer_class = IQuestCoderTokenizer
439
+
440
+ def __init__(
441
+ self,
442
+ vocab_file=None,
443
+ tokenizer_file=None,
444
+ unk_token="<unk>",
445
+ bos_token="<s>",
446
+ eos_token="</s>",
447
+ pad_token=None,
448
+ add_bos_token=True,
449
+ add_eos_token=False,
450
+ add_prefix_space=False,
451
+ use_default_system_prompt=False,
452
+ chat_template=None,
453
+ **kwargs,
454
+ ):
455
+ self.add_bos_token = add_bos_token
456
+ self.add_eos_token = add_eos_token
457
+ self.add_prefix_space = add_prefix_space
458
+ self.use_default_system_prompt = use_default_system_prompt
459
+
460
+ if chat_template is None:
461
+ chat_template = DEFAULT_CHAT_TEMPLATE
462
+
463
+ super().__init__(
464
+ vocab_file=vocab_file,
465
+ tokenizer_file=tokenizer_file,
466
+ unk_token=unk_token,
467
+ bos_token=bos_token,
468
+ eos_token=eos_token,
469
+ pad_token=pad_token,
470
+ add_bos_token=add_bos_token,
471
+ add_eos_token=add_eos_token,
472
+ add_prefix_space=add_prefix_space,
473
+ use_default_system_prompt=use_default_system_prompt,
474
+ chat_template=chat_template,
475
+ **kwargs,
476
+ )
477
+
478
+ @property
479
+ def can_save_slow_tokenizer(self) -> bool:
480
+ return os.path.isfile(self.vocab_file) if self.vocab_file else False
481
+
482
+ @property
483
+ def default_chat_template(self) -> str:
484
+ """Returns the default chat template."""
485
+ return DEFAULT_CHAT_TEMPLATE
486
+
487
+ def build_inputs_with_special_tokens(
488
+ self,
489
+ token_ids_0: List[int],
490
+ token_ids_1: Optional[List[int]] = None
491
+ ) -> List[int]:
492
+ """Build model inputs with special tokens."""
493
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
494
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
495
+
496
+ output = bos_token_id + token_ids_0 + eos_token_id
497
+
498
+ if token_ids_1 is not None:
499
+ output = output + bos_token_id + token_ids_1 + eos_token_id
500
+
501
+ return output
502
+
503
+ def get_special_tokens_mask(
504
+ self,
505
+ token_ids_0: List[int],
506
+ token_ids_1: Optional[List[int]] = None,
507
+ already_has_special_tokens: bool = False
508
+ ) -> List[int]:
509
+ """Retrieve special tokens mask."""
510
+ if already_has_special_tokens:
511
+ return super().get_special_tokens_mask(
512
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
513
+ )
514
+
515
+ bos_token_id = [1] if self.add_bos_token else []
516
+ eos_token_id = [1] if self.add_eos_token else []
517
+
518
+ if token_ids_1 is None:
519
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
520
+ return (
521
+ bos_token_id
522
+ + ([0] * len(token_ids_0))
523
+ + eos_token_id
524
+ + bos_token_id
525
+ + ([0] * len(token_ids_1))
526
+ + eos_token_id
527
+ )
528
+
529
+ def create_token_type_ids_from_sequences(
530
+ self,
531
+ token_ids_0: List[int],
532
+ token_ids_1: Optional[List[int]] = None
533
+ ) -> List[int]:
534
+ """Create token type IDs from sequences."""
535
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
536
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
537
+
538
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
539
+
540
+ if token_ids_1 is not None:
541
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
542
+
543
+ return output
544
+
545
+ except ImportError:
546
+ # tokenizers library not available, Fast tokenizer not supported
547
+ IQuestCoderTokenizerFast = None
548
+ logger.info(
549
+ "The `tokenizers` library is not installed. "
550
+ "IQuestCoderTokenizerFast will not be available. "
551
+ "Install it with `pip install tokenizers`."
552
+ )
553
+