tokenization_camembert.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University 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 Camembert model."""
  15. from tokenizers import Regex, Tokenizer, decoders, normalizers, pre_tokenizers, processors
  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 CamembertTokenizer(TokenizersBackend):
  24. """
  25. Construct a "fast" CamemBERT tokenizer (backed by HuggingFace's *tokenizers* library). Adapted from
  26. [`RobertaTokenizer`] and [`XLNetTokenizer`]. Based on
  27. [Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models).
  28. This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
  29. refer to this superclass for more information regarding those methods.
  30. Args:
  31. bos_token (`str`, *optional*, defaults to `"<s>"`):
  32. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  33. <Tip>
  34. When building a sequence using special tokens, this is not the token that is used for the beginning of
  35. sequence. The token used is the `cls_token`.
  36. </Tip>
  37. eos_token (`str`, *optional*, defaults to `"</s>"`):
  38. The end of sequence token.
  39. <Tip>
  40. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  41. The token used is the `sep_token`.
  42. </Tip>
  43. sep_token (`str`, *optional*, defaults to `"</s>"`):
  44. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  45. sequence classification or for a text and a question for question answering. It is also used as the last
  46. token of a sequence built with special tokens.
  47. cls_token (`str`, *optional*, defaults to `"<s>"`):
  48. The classifier token which is used when doing sequence classification (classification of the whole sequence
  49. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  50. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  51. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  52. token instead.
  53. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  54. The token used for padding, for example when batching sequences of different lengths.
  55. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  56. The token used for masking values. This is the token used when training this model with masked language
  57. modeling. This is the token which the model will try to predict.
  58. additional_special_tokens (`list[str]`, *optional*, defaults to `["<s>NOTUSED", "</s>NOTUSED"]`):
  59. Additional special tokens used by the tokenizer.
  60. add_prefix_space (`bool`, *optional*, defaults to `True`):
  61. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  62. other word.
  63. vocab_file (`str`, *optional*):
  64. [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
  65. contains the vocabulary necessary to instantiate a tokenizer.
  66. vocab (`str`, `dict` or `list`, *optional*):
  67. Custom vocabulary dictionary. If not provided, vocabulary is loaded from vocab_file.
  68. """
  69. vocab_files_names = VOCAB_FILES_NAMES
  70. model_input_names = ["input_ids", "attention_mask"]
  71. slow_tokenizer_class = None
  72. def __init__(
  73. self,
  74. bos_token="<s>",
  75. eos_token="</s>",
  76. sep_token="</s>",
  77. cls_token="<s>",
  78. unk_token="<unk>",
  79. pad_token="<pad>",
  80. mask_token="<mask>",
  81. additional_special_tokens=None,
  82. add_prefix_space=True,
  83. vocab_file=None,
  84. vocab: str | dict | list | None = None,
  85. **kwargs,
  86. ):
  87. self.vocab_file = vocab_file
  88. self.add_prefix_space = add_prefix_space
  89. mask_token = AddedToken(mask_token, lstrip=True, special=True) if isinstance(mask_token, str) else mask_token
  90. if additional_special_tokens is None:
  91. additional_special_tokens = ["<s>NOTUSED", "</s>NOTUSED", "<unk>NOTUSED"]
  92. if vocab is not None:
  93. self._vocab = vocab
  94. unk_index = next((i for i, (tok, _) in enumerate(self._vocab) if tok == str(unk_token)), 0)
  95. self._tokenizer = Tokenizer(Unigram(self._vocab, unk_id=unk_index, byte_fallback=False))
  96. else:
  97. self._vocab = [
  98. ("<s>NOTUSED", 0.0),
  99. (str(pad_token), 0.0),
  100. ("</s>NOTUSED", 0.0),
  101. (str(unk_token), 0.0),
  102. ("<unk>NOTUSED", -100),
  103. (str(mask_token), 0.0),
  104. ]
  105. self._tokenizer = Tokenizer(Unigram(self._vocab, unk_id=3, byte_fallback=False))
  106. self._tokenizer.normalizer = normalizers.Sequence(
  107. [
  108. normalizers.Replace(Regex(r"\s{2,}|[\n\r\t]"), " "),
  109. normalizers.Strip(left=False, right=True),
  110. ]
  111. )
  112. prepend_scheme = "always" if add_prefix_space else "never"
  113. self._tokenizer.pre_tokenizer = pre_tokenizers.Metaspace(replacement="▁", prepend_scheme=prepend_scheme)
  114. self._tokenizer.decoder = decoders.Metaspace(replacement="▁", prepend_scheme=prepend_scheme)
  115. super().__init__(
  116. bos_token=bos_token,
  117. eos_token=eos_token,
  118. sep_token=sep_token,
  119. cls_token=cls_token,
  120. unk_token=unk_token,
  121. pad_token=pad_token,
  122. mask_token=mask_token,
  123. additional_special_tokens=additional_special_tokens,
  124. add_prefix_space=add_prefix_space,
  125. **kwargs,
  126. )
  127. # always adds BOS/EOS with "</s> </s>" separator for pairs
  128. self._tokenizer.post_processor = processors.TemplateProcessing(
  129. single=f"{self.bos_token} $A {self.eos_token}",
  130. pair=f"{self.bos_token} $A {self.eos_token} {self.eos_token} $B {self.eos_token}",
  131. special_tokens=[
  132. (self.bos_token, self.bos_token_id),
  133. (self.eos_token, self.eos_token_id),
  134. ],
  135. )
  136. __all__ = ["CamembertTokenizer"]