tokenization_barthez_fast.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. # coding=utf-8
  2. # Copyright 2020 Ecole Polytechnique 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. """Tokenization classes for the BARThez model."""
  16. import os
  17. from shutil import copyfile
  18. from typing import List, Optional, Tuple
  19. from ...tokenization_utils import AddedToken
  20. from ...tokenization_utils_fast import PreTrainedTokenizerFast
  21. from ...utils import is_sentencepiece_available, logging
  22. if is_sentencepiece_available():
  23. from .tokenization_barthez import BarthezTokenizer
  24. else:
  25. BarthezTokenizer = None
  26. logger = logging.get_logger(__name__)
  27. VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"}
  28. SPIECE_UNDERLINE = "▁"
  29. class BarthezTokenizerFast(PreTrainedTokenizerFast):
  30. """
  31. Adapted from [`CamembertTokenizer`] and [`BartTokenizer`]. Construct a "fast" BARThez tokenizer. Based on
  32. [SentencePiece](https://github.com/google/sentencepiece).
  33. This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
  34. refer to this superclass for more information regarding those methods.
  35. Args:
  36. vocab_file (`str`):
  37. [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
  38. contains the vocabulary necessary to instantiate a tokenizer.
  39. bos_token (`str`, *optional*, defaults to `"<s>"`):
  40. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  41. <Tip>
  42. When building a sequence using special tokens, this is not the token that is used for the beginning of
  43. sequence. The token used is the `cls_token`.
  44. </Tip>
  45. eos_token (`str`, *optional*, defaults to `"</s>"`):
  46. The end of sequence token.
  47. <Tip>
  48. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  49. The token used is the `sep_token`.
  50. </Tip>
  51. sep_token (`str`, *optional*, defaults to `"</s>"`):
  52. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  53. sequence classification or for a text and a question for question answering. It is also used as the last
  54. token of a sequence built with special tokens.
  55. cls_token (`str`, *optional*, defaults to `"<s>"`):
  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. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  59. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  60. token instead.
  61. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  62. The token used for padding, for example when batching sequences of different lengths.
  63. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  64. The token used for masking values. This is the token used when training this model with masked language
  65. modeling. This is the token which the model will try to predict.
  66. additional_special_tokens (`List[str]`, *optional*, defaults to `["<s>NOTUSED", "</s>NOTUSED"]`):
  67. Additional special tokens used by the tokenizer.
  68. """
  69. vocab_files_names = VOCAB_FILES_NAMES
  70. model_input_names = ["input_ids", "attention_mask"]
  71. slow_tokenizer_class = BarthezTokenizer
  72. def __init__(
  73. self,
  74. vocab_file=None,
  75. tokenizer_file=None,
  76. bos_token="<s>",
  77. eos_token="</s>",
  78. sep_token="</s>",
  79. cls_token="<s>",
  80. unk_token="<unk>",
  81. pad_token="<pad>",
  82. mask_token="<mask>",
  83. **kwargs,
  84. ):
  85. # Mask token behave like a normal word, i.e. include the space before it
  86. mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
  87. super().__init__(
  88. vocab_file,
  89. tokenizer_file=tokenizer_file,
  90. bos_token=bos_token,
  91. eos_token=eos_token,
  92. unk_token=unk_token,
  93. sep_token=sep_token,
  94. cls_token=cls_token,
  95. pad_token=pad_token,
  96. mask_token=mask_token,
  97. **kwargs,
  98. )
  99. self.vocab_file = vocab_file
  100. @property
  101. def can_save_slow_tokenizer(self) -> bool:
  102. return os.path.isfile(self.vocab_file) if self.vocab_file else False
  103. def build_inputs_with_special_tokens(
  104. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  105. ) -> List[int]:
  106. """
  107. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  108. adding special tokens. A BARThez sequence has the following format:
  109. - single sequence: `<s> X </s>`
  110. - pair of sequences: `<s> A </s></s> B </s>`
  111. Args:
  112. token_ids_0 (`List[int]`):
  113. List of IDs to which the special tokens will be added.
  114. token_ids_1 (`List[int]`, *optional*):
  115. Optional second list of IDs for sequence pairs.
  116. Returns:
  117. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  118. """
  119. if token_ids_1 is None:
  120. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  121. cls = [self.cls_token_id]
  122. sep = [self.sep_token_id]
  123. return cls + token_ids_0 + sep + sep + token_ids_1 + sep
  124. def create_token_type_ids_from_sequences(
  125. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  126. ) -> List[int]:
  127. """
  128. Create a mask from the two sequences passed to be used in a sequence-pair classification task.
  129. Args:
  130. token_ids_0 (`List[int]`):
  131. List of IDs.
  132. token_ids_1 (`List[int]`, *optional*):
  133. Optional second list of IDs for sequence pairs.
  134. Returns:
  135. `List[int]`: List of zeros.
  136. """
  137. sep = [self.sep_token_id]
  138. cls = [self.cls_token_id]
  139. if token_ids_1 is None:
  140. return len(cls + token_ids_0 + sep) * [0]
  141. return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
  142. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  143. if not self.can_save_slow_tokenizer:
  144. raise ValueError(
  145. "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
  146. "tokenizer."
  147. )
  148. if not os.path.isdir(save_directory):
  149. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  150. return
  151. out_vocab_file = os.path.join(
  152. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  153. )
  154. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
  155. copyfile(self.vocab_file, out_vocab_file)
  156. return (out_vocab_file,)