tokenization_barthez.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. # Copyright 2020 Ecole Polytechnique 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 the BARThez model."""
  15. from tokenizers import Regex, Tokenizer, decoders, normalizers, pre_tokenizers
  16. from tokenizers.models import Unigram
  17. from ...tokenization_python import AddedToken
  18. from ...tokenization_utils_tokenizers import TokenizersBackend
  19. from ...utils import logging
  20. logger = logging.get_logger(__name__)
  21. VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"}
  22. SPIECE_UNDERLINE = "▁"
  23. class BarthezTokenizer(TokenizersBackend):
  24. """
  25. Adapted from [`CamembertTokenizer`] and [`BartTokenizer`]. Construct a "fast" BARThez tokenizer. Based on
  26. [SentencePiece](https://github.com/google/sentencepiece).
  27. This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
  28. refer to this superclass for more information regarding those methods.
  29. Args:
  30. bos_token (`str`, *optional*, defaults to `"<s>"`):
  31. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  32. <Tip>
  33. When building a sequence using special tokens, this is not the token that is used for the beginning of
  34. sequence. The token used is the `cls_token`.
  35. </Tip>
  36. eos_token (`str`, *optional*, defaults to `"</s>"`):
  37. The end of sequence token.
  38. <Tip>
  39. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  40. The token used is the `sep_token`.
  41. </Tip>
  42. sep_token (`str`, *optional*, defaults to `"</s>"`):
  43. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  44. sequence classification or for a text and a question for question answering. It is also used as the last
  45. token of a sequence built with special tokens.
  46. cls_token (`str`, *optional*, defaults to `"<s>"`):
  47. The classifier token which is used when doing sequence classification (classification of the whole sequence
  48. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  49. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  50. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  51. token instead.
  52. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  53. The token used for padding, for example when batching sequences of different lengths.
  54. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  55. The token used for masking values. This is the token used when training this model with masked language
  56. modeling. This is the token which the model will try to predict.
  57. vocab_file (`str`, *optional*):
  58. [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
  59. contains the vocabulary necessary to instantiate a tokenizer.
  60. vocab (`str`, `dict` or `list`, *optional*):
  61. Custom vocabulary dictionary. If not provided, vocabulary is loaded from vocab_file.
  62. add_prefix_space (`bool`, *optional*, defaults to `True`):
  63. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  64. other word.
  65. """
  66. vocab_files_names = VOCAB_FILES_NAMES
  67. model_input_names = ["input_ids", "attention_mask"]
  68. slow_tokenizer_class = None
  69. def __init__(
  70. self,
  71. vocab: str | dict | list | None = None,
  72. bos_token="<s>",
  73. eos_token="</s>",
  74. sep_token="</s>",
  75. cls_token="<s>",
  76. unk_token="<unk>",
  77. pad_token="<pad>",
  78. mask_token="<mask>",
  79. add_prefix_space=True,
  80. **kwargs,
  81. ):
  82. # Mask token behave like a normal word, i.e. include the space before it
  83. mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
  84. self.add_prefix_space = add_prefix_space
  85. if vocab is not None:
  86. self._vocab = vocab
  87. else:
  88. self._vocab = [
  89. (str(pad_token), 0.0),
  90. (str(unk_token), 0.0),
  91. (str(cls_token), 0.0),
  92. (str(sep_token), 0.0),
  93. (str(mask_token), 0.0),
  94. ]
  95. self._tokenizer = Tokenizer(Unigram(self._vocab, unk_id=3, byte_fallback=False))
  96. self._tokenizer.normalizer = normalizers.Sequence(
  97. [
  98. normalizers.Replace(Regex(r"\s{2,}|[\n\r\t]"), " "),
  99. normalizers.NFC(),
  100. normalizers.Strip(left=False, right=True),
  101. ]
  102. )
  103. prepend_scheme = "always" if add_prefix_space else "never"
  104. self._tokenizer.pre_tokenizer = pre_tokenizers.Metaspace(replacement="▁", prepend_scheme=prepend_scheme)
  105. self._tokenizer.decoder = decoders.Metaspace(replacement="▁", prepend_scheme=prepend_scheme)
  106. super().__init__(
  107. bos_token=bos_token,
  108. eos_token=eos_token,
  109. unk_token=unk_token,
  110. sep_token=sep_token,
  111. cls_token=cls_token,
  112. pad_token=pad_token,
  113. mask_token=mask_token,
  114. add_prefix_space=add_prefix_space,
  115. **kwargs,
  116. )
  117. __all__ = ["BarthezTokenizer"]