tokenization_herbert_fast.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. # coding=utf-8
  2. # Copyright 2020 The Google AI Language Team Authors, Allegro.pl, Facebook Inc. and 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. from typing import List, Optional, Tuple
  16. from ...tokenization_utils_fast import PreTrainedTokenizerFast
  17. from ...utils import logging
  18. from .tokenization_herbert import HerbertTokenizer
  19. logger = logging.get_logger(__name__)
  20. VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
  21. class HerbertTokenizerFast(PreTrainedTokenizerFast):
  22. """
  23. Construct a "Fast" BPE tokenizer for HerBERT (backed by HuggingFace's *tokenizers* library).
  24. Peculiarities:
  25. - uses BERT's pre-tokenizer: BertPreTokenizer splits tokens on spaces, and also on punctuation. Each occurrence of
  26. a punctuation character will be treated separately.
  27. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the methods. Users should refer to the
  28. superclass for more information regarding methods.
  29. Args:
  30. vocab_file (`str`):
  31. Path to the vocabulary file.
  32. merges_file (`str`):
  33. Path to the merges file.
  34. """
  35. vocab_files_names = VOCAB_FILES_NAMES
  36. slow_tokenizer_class = HerbertTokenizer
  37. def __init__(
  38. self,
  39. vocab_file=None,
  40. merges_file=None,
  41. tokenizer_file=None,
  42. cls_token="<s>",
  43. unk_token="<unk>",
  44. pad_token="<pad>",
  45. mask_token="<mask>",
  46. sep_token="</s>",
  47. **kwargs,
  48. ):
  49. super().__init__(
  50. vocab_file,
  51. merges_file,
  52. tokenizer_file=tokenizer_file,
  53. cls_token=cls_token,
  54. unk_token=unk_token,
  55. pad_token=pad_token,
  56. mask_token=mask_token,
  57. sep_token=sep_token,
  58. **kwargs,
  59. )
  60. def build_inputs_with_special_tokens(
  61. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  62. ) -> List[int]:
  63. """
  64. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  65. adding special tokens. An HerBERT, like BERT sequence has the following format:
  66. - single sequence: `<s> X </s>`
  67. - pair of sequences: `<s> A </s> B </s>`
  68. Args:
  69. token_ids_0 (`List[int]`):
  70. List of IDs to which the special tokens will be added.
  71. token_ids_1 (`List[int]`, *optional*):
  72. Optional second list of IDs for sequence pairs.
  73. Returns:
  74. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  75. """
  76. cls = [self.cls_token_id]
  77. sep = [self.sep_token_id]
  78. if token_ids_1 is None:
  79. return cls + token_ids_0 + sep
  80. return cls + token_ids_0 + sep + token_ids_1 + sep
  81. def get_special_tokens_mask(
  82. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
  83. ) -> List[int]:
  84. """
  85. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  86. special tokens using the tokenizer `prepare_for_model` method.
  87. Args:
  88. token_ids_0 (`List[int]`):
  89. List of IDs.
  90. token_ids_1 (`List[int]`, *optional*):
  91. Optional second list of IDs for sequence pairs.
  92. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  93. Whether or not the token list is already formatted with special tokens for the model.
  94. Returns:
  95. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  96. """
  97. if already_has_special_tokens:
  98. return super().get_special_tokens_mask(
  99. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  100. )
  101. if token_ids_1 is None:
  102. return [1] + ([0] * len(token_ids_0)) + [1]
  103. return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  104. def create_token_type_ids_from_sequences(
  105. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  106. ) -> List[int]:
  107. """
  108. Create a mask from the two sequences passed to be used in a sequence-pair classification task. HerBERT, like
  109. BERT sequence pair mask has the following format:
  110. ```
  111. 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
  112. | first sequence | second sequence |
  113. ```
  114. Args:
  115. token_ids_0 (`List[int]`):
  116. List of IDs.
  117. token_ids_1 (`List[int]`, *optional*):
  118. Optional second list of IDs for sequence pairs.
  119. Returns:
  120. `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
  121. """
  122. sep = [self.sep_token_id]
  123. cls = [self.cls_token_id]
  124. if token_ids_1 is None:
  125. return len(cls + token_ids_0 + sep) * [0]
  126. return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
  127. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  128. files = self._tokenizer.model.save(save_directory, name=filename_prefix)
  129. return tuple(files)