tokenization_funnel.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. # Copyright 2020 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 class for Funnel Transformer."""
  15. from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
  16. from tokenizers.models import WordPiece
  17. from ...tokenization_utils_tokenizers import TokenizersBackend
  18. from ...utils import logging
  19. logger = logging.get_logger(__name__)
  20. VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
  21. _model_names = [
  22. "small",
  23. "small-base",
  24. "medium",
  25. "medium-base",
  26. "intermediate",
  27. "intermediate-base",
  28. "large",
  29. "large-base",
  30. "xlarge",
  31. "xlarge-base",
  32. ]
  33. class FunnelTokenizer(TokenizersBackend):
  34. r"""
  35. Construct a Funnel Transformer tokenizer (backed by HuggingFace's tokenizers library). Based on WordPiece.
  36. This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
  37. refer to this superclass for more information regarding those methods.
  38. Args:
  39. vocab_file (`str`):
  40. File containing the vocabulary.
  41. do_lower_case (`bool`, *optional*, defaults to `True`):
  42. Whether or not to lowercase the input when tokenizing.
  43. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  44. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  45. token instead.
  46. sep_token (`str`, *optional*, defaults to `"<sep>"`):
  47. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  48. sequence classification or for a text and a question for question answering. It is also used as the last
  49. token of a sequence built with special tokens.
  50. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  51. The token used for padding, for example when batching sequences of different lengths.
  52. cls_token (`str`, *optional*, defaults to `"<cls>"`):
  53. The classifier token which is used when doing sequence classification (classification of the whole sequence
  54. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  55. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  56. The token used for masking values. This is the token used when training this model with masked language
  57. modeling. This is the token which the model will try to predict.
  58. clean_text (`bool`, *optional*, defaults to `True`):
  59. Whether or not to clean the text before tokenization by removing any control characters and replacing all
  60. whitespaces by the classic one.
  61. tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
  62. Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
  63. issue](https://github.com/huggingface/transformers/issues/328)).
  64. bos_token (`str`, `optional`, defaults to `"<s>"`):
  65. The beginning of sentence token.
  66. eos_token (`str`, `optional`, defaults to `"</s>"`):
  67. The end of sentence token.
  68. strip_accents (`bool`, *optional*):
  69. Whether or not to strip all accents. If this option is not specified, then it will be determined by the
  70. value for `lowercase` (as in the original BERT).
  71. wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
  72. The prefix for subwords.
  73. vocab (`str` or `dict[str, int]`, *optional*):
  74. Custom vocabulary dictionary.
  75. """
  76. vocab_files_names = VOCAB_FILES_NAMES
  77. model = WordPiece
  78. cls_token_type_id: int = 2
  79. def __init__(
  80. self,
  81. vocab: str | dict[str, int] | None = None,
  82. do_lower_case: bool = True,
  83. unk_token: str = "<unk>",
  84. sep_token: str = "<sep>",
  85. pad_token: str = "<pad>",
  86. cls_token: str = "<cls>",
  87. mask_token: str = "<mask>",
  88. bos_token: str = "<s>",
  89. eos_token: str = "</s>",
  90. clean_text: bool = True,
  91. tokenize_chinese_chars: bool = True,
  92. strip_accents: bool | None = None,
  93. wordpieces_prefix: str = "##",
  94. **kwargs,
  95. ):
  96. self.do_lower_case = do_lower_case
  97. self.tokenize_chinese_chars = tokenize_chinese_chars
  98. self.strip_accents = strip_accents
  99. self.clean_text = clean_text
  100. self.wordpieces_prefix = wordpieces_prefix
  101. self._vocab = (
  102. vocab
  103. if vocab is not None
  104. else {
  105. str(pad_token): 0,
  106. str(unk_token): 1,
  107. str(cls_token): 2,
  108. str(sep_token): 3,
  109. str(mask_token): 4,
  110. str(bos_token): 5,
  111. str(eos_token): 6,
  112. }
  113. )
  114. self._tokenizer = Tokenizer(WordPiece(self._vocab, unk_token=str(unk_token)))
  115. self._tokenizer.normalizer = normalizers.BertNormalizer(
  116. clean_text=clean_text,
  117. handle_chinese_chars=tokenize_chinese_chars,
  118. strip_accents=strip_accents,
  119. lowercase=do_lower_case,
  120. )
  121. self._tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer()
  122. self._tokenizer.decoder = decoders.WordPiece(prefix=wordpieces_prefix)
  123. super().__init__(
  124. do_lower_case=do_lower_case,
  125. unk_token=unk_token,
  126. sep_token=sep_token,
  127. pad_token=pad_token,
  128. cls_token=cls_token,
  129. mask_token=mask_token,
  130. bos_token=bos_token,
  131. eos_token=eos_token,
  132. clean_text=clean_text,
  133. tokenize_chinese_chars=tokenize_chinese_chars,
  134. strip_accents=strip_accents,
  135. wordpieces_prefix=wordpieces_prefix,
  136. **kwargs,
  137. )
  138. self._tokenizer.post_processor = processors.TemplateProcessing(
  139. single=f"{cls_token}:2 $A:0 {sep_token}:0", # token_type_id is 2 for Funnel transformer
  140. pair=f"{cls_token}:2 $A:0 {sep_token}:0 $B:1 {sep_token}:1",
  141. special_tokens=[
  142. (str(cls_token), self.cls_token_id),
  143. (str(sep_token), self.sep_token_id),
  144. ],
  145. )
  146. __all__ = ["FunnelTokenizer"]