tokenization_clvp.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. # Copyright 2023 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 class for CLVP."""
  15. import json
  16. from functools import lru_cache
  17. import regex as re
  18. from ...tokenization_python import AddedToken, PreTrainedTokenizer
  19. from ...utils import logging
  20. from .number_normalizer import EnglishNormalizer
  21. logger = logging.get_logger(__name__)
  22. VOCAB_FILES_NAMES = {
  23. "vocab_file": "vocab.json",
  24. "merges_file": "merges.txt",
  25. }
  26. @lru_cache
  27. def bytes_to_unicode():
  28. """
  29. Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
  30. characters the bpe code barfs on.
  31. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
  32. if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
  33. decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
  34. tables between utf-8 bytes and unicode strings.
  35. """
  36. bs = (
  37. list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
  38. )
  39. cs = bs[:]
  40. n = 0
  41. for b in range(2**8):
  42. if b not in bs:
  43. bs.append(b)
  44. cs.append(2**8 + n)
  45. n += 1
  46. cs = [chr(n) for n in cs]
  47. return dict(zip(bs, cs))
  48. def get_pairs(word):
  49. """
  50. Return set of symbol pairs in a word.
  51. Word is represented as tuple of symbols (symbols being variable-length strings).
  52. """
  53. pairs = set()
  54. prev_char = word[0]
  55. for char in word[1:]:
  56. pairs.add((prev_char, char))
  57. prev_char = char
  58. return pairs
  59. class ClvpTokenizer(PreTrainedTokenizer):
  60. """
  61. Construct a CLVP tokenizer. Based on byte-level Byte-Pair-Encoding.
  62. This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
  63. be encoded differently whether it is at the beginning of the sentence (without space) or not:
  64. ```python
  65. >>> from transformers import ClvpTokenizer
  66. >>> tokenizer = ClvpTokenizer.from_pretrained("susnato/clvp_dev")
  67. >>> tokenizer("Hello world")["input_ids"]
  68. [62, 84, 28, 2, 179, 79]
  69. >>> tokenizer(" Hello world")["input_ids"]
  70. [2, 62, 84, 28, 2, 179, 79]
  71. ```
  72. You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
  73. call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
  74. <Tip>
  75. When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
  76. </Tip>
  77. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  78. this superclass for more information regarding those methods.
  79. Args:
  80. vocab_file (`str`):
  81. Path to the vocabulary file.
  82. merges_file (`str`):
  83. Path to the merges file.
  84. errors (`str`, *optional*, defaults to `"replace"`):
  85. Paradigm to follow when decoding bytes to UTF-8. See
  86. [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
  87. unk_token (`str`, *optional*, defaults to `"[UNK]"`):
  88. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  89. token instead.
  90. bos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  91. The beginning of sequence token.
  92. eos_token (`str`, *optional*, defaults to `"[STOP]"`):
  93. The end of sequence token.
  94. pad_token (`str`, *optional*, defaults to `"[STOP]"`):
  95. The pad token of the sequence.
  96. add_prefix_space (`bool`, *optional*, defaults to `False`):
  97. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  98. other word. (CLVP tokenizer detect beginning of words by the preceding space).
  99. """
  100. vocab_files_names = VOCAB_FILES_NAMES
  101. model_input_names = [
  102. "input_ids",
  103. "attention_mask",
  104. ]
  105. def __init__(
  106. self,
  107. vocab_file,
  108. merges_file,
  109. errors="replace",
  110. unk_token="[UNK]",
  111. bos_token="<|endoftext|>",
  112. eos_token="[STOP]",
  113. pad_token="[STOP]",
  114. add_prefix_space=False,
  115. **kwargs,
  116. ):
  117. bos_token = AddedToken(bos_token, special=True) if isinstance(bos_token, str) else bos_token
  118. eos_token = AddedToken(eos_token, special=True) if isinstance(eos_token, str) else eos_token
  119. unk_token = AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token
  120. pad_token = AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token
  121. self._normalizer = None
  122. with open(vocab_file, encoding="utf-8") as vocab_handle:
  123. self.encoder = json.load(vocab_handle)
  124. self.decoder = {v: k for k, v in self.encoder.items()}
  125. self.errors = errors # how to handle errors in decoding
  126. self.byte_encoder = bytes_to_unicode()
  127. self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
  128. with open(merges_file, encoding="utf-8") as merges_handle:
  129. bpe_merges = merges_handle.read().split("\n")[1:-1]
  130. bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
  131. self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
  132. self.cache = {}
  133. self.add_prefix_space = add_prefix_space
  134. # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
  135. self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
  136. super().__init__(
  137. errors=errors,
  138. unk_token=unk_token,
  139. bos_token=bos_token,
  140. eos_token=eos_token,
  141. pad_token=pad_token,
  142. add_prefix_space=add_prefix_space,
  143. special_tokens_pattern="none",
  144. **kwargs,
  145. )
  146. @property
  147. def vocab_size(self):
  148. return len(self.encoder)
  149. @property
  150. def normalizer(self):
  151. if self._normalizer is None:
  152. self._normalizer = EnglishNormalizer()
  153. return self._normalizer
  154. def get_vocab(self):
  155. return dict(self.encoder, **self.added_tokens_encoder)
  156. def bpe(self, token):
  157. if token in self.cache:
  158. return self.cache[token]
  159. word = tuple(token)
  160. pairs = get_pairs(word)
  161. if not pairs:
  162. return token
  163. while True:
  164. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  165. if bigram not in self.bpe_ranks:
  166. break
  167. first, second = bigram
  168. new_word = []
  169. i = 0
  170. while i < len(word):
  171. try:
  172. j = word.index(first, i)
  173. except ValueError:
  174. new_word.extend(word[i:])
  175. break
  176. else:
  177. new_word.extend(word[i:j])
  178. i = j
  179. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  180. new_word.append(first + second)
  181. i += 2
  182. else:
  183. new_word.append(word[i])
  184. i += 1
  185. new_word = tuple(new_word)
  186. word = new_word
  187. if len(word) == 1:
  188. break
  189. else:
  190. pairs = get_pairs(word)
  191. word = " ".join(word)
  192. self.cache[token] = word
  193. return word
  194. def _tokenize(self, text):
  195. """Tokenize a string."""
  196. bpe_tokens = []
  197. text = self.normalizer(text)
  198. for token in re.findall(self.pat, text):
  199. token = "".join(
  200. self.byte_encoder[b] for b in token.encode("utf-8")
  201. ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
  202. # if the token is "Ġ" we replace it with "[SPACE]" (if "[SPACE]" is present in the vocab), otherwise we keep the "Ġ".
  203. bpe_tokens.extend(
  204. "[SPACE]" if bpe_token == "\u0120" and "[SPACE]" in self.encoder else bpe_token
  205. for bpe_token in self.bpe(token).split(" ")
  206. )
  207. return bpe_tokens
  208. def _convert_token_to_id(self, token):
  209. """Converts a token (str) in an id using the vocab."""
  210. return self.encoder.get(token, self.encoder.get(self.unk_token))
  211. def _convert_id_to_token(self, index):
  212. """Converts an index (integer) in a token (str) using the vocab."""
  213. return self.decoder.get(index)
  214. def convert_tokens_to_string(self, tokens):
  215. """Converts a sequence of tokens (string) in a single string."""
  216. text = "".join(tokens)
  217. text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
  218. return text
  219. def clean_up_tokenization(self, text):
  220. text = "".join(text) if isinstance(text, list) else text
  221. vocab_tokens = list(self.encoder.keys()) + list(self.added_tokens_encoder.keys())
  222. text = text.replace("[SPACE]", " ") if "[SPACE]" in vocab_tokens else text
  223. text = text.replace("[STOP]", " ") if "[STOP]" in vocab_tokens else text
  224. text = text.replace(self.unk_token, "").replace(" ", " ").replace(" ", " ")
  225. return text
  226. __all__ = ["ClvpTokenizer"]