versae commited on
Commit
0a609c6
·
1 Parent(s): 1cbd223

Upload tokenization_gzip_bert.py

Browse files
Files changed (1) hide show
  1. tokenization_gzip_bert.py +258 -0
tokenization_gzip_bert.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Javier de la Rosa, T5 Authors and 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 class for model GzipBERT."""
16
+
17
+ import gzip
18
+ import warnings
19
+ from typing import Dict, List, Optional, Tuple
20
+
21
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
22
+ from transformers.utils import logging
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ class GzipBertTokenizer(PreTrainedTokenizer):
29
+ """
30
+ Construct a GzipBert tokenizer. GzipBert simply uses raw bytes utf-8 encoding.
31
+
32
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
33
+ this superclass for more information regarding those methods.
34
+
35
+ Args:
36
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
37
+ The end of sequence token.
38
+
39
+ <Tip>
40
+
41
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
42
+ The token used is the `sep_token`.
43
+
44
+ </Tip>
45
+
46
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
47
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
48
+ token instead.
49
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
50
+ The token used for padding, for example when batching sequences of different lengths.
51
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
52
+ The token used for padding, for example when batching sequences of different lengths.
53
+ extra_ids (`int`, *optional*, defaults to 100):
54
+ Add a number of extra ids added to the end of the vocabulary for use as sentinels. These tokens are
55
+ accessible as "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. Extra tokens are
56
+ indexed from the end of the vocabulary up to beginning ("<extra_id_0>" is the last token in the vocabulary
57
+ like in ByT5 preprocessing see
58
+ [here](https://github.com/google-research/text-to-text-transfer-transformer/blob/9fd7b14a769417be33bc6c850f9598764913c833/t5/data/preprocessors.py#L2117)).
59
+ additional_special_tokens (`List[str]`, *optional*):
60
+ Additional special tokens used by the tokenizer.
61
+ """
62
+
63
+ model_input_names = ["input_ids", "attention_mask"]
64
+
65
+ def __init__(
66
+ self,
67
+ eos_token="</s>",
68
+ unk_token="<unk>",
69
+ pad_token="<pad>",
70
+ mask_token="<mask>",
71
+ extra_ids=0,
72
+ additional_special_tokens=None,
73
+ **kwargs,
74
+ ) -> None:
75
+ # Add extra_ids to the special token list
76
+ if extra_ids > 0 and additional_special_tokens is None:
77
+ additional_special_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)]
78
+ elif extra_ids > 0 and additional_special_tokens is not None:
79
+ # Check that we have the right number of extra_id special tokens
80
+ extra_tokens = len(set(filter(lambda x: bool("extra_id" in str(x)), additional_special_tokens)))
81
+ if extra_tokens != extra_ids:
82
+ raise ValueError(
83
+ f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"
84
+ " provided to GzipBertTokenizer. In this case the additional_special_tokens must include the"
85
+ " extra_ids tokens"
86
+ )
87
+ elif extra_ids == 0 and additional_special_tokens is None:
88
+ additional_special_tokens = []
89
+
90
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
91
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
92
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
93
+ mask_token = AddedToken(mask_token, lstrip=False, rstrip=False) if isinstance(mask_token, str) else mask_token
94
+
95
+ super().__init__(
96
+ eos_token=eos_token,
97
+ unk_token=unk_token,
98
+ pad_token=pad_token,
99
+ mask_token=mask_token,
100
+ extra_ids=extra_ids,
101
+ additional_special_tokens=additional_special_tokens,
102
+ **kwargs,
103
+ )
104
+
105
+ self._extra_ids = extra_ids
106
+
107
+ self._utf_vocab_size = 2**8 # utf is 8 bits
108
+
109
+ # define special tokens dict
110
+ self.special_tokens_encoder: Dict[int, str] = {
111
+ self.pad_token: 0,
112
+ self.eos_token: 1,
113
+ self.unk_token: 2,
114
+ self.mask_token: 3,
115
+ }
116
+ self._num_special_tokens = len(self.special_tokens_encoder)
117
+ n = len(additional_special_tokens)
118
+ for i, token in enumerate(additional_special_tokens):
119
+ self.special_tokens_encoder[token] = self.vocab_size + i - n
120
+ self.special_tokens_decoder: Dict[str, int] = {v: k for k, v in self.special_tokens_encoder.items()}
121
+
122
+ @property
123
+ def vocab_size(self):
124
+ return self._utf_vocab_size + self._num_special_tokens + self._extra_ids
125
+
126
+ def get_special_tokens_mask(
127
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
128
+ ) -> List[int]:
129
+ """
130
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
131
+ special tokens using the tokenizer `prepare_for_model` method.
132
+
133
+ Args:
134
+ token_ids_0 (`List[int]`):
135
+ List of IDs.
136
+ token_ids_1 (`List[int]`, *optional*):
137
+ Optional second list of IDs for sequence pairs.
138
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
139
+ Whether or not the token list is already formatted with special tokens for the model.
140
+
141
+ Returns:
142
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
143
+ """
144
+ if already_has_special_tokens:
145
+ return super().get_special_tokens_mask(
146
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
147
+ )
148
+
149
+ # normal case: some special tokens
150
+ if token_ids_1 is None:
151
+ return ([0] * len(token_ids_0)) + [1]
152
+ return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
153
+
154
+ def _add_eos_if_not_present(self, token_ids: List[int]) -> List[int]:
155
+ """Do not add eos again if user already added it."""
156
+ if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
157
+ warnings.warn(
158
+ f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"
159
+ " eos tokens being added."
160
+ )
161
+ return token_ids
162
+ else:
163
+ return token_ids + [self.eos_token_id]
164
+
165
+ def create_token_type_ids_from_sequences(
166
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
167
+ ) -> List[int]:
168
+ """
169
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. GzipBert does not
170
+ make use of token type ids, therefore a list of zeros is returned.
171
+
172
+ Args:
173
+ token_ids_0 (`List[int]`):
174
+ List of IDs.
175
+ token_ids_1 (`List[int]`, *optional*):
176
+ Optional second list of IDs for sequence pairs.
177
+
178
+ Returns:
179
+ `List[int]`: List of zeros.
180
+ """
181
+ eos = [self.eos_token_id]
182
+
183
+ if token_ids_1 is None:
184
+ return len(token_ids_0 + eos) * [0]
185
+ return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
186
+
187
+ def build_inputs_with_special_tokens(
188
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
189
+ ) -> List[int]:
190
+ """
191
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
192
+ adding special tokens. A sequence has the following format:
193
+
194
+ - single sequence: `X </s>`
195
+ - pair of sequences: `A </s> B </s>`
196
+
197
+ Args:
198
+ token_ids_0 (`List[int]`):
199
+ List of IDs to which the special tokens will be added.
200
+ token_ids_1 (`List[int]`, *optional*):
201
+ Optional second list of IDs for sequence pairs.
202
+
203
+ Returns:
204
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
205
+ """
206
+ token_ids_0 = self._add_eos_if_not_present(token_ids_0)
207
+ if token_ids_1 is None:
208
+ return token_ids_0
209
+ else:
210
+ token_ids_1 = self._add_eos_if_not_present(token_ids_1)
211
+ return token_ids_0 + token_ids_1
212
+
213
+ def _tokenize(self, text: str) -> List[str]:
214
+ """Take as input a string and return a list of bytes (str) for binary gzip content"""
215
+ tokens = [chr(i) for i in gzip.compress(bytes(text, 'utf-8'))]
216
+ return tokens
217
+
218
+ def _convert_token_to_id(self, token):
219
+ """Converts a token (str) in an id using the vocab."""
220
+ if token in self.special_tokens_encoder:
221
+ token_id = self.special_tokens_encoder[token]
222
+ elif token in self.added_tokens_encoder:
223
+ token_id = self.added_tokens_encoder[token]
224
+ elif len(token) != 1:
225
+ token_id = self.unk_token_id
226
+ else:
227
+ token_id = ord(token) + self._num_special_tokens
228
+ return token_id
229
+
230
+ def _convert_id_to_token(self, index):
231
+ """Converts an index (integer) in a token (str) using the vocab."""
232
+ if index in self.special_tokens_decoder:
233
+ token = self.special_tokens_decoder[index]
234
+ else:
235
+ token = chr(index - self._num_special_tokens)
236
+ return token
237
+
238
+ def convert_tokens_to_string(self, tokens):
239
+ """Converts a sequence of tokens (string) in a single string."""
240
+ bstring = b""
241
+ for token in tokens:
242
+ if token in self.special_tokens_decoder:
243
+ tok_string = self.special_tokens_decoder[token].encode("utf-8")
244
+ elif token in self.added_tokens_decoder:
245
+ tok_string = self.special_tokens_decoder[token].encode("utf-8")
246
+ elif token in self.special_tokens_encoder:
247
+ tok_string = token.encode("utf-8")
248
+ elif token in self.added_tokens_encoder:
249
+ tok_string = token.encode("utf-8")
250
+ else:
251
+ tok_string = bytes([ord(token)])
252
+ bstring += tok_string
253
+ string = gzip.decompress(bstring).decode("utf8")
254
+ return string
255
+
256
+ # GzipBertTokenizer has no vocab file
257
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
258
+ return ()