tokenization_funnel_fast.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. # coding=utf-8
  2. # Copyright 2020 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 class for Funnel Transformer."""
  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_funnel import FunnelTokenizer
  22. logger = logging.get_logger(__name__)
  23. VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
  24. _model_names = [
  25. "small",
  26. "small-base",
  27. "medium",
  28. "medium-base",
  29. "intermediate",
  30. "intermediate-base",
  31. "large",
  32. "large-base",
  33. "xlarge",
  34. "xlarge-base",
  35. ]
  36. class FunnelTokenizerFast(PreTrainedTokenizerFast):
  37. r"""
  38. Construct a "fast" Funnel Transformer tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
  39. This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
  40. refer to this superclass for more information regarding those methods.
  41. Args:
  42. vocab_file (`str`):
  43. File containing the vocabulary.
  44. do_lower_case (`bool`, *optional*, defaults to `True`):
  45. Whether or not to lowercase the input when tokenizing.
  46. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  47. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  48. token instead.
  49. sep_token (`str`, *optional*, defaults to `"<sep>"`):
  50. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  51. sequence classification or for a text and a question for question answering. It is also used as the last
  52. token of a sequence built with special tokens.
  53. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  54. The token used for padding, for example when batching sequences of different lengths.
  55. cls_token (`str`, *optional*, defaults to `"<cls>"`):
  56. The classifier token which is used when doing sequence classification (classification of the whole sequence
  57. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  58. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  59. The token used for masking values. This is the token used when training this model with masked language
  60. modeling. This is the token which the model will try to predict.
  61. clean_text (`bool`, *optional*, defaults to `True`):
  62. Whether or not to clean the text before tokenization by removing any control characters and replacing all
  63. whitespaces by the classic one.
  64. tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
  65. Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
  66. issue](https://github.com/huggingface/transformers/issues/328)).
  67. bos_token (`str`, `optional`, defaults to `"<s>"`):
  68. The beginning of sentence token.
  69. eos_token (`str`, `optional`, defaults to `"</s>"`):
  70. The end of sentence token.
  71. strip_accents (`bool`, *optional*):
  72. Whether or not to strip all accents. If this option is not specified, then it will be determined by the
  73. value for `lowercase` (as in the original BERT).
  74. wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
  75. The prefix for subwords.
  76. """
  77. vocab_files_names = VOCAB_FILES_NAMES
  78. slow_tokenizer_class = FunnelTokenizer
  79. cls_token_type_id: int = 2
  80. def __init__(
  81. self,
  82. vocab_file=None,
  83. tokenizer_file=None,
  84. do_lower_case=True,
  85. unk_token="<unk>",
  86. sep_token="<sep>",
  87. pad_token="<pad>",
  88. cls_token="<cls>",
  89. mask_token="<mask>",
  90. bos_token="<s>",
  91. eos_token="</s>",
  92. clean_text=True,
  93. tokenize_chinese_chars=True,
  94. strip_accents=None,
  95. wordpieces_prefix="##",
  96. **kwargs,
  97. ):
  98. super().__init__(
  99. vocab_file,
  100. tokenizer_file=tokenizer_file,
  101. do_lower_case=do_lower_case,
  102. unk_token=unk_token,
  103. sep_token=sep_token,
  104. pad_token=pad_token,
  105. cls_token=cls_token,
  106. mask_token=mask_token,
  107. bos_token=bos_token,
  108. eos_token=eos_token,
  109. clean_text=clean_text,
  110. tokenize_chinese_chars=tokenize_chinese_chars,
  111. strip_accents=strip_accents,
  112. wordpieces_prefix=wordpieces_prefix,
  113. **kwargs,
  114. )
  115. normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
  116. if (
  117. normalizer_state.get("lowercase", do_lower_case) != do_lower_case
  118. or normalizer_state.get("strip_accents", strip_accents) != strip_accents
  119. or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
  120. ):
  121. normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
  122. normalizer_state["lowercase"] = do_lower_case
  123. normalizer_state["strip_accents"] = strip_accents
  124. normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
  125. self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
  126. self.do_lower_case = do_lower_case
  127. # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast.build_inputs_with_special_tokens with BERT->Funnel
  128. def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
  129. """
  130. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  131. adding special tokens. A Funnel sequence has the following format:
  132. - single sequence: `[CLS] X [SEP]`
  133. - pair of sequences: `[CLS] A [SEP] B [SEP]`
  134. Args:
  135. token_ids_0 (`List[int]`):
  136. List of IDs to which the special tokens will be added.
  137. token_ids_1 (`List[int]`, *optional*):
  138. Optional second list of IDs for sequence pairs.
  139. Returns:
  140. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  141. """
  142. output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  143. if token_ids_1 is not None:
  144. output += token_ids_1 + [self.sep_token_id]
  145. return output
  146. def create_token_type_ids_from_sequences(
  147. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  148. ) -> List[int]:
  149. """
  150. Create a mask from the two sequences passed to be used in a sequence-pair classification task. A Funnel
  151. Transformer sequence pair mask has the following format:
  152. ```
  153. 2 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
  154. | first sequence | second sequence |
  155. ```
  156. If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
  157. Args:
  158. token_ids_0 (`List[int]`):
  159. List of IDs.
  160. token_ids_1 (`List[int]`, *optional*):
  161. Optional second list of IDs for sequence pairs.
  162. Returns:
  163. `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
  164. """
  165. sep = [self.sep_token_id]
  166. cls = [self.cls_token_id]
  167. if token_ids_1 is None:
  168. return len(cls) * [self.cls_token_type_id] + len(token_ids_0 + sep) * [0]
  169. return len(cls) * [self.cls_token_type_id] + len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
  170. # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast.save_vocabulary
  171. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  172. files = self._tokenizer.model.save(save_directory, name=filename_prefix)
  173. return tuple(files)