tokenization_albert_fast.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. import os
  17. from shutil import copyfile
  18. from typing import List, Optional, Tuple
  19. from ...tokenization_utils import AddedToken
  20. from ...tokenization_utils_fast import PreTrainedTokenizerFast
  21. from ...utils import is_sentencepiece_available, logging
  22. if is_sentencepiece_available():
  23. from .tokenization_albert import AlbertTokenizer
  24. else:
  25. AlbertTokenizer = None
  26. logger = logging.get_logger(__name__)
  27. VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
  28. SPIECE_UNDERLINE = "▁"
  29. class AlbertTokenizerFast(PreTrainedTokenizerFast):
  30. """
  31. Construct a "fast" ALBERT tokenizer (backed by HuggingFace's *tokenizers* library). Based on
  32. [Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models). This
  33. tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should refer to
  34. this superclass for more information regarding those methods
  35. Args:
  36. vocab_file (`str`):
  37. [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
  38. contains the vocabulary necessary to instantiate a tokenizer.
  39. do_lower_case (`bool`, *optional*, defaults to `True`):
  40. Whether or not to lowercase the input when tokenizing.
  41. remove_space (`bool`, *optional*, defaults to `True`):
  42. Whether or not to strip the text when tokenizing (removing excess spaces before and after the string).
  43. keep_accents (`bool`, *optional*, defaults to `False`):
  44. Whether or not to keep accents when tokenizing.
  45. bos_token (`str`, *optional*, defaults to `"[CLS]"`):
  46. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  47. <Tip>
  48. When building a sequence using special tokens, this is not the token that is used for the beginning of
  49. sequence. The token used is the `cls_token`.
  50. </Tip>
  51. eos_token (`str`, *optional*, defaults to `"[SEP]"`):
  52. The end of sequence token. .. note:: When building a sequence using special tokens, this is not the token
  53. that is used for the end of sequence. The token used is the `sep_token`.
  54. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  55. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  56. token instead.
  57. sep_token (`str`, *optional*, defaults to `"[SEP]"`):
  58. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  59. sequence classification or for a text and a question for question answering. It is also used as the last
  60. token of a sequence built with special tokens.
  61. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  62. The token used for padding, for example when batching sequences of different lengths.
  63. cls_token (`str`, *optional*, defaults to `"[CLS]"`):
  64. The classifier token which is used when doing sequence classification (classification of the whole sequence
  65. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  66. mask_token (`str`, *optional*, defaults to `"[MASK]"`):
  67. The token used for masking values. This is the token used when training this model with masked language
  68. modeling. This is the token which the model will try to predict.
  69. """
  70. vocab_files_names = VOCAB_FILES_NAMES
  71. slow_tokenizer_class = AlbertTokenizer
  72. def __init__(
  73. self,
  74. vocab_file=None,
  75. tokenizer_file=None,
  76. do_lower_case=True,
  77. remove_space=True,
  78. keep_accents=False,
  79. bos_token="[CLS]",
  80. eos_token="[SEP]",
  81. unk_token="<unk>",
  82. sep_token="[SEP]",
  83. pad_token="<pad>",
  84. cls_token="[CLS]",
  85. mask_token="[MASK]",
  86. **kwargs,
  87. ):
  88. # Mask token behave like a normal word, i.e. include the space before it and
  89. # is included in the raw text, there should be a match in a non-normalized sentence.
  90. mask_token = (
  91. AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False)
  92. if isinstance(mask_token, str)
  93. else mask_token
  94. )
  95. super().__init__(
  96. vocab_file,
  97. tokenizer_file=tokenizer_file,
  98. do_lower_case=do_lower_case,
  99. remove_space=remove_space,
  100. keep_accents=keep_accents,
  101. bos_token=bos_token,
  102. eos_token=eos_token,
  103. unk_token=unk_token,
  104. sep_token=sep_token,
  105. pad_token=pad_token,
  106. cls_token=cls_token,
  107. mask_token=mask_token,
  108. **kwargs,
  109. )
  110. self.do_lower_case = do_lower_case
  111. self.remove_space = remove_space
  112. self.keep_accents = keep_accents
  113. self.vocab_file = vocab_file
  114. @property
  115. def can_save_slow_tokenizer(self) -> bool:
  116. return os.path.isfile(self.vocab_file) if self.vocab_file else False
  117. def build_inputs_with_special_tokens(
  118. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  119. ) -> List[int]:
  120. """
  121. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  122. adding special tokens. An ALBERT sequence has the following format:
  123. - single sequence: `[CLS] X [SEP]`
  124. - pair of sequences: `[CLS] A [SEP] B [SEP]`
  125. Args:
  126. token_ids_0 (`List[int]`):
  127. List of IDs to which the special tokens will be added
  128. token_ids_1 (`List[int]`, *optional*):
  129. Optional second list of IDs for sequence pairs.
  130. Returns:
  131. `List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  132. """
  133. sep = [self.sep_token_id]
  134. cls = [self.cls_token_id]
  135. if token_ids_1 is None:
  136. return cls + token_ids_0 + sep
  137. return cls + token_ids_0 + sep + token_ids_1 + sep
  138. def create_token_type_ids_from_sequences(
  139. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  140. ) -> List[int]:
  141. """
  142. Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
  143. sequence pair mask has the following format:
  144. ```
  145. 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
  146. | first sequence | second sequence |
  147. ```
  148. if token_ids_1 is None, only returns the first portion of the mask (0s).
  149. Args:
  150. token_ids_0 (`List[int]`):
  151. List of ids.
  152. token_ids_1 (`List[int]`, *optional*):
  153. Optional second list of IDs for sequence pairs.
  154. Returns:
  155. `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
  156. """
  157. sep = [self.sep_token_id]
  158. cls = [self.cls_token_id]
  159. if token_ids_1 is None:
  160. return len(cls + token_ids_0 + sep) * [0]
  161. return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
  162. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  163. if not self.can_save_slow_tokenizer:
  164. raise ValueError(
  165. "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
  166. "tokenizer."
  167. )
  168. if not os.path.isdir(save_directory):
  169. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  170. return
  171. out_vocab_file = os.path.join(
  172. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  173. )
  174. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
  175. copyfile(self.vocab_file, out_vocab_file)
  176. return (out_vocab_file,)
  177. __all__ = ["AlbertTokenizerFast"]