tokenization_xlnet.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 XLNet model."""
  16. import os
  17. import unicodedata
  18. from shutil import copyfile
  19. from typing import Any, Optional
  20. import sentencepiece as spm
  21. from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  22. from ...utils import SPIECE_UNDERLINE, logging
  23. from ...utils.import_utils import requires
  24. logger = logging.get_logger(__name__)
  25. VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
  26. # Segments (not really needed)
  27. SEG_ID_A = 0
  28. SEG_ID_B = 1
  29. SEG_ID_CLS = 2
  30. SEG_ID_SEP = 3
  31. SEG_ID_PAD = 4
  32. @requires(backends=("sentencepiece",))
  33. class XLNetTokenizer(PreTrainedTokenizer):
  34. """
  35. Construct an XLNet tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
  36. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  37. this superclass for more information regarding those methods.
  38. Args:
  39. vocab_file (`str`):
  40. [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
  41. contains the vocabulary necessary to instantiate a tokenizer.
  42. do_lower_case (`bool`, *optional*, defaults to `False`):
  43. Whether to lowercase the input when tokenizing.
  44. remove_space (`bool`, *optional*, defaults to `True`):
  45. Whether to strip the text when tokenizing (removing excess spaces before and after the string).
  46. keep_accents (`bool`, *optional*, defaults to `False`):
  47. Whether to keep accents when tokenizing.
  48. bos_token (`str`, *optional*, defaults to `"<s>"`):
  49. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  50. <Tip>
  51. When building a sequence using special tokens, this is not the token that is used for the beginning of
  52. sequence. The token used is the `cls_token`.
  53. </Tip>
  54. eos_token (`str`, *optional*, defaults to `"</s>"`):
  55. The end of sequence token.
  56. <Tip>
  57. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  58. The token used is the `sep_token`.
  59. </Tip>
  60. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  61. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  62. token instead.
  63. sep_token (`str`, *optional*, defaults to `"<sep>"`):
  64. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  65. sequence classification or for a text and a question for question answering. It is also used as the last
  66. token of a sequence built with special tokens.
  67. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  68. The token used for padding, for example when batching sequences of different lengths.
  69. cls_token (`str`, *optional*, defaults to `"<cls>"`):
  70. The classifier token which is used when doing sequence classification (classification of the whole sequence
  71. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  72. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  73. The token used for masking values. This is the token used when training this model with masked language
  74. modeling. This is the token which the model will try to predict.
  75. additional_special_tokens (`list[str]`, *optional*, defaults to `['<eop>', '<eod>']`):
  76. Additional special tokens used by the tokenizer.
  77. sp_model_kwargs (`dict`, *optional*):
  78. Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
  79. SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
  80. to set:
  81. - `enable_sampling`: Enable subword regularization.
  82. - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
  83. - `nbest_size = {0,1}`: No sampling is performed.
  84. - `nbest_size > 1`: samples from the nbest_size results.
  85. - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
  86. using forward-filtering-and-backward-sampling algorithm.
  87. - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
  88. BPE-dropout.
  89. Attributes:
  90. sp_model (`SentencePieceProcessor`):
  91. The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
  92. """
  93. vocab_files_names = VOCAB_FILES_NAMES
  94. padding_side = "left"
  95. def __init__(
  96. self,
  97. vocab_file,
  98. do_lower_case=False,
  99. remove_space=True,
  100. keep_accents=False,
  101. bos_token="<s>",
  102. eos_token="</s>",
  103. unk_token="<unk>",
  104. sep_token="<sep>",
  105. pad_token="<pad>",
  106. cls_token="<cls>",
  107. mask_token="<mask>",
  108. additional_special_tokens=["<eop>", "<eod>"],
  109. sp_model_kwargs: Optional[dict[str, Any]] = None,
  110. **kwargs,
  111. ) -> None:
  112. # Mask token behave like a normal word, i.e. include the space before it
  113. mask_token = AddedToken(mask_token, lstrip=True, special=True) if isinstance(mask_token, str) else mask_token
  114. self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
  115. self.do_lower_case = do_lower_case
  116. self.remove_space = remove_space
  117. self.keep_accents = keep_accents
  118. self.vocab_file = vocab_file
  119. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  120. self.sp_model.Load(vocab_file)
  121. super().__init__(
  122. do_lower_case=do_lower_case,
  123. remove_space=remove_space,
  124. keep_accents=keep_accents,
  125. bos_token=bos_token,
  126. eos_token=eos_token,
  127. unk_token=unk_token,
  128. sep_token=sep_token,
  129. pad_token=pad_token,
  130. cls_token=cls_token,
  131. mask_token=mask_token,
  132. additional_special_tokens=additional_special_tokens,
  133. sp_model_kwargs=self.sp_model_kwargs,
  134. **kwargs,
  135. )
  136. self._pad_token_type_id = 3
  137. @property
  138. def vocab_size(self):
  139. return len(self.sp_model)
  140. def get_vocab(self):
  141. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
  142. vocab.update(self.added_tokens_encoder)
  143. return vocab
  144. def __getstate__(self):
  145. state = self.__dict__.copy()
  146. state["sp_model"] = None
  147. return state
  148. def __setstate__(self, d):
  149. self.__dict__ = d
  150. # for backward compatibility
  151. if not hasattr(self, "sp_model_kwargs"):
  152. self.sp_model_kwargs = {}
  153. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  154. self.sp_model.Load(self.vocab_file)
  155. def preprocess_text(self, inputs):
  156. if self.remove_space:
  157. outputs = " ".join(inputs.strip().split())
  158. else:
  159. outputs = inputs
  160. outputs = outputs.replace("``", '"').replace("''", '"')
  161. if not self.keep_accents:
  162. outputs = unicodedata.normalize("NFKD", outputs)
  163. outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
  164. if self.do_lower_case:
  165. outputs = outputs.lower()
  166. return outputs
  167. def _tokenize(self, text: str) -> list[str]:
  168. """Tokenize a string."""
  169. text = self.preprocess_text(text)
  170. pieces = self.sp_model.encode(text, out_type=str)
  171. new_pieces = []
  172. for piece in pieces:
  173. if len(piece) > 1 and piece[-1] == "," and piece[-2].isdigit():
  174. cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
  175. if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
  176. if len(cur_pieces[0]) == 1:
  177. cur_pieces = cur_pieces[1:]
  178. else:
  179. cur_pieces[0] = cur_pieces[0][1:]
  180. cur_pieces.append(piece[-1])
  181. new_pieces.extend(cur_pieces)
  182. else:
  183. new_pieces.append(piece)
  184. return new_pieces
  185. def _convert_token_to_id(self, token):
  186. """Converts a token (str) in an id using the vocab."""
  187. return self.sp_model.PieceToId(token)
  188. def _convert_id_to_token(self, index):
  189. """Converts an index (integer) in a token (str) using the vocab."""
  190. return self.sp_model.IdToPiece(index)
  191. def convert_tokens_to_string(self, tokens):
  192. """Converts a sequence of tokens (strings for sub-words) in a single string."""
  193. out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
  194. return out_string
  195. def _decode(
  196. self,
  197. token_ids: list[int],
  198. skip_special_tokens: bool = False,
  199. clean_up_tokenization_spaces: Optional[bool] = None,
  200. spaces_between_special_tokens: bool = True,
  201. **kwargs,
  202. ) -> str:
  203. self._decode_use_source_tokenizer = kwargs.pop("use_source_tokenizer", False)
  204. filtered_tokens = self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)
  205. # To avoid mixing byte-level and unicode for byte-level BPT
  206. # we need to build string separately for added tokens and byte-level tokens
  207. # cf. https://github.com/huggingface/transformers/issues/1133
  208. sub_texts = []
  209. current_sub_text = []
  210. for token in filtered_tokens:
  211. if skip_special_tokens and token in self.all_special_ids:
  212. continue
  213. if token in self.added_tokens_encoder:
  214. if current_sub_text:
  215. sub_texts.append(self.convert_tokens_to_string(current_sub_text))
  216. current_sub_text = []
  217. sub_texts.append(token)
  218. else:
  219. current_sub_text.append(token)
  220. if current_sub_text:
  221. sub_texts.append(self.convert_tokens_to_string(current_sub_text))
  222. # Mimic the behavior of the Rust tokenizer:
  223. # By default, there are no spaces between special tokens
  224. text = "".join(sub_texts)
  225. clean_up_tokenization_spaces = (
  226. clean_up_tokenization_spaces
  227. if clean_up_tokenization_spaces is not None
  228. else self.clean_up_tokenization_spaces
  229. )
  230. if clean_up_tokenization_spaces:
  231. clean_text = self.clean_up_tokenization(text)
  232. return clean_text
  233. else:
  234. return text
  235. def build_inputs_with_special_tokens(
  236. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  237. ) -> list[int]:
  238. """
  239. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  240. adding special tokens. An XLNet sequence has the following format:
  241. - single sequence: `X <sep> <cls>`
  242. - pair of sequences: `A <sep> B <sep> <cls>`
  243. Args:
  244. token_ids_0 (`list[int]`):
  245. List of IDs to which the special tokens will be added.
  246. token_ids_1 (`list[int]`, *optional*):
  247. Optional second list of IDs for sequence pairs.
  248. Returns:
  249. `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  250. """
  251. sep = [self.sep_token_id]
  252. cls = [self.cls_token_id]
  253. if token_ids_1 is None:
  254. return token_ids_0 + sep + cls
  255. return token_ids_0 + sep + token_ids_1 + sep + cls
  256. def get_special_tokens_mask(
  257. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
  258. ) -> list[int]:
  259. """
  260. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  261. special tokens using the tokenizer `prepare_for_model` method.
  262. Args:
  263. token_ids_0 (`list[int]`):
  264. List of IDs.
  265. token_ids_1 (`list[int]`, *optional*):
  266. Optional second list of IDs for sequence pairs.
  267. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  268. Whether or not the token list is already formatted with special tokens for the model.
  269. Returns:
  270. `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  271. """
  272. if already_has_special_tokens:
  273. return super().get_special_tokens_mask(
  274. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  275. )
  276. if token_ids_1 is not None:
  277. return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1, 1]
  278. return ([0] * len(token_ids_0)) + [1, 1]
  279. def create_token_type_ids_from_sequences(
  280. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  281. ) -> list[int]:
  282. """
  283. Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLNet
  284. sequence pair mask has the following format:
  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. If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
  290. Args:
  291. token_ids_0 (`list[int]`):
  292. List of IDs.
  293. token_ids_1 (`list[int]`, *optional*):
  294. Optional second list of IDs for sequence pairs.
  295. Returns:
  296. `list[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
  297. """
  298. sep = [self.sep_token_id]
  299. cls_segment_id = [2]
  300. if token_ids_1 is None:
  301. return len(token_ids_0 + sep) * [0] + cls_segment_id
  302. return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] + cls_segment_id
  303. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
  304. if not os.path.isdir(save_directory):
  305. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  306. return
  307. out_vocab_file = os.path.join(
  308. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  309. )
  310. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
  311. copyfile(self.vocab_file, out_vocab_file)
  312. elif not os.path.isfile(self.vocab_file):
  313. with open(out_vocab_file, "wb") as fi:
  314. content_spiece_model = self.sp_model.serialized_model_proto()
  315. fi.write(content_spiece_model)
  316. return (out_vocab_file,)
  317. __all__ = ["XLNetTokenizer"]