tokenization_splinter_fast.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. # coding=utf-8
  2. # Copyright 2021 Tel AViv University, AllenAI and The HuggingFace Inc. team. All rights reserved.
  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. """Fast Tokenization classes for Splinter."""
  16. import json
  17. from typing import List, Optional, Tuple
  18. from tokenizers import normalizers
  19. from ...tokenization_utils_fast import PreTrainedTokenizerFast
  20. from ...utils import logging
  21. from .tokenization_splinter import SplinterTokenizer
  22. logger = logging.get_logger(__name__)
  23. VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
  24. class SplinterTokenizerFast(PreTrainedTokenizerFast):
  25. r"""
  26. Construct a "fast" Splinter tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
  27. This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
  28. refer to this superclass for more information regarding those methods.
  29. Args:
  30. vocab_file (`str`):
  31. File containing the vocabulary.
  32. do_lower_case (`bool`, *optional*, defaults to `True`):
  33. Whether or not to lowercase the input when tokenizing.
  34. unk_token (`str`, *optional*, defaults to `"[UNK]"`):
  35. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  36. token instead.
  37. sep_token (`str`, *optional*, defaults to `"[SEP]"`):
  38. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  39. sequence classification or for a text and a question for question answering. It is also used as the last
  40. token of a sequence built with special tokens.
  41. pad_token (`str`, *optional*, defaults to `"[PAD]"`):
  42. The token used for padding, for example when batching sequences of different lengths.
  43. cls_token (`str`, *optional*, defaults to `"[CLS]"`):
  44. The classifier token which is used when doing sequence classification (classification of the whole sequence
  45. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  46. mask_token (`str`, *optional*, defaults to `"[MASK]"`):
  47. The token used for masking values. This is the token used when training this model with masked language
  48. modeling. This is the token which the model will try to predict.
  49. question_token (`str`, *optional*, defaults to `"[QUESTION]"`):
  50. The token used for constructing question representations.
  51. clean_text (`bool`, *optional*, defaults to `True`):
  52. Whether or not to clean the text before tokenization by removing any control characters and replacing all
  53. whitespaces by the classic one.
  54. tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
  55. Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
  56. issue](https://github.com/huggingface/transformers/issues/328)).
  57. strip_accents (`bool`, *optional*):
  58. Whether or not to strip all accents. If this option is not specified, then it will be determined by the
  59. value for `lowercase` (as in the original BERT).
  60. wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
  61. The prefix for subwords.
  62. """
  63. vocab_files_names = VOCAB_FILES_NAMES
  64. slow_tokenizer_class = SplinterTokenizer
  65. def __init__(
  66. self,
  67. vocab_file=None,
  68. tokenizer_file=None,
  69. do_lower_case=True,
  70. unk_token="[UNK]",
  71. sep_token="[SEP]",
  72. pad_token="[PAD]",
  73. cls_token="[CLS]",
  74. mask_token="[MASK]",
  75. question_token="[QUESTION]",
  76. tokenize_chinese_chars=True,
  77. strip_accents=None,
  78. **kwargs,
  79. ):
  80. super().__init__(
  81. vocab_file,
  82. tokenizer_file=tokenizer_file,
  83. do_lower_case=do_lower_case,
  84. unk_token=unk_token,
  85. sep_token=sep_token,
  86. pad_token=pad_token,
  87. cls_token=cls_token,
  88. mask_token=mask_token,
  89. tokenize_chinese_chars=tokenize_chinese_chars,
  90. strip_accents=strip_accents,
  91. additional_special_tokens=(question_token,),
  92. **kwargs,
  93. )
  94. pre_tok_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
  95. if (
  96. pre_tok_state.get("lowercase", do_lower_case) != do_lower_case
  97. or pre_tok_state.get("strip_accents", strip_accents) != strip_accents
  98. ):
  99. pre_tok_class = getattr(normalizers, pre_tok_state.pop("type"))
  100. pre_tok_state["lowercase"] = do_lower_case
  101. pre_tok_state["strip_accents"] = strip_accents
  102. self.backend_tokenizer.normalizer = pre_tok_class(**pre_tok_state)
  103. self.do_lower_case = do_lower_case
  104. @property
  105. def question_token_id(self):
  106. """
  107. `Optional[int]`: Id of the question token in the vocabulary, used to condition the answer on a question
  108. representation.
  109. """
  110. return self.convert_tokens_to_ids(self.question_token)
  111. def build_inputs_with_special_tokens(
  112. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  113. ) -> List[int]:
  114. """
  115. Build model inputs from a pair of sequence for question answering tasks by concatenating and adding special
  116. tokens. A Splinter sequence has the following format:
  117. - single sequence: `[CLS] X [SEP]`
  118. - pair of sequences for question answering: `[CLS] question_tokens [QUESTION] . [SEP] context_tokens [SEP]`
  119. Args:
  120. token_ids_0 (`List[int]`):
  121. The question token IDs if pad_on_right, else context tokens IDs
  122. token_ids_1 (`List[int]`, *optional*):
  123. The context token IDs if pad_on_right, else question token IDs
  124. Returns:
  125. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  126. """
  127. if token_ids_1 is None:
  128. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  129. cls = [self.cls_token_id]
  130. sep = [self.sep_token_id]
  131. question_suffix = [self.question_token_id] + [self.convert_tokens_to_ids(".")]
  132. if self.padding_side == "right":
  133. # Input is question-then-context
  134. return cls + token_ids_0 + question_suffix + sep + token_ids_1 + sep
  135. else:
  136. # Input is context-then-question
  137. return cls + token_ids_0 + sep + token_ids_1 + question_suffix + 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. Create the token type IDs corresponding to the sequences passed. [What are token type
  143. IDs?](../glossary#token-type-ids)
  144. Should be overridden in a subclass if the model has a special way of building those.
  145. Args:
  146. token_ids_0 (`List[int]`): The first tokenized sequence.
  147. token_ids_1 (`List[int]`, *optional*): The second tokenized sequence.
  148. Returns:
  149. `List[int]`: The token type ids.
  150. """
  151. sep = [self.sep_token_id]
  152. cls = [self.cls_token_id]
  153. question_suffix = [self.question_token_id] + [self.convert_tokens_to_ids(".")]
  154. if token_ids_1 is None:
  155. return len(cls + token_ids_0 + sep) * [0]
  156. if self.padding_side == "right":
  157. # Input is question-then-context
  158. return len(cls + token_ids_0 + question_suffix + sep) * [0] + len(token_ids_1 + sep) * [1]
  159. else:
  160. # Input is context-then-question
  161. return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + question_suffix + sep) * [1]
  162. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  163. files = self._tokenizer.model.save(save_directory, name=filename_prefix)
  164. return tuple(files)