optimum-rbln 0.1.1__py3-none-any.whl → 0.1.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -39,12 +39,20 @@ from ....modeling_base import RBLNBaseModel
39
39
  from ....modeling_config import DEFAULT_COMPILED_MODEL_NAME, RBLNConfig, RBLNRuntimeConfig
40
40
  from ....utils.runtime_utils import RBLNPytorchRuntime
41
41
  from ....utils.save_utils import maybe_save_preprocessors
42
+
43
+
44
+ # FIXME:: Merge Two architecture Codes
42
45
  from .llama_architecture import (
43
46
  LlamaWrapper,
44
47
  wrap_llama,
45
48
  unwrap_llama,
46
49
  )
47
50
 
51
+ from .llama_architecture_cb import (
52
+ LlamaDynamicBatchWrapper as LlamaWrapper_cb,
53
+ wrap_llama as wrap_llama_cb,
54
+ )
55
+
48
56
 
49
57
  logger = logging.getLogger(__name__)
50
58
 
@@ -57,24 +65,12 @@ if TYPE_CHECKING:
57
65
  )
58
66
 
59
67
 
68
+ SUPPORTED_BATCHING_MODES = ["static", "vllm"]
69
+
70
+
60
71
  class RBLNRuntimeModel(RBLNPytorchRuntime):
61
72
  mandatory_members = ["main_input_name"]
62
73
 
63
- # RBLN_Runtimemodule
64
- def forward(
65
- self,
66
- input_ids: torch.LongTensor = None,
67
- attention_mask: torch.LongTensor = None,
68
- cache_position: torch.Tensor = None,
69
- **kwargs: Dict[str, Any],
70
- ):
71
- logits = super().forward(
72
- input_ids=input_ids,
73
- attention_mask=attention_mask,
74
- cache_position=cache_position,
75
- )
76
- return logits
77
-
78
74
 
79
75
  class RBLNLlamaForCausalLM(RBLNBaseModel, RBLNGenerationMixin):
80
76
  """
@@ -95,13 +91,16 @@ class RBLNLlamaForCausalLM(RBLNBaseModel, RBLNGenerationMixin):
95
91
  self.batch_size = self.rbln_config.meta["rbln_batch_size"]
96
92
  self.max_seq_len = self.rbln_config.meta["rbln_max_seq_len"]
97
93
  self.prefill_chunk_size = self.rbln_config.meta["rbln_prefill_chunk_size"]
94
+ self.use_continuous_batch = self.rbln_config.meta["rbln_batching"] == "vllm"
98
95
 
96
+ prefill_batch_size = self.batch_size if not self.use_continuous_batch else 1
99
97
  self.prefill_attention_mask = torch.zeros(
100
- self.batch_size, 1, self.prefill_chunk_size, self.max_seq_len, dtype=torch.int64
98
+ prefill_batch_size, 1, self.prefill_chunk_size, self.max_seq_len, dtype=torch.int64
101
99
  )
102
100
  self.causal_mask = 1 - torch.triu(
103
- torch.ones(self.batch_size, 1, self.prefill_chunk_size, self.prefill_chunk_size), diagonal=1
101
+ torch.ones(prefill_batch_size, 1, self.prefill_chunk_size, self.prefill_chunk_size), diagonal=1
104
102
  )
103
+ self.decoder_attention_mask = torch.zeros(self.batch_size, 1, 1, self.max_seq_len, dtype=torch.int64)
105
104
 
106
105
  self.prefill_decoder = RBLNRuntimeModel(runtime=self.runtimes[0], main_input_name="input_ids")
107
106
  self.decoder = RBLNRuntimeModel(runtime=self.runtimes[1], main_input_name="input_ids")
@@ -164,7 +163,10 @@ class RBLNLlamaForCausalLM(RBLNBaseModel, RBLNGenerationMixin):
164
163
 
165
164
  rbln_config_kwargs, rbln_constructor_kwargs = cls.pop_rbln_kwargs_from_kwargs(kwargs)
166
165
 
167
- origin_mehtods = wrap_llama()
166
+ # FIXME :: This should be moved when wrapping removed.
167
+ use_continuous_batch = rbln_config_kwargs.get("rbln_batching", "static") == "vllm"
168
+ origin_mehtods = wrap_llama_cb() if use_continuous_batch else wrap_llama()
169
+
168
170
  model: LlamaForCausalLM = TasksManager.get_model_from_task(
169
171
  task=task,
170
172
  model_name_or_path=model_id,
@@ -191,14 +193,18 @@ class RBLNLlamaForCausalLM(RBLNBaseModel, RBLNGenerationMixin):
191
193
  preprocessors=preprocessors, model_config=model.config, **rbln_config_kwargs
192
194
  )
193
195
 
194
- def compile_llama():
195
- wrapped_model = LlamaWrapper(model).eval()
196
+ def compile_llama(use_continuous_batch, wrapper_cls):
197
+ wrapped_model = wrapper_cls(model).eval()
196
198
 
197
199
  prefill_rbln_runtime_config = rbln_config[DEFAULT_COMPILED_MODEL_NAME][0]
198
200
  dec_rbln_runtime_config = rbln_config[DEFAULT_COMPILED_MODEL_NAME][1]
199
201
 
200
202
  prefill_example_inputs = prefill_rbln_runtime_config.get_dummy_inputs(fill=0)
201
- dec_example_inputs = dec_rbln_runtime_config.get_dummy_inputs(fill=0)
203
+ dec_example_inputs = dec_rbln_runtime_config.get_dummy_inputs(fill=4)
204
+
205
+ if use_continuous_batch:
206
+ batch_index_index = 3
207
+ dec_example_inputs[batch_index_index].fill_(-1) # fill batch_position -1 to indicate it is decoder.
202
208
 
203
209
  prefill_scripted_model = torch.jit.trace(wrapped_model, prefill_example_inputs)
204
210
  dec_scripted_model = torch.jit.trace(wrapped_model, dec_example_inputs)
@@ -213,8 +219,9 @@ class RBLNLlamaForCausalLM(RBLNBaseModel, RBLNGenerationMixin):
213
219
  )
214
220
 
215
221
  # Caching prefill_decoder/decoder I/O
222
+ cache_index_offset = 4 if use_continuous_batch else 3
216
223
  connections = [
217
- (prefill_ir.outputs[1 + i], prefill_ir.inputs[3 + i])
224
+ (prefill_ir.outputs[1 + i], prefill_ir.inputs[cache_index_offset + i])
218
225
  for i in range(model.config.num_hidden_layers * 2)
219
226
  ]
220
227
 
@@ -229,7 +236,8 @@ class RBLNLlamaForCausalLM(RBLNBaseModel, RBLNGenerationMixin):
229
236
  )
230
237
  compiled_model.save(save_dir_path / f"{DEFAULT_COMPILED_MODEL_NAME}.rbln")
231
238
 
232
- compile_llama()
239
+ wrapper_cls = LlamaWrapper_cb if use_continuous_batch else LlamaWrapper
240
+ compile_llama(use_continuous_batch=use_continuous_batch, wrapper_cls=wrapper_cls)
233
241
  unwrap_llama(origin_mehtods)
234
242
 
235
243
  rbln_config.save(save_dir_path)
@@ -249,6 +257,7 @@ class RBLNLlamaForCausalLM(RBLNBaseModel, RBLNGenerationMixin):
249
257
  model_config: "PretrainedConfig",
250
258
  rbln_max_seq_len: Optional[int] = None,
251
259
  rbln_batch_size: Optional[int] = None,
260
+ rbln_batching: Optional[str] = None,
252
261
  ) -> RBLNConfig:
253
262
  meta = {}
254
263
 
@@ -256,21 +265,38 @@ class RBLNLlamaForCausalLM(RBLNBaseModel, RBLNGenerationMixin):
256
265
  if rbln_max_seq_len is None:
257
266
  rbln_max_seq_len = getattr(model_config, "max_position_embeddings", None)
258
267
  rbln_batch_size = 1 if rbln_batch_size is None else rbln_batch_size
268
+ rbln_batching = "static" if rbln_batching is None else rbln_batching
259
269
 
260
270
  meta["rbln_max_seq_len"] = rbln_max_seq_len
261
271
  meta["rbln_batch_size"] = rbln_batch_size
262
272
  meta["rbln_prefill_chunk_size"] = prefill_chunk_size
273
+ meta["rbln_batching"] = rbln_batching
274
+ use_continuous_batching = meta["rbln_batching"] == "vllm"
275
+
276
+ if rbln_batching not in SUPPORTED_BATCHING_MODES:
277
+ raise ValueError(
278
+ f'rbln_batching="{rbln_batching}" is not a supported batch mode, '
279
+ f"Possible: {SUPPORTED_BATCHING_MODES}"
280
+ )
263
281
 
264
- def get_input_info(query_length):
282
+ def get_input_info(
283
+ batch_size, # should be 1 if continous batch prefill
284
+ query_length,
285
+ continuous_batch=False, # determines the shape of `cache position`
286
+ ):
265
287
  input_info = [
266
- ("input_ids", [rbln_batch_size, query_length], "int64"),
267
- ("attention_mask", [rbln_batch_size, 1, query_length, rbln_max_seq_len], "int64"),
288
+ ("input_ids", [batch_size, query_length], "int64"),
289
+ ("attention_mask", [batch_size, 1, query_length, rbln_max_seq_len], "int64"),
268
290
  (
269
291
  "cache_position",
270
- [],
292
+ [batch_size, query_length] if continuous_batch else [],
271
293
  "int32",
272
294
  ),
273
295
  ]
296
+
297
+ if continuous_batch:
298
+ input_info.append(("batch_position", [], "int16"))
299
+
274
300
  input_info.extend(
275
301
  [
276
302
  (
@@ -286,10 +312,19 @@ class RBLNLlamaForCausalLM(RBLNBaseModel, RBLNGenerationMixin):
286
312
  for i in range(model_config.num_hidden_layers * 2)
287
313
  ]
288
314
  )
315
+
289
316
  return input_info
290
317
 
291
- prefill_input_info = get_input_info(query_length=prefill_chunk_size)
292
- dec_input_info = get_input_info(query_length=1)
318
+ prefill_input_info = get_input_info(
319
+ batch_size=1 if use_continuous_batching else rbln_batch_size,
320
+ query_length=prefill_chunk_size,
321
+ continuous_batch=use_continuous_batching,
322
+ )
323
+ dec_input_info = get_input_info(
324
+ batch_size=rbln_batch_size,
325
+ query_length=1,
326
+ continuous_batch=use_continuous_batching,
327
+ )
293
328
 
294
329
  prefill_rbln_runtime_config = RBLNRuntimeConfig(input_info=prefill_input_info)
295
330
  dec_rbln_runtime_config = RBLNRuntimeConfig(input_info=dec_input_info)
@@ -337,7 +372,6 @@ class RBLNLlamaForCausalLM(RBLNBaseModel, RBLNGenerationMixin):
337
372
 
338
373
  # In greedy decoding
339
374
  if past_cached_length == 0:
340
-
341
375
  # padding with prefill_chunk_size
342
376
  # TODO left padding + left padding has issue on stoppingcriteria(max_len)
343
377
  if cur_len % self.prefill_chunk_size != 0:
@@ -384,7 +418,13 @@ class RBLNLlamaForCausalLM(RBLNBaseModel, RBLNGenerationMixin):
384
418
 
385
419
  return model_inputs
386
420
 
387
- def forward(
421
+ def forward(self, *args, **kwargs):
422
+ if self.use_continuous_batch:
423
+ return self.forward_cb(*args, **kwargs)
424
+ else:
425
+ return self.forward_static(*args, **kwargs)
426
+
427
+ def forward_static(
388
428
  self,
389
429
  input_ids: torch.LongTensor = None,
390
430
  attention_mask: Optional[torch.Tensor] = None,
@@ -393,7 +433,6 @@ class RBLNLlamaForCausalLM(RBLNBaseModel, RBLNGenerationMixin):
393
433
  query_length: Optional[torch.Tensor] = None,
394
434
  **kwargs,
395
435
  ) -> Tuple[torch.FloatTensor]:
396
-
397
436
  if past_key_values is not None:
398
437
  past_key_values += query_length
399
438
 
@@ -425,3 +464,58 @@ class RBLNLlamaForCausalLM(RBLNBaseModel, RBLNGenerationMixin):
425
464
  logits=outputs,
426
465
  past_key_values=past_key_values,
427
466
  )
467
+
468
+ def forward_cb(
469
+ self,
470
+ input_ids: torch.LongTensor = None,
471
+ cache_position: Optional[torch.Tensor] = None, # torch.tensor(,dtype=int32) (1,64) // (4,1)
472
+ batch_idx: int = None,
473
+ **kwargs,
474
+ ) -> Tuple[torch.FloatTensor]:
475
+ # prefill_decoder
476
+ if cache_position.shape[1] > 1:
477
+ query_length = input_ids.shape[1]
478
+ attention_mask = self.prefill_attention_mask.clone()
479
+ for step in range(0, query_length, self.prefill_chunk_size):
480
+ if step + self.prefill_chunk_size > query_length:
481
+ input_ids = torch.nn.functional.pad(input_ids, (0, step + self.prefill_chunk_size - query_length))
482
+ cache_position = torch.cat(
483
+ [
484
+ cache_position,
485
+ torch.arange(
486
+ query_length,
487
+ step + self.prefill_chunk_size,
488
+ dtype=torch.int32,
489
+ ).unsqueeze(0),
490
+ ],
491
+ dim=-1,
492
+ )
493
+
494
+ sliced_input_ids = input_ids[:, step : step + self.prefill_chunk_size]
495
+ sliced_cache_positions = cache_position[:, step : step + self.prefill_chunk_size]
496
+ attention_mask[:, :, :, :step] = 1
497
+ attention_mask[:, :, :, step : step + self.prefill_chunk_size] = self.causal_mask
498
+
499
+ outputs, _ = self.prefill_decoder(
500
+ sliced_input_ids.contiguous(),
501
+ attention_mask.contiguous(),
502
+ sliced_cache_positions.contiguous(),
503
+ torch.tensor(batch_idx, dtype=torch.int16),
504
+ )
505
+ outputs = outputs[:, query_length % self.prefill_chunk_size - 1].unsqueeze(1)
506
+ # decoder
507
+ else:
508
+ attention_mask = self.decoder_attention_mask.clone()
509
+ for b_idx in range(self.batch_size):
510
+ attention_mask[b_idx, :, :, : cache_position[b_idx].item() + 1] = 1
511
+
512
+ outputs = self.decoder(
513
+ input_ids.contiguous(),
514
+ attention_mask.contiguous(),
515
+ cache_position.contiguous(),
516
+ torch.tensor(0, dtype=torch.int16),
517
+ )[0]
518
+
519
+ return CausalLMOutputWithPast(
520
+ logits=outputs,
521
+ )
@@ -0,0 +1,32 @@
1
+ # Copyright 2024 Rebellions Inc.
2
+
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at:
6
+
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # Portions of this software are licensed under the Apache License,
16
+ # Version 2.0. See the NOTICE file distributed with this work for
17
+ # additional information regarding copyright ownership.
18
+
19
+ # All other portions of this software, including proprietary code,
20
+ # are the intellectual property of Rebellions Inc. and may not be
21
+ # copied, modified, or distributed without prior written permission
22
+ # from Rebellions Inc.
23
+
24
+ import os
25
+ from os import environ
26
+
27
+
28
+ this_path = os.path.abspath(__file__)
29
+ local_dir = "/" + os.path.join(*this_path.split("/")[:-1]) + "/hf_hub_cached"
30
+ environ["LOCAL_CACHE_ROOT_CUSTOM_CODE_MIDM"] = local_dir
31
+
32
+ from .modeling_midm import RBLNMidmLMHeadModel
@@ -0,0 +1,22 @@
1
+ from transformers.models.gpt2.configuration_gpt2 import GPT2Config
2
+
3
+
4
+ class MidmBitextConfig(GPT2Config):
5
+ model_type = "midm-bitext-S"
6
+
7
+ def __init__(
8
+ self,
9
+ use_absolute_position_embedding: bool = True,
10
+ use_rotary_position_embedding: bool = False,
11
+ rotary_percentage: float = 1.0,
12
+ normalization_type: str = "layernorm",
13
+ scale_qk_by_inverse_layer_idx: bool = False,
14
+ *args,
15
+ **kwargs,
16
+ ):
17
+ super().__init__(*args, **kwargs)
18
+ self.use_absolute_position_embedding = use_absolute_position_embedding
19
+ self.use_rotary_position_embedding = use_rotary_position_embedding
20
+ self.rotary_percentage = rotary_percentage
21
+ self.normalization_type = normalization_type
22
+ self.scale_qk_by_inverse_layer_idx = scale_qk_by_inverse_layer_idx
@@ -0,0 +1,303 @@
1
+ # coding=utf-8
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ """ Tokenization class for model Midm_bitext_tonkenizer."""
14
+ import os
15
+ import re
16
+ import warnings
17
+ from shutil import copyfile
18
+ from typing import Any, Dict, List, Optional, Tuple
19
+
20
+ import sentencepiece as spm
21
+ from transformers.tokenization_utils import PreTrainedTokenizer
22
+ from transformers.utils import logging
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+ VOCAB_FILES_NAMES = {"vocab_file": "midm_bitext_tokenizer.model"}
28
+
29
+ PRETRAINED_VOCAB_FILES_MAP = {}
30
+
31
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
32
+
33
+
34
+ class Midm_bitext_Tokenizer(PreTrainedTokenizer):
35
+ """
36
+ Construct a Midm bitext tonkenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
37
+
38
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
39
+ this superclass for more information regarding those methods.
40
+
41
+ Args:
42
+ vocab_file (`str`):
43
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
44
+ contains the vocabulary necessary to instantiate a tokenizer.
45
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
46
+ The end of sequence token.
47
+
48
+ <Tip>
49
+
50
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
51
+ The token used is the `sep_token`.
52
+
53
+ </Tip>
54
+
55
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
56
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
57
+ token instead.
58
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
59
+ The token used for padding, for example when batching sequences of different lengths.
60
+ extra_ids (`int`, *optional*, defaults to 100):
61
+ Add a number of extra ids added to the end of the vocabulary for use as sentinels. These tokens are
62
+ accessible as "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. Extra tokens are
63
+ indexed from the end of the vocabulary up to beginning.
64
+ additional_special_tokens (`List[str]`, *optional*):
65
+ Additional special tokens used by the tokenizer.
66
+ sp_model_kwargs (`dict`, *optional*):
67
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
68
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
69
+ to set:
70
+
71
+ - `enable_sampling`: Enable subword regularization.
72
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
73
+
74
+ - `nbest_size = {0,1}`: No sampling is performed.
75
+ - `nbest_size > 1`: samples from the nbest_size results.
76
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
77
+ using forward-filtering-and-backward-sampling algorithm.
78
+
79
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
80
+ BPE-dropout.
81
+
82
+ Attributes:
83
+ sp_model (`SentencePieceProcessor`):
84
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
85
+ """
86
+
87
+ vocab_files_names = VOCAB_FILES_NAMES
88
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
89
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
90
+ model_input_names = ["input_ids", "attention_mask"]
91
+
92
+ def __init__(
93
+ self,
94
+ vocab_file,
95
+ eos_token="</s>",
96
+ unk_token="<unk>",
97
+ pad_token="<pad>",
98
+ extra_ids=100,
99
+ additional_special_tokens=None,
100
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
101
+ **kwargs,
102
+ ) -> None:
103
+ # Add extra_ids to the special token list
104
+ if extra_ids > 0 and additional_special_tokens is None:
105
+ additional_special_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)]
106
+ elif extra_ids > 0 and additional_special_tokens is not None:
107
+ # Check that we have the right number of extra_id special tokens
108
+ extra_tokens = len(set(filter(lambda x: bool("extra_id" in str(x)), additional_special_tokens)))
109
+ if extra_tokens != extra_ids:
110
+ raise ValueError(
111
+ f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are provided to Midm_bitext_Tonkenizer. "
112
+ "In this case the additional_special_tokens must include the extra_ids tokens"
113
+ )
114
+
115
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
116
+
117
+ # custom special tokens
118
+ # convert \n, \t in input text -> <[!newline]>, <[!tab]>
119
+ self.newline_token = "<[!newline]>"
120
+ self.tab_token = "<[!tab]>"
121
+
122
+ self.vocab_file = vocab_file
123
+ self._extra_ids = extra_ids
124
+
125
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
126
+ self.sp_model.Load(vocab_file)
127
+ super().__init__(
128
+ eos_token=eos_token,
129
+ unk_token=unk_token,
130
+ pad_token=pad_token,
131
+ extra_ids=extra_ids,
132
+ additional_special_tokens=additional_special_tokens,
133
+ sp_model_kwargs=self.sp_model_kwargs,
134
+ **kwargs,
135
+ )
136
+
137
+ @property
138
+ def vocab_size(self):
139
+ return self.sp_model.get_piece_size() + self._extra_ids
140
+
141
+ def get_vocab(self):
142
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
143
+ vocab.update(self.added_tokens_encoder)
144
+ return vocab
145
+
146
+ def get_special_tokens_mask(
147
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
148
+ ) -> List[int]:
149
+ """
150
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
151
+ special tokens using the tokenizer `prepare_for_model` method.
152
+
153
+ Args:
154
+ token_ids_0 (`List[int]`):
155
+ List of IDs.
156
+ token_ids_1 (`List[int]`, *optional*):
157
+ Optional second list of IDs for sequence pairs.
158
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
159
+ Whether or not the token list is already formatted with special tokens for the model.
160
+
161
+ Returns:
162
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
163
+ """
164
+ if already_has_special_tokens:
165
+ return super().get_special_tokens_mask(
166
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
167
+ )
168
+
169
+ # normal case: some special tokens
170
+ if token_ids_1 is None:
171
+ return ([0] * len(token_ids_0)) + [1]
172
+ return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
173
+
174
+ def _add_eos_if_not_present(self, token_ids: List[int]) -> List[int]:
175
+ """Do not add eos again if user already added it."""
176
+ if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
177
+ warnings.warn(
178
+ f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated eos tokens being added."
179
+ )
180
+ return token_ids
181
+ else:
182
+ return token_ids + [self.eos_token_id]
183
+
184
+ def create_token_type_ids_from_sequences(
185
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
186
+ ) -> List[int]:
187
+ """
188
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. Midm does not make
189
+ use of token type ids, therefore a list of zeros is returned.
190
+
191
+ Args:
192
+ token_ids_0 (`List[int]`):
193
+ List of IDs.
194
+ token_ids_1 (`List[int]`, *optional*):
195
+ Optional second list of IDs for sequence pairs.
196
+
197
+ Returns:
198
+ `List[int]`: List of zeros.
199
+ """
200
+ eos = [self.eos_token_id]
201
+
202
+ if token_ids_1 is None:
203
+ return len(token_ids_0 + eos) * [0]
204
+ return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
205
+
206
+ def build_inputs_with_special_tokens(
207
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
208
+ ) -> List[int]:
209
+ """
210
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
211
+ adding special tokens. A sequence has the following format:
212
+
213
+ - single sequence: `X </s>`
214
+ - pair of sequences: `A </s> B </s>`
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](../glossary#input-ids) with the appropriate special tokens.
224
+ """
225
+ token_ids_0 = self._add_eos_if_not_present(token_ids_0)
226
+ if token_ids_1 is None:
227
+ return token_ids_0
228
+ else:
229
+ token_ids_1 = self._add_eos_if_not_present(token_ids_1)
230
+ return token_ids_0 + token_ids_1
231
+
232
+ def __getstate__(self):
233
+ state = self.__dict__.copy()
234
+ state["sp_model"] = None
235
+ return state
236
+
237
+ def __setstate__(self, d):
238
+ self.__dict__ = d
239
+
240
+ # for backward compatibility
241
+ if not hasattr(self, "sp_model_kwargs"):
242
+ self.sp_model_kwargs = {}
243
+
244
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
245
+ self.sp_model.Load(self.vocab_file)
246
+
247
+ def _tokenize(self, text: str) -> List[str]:
248
+ """Take as input a string and return a list of strings (tokens) for words/sub-words"""
249
+ text = text.replace("\n", self.newline_token)
250
+ text = text.replace("\t", self.tab_token)
251
+
252
+ return self.sp_model.encode(text, out_type=str)
253
+
254
+ def _convert_token_to_id(self, token):
255
+ """Converts a token (str) in an id using the vocab."""
256
+ if token.startswith("<extra_id_"):
257
+ match = re.match(r"<extra_id_(\d+)>", token)
258
+ num = int(match.group(1))
259
+ return self.vocab_size - num - 1
260
+ return self.sp_model.piece_to_id(token)
261
+
262
+ def _convert_id_to_token(self, index):
263
+ """Converts an index (integer) in a token (str) using the vocab."""
264
+ if index < self.sp_model.get_piece_size():
265
+ token = self.sp_model.IdToPiece(index)
266
+ else:
267
+ token = f"<extra_id_{self.vocab_size - 1 - index}>"
268
+ return token
269
+
270
+ def convert_tokens_to_string(self, tokens):
271
+ """Converts a sequence of tokens (string) in a single string."""
272
+ current_sub_tokens = []
273
+ out_string = ""
274
+ for token in tokens:
275
+ # make sure that special tokens are not decoded using sentencepiece model
276
+ if token in self.all_special_tokens:
277
+ out_string += self.sp_model.decode_pieces(current_sub_tokens) + token + " "
278
+ current_sub_tokens = []
279
+ else:
280
+ current_sub_tokens.append(token)
281
+ out_string += self.sp_model.decode_pieces(current_sub_tokens)
282
+
283
+ out_string.replace(self.newline_token, "\n")
284
+ out_string.replace(self.tab_token, "\t")
285
+
286
+ return out_string.strip()
287
+
288
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
289
+ if not os.path.isdir(save_directory):
290
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
291
+ return
292
+ out_vocab_file = os.path.join(
293
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
294
+ )
295
+
296
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
297
+ copyfile(self.vocab_file, out_vocab_file)
298
+ elif not os.path.isfile(self.vocab_file):
299
+ with open(out_vocab_file, "wb") as fi:
300
+ content_spiece_model = self.sp_model.serialized_model_proto()
301
+ fi.write(content_spiece_model)
302
+
303
+ return (out_vocab_file,)