tokenization_bert.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. # Copyright 2018 The Google AI Language Team 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 Bert."""
  15. import collections
  16. from tokenizers import Tokenizer, decoders, normalizers, pre_tokenizers, processors
  17. from tokenizers.models import WordPiece
  18. from ...tokenization_utils_tokenizers import TokenizersBackend
  19. from ...utils import logging
  20. logger = logging.get_logger(__name__)
  21. VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
  22. def load_vocab(vocab_file):
  23. """Loads a vocabulary file into a dictionary."""
  24. vocab = collections.OrderedDict()
  25. with open(vocab_file, "r", encoding="utf-8") as reader:
  26. tokens = reader.readlines()
  27. for index, token in enumerate(tokens):
  28. token = token.rstrip("\n")
  29. vocab[token] = index
  30. return vocab
  31. class BertTokenizer(TokenizersBackend):
  32. r"""
  33. Construct a BERT tokenizer (backed by HuggingFace's tokenizers library). Based on WordPiece.
  34. This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should refer to
  35. this superclass for more information regarding those methods.
  36. Args:
  37. vocab (`str` or `dict[str, int]`, *optional*):
  38. Custom vocabulary dictionary. If not provided, vocabulary is loaded from `vocab_file`.
  39. do_lower_case (`bool`, *optional*, defaults to `True`):
  40. Whether or not to lowercase the input when tokenizing.
  41. unk_token (`str`, *optional*, defaults to `"[UNK]"`):
  42. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  43. token instead.
  44. sep_token (`str`, *optional*, defaults to `"[SEP]"`):
  45. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  46. sequence classification or for a text and a question for question answering. It is also used as the last
  47. token of a sequence built with special tokens.
  48. pad_token (`str`, *optional*, defaults to `"[PAD]"`):
  49. The token used for padding, for example when batching sequences of different lengths.
  50. cls_token (`str`, *optional*, defaults to `"[CLS]"`):
  51. The classifier token which is used when doing sequence classification (classification of the whole sequence
  52. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  53. mask_token (`str`, *optional*, defaults to `"[MASK]"`):
  54. The token used for masking values. This is the token used when training this model with masked language
  55. modeling. This is the token which the model will try to predict.
  56. tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
  57. Whether or not to tokenize Chinese characters.
  58. strip_accents (`bool`, *optional*):
  59. Whether or not to strip all accents. If this option is not specified, then it will be determined by the
  60. value for `lowercase` (as in the original BERT).
  61. """
  62. vocab_files_names = VOCAB_FILES_NAMES
  63. model_input_names = ["input_ids", "token_type_ids", "attention_mask"]
  64. model = WordPiece
  65. def __init__(
  66. self,
  67. vocab: str | dict[str, int] | None = None,
  68. do_lower_case: bool = True,
  69. unk_token: str = "[UNK]",
  70. sep_token: str = "[SEP]",
  71. pad_token: str = "[PAD]",
  72. cls_token: str = "[CLS]",
  73. mask_token: str = "[MASK]",
  74. tokenize_chinese_chars: bool = True,
  75. strip_accents: bool | None = None,
  76. **kwargs,
  77. ):
  78. self.do_lower_case = do_lower_case
  79. self.tokenize_chinese_chars = tokenize_chinese_chars
  80. self.strip_accents = strip_accents
  81. if vocab is None:
  82. vocab = {
  83. str(pad_token): 0,
  84. str(unk_token): 1,
  85. str(cls_token): 2,
  86. str(sep_token): 3,
  87. str(mask_token): 4,
  88. }
  89. self._vocab = vocab
  90. self._tokenizer = Tokenizer(WordPiece(self._vocab, unk_token=str(unk_token)))
  91. self._tokenizer.normalizer = normalizers.BertNormalizer(
  92. clean_text=True,
  93. handle_chinese_chars=tokenize_chinese_chars,
  94. strip_accents=strip_accents,
  95. lowercase=do_lower_case,
  96. )
  97. self._tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer()
  98. self._tokenizer.decoder = decoders.WordPiece(prefix="##")
  99. super().__init__(
  100. do_lower_case=do_lower_case,
  101. unk_token=unk_token,
  102. sep_token=sep_token,
  103. pad_token=pad_token,
  104. cls_token=cls_token,
  105. mask_token=mask_token,
  106. tokenize_chinese_chars=tokenize_chinese_chars,
  107. strip_accents=strip_accents,
  108. **kwargs,
  109. )
  110. cls_token_id = self.cls_token_id if self.cls_token_id is not None else 2
  111. sep_token_id = self.sep_token_id if self.sep_token_id is not None else 3
  112. self._tokenizer.post_processor = processors.TemplateProcessing(
  113. single=f"{str(self.cls_token)}:0 $A:0 {str(self.sep_token)}:0",
  114. pair=f"{str(self.cls_token)}:0 $A:0 {str(self.sep_token)}:0 $B:1 {str(self.sep_token)}:1",
  115. special_tokens=[
  116. (str(self.cls_token), cls_token_id),
  117. (str(self.sep_token), sep_token_id),
  118. ],
  119. )
  120. __all__ = ["BertTokenizer"]
  121. BertTokenizerFast = BertTokenizer