tokenization_xglm.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. # Copyright The HuggingFace Team and The HuggingFace Inc. team. All rights reserved.
  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 XGLM."""
  15. from tokenizers import Regex, Tokenizer, decoders, normalizers, pre_tokenizers, processors
  16. from tokenizers.models import Unigram
  17. from ...tokenization_utils_tokenizers import TokenizersBackend
  18. from ...utils import logging
  19. logger = logging.get_logger(__name__)
  20. VOCAB_FILES_NAMES = {"tokenizer_file": "tokenizer.json"}
  21. class XGLMTokenizer(TokenizersBackend):
  22. """
  23. Construct a XGLM tokenizer (backed by HuggingFace's tokenizers library). Based on BPE.
  24. This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
  25. refer to this superclass for more information regarding those methods.
  26. Args:
  27. tokenizer_file (`str`, *optional*):
  28. Path to a tokenizers JSON file containing the serialization of a tokenizer.
  29. bos_token (`str`, *optional*, defaults to `"<s>"`):
  30. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  31. eos_token (`str`, *optional*, defaults to `"</s>"`):
  32. The end of sequence token.
  33. sep_token (`str`, *optional*, defaults to `"</s>"`):
  34. The separator token, which is used when building a sequence from multiple sequences.
  35. cls_token (`str`, *optional*, defaults to `"<s>"`):
  36. The classifier token which is used when doing sequence classification.
  37. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  38. The unknown token.
  39. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  40. The token used for padding.
  41. vocab (`str`, `dict` or `list`, *optional*):
  42. Custom vocabulary dictionary. If not provided, a minimal vocabulary is created.
  43. merges (`list[tuple[str, str]]`, *optional*):
  44. Custom merge rules for BPE. If not provided, merges are generated from the vocabulary.
  45. add_prefix_space (`bool`, *optional*, defaults to `True`):
  46. Whether to add a prefix space before encoding.
  47. """
  48. vocab_files_names = VOCAB_FILES_NAMES
  49. model_input_names = ["input_ids", "attention_mask"]
  50. model = Unigram
  51. def __init__(
  52. self,
  53. vocab: str | list[tuple[str, float]] | None = None,
  54. bos_token: str = "<s>",
  55. eos_token: str = "</s>",
  56. sep_token: str = "</s>",
  57. cls_token: str = "<s>",
  58. unk_token: str = "<unk>",
  59. pad_token: str = "<pad>",
  60. add_prefix_space: bool = True,
  61. **kwargs,
  62. ):
  63. self.num_madeup_words = 7
  64. madeup_words = [f"<madeupword{i}>" for i in range(self.num_madeup_words)]
  65. kwargs["additional_special_tokens"] = kwargs.get("additional_special_tokens", []) or []
  66. kwargs["additional_special_tokens"] += [
  67. word for word in madeup_words if word not in kwargs["additional_special_tokens"]
  68. ]
  69. self.add_prefix_space = add_prefix_space
  70. if vocab is not None:
  71. self._vocab = vocab
  72. else:
  73. self._vocab = [
  74. (str(bos_token), 0.0),
  75. (str(pad_token), 0.0),
  76. (str(eos_token), 0.0),
  77. (str(unk_token), 0.0),
  78. ]
  79. self._tokenizer = Tokenizer(Unigram(vocab=self._vocab, unk_id=3, byte_fallback=False))
  80. self._tokenizer.normalizer = normalizers.Sequence(
  81. [
  82. normalizers.Replace(Regex(r"[\n\r\t]"), " "),
  83. normalizers.NFKC(),
  84. normalizers.Replace(Regex(r" {2,}"), " "),
  85. ]
  86. )
  87. prepend_scheme = "always" if add_prefix_space else "never"
  88. self._tokenizer.pre_tokenizer = pre_tokenizers.Metaspace(replacement="▁", prepend_scheme=prepend_scheme)
  89. self._tokenizer.decoder = decoders.Metaspace(replacement="▁", prepend_scheme=prepend_scheme)
  90. super().__init__(
  91. bos_token=bos_token,
  92. eos_token=eos_token,
  93. sep_token=sep_token,
  94. cls_token=cls_token,
  95. unk_token=unk_token,
  96. pad_token=pad_token,
  97. add_prefix_space=add_prefix_space,
  98. **kwargs,
  99. )
  100. self._tokenizer.post_processor = processors.TemplateProcessing(
  101. single=f"{self.eos_token} $A {self.eos_token}",
  102. pair=f"{self.eos_token} $A {self.eos_token} {self.eos_token} $B {self.eos_token}",
  103. special_tokens=[
  104. (self.bos_token, self.bos_token_id),
  105. (self.eos_token, self.eos_token_id),
  106. ],
  107. )
  108. __all__ = ["XGLMTokenizer"]