tokenization_mobilebert_fast.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. # coding=utf-8
  2. #
  3. # Copyright 2020 The HuggingFace Team. All rights reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Tokenization classes for MobileBERT."""
  17. import json
  18. from typing import List, Optional, Tuple
  19. from tokenizers import normalizers
  20. from ...tokenization_utils_fast import PreTrainedTokenizerFast
  21. from ...utils import logging
  22. from .tokenization_mobilebert import MobileBertTokenizer
  23. logger = logging.get_logger(__name__)
  24. VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
  25. # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast with BERT->MobileBERT,Bert->MobileBert
  26. class MobileBertTokenizerFast(PreTrainedTokenizerFast):
  27. r"""
  28. Construct a "fast" MobileBERT tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
  29. This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
  30. refer to this superclass for more information regarding those methods.
  31. Args:
  32. vocab_file (`str`):
  33. File containing the vocabulary.
  34. do_lower_case (`bool`, *optional*, defaults to `True`):
  35. Whether or not to lowercase the input when tokenizing.
  36. unk_token (`str`, *optional*, defaults to `"[UNK]"`):
  37. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  38. token instead.
  39. sep_token (`str`, *optional*, defaults to `"[SEP]"`):
  40. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  41. sequence classification or for a text and a question for question answering. It is also used as the last
  42. token of a sequence built with special tokens.
  43. pad_token (`str`, *optional*, defaults to `"[PAD]"`):
  44. The token used for padding, for example when batching sequences of different lengths.
  45. cls_token (`str`, *optional*, defaults to `"[CLS]"`):
  46. The classifier token which is used when doing sequence classification (classification of the whole sequence
  47. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  48. mask_token (`str`, *optional*, defaults to `"[MASK]"`):
  49. The token used for masking values. This is the token used when training this model with masked language
  50. modeling. This is the token which the model will try to predict.
  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 MobileBERT).
  60. wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
  61. The prefix for subwords.
  62. """
  63. vocab_files_names = VOCAB_FILES_NAMES
  64. slow_tokenizer_class = MobileBertTokenizer
  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. tokenize_chinese_chars=True,
  76. strip_accents=None,
  77. **kwargs,
  78. ):
  79. super().__init__(
  80. vocab_file,
  81. tokenizer_file=tokenizer_file,
  82. do_lower_case=do_lower_case,
  83. unk_token=unk_token,
  84. sep_token=sep_token,
  85. pad_token=pad_token,
  86. cls_token=cls_token,
  87. mask_token=mask_token,
  88. tokenize_chinese_chars=tokenize_chinese_chars,
  89. strip_accents=strip_accents,
  90. **kwargs,
  91. )
  92. normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
  93. if (
  94. normalizer_state.get("lowercase", do_lower_case) != do_lower_case
  95. or normalizer_state.get("strip_accents", strip_accents) != strip_accents
  96. or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
  97. ):
  98. normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
  99. normalizer_state["lowercase"] = do_lower_case
  100. normalizer_state["strip_accents"] = strip_accents
  101. normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
  102. self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
  103. self.do_lower_case = do_lower_case
  104. def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
  105. """
  106. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  107. adding special tokens. A MobileBERT sequence has the following format:
  108. - single sequence: `[CLS] X [SEP]`
  109. - pair of sequences: `[CLS] A [SEP] B [SEP]`
  110. Args:
  111. token_ids_0 (`List[int]`):
  112. List of IDs to which the special tokens will be added.
  113. token_ids_1 (`List[int]`, *optional*):
  114. Optional second list of IDs for sequence pairs.
  115. Returns:
  116. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  117. """
  118. output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  119. if token_ids_1 is not None:
  120. output += token_ids_1 + [self.sep_token_id]
  121. return output
  122. def create_token_type_ids_from_sequences(
  123. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  124. ) -> List[int]:
  125. """
  126. Create a mask from the two sequences passed to be used in a sequence-pair classification task. A MobileBERT sequence
  127. pair mask has the following format:
  128. ```
  129. 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
  130. | first sequence | second sequence |
  131. ```
  132. If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
  133. Args:
  134. token_ids_0 (`List[int]`):
  135. List of IDs.
  136. token_ids_1 (`List[int]`, *optional*):
  137. Optional second list of IDs for sequence pairs.
  138. Returns:
  139. `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
  140. """
  141. sep = [self.sep_token_id]
  142. cls = [self.cls_token_id]
  143. if token_ids_1 is None:
  144. return len(cls + token_ids_0 + sep) * [0]
  145. return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
  146. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  147. files = self._tokenizer.model.save(save_directory, name=filename_prefix)
  148. return tuple(files)