tokenization_roberta.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. # Copyright 2018 The Open AI Team 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 RoBERTa."""
  15. from tokenizers import Tokenizer, decoders, pre_tokenizers, processors
  16. from tokenizers.models import BPE
  17. from ...tokenization_utils_tokenizers import TokenizersBackend
  18. from ...utils import logging
  19. logger = logging.get_logger(__name__)
  20. VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
  21. class RobertaTokenizer(TokenizersBackend):
  22. r"""
  23. Construct a RoBERTa tokenizer (backed by HuggingFace's tokenizers library). Based on Byte-Pair-Encoding.
  24. This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
  25. be encoded differently whether it is at the beginning of the sentence (without space) or not:
  26. ```python
  27. >>> from transformers import RobertaTokenizer
  28. >>> tokenizer = RobertaTokenizer.from_pretrained("FacebookAI/roberta-base")
  29. >>> tokenizer("Hello world")["input_ids"]
  30. [0, 31414, 232, 2]
  31. >>> tokenizer(" Hello world")["input_ids"]
  32. [0, 20920, 232, 2]
  33. ```
  34. You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
  35. call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
  36. <Tip>
  37. When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
  38. </Tip>
  39. This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should refer to
  40. this superclass for more information regarding those methods.
  41. Args:
  42. vocab (`str`, `dict` or `list`, *optional*):
  43. Custom vocabulary dictionary. If not provided, vocabulary is loaded from vocab_file.
  44. merges (`str` or `list`, *optional*):
  45. Custom merges list. If not provided, merges are loaded from merges_file.
  46. errors (`str`, *optional*, defaults to `"replace"`):
  47. Paradigm to follow when decoding bytes to UTF-8. See
  48. [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
  49. bos_token (`str`, *optional*, defaults to `"<s>"`):
  50. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  51. <Tip>
  52. When building a sequence using special tokens, this is not the token that is used for the beginning of
  53. sequence. The token used is the `cls_token`.
  54. </Tip>
  55. eos_token (`str`, *optional*, defaults to `"</s>"`):
  56. The end of sequence token.
  57. <Tip>
  58. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  59. The token used is the `sep_token`.
  60. </Tip>
  61. sep_token (`str`, *optional*, defaults to `"</s>"`):
  62. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  63. sequence classification or for a text and a question for question answering. It is also used as the last
  64. token of a sequence built with special tokens.
  65. cls_token (`str`, *optional*, defaults to `"<s>"`):
  66. The classifier token which is used when doing sequence classification (classification of the whole sequence
  67. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  68. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  69. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  70. token instead.
  71. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  72. The token used for padding, for example when batching sequences of different lengths.
  73. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  74. The token used for masking values. This is the token used when training this model with masked language
  75. modeling. This is the token which the model will try to predict.
  76. add_prefix_space (`bool`, *optional*, defaults to `False`):
  77. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  78. other word. (RoBERTa tokenizer detect beginning of words by the preceding space).
  79. trim_offsets (`bool`, *optional*, defaults to `True`):
  80. Whether the post processing step should trim offsets to avoid including whitespaces.
  81. """
  82. vocab_files_names = VOCAB_FILES_NAMES
  83. model_input_names = ["input_ids", "attention_mask"]
  84. model = BPE
  85. def __init__(
  86. self,
  87. vocab: str | dict[str, int] | None = None,
  88. merges: str | list[str] | None = None,
  89. errors: str = "replace",
  90. bos_token: str = "<s>",
  91. eos_token: str = "</s>",
  92. sep_token: str = "</s>",
  93. cls_token: str = "<s>",
  94. unk_token: str = "<unk>",
  95. pad_token: str = "<pad>",
  96. mask_token: str = "<mask>",
  97. add_prefix_space: bool = False,
  98. trim_offsets: bool = True,
  99. **kwargs,
  100. ):
  101. self.add_prefix_space = add_prefix_space
  102. self.trim_offsets = trim_offsets
  103. if vocab is None:
  104. vocab = {
  105. str(pad_token): 0,
  106. str(unk_token): 1,
  107. str(cls_token): 2,
  108. str(sep_token): 3,
  109. str(mask_token): 4,
  110. }
  111. self._vocab = vocab
  112. self._merges = merges or []
  113. self._tokenizer = Tokenizer(
  114. BPE(
  115. vocab=self._vocab,
  116. merges=self._merges,
  117. dropout=None,
  118. continuing_subword_prefix="",
  119. end_of_word_suffix="",
  120. fuse_unk=False,
  121. )
  122. )
  123. self._tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=add_prefix_space)
  124. self._tokenizer.decoder = decoders.ByteLevel()
  125. super().__init__(
  126. errors=errors,
  127. bos_token=bos_token,
  128. eos_token=eos_token,
  129. sep_token=sep_token,
  130. cls_token=cls_token,
  131. unk_token=unk_token,
  132. pad_token=pad_token,
  133. mask_token=mask_token,
  134. add_prefix_space=add_prefix_space,
  135. trim_offsets=trim_offsets,
  136. **kwargs,
  137. )
  138. self._tokenizer.post_processor = processors.RobertaProcessing(
  139. sep=(str(sep_token), self.sep_token_id),
  140. cls=(str(cls_token), self.cls_token_id),
  141. add_prefix_space=add_prefix_space,
  142. trim_offsets=trim_offsets,
  143. )
  144. __all__ = ["RobertaTokenizer"]