woldemarg commited on
Commit
bb62cde
·
verified ·
1 Parent(s): 82b5920

Upload folder using huggingface_hub

Browse files
Files changed (5) hide show
  1. config.json +84 -0
  2. model.safetensors +3 -0
  3. spm.model +3 -0
  4. tokenization_liberta.py +295 -0
  5. tokenizer_config.json +63 -0
config.json ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ModernBertForSequenceClassification"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 50281,
8
+ "classifier_activation": "gelu",
9
+ "classifier_bias": false,
10
+ "classifier_dropout": 0.0,
11
+ "classifier_pooling": "mean",
12
+ "cls_token_id": 2,
13
+ "decoder_bias": true,
14
+ "deterministic_flash_attn": false,
15
+ "dtype": "float32",
16
+ "embedding_dropout": 0.0,
17
+ "eos_token_id": 50282,
18
+ "global_attn_every_n_layers": 3,
19
+ "gradient_checkpointing": false,
20
+ "hidden_activation": "gelu",
21
+ "hidden_size": 1024,
22
+ "initializer_cutoff_factor": 2.0,
23
+ "initializer_range": 0.02,
24
+ "intermediate_size": 2624,
25
+ "layer_norm_eps": 1e-05,
26
+ "layer_types": [
27
+ "full_attention",
28
+ "sliding_attention",
29
+ "sliding_attention",
30
+ "full_attention",
31
+ "sliding_attention",
32
+ "sliding_attention",
33
+ "full_attention",
34
+ "sliding_attention",
35
+ "sliding_attention",
36
+ "full_attention",
37
+ "sliding_attention",
38
+ "sliding_attention",
39
+ "full_attention",
40
+ "sliding_attention",
41
+ "sliding_attention",
42
+ "full_attention",
43
+ "sliding_attention",
44
+ "sliding_attention",
45
+ "full_attention",
46
+ "sliding_attention",
47
+ "sliding_attention",
48
+ "full_attention",
49
+ "sliding_attention",
50
+ "sliding_attention",
51
+ "full_attention",
52
+ "sliding_attention",
53
+ "sliding_attention",
54
+ "full_attention"
55
+ ],
56
+ "local_attention": 128,
57
+ "max_position_embeddings": 8192,
58
+ "mlp_bias": false,
59
+ "mlp_dropout": 0.0,
60
+ "model_type": "modernbert",
61
+ "norm_bias": false,
62
+ "norm_eps": 1e-05,
63
+ "num_attention_heads": 16,
64
+ "num_hidden_layers": 28,
65
+ "pad_token_id": 0,
66
+ "position_embedding_type": "absolute",
67
+ "repad_logits_with_grad": false,
68
+ "rope_parameters": {
69
+ "full_attention": {
70
+ "rope_theta": 160000,
71
+ "rope_type": "default"
72
+ },
73
+ "sliding_attention": {
74
+ "rope_theta": 10000,
75
+ "rope_type": "default"
76
+ }
77
+ },
78
+ "sep_token_id": 3,
79
+ "sparse_pred_ignore_index": -100,
80
+ "sparse_prediction": false,
81
+ "tie_word_embeddings": true,
82
+ "transformers_version": "5.3.0",
83
+ "vocab_size": 64000
84
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ce9d7fdb891b4e2f05b940e38e47fed31f9edadc5b7d1afdf155ce123b5cb77
3
+ size 1639188320
spm.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8c9699b255aa5ddd6575f1f3834454778153ebb60f957ac139d7b1685865e5e7
3
+ size 2404944
tokenization_liberta.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License
15
+ """ Tokenization classes for Liberta model."""
16
+
17
+
18
+ import os
19
+ from shutil import copyfile
20
+ from typing import Any, Dict, List, Optional, Tuple
21
+
22
+ import sentencepiece as spm
23
+
24
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
25
+ from transformers.utils import logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ VOCAB_FILES_NAMES = {"vocab_file": "spm.model"}
31
+
32
+ PRETRAINED_VOCAB_FILES_MAP = {}
33
+
34
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
35
+ "liberta-test": 512,
36
+ "liberta-large": 512,
37
+ }
38
+
39
+ SPIECE_UNDERLINE = "▁"
40
+
41
+
42
+ class LibertaTokenizer(PreTrainedTokenizer):
43
+ """
44
+ Adapted from [`RobertaTokenizer`] and [`XLNetTokenizer`]. Construct a CamemBERT tokenizer. Based on
45
+ [SentencePiece](https://github.com/google/sentencepiece).
46
+
47
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
48
+ this superclass for more information regarding those methods.
49
+
50
+ Args:
51
+ vocab_file (`str`):
52
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
53
+ contains the vocabulary necessary to instantiate a tokenizer.
54
+ bos_token (`str`, *optional*, defaults to `"<cls>"`):
55
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
56
+
57
+ <Tip>
58
+
59
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
60
+ sequence. The token used is the `cls_token`.
61
+
62
+ </Tip>
63
+
64
+ eos_token (`str`, *optional*, defaults to `"<sep>"`):
65
+ The end of sequence token.
66
+
67
+ <Tip>
68
+
69
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
70
+ The token used is the `sep_token`.
71
+
72
+ </Tip>
73
+
74
+ sep_token (`str`, *optional*, defaults to `"<sep>"`):
75
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
76
+ sequence classification or for a text and a question for question answering. It is also used as the last
77
+ token of a sequence built with special tokens.
78
+ cls_token (`str`, *optional*, defaults to `"<cls>"`):
79
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
80
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
81
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
82
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
83
+ token instead.
84
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
85
+ The token used for padding, for example when batching sequences of different lengths.
86
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
87
+ The token used for masking values. This is the token used when training this model with masked language
88
+ modeling. This is the token which the model will try to predict.
89
+ sp_model_kwargs (`dict`, *optional*):
90
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
91
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
92
+ to set:
93
+
94
+ - `enable_sampling`: Enable subword regularization.
95
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
96
+
97
+ - `nbest_size = {0,1}`: No sampling is performed.
98
+ - `nbest_size > 1`: samples from the nbest_size results.
99
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
100
+ using forward-filtering-and-backward-sampling algorithm.
101
+
102
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
103
+ BPE-dropout.
104
+
105
+ Attributes:
106
+ sp_model (`SentencePieceProcessor`):
107
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
108
+ """
109
+
110
+ vocab_files_names = VOCAB_FILES_NAMES
111
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
112
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
113
+ model_input_names = ["input_ids", "attention_mask"]
114
+
115
+ def __init__(
116
+ self,
117
+ vocab_file,
118
+ bos_token="<cls>",
119
+ eos_token="<sep>",
120
+ sep_token="<sep>",
121
+ cls_token="<cls>",
122
+ unk_token="<unk>",
123
+ pad_token="<pad>",
124
+ mask_token="<mask>",
125
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
126
+ **kwargs,
127
+ ) -> None:
128
+ # Mask token behave like a normal word, i.e. include the space before it
129
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
130
+
131
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
132
+
133
+ self.vocab_file = vocab_file
134
+
135
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
136
+ self.sp_model.Load(str(vocab_file))
137
+
138
+ super().__init__(
139
+ bos_token=bos_token,
140
+ eos_token=eos_token,
141
+ unk_token=unk_token,
142
+ sep_token=sep_token,
143
+ cls_token=cls_token,
144
+ pad_token=pad_token,
145
+ mask_token=mask_token,
146
+ sp_model_kwargs=self.sp_model_kwargs,
147
+ **kwargs,
148
+ )
149
+
150
+ @property
151
+ def vocab_size(self):
152
+ return len(self.sp_model)
153
+
154
+ def get_vocab(self):
155
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
156
+ vocab.update(self.added_tokens_encoder)
157
+ return vocab
158
+
159
+ def __getstate__(self):
160
+ state = self.__dict__.copy()
161
+ state["sp_model"] = None
162
+ return state
163
+
164
+ def __setstate__(self, d):
165
+ self.__dict__ = d
166
+
167
+ # for backward compatibility
168
+ if not hasattr(self, "sp_model_kwargs"):
169
+ self.sp_model_kwargs = {}
170
+
171
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
172
+ self.sp_model.Load(self.vocab_file)
173
+
174
+ def _tokenize(self, text: str) -> List[str]:
175
+ """Tokenize a string."""
176
+ return self.sp_model.Encode(text, out_type=str)
177
+
178
+ def _convert_token_to_id(self, token):
179
+ """Converts a token (str) in an id using the vocab."""
180
+ return self.sp_model.PieceToId(token)
181
+
182
+ def _convert_id_to_token(self, index):
183
+ """Converts an index (integer) in a token (str) using the vocab."""
184
+ return self.sp_model.IdToPiece(index)
185
+
186
+ def convert_tokens_to_string(self, tokens):
187
+ """Converts a sequence of tokens (string) in a single string."""
188
+ current_sub_tokens = []
189
+ out_string = ""
190
+ prev_is_special = False
191
+ for token in tokens:
192
+ # make sure that special tokens are not decoded using sentencepiece model
193
+ if token in self.all_special_tokens:
194
+ if not prev_is_special:
195
+ out_string += " "
196
+ out_string += self.sp_model.Decode(current_sub_tokens) + token
197
+ prev_is_special = True
198
+ current_sub_tokens = []
199
+ else:
200
+ current_sub_tokens.append(token)
201
+ prev_is_special = False
202
+ out_string += self.sp_model.Decode(current_sub_tokens)
203
+ return out_string.strip()
204
+
205
+ def build_inputs_with_special_tokens(
206
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
207
+ ) -> List[int]:
208
+ """
209
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
210
+ adding special tokens. An LiBERTa sequence has the following format:
211
+
212
+ - single sequence: `<cls> X <sep>`
213
+ - pair of sequences: `<cls> A <sep> B <sep>`
214
+
215
+ Args:
216
+ token_ids_0 (`List[int]`):
217
+ List of IDs to which the special tokens will be added.
218
+ token_ids_1 (`List[int]`, *optional*):
219
+ Optional second list of IDs for sequence pairs.
220
+
221
+ Returns:
222
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
223
+ """
224
+ cls = [self.cls_token_id]
225
+ sep = [self.sep_token_id]
226
+ if token_ids_1 is None:
227
+ return cls + token_ids_0 + sep
228
+ return cls + token_ids_0 + sep + token_ids_1 + sep
229
+
230
+ def get_special_tokens_mask(
231
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
232
+ ) -> List[int]:
233
+ """
234
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
235
+ special tokens using the tokenizer `prepare_for_model` method.
236
+
237
+ Args:
238
+ token_ids_0 (`List[int]`):
239
+ List of IDs.
240
+ token_ids_1 (`List[int]`, *optional*):
241
+ Optional second list of IDs for sequence pairs.
242
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
243
+ Whether or not the token list is already formatted with special tokens for the model.
244
+
245
+ Returns:
246
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
247
+ """
248
+ if already_has_special_tokens:
249
+ return super().get_special_tokens_mask(
250
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
251
+ )
252
+
253
+ if token_ids_1 is None:
254
+ return [1] + ([0] * len(token_ids_0)) + [1]
255
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
256
+
257
+ def create_token_type_ids_from_sequences(
258
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
259
+ ) -> List[int]:
260
+ """
261
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. CamemBERT, like
262
+ RoBERTa, does not make use of token type ids, therefore a list of zeros is returned.
263
+
264
+ Args:
265
+ token_ids_0 (`List[int]`):
266
+ List of IDs.
267
+ token_ids_1 (`List[int]`, *optional*):
268
+ Optional second list of IDs for sequence pairs.
269
+
270
+ Returns:
271
+ `List[int]`: List of zeros.
272
+ """
273
+ cls = [self.cls_token_id]
274
+ sep = [self.sep_token_id]
275
+
276
+ if token_ids_1 is None:
277
+ return len(cls + token_ids_0 + sep) * [0]
278
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
279
+
280
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
281
+ if not os.path.isdir(save_directory):
282
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
283
+ return
284
+ out_vocab_file = os.path.join(
285
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
286
+ )
287
+
288
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
289
+ copyfile(self.vocab_file, out_vocab_file)
290
+ elif not os.path.isfile(self.vocab_file):
291
+ with open(out_vocab_file, "wb") as fi:
292
+ content_spiece_model = self.sp_model.serialized_model_proto()
293
+ fi.write(content_spiece_model)
294
+
295
+ return (out_vocab_file,)
tokenizer_config.json ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<pad>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<unk>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "<cls>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "<sep>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "4": {
36
+ "content": "<mask>",
37
+ "lstrip": true,
38
+ "normalized": true,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "auto_map": {
45
+ "AutoTokenizer": [
46
+ "tokenization_liberta.LibertaTokenizer",
47
+ null
48
+ ]
49
+ },
50
+ "backend": "custom",
51
+ "bos_token": "<cls>",
52
+ "clean_up_tokenization_spaces": false,
53
+ "cls_token": "<cls>",
54
+ "eos_token": "<sep>",
55
+ "is_local": false,
56
+ "mask_token": "<mask>",
57
+ "model_max_length": 1000000000000000019884624838656,
58
+ "pad_token": "<pad>",
59
+ "sep_token": "<sep>",
60
+ "sp_model_kwargs": {},
61
+ "tokenizer_class": "LibertaTokenizer",
62
+ "unk_token": "<unk>"
63
+ }