tokenization_clip.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. # Copyright 2021 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 CLIP."""
  15. from tokenizers import Regex, Tokenizer, decoders, normalizers, 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 CLIPTokenizer(TokenizersBackend):
  22. """
  23. Construct a CLIP tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
  24. Byte-Pair-Encoding.
  25. This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
  26. refer to this superclass for more information regarding those methods.
  27. Args:
  28. vocab (`str`, `dict` or `list`, *optional*):
  29. Vocabulary dict to use for the tokenizer.
  30. merges (`str` or `list`, *optional*):
  31. Merges list to use for the BPE tokenizer.
  32. unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  33. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  34. token instead.
  35. bos_token (`str`, *optional*, defaults to `"<|startoftext|>"`):
  36. The beginning of sequence token.
  37. eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  38. The end of sequence token.
  39. pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  40. The token used for padding, for example when batching sequences of different lengths.
  41. """
  42. vocab_files_names = VOCAB_FILES_NAMES
  43. model_input_names = ["input_ids", "attention_mask"]
  44. model = BPE
  45. def __init__(
  46. self,
  47. vocab: str | dict[str, int] | None = None,
  48. merges: str | list[str] | None = None,
  49. unk_token: str = "<|endoftext|>",
  50. bos_token: str = "<|startoftext|>",
  51. eos_token: str = "<|endoftext|>",
  52. pad_token: str = "<|endoftext|>",
  53. **kwargs,
  54. ):
  55. _vocab = (
  56. vocab
  57. if vocab is not None
  58. else {
  59. str(bos_token): 0,
  60. str(eos_token): 1,
  61. str(pad_token): 2,
  62. }
  63. )
  64. self._merges = merges or []
  65. self._tokenizer = Tokenizer(
  66. BPE(
  67. vocab=_vocab,
  68. merges=self._merges,
  69. dropout=None,
  70. continuing_subword_prefix="",
  71. end_of_word_suffix="</w>",
  72. fuse_unk=False,
  73. unk_token=str(unk_token),
  74. )
  75. )
  76. self._tokenizer.normalizer = normalizers.Sequence(
  77. [normalizers.NFC(), normalizers.Replace(Regex(r"\s+"), " "), normalizers.Lowercase()]
  78. )
  79. self._tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
  80. [
  81. pre_tokenizers.Split(
  82. Regex(
  83. r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+"""
  84. ),
  85. behavior="removed",
  86. invert=True,
  87. ),
  88. pre_tokenizers.ByteLevel(add_prefix_space=False),
  89. ]
  90. )
  91. self._tokenizer.decoder = decoders.ByteLevel()
  92. super().__init__(
  93. unk_token=unk_token,
  94. bos_token=bos_token,
  95. eos_token=eos_token,
  96. pad_token=pad_token,
  97. **kwargs,
  98. )
  99. self._tokenizer.post_processor = processors.RobertaProcessing(
  100. sep=(str(eos_token), self.eos_token_id),
  101. cls=(str(bos_token), self.bos_token_id),
  102. add_prefix_space=False,
  103. trim_offsets=False,
  104. )
  105. # Very ugly hack to enable padding to have a correct decoding see https://github.com/huggingface/tokenizers/issues/872
  106. self._wrap_decode_method_backend_tokenizer()
  107. def _wrap_decode_method_backend_tokenizer(self):
  108. orig_decode_method = self.backend_tokenizer.decode
  109. ## define this as a local variable to avoid circular reference
  110. ## See: https://github.com/huggingface/transformers/issues/30930
  111. end_of_word_suffix = self.backend_tokenizer.model.end_of_word_suffix
  112. def new_decode_method(*args, **kwargs):
  113. text = orig_decode_method(*args, **kwargs)
  114. text = text.replace(end_of_word_suffix, " ").strip()
  115. return text
  116. self.backend_tokenizer.decode = new_decode_method
  117. __all__ = ["CLIPTokenizer"]