tokenization_xlnet.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
  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. """Tokenization classes for XLNet model."""
  15. from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, processors
  16. from tokenizers.models import Unigram
  17. from ...tokenization_utils_base import _get_prepend_scheme
  18. from ...tokenization_utils_tokenizers import TokenizersBackend
  19. from ...utils import logging
  20. logger = logging.get_logger(__name__)
  21. VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
  22. SPIECE_UNDERLINE = "▁"
  23. # Segments (not really needed)
  24. SEG_ID_A = 0
  25. SEG_ID_B = 1
  26. SEG_ID_CLS = 2
  27. SEG_ID_SEP = 3
  28. SEG_ID_PAD = 4
  29. class XLNetTokenizer(TokenizersBackend):
  30. """
  31. Construct a XLNet tokenizer (backed by HuggingFace's *tokenizers* library). Based on
  32. [Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models).
  33. This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
  34. refer to this superclass for more information regarding those methods.
  35. Args:
  36. vocab (`list of tuples`, *optional*):
  37. List of (token, score) tuples for Unigram model. If not provided, an empty list is used.
  38. unk_id (`int`, *optional*, defaults to 0):
  39. The ID of the unknown token in the vocabulary.
  40. do_lower_case (`bool`, *optional*, defaults to `False`):
  41. Whether to lowercase the input when tokenizing.
  42. remove_space (`bool`, *optional*, defaults to `True`):
  43. Whether to strip the text when tokenizing (removing excess spaces before and after the string).
  44. keep_accents (`bool`, *optional*, defaults to `False`):
  45. Whether to keep accents when tokenizing.
  46. bos_token (`str`, *optional*, defaults to `"<s>"`):
  47. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  48. <Tip>
  49. When building a sequence using special tokens, this is not the token that is used for the beginning of
  50. sequence. The token used is the `cls_token`.
  51. </Tip>
  52. eos_token (`str`, *optional*, defaults to `"</s>"`):
  53. The end of sequence token.
  54. <Tip>
  55. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  56. The token used is the `sep_token`.
  57. </Tip>
  58. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  59. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  60. token instead.
  61. sep_token (`str`, *optional*, defaults to `"<sep>"`):
  62. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  63. sequence classification or for a text and a question for question answering. It is also used as the last
  64. token of a sequence built with special tokens.
  65. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  66. The token used for padding, for example when batching sequences of different lengths.
  67. cls_token (`str`, *optional*, defaults to `"<cls>"`):
  68. The classifier token which is used when doing sequence classification (classification of the whole sequence
  69. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  70. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  71. The token used for masking values. This is the token used when training this model with masked language
  72. modeling. This is the token which the model will try to predict.
  73. additional_special_tokens (`list[str]`, *optional*, defaults to `["<eop>", "<eod>"]`):
  74. Additional special tokens used by the tokenizer.
  75. """
  76. vocab_files_names = VOCAB_FILES_NAMES
  77. padding_side = "left"
  78. model = Unigram
  79. def __init__(
  80. self,
  81. vocab: str | list[tuple[str, float]] | None = None,
  82. unk_id: int = 0,
  83. do_lower_case=False,
  84. remove_space=True,
  85. keep_accents=False,
  86. bos_token="<s>",
  87. eos_token="</s>",
  88. unk_token="<unk>",
  89. sep_token="<sep>",
  90. pad_token="<pad>",
  91. cls_token="<cls>",
  92. mask_token="<mask>",
  93. additional_special_tokens=None,
  94. **kwargs,
  95. ):
  96. if additional_special_tokens is None:
  97. additional_special_tokens = ["<eop>", "<eod>"]
  98. if vocab is not None:
  99. self._vocab = vocab
  100. else:
  101. self._vocab = [(str(unk_token), 0.0)]
  102. self._tokenizer = Tokenizer(
  103. Unigram(
  104. self._vocab,
  105. unk_id=unk_id,
  106. byte_fallback=False,
  107. )
  108. )
  109. list_normalizers = [
  110. normalizers.Replace("``", '"'),
  111. normalizers.Replace("''", '"'),
  112. ]
  113. # if not keep_accents:
  114. list_normalizers.append(normalizers.NFKD())
  115. list_normalizers.append(normalizers.StripAccents())
  116. if do_lower_case:
  117. list_normalizers.append(normalizers.Lowercase())
  118. list_normalizers.append(normalizers.Replace(Regex(" {2,}"), " "))
  119. self._tokenizer.normalizer = normalizers.Sequence(list_normalizers)
  120. add_prefix_space = True
  121. prepend_scheme = _get_prepend_scheme(add_prefix_space, self)
  122. self._tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
  123. [
  124. pre_tokenizers.WhitespaceSplit(),
  125. pre_tokenizers.Metaspace(replacement="▁", prepend_scheme=prepend_scheme),
  126. ]
  127. )
  128. self._tokenizer.decoder = decoders.Metaspace(replacement="▁", prepend_scheme=prepend_scheme)
  129. self._pad_token_type_id = 3
  130. self.do_lower_case = do_lower_case
  131. self.remove_space = remove_space
  132. self.keep_accents = keep_accents
  133. mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
  134. super().__init__(
  135. unk_id=unk_id,
  136. do_lower_case=do_lower_case,
  137. remove_space=remove_space,
  138. keep_accents=keep_accents,
  139. bos_token=bos_token,
  140. eos_token=eos_token,
  141. unk_token=unk_token,
  142. sep_token=sep_token,
  143. pad_token=pad_token,
  144. cls_token=cls_token,
  145. mask_token=mask_token,
  146. additional_special_tokens=additional_special_tokens,
  147. **kwargs,
  148. )
  149. self._tokenizer.post_processor = processors.TemplateProcessing(
  150. single=f"$A:0 {str(self.sep_token)}:0 {str(self.cls_token)}:2",
  151. pair=f"$A:0 {str(self.sep_token)}:0 $B:1 {str(self.sep_token)}:1 {str(self.cls_token)}:2",
  152. special_tokens=[
  153. (str(self.sep_token), self.sep_token_id),
  154. (str(self.cls_token), self.cls_token_id),
  155. ],
  156. )
  157. __all__ = ["XLNetTokenizer"]