CSS-LM
342 строки · 13.8 Кб
1# coding=utf-8
2# Copyright 2018 Google AI, Google Brain 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 ALBERT model."""
16
17
18import logging
19import os
20import unicodedata
21from shutil import copyfile
22from typing import List, Optional
23
24from .tokenization_utils import PreTrainedTokenizer
25
26
27logger = logging.getLogger(__name__)
28VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
29
30PRETRAINED_VOCAB_FILES_MAP = {
31"vocab_file": {
32"albert-base-v1": "https://s3.amazonaws.com/models.huggingface.co/bert/albert-base-v1-spiece.model",
33"albert-large-v1": "https://s3.amazonaws.com/models.huggingface.co/bert/albert-large-v1-spiece.model",
34"albert-xlarge-v1": "https://s3.amazonaws.com/models.huggingface.co/bert/albert-xlarge-v1-spiece.model",
35"albert-xxlarge-v1": "https://s3.amazonaws.com/models.huggingface.co/bert/albert-xxlarge-v1-spiece.model",
36"albert-base-v2": "https://s3.amazonaws.com/models.huggingface.co/bert/albert-base-v2-spiece.model",
37"albert-large-v2": "https://s3.amazonaws.com/models.huggingface.co/bert/albert-large-v2-spiece.model",
38"albert-xlarge-v2": "https://s3.amazonaws.com/models.huggingface.co/bert/albert-xlarge-v2-spiece.model",
39"albert-xxlarge-v2": "https://s3.amazonaws.com/models.huggingface.co/bert/albert-xxlarge-v2-spiece.model",
40}
41}
42
43PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
44"albert-base-v1": 512,
45"albert-large-v1": 512,
46"albert-xlarge-v1": 512,
47"albert-xxlarge-v1": 512,
48"albert-base-v2": 512,
49"albert-large-v2": 512,
50"albert-xlarge-v2": 512,
51"albert-xxlarge-v2": 512,
52}
53
54SPIECE_UNDERLINE = "▁"
55
56
57class AlbertTokenizer(PreTrainedTokenizer):
58"""
59Constructs an ALBERT tokenizer. Based on `SentencePiece <https://github.com/google/sentencepiece>`__
60
61This tokenizer inherits from :class:`~transformers.PreTrainedTokenizer` which contains most of the methods. Users
62should refer to the superclass for more information regarding methods.
63
64Args:
65vocab_file (:obj:`string`):
66`SentencePiece <https://github.com/google/sentencepiece>`__ file (generally has a .spm extension) that
67contains the vocabulary necessary to instantiate a tokenizer.
68do_lower_case (:obj:`bool`, `optional`, defaults to :obj:`True`):
69Whether to lowercase the input when tokenizing.
70remove_space (:obj:`bool`, `optional`, defaults to :obj:`True`):
71Whether to strip the text when tokenizing (removing excess spaces before and after the string).
72keep_accents (:obj:`bool`, `optional`, defaults to :obj:`False`):
73Whether to keep accents when tokenizing.
74bos_token (:obj:`string`, `optional`, defaults to "[CLS]"):
75The beginning of sequence token that was used during pre-training. Can be used a sequence classifier token.
76
77.. note::
78
79When building a sequence using special tokens, this is not the token that is used for the beginning
80of sequence. The token used is the :obj:`cls_token`.
81eos_token (:obj:`string`, `optional`, defaults to "[SEP]"):
82The end of sequence token.
83
84.. note::
85
86When building a sequence using special tokens, this is not the token that is used for the end
87of sequence. The token used is the :obj:`sep_token`.
88unk_token (:obj:`string`, `optional`, defaults to "<unk>"):
89The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
90token instead.
91sep_token (:obj:`string`, `optional`, defaults to "[SEP]"):
92The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences
93for sequence classification or for a text and a question for question answering.
94It is also used as the last token of a sequence built with special tokens.
95pad_token (:obj:`string`, `optional`, defaults to "<pad>"):
96The token used for padding, for example when batching sequences of different lengths.
97cls_token (:obj:`string`, `optional`, defaults to "[CLS]"):
98The classifier token which is used when doing sequence classification (classification of the whole
99sequence instead of per-token classification). It is the first token of the sequence when built with
100special tokens.
101mask_token (:obj:`string`, `optional`, defaults to "[MASK]"):
102The token used for masking values. This is the token used when training this model with masked language
103modeling. This is the token which the model will try to predict.
104
105Attributes:
106sp_model (:obj:`SentencePieceProcessor`):
107The `SentencePiece` processor that is used for every conversion (string, tokens and IDs).
108"""
109
110vocab_files_names = VOCAB_FILES_NAMES
111pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
112max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
113
114def __init__(
115self,
116vocab_file,
117do_lower_case=True,
118remove_space=True,
119keep_accents=False,
120bos_token="[CLS]",
121eos_token="[SEP]",
122unk_token="<unk>",
123sep_token="[SEP]",
124pad_token="<pad>",
125cls_token="[CLS]",
126mask_token="[MASK]",
127**kwargs
128):
129super().__init__(
130bos_token=bos_token,
131eos_token=eos_token,
132unk_token=unk_token,
133sep_token=sep_token,
134pad_token=pad_token,
135cls_token=cls_token,
136mask_token=mask_token,
137**kwargs,
138)
139
140try:
141import sentencepiece as spm
142except ImportError:
143logger.warning(
144"You need to install SentencePiece to use AlbertTokenizer: https://github.com/google/sentencepiece"
145"pip install sentencepiece"
146)
147raise
148
149self.do_lower_case = do_lower_case
150self.remove_space = remove_space
151self.keep_accents = keep_accents
152self.vocab_file = vocab_file
153
154self.sp_model = spm.SentencePieceProcessor()
155self.sp_model.Load(vocab_file)
156
157@property
158def vocab_size(self):
159return len(self.sp_model)
160
161def get_vocab(self):
162vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
163vocab.update(self.added_tokens_encoder)
164return vocab
165
166def __getstate__(self):
167state = self.__dict__.copy()
168state["sp_model"] = None
169return state
170
171def __setstate__(self, d):
172self.__dict__ = d
173try:
174import sentencepiece as spm
175except ImportError:
176logger.warning(
177"You need to install SentencePiece to use AlbertTokenizer: https://github.com/google/sentencepiece"
178"pip install sentencepiece"
179)
180raise
181self.sp_model = spm.SentencePieceProcessor()
182self.sp_model.Load(self.vocab_file)
183
184def preprocess_text(self, inputs):
185if self.remove_space:
186outputs = " ".join(inputs.strip().split())
187else:
188outputs = inputs
189outputs = outputs.replace("``", '"').replace("''", '"')
190
191if not self.keep_accents:
192outputs = unicodedata.normalize("NFKD", outputs)
193outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
194if self.do_lower_case:
195outputs = outputs.lower()
196
197return outputs
198
199def _tokenize(self, text, sample=False):
200""" Tokenize a string. """
201text = self.preprocess_text(text)
202
203if not sample:
204pieces = self.sp_model.EncodeAsPieces(text)
205else:
206pieces = self.sp_model.SampleEncodeAsPieces(text, 64, 0.1)
207new_pieces = []
208for piece in pieces:
209if len(piece) > 1 and piece[-1] == str(",") and piece[-2].isdigit():
210cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
211if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
212if len(cur_pieces[0]) == 1:
213cur_pieces = cur_pieces[1:]
214else:
215cur_pieces[0] = cur_pieces[0][1:]
216cur_pieces.append(piece[-1])
217new_pieces.extend(cur_pieces)
218else:
219new_pieces.append(piece)
220
221return new_pieces
222
223def _convert_token_to_id(self, token):
224""" Converts a token (str) in an id using the vocab. """
225return self.sp_model.PieceToId(token)
226
227def _convert_id_to_token(self, index):
228"""Converts an index (integer) in a token (str) using the vocab."""
229return self.sp_model.IdToPiece(index)
230
231def convert_tokens_to_string(self, tokens):
232out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
233return out_string
234
235def build_inputs_with_special_tokens(
236self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
237) -> List[int]:
238"""
239Build model inputs from a sequence or a pair of sequence for sequence classification tasks
240by concatenating and adding special tokens.
241An ALBERT sequence has the following format:
242
243- single sequence: ``[CLS] X [SEP]``
244- pair of sequences: ``[CLS] A [SEP] B [SEP]``
245
246Args:
247token_ids_0 (:obj:`List[int]`):
248List of IDs to which the special tokens will be added
249token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
250Optional second list of IDs for sequence pairs.
251
252Returns:
253:obj:`List[int]`: list of `input IDs <../glossary.html#input-ids>`__ with the appropriate special tokens.
254"""
255sep = [self.sep_token_id]
256cls = [self.cls_token_id]
257if token_ids_1 is None:
258return cls + token_ids_0 + sep
259return cls + token_ids_0 + sep + token_ids_1 + sep
260
261def get_special_tokens_mask(
262self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
263) -> List[int]:
264"""
265Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
266special tokens using the tokenizer ``prepare_for_model`` method.
267
268Args:
269token_ids_0 (:obj:`List[int]`):
270List of ids.
271token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
272Optional second list of IDs for sequence pairs.
273already_has_special_tokens (:obj:`bool`, `optional`, defaults to :obj:`False`):
274Set to True if the token list is already formatted with special tokens for the model
275
276Returns:
277:obj:`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
278"""
279
280if already_has_special_tokens:
281if token_ids_1 is not None:
282raise ValueError(
283"You should not supply a second sequence if the provided sequence of "
284"ids is already formatted with special tokens for the model."
285)
286return list(map(lambda x: 1 if x in [self.sep_token_id, self.cls_token_id] else 0, token_ids_0))
287
288if token_ids_1 is not None:
289return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
290return [1] + ([0] * len(token_ids_0)) + [1]
291
292def create_token_type_ids_from_sequences(
293self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
294) -> List[int]:
295"""
296Creates a mask from the two sequences passed to be used in a sequence-pair classification task.
297An ALBERT sequence pair mask has the following format:
298
299::
300
3010 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
302| first sequence | second sequence |
303
304if token_ids_1 is None, only returns the first portion of the mask (0s).
305
306Args:
307token_ids_0 (:obj:`List[int]`):
308List of ids.
309token_ids_1 (:obj:`List[int]`, `optional`, defaults to :obj:`None`):
310Optional second list of IDs for sequence pairs.
311
312Returns:
313:obj:`List[int]`: List of `token type IDs <../glossary.html#token-type-ids>`_ according to the given
314sequence(s).
315"""
316sep = [self.sep_token_id]
317cls = [self.cls_token_id]
318
319if token_ids_1 is None:
320return len(cls + token_ids_0 + sep) * [0]
321return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
322
323def save_vocabulary(self, save_directory):
324"""
325Save the sentencepiece vocabulary (copy original file) and special tokens file to a directory.
326
327Args:
328save_directory (:obj:`str`):
329The directory in which to save the vocabulary.
330
331Returns:
332:obj:`Tuple(str)`: Paths to the files saved.
333"""
334if not os.path.isdir(save_directory):
335logger.error("Vocabulary path ({}) should be a directory".format(save_directory))
336return
337out_vocab_file = os.path.join(save_directory, VOCAB_FILES_NAMES["vocab_file"])
338
339if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
340copyfile(self.vocab_file, out_vocab_file)
341
342return (out_vocab_file,)
343