tokenization_clvp.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. # coding=utf-8
  2. # Copyright 2023 The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Tokenization class for CLVP."""
  16. import json
  17. import os
  18. from functools import lru_cache
  19. from typing import List, Optional, Tuple
  20. import regex as re
  21. from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  22. from ...utils import logging
  23. from .number_normalizer import EnglishNormalizer
  24. logger = logging.get_logger(__name__)
  25. VOCAB_FILES_NAMES = {
  26. "vocab_file": "vocab.json",
  27. "merges_file": "merges.txt",
  28. }
  29. @lru_cache()
  30. # Copied from transformers.models.gpt2.tokenization_gpt2.bytes_to_unicode
  31. def bytes_to_unicode():
  32. """
  33. Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
  34. characters the bpe code barfs on.
  35. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
  36. if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
  37. decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
  38. tables between utf-8 bytes and unicode strings.
  39. """
  40. bs = (
  41. list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
  42. )
  43. cs = bs[:]
  44. n = 0
  45. for b in range(2**8):
  46. if b not in bs:
  47. bs.append(b)
  48. cs.append(2**8 + n)
  49. n += 1
  50. cs = [chr(n) for n in cs]
  51. return dict(zip(bs, cs))
  52. # Copied from transformers.models.gpt2.tokenization_gpt2.get_pairs
  53. def get_pairs(word):
  54. """
  55. Return set of symbol pairs in a word.
  56. Word is represented as tuple of symbols (symbols being variable-length strings).
  57. """
  58. pairs = set()
  59. prev_char = word[0]
  60. for char in word[1:]:
  61. pairs.add((prev_char, char))
  62. prev_char = char
  63. return pairs
  64. class ClvpTokenizer(PreTrainedTokenizer):
  65. """
  66. Construct a CLVP tokenizer. Based on byte-level Byte-Pair-Encoding.
  67. This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
  68. be encoded differently whether it is at the beginning of the sentence (without space) or not:
  69. ```python
  70. >>> from transformers import ClvpTokenizer
  71. >>> tokenizer = ClvpTokenizer.from_pretrained("susnato/clvp_dev")
  72. >>> tokenizer("Hello world")["input_ids"]
  73. [62, 84, 28, 2, 179, 79]
  74. >>> tokenizer(" Hello world")["input_ids"]
  75. [2, 62, 84, 28, 2, 179, 79]
  76. ```
  77. You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
  78. call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
  79. <Tip>
  80. When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
  81. </Tip>
  82. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  83. this superclass for more information regarding those methods.
  84. Args:
  85. vocab_file (`str`):
  86. Path to the vocabulary file.
  87. merges_file (`str`):
  88. Path to the merges file.
  89. errors (`str`, *optional*, defaults to `"replace"`):
  90. Paradigm to follow when decoding bytes to UTF-8. See
  91. [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
  92. unk_token (`str`, *optional*, defaults to `"[UNK]"`):
  93. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  94. token instead.
  95. bos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  96. The beginning of sequence token.
  97. eos_token (`str`, *optional*, defaults to `"[STOP]"`):
  98. The end of sequence token.
  99. pad_token (`str`, *optional*, defaults to `"[STOP]"`):
  100. The pad token of the sequence.
  101. add_prefix_space (`bool`, *optional*, defaults to `False`):
  102. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  103. other word. (CLVP tokenizer detect beginning of words by the preceding space).
  104. add_bos_token (`bool`, *optional*, defaults to `False`):
  105. Whether to add `bos_token` in front of the sequence when add_special_tokens=True.
  106. add_eos_token (`bool`, *optional*, defaults to `False`):
  107. Whether to add `eos_token` in end of the sequence when add_special_tokens=True.
  108. """
  109. vocab_files_names = VOCAB_FILES_NAMES
  110. model_input_names = [
  111. "input_ids",
  112. "attention_mask",
  113. ]
  114. def __init__(
  115. self,
  116. vocab_file,
  117. merges_file,
  118. errors="replace",
  119. unk_token="[UNK]",
  120. bos_token="<|endoftext|>",
  121. eos_token="[STOP]",
  122. pad_token="[STOP]",
  123. add_prefix_space=False,
  124. add_bos_token=False,
  125. add_eos_token=False,
  126. **kwargs,
  127. ):
  128. bos_token = AddedToken(bos_token, special=True) if isinstance(bos_token, str) else bos_token
  129. eos_token = AddedToken(eos_token, special=True) if isinstance(eos_token, str) else eos_token
  130. unk_token = AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token
  131. pad_token = AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token
  132. self.add_bos_token = add_bos_token
  133. self.add_eos_token = add_eos_token
  134. self._normalizer = None
  135. with open(vocab_file, encoding="utf-8") as vocab_handle:
  136. self.encoder = json.load(vocab_handle)
  137. self.decoder = {v: k for k, v in self.encoder.items()}
  138. self.errors = errors # how to handle errors in decoding
  139. self.byte_encoder = bytes_to_unicode()
  140. self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
  141. with open(merges_file, encoding="utf-8") as merges_handle:
  142. bpe_merges = merges_handle.read().split("\n")[1:-1]
  143. bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
  144. self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
  145. self.cache = {}
  146. self.add_prefix_space = add_prefix_space
  147. # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
  148. self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
  149. super().__init__(
  150. errors=errors,
  151. unk_token=unk_token,
  152. bos_token=bos_token,
  153. eos_token=eos_token,
  154. pad_token=pad_token,
  155. add_prefix_space=add_prefix_space,
  156. add_bos_token=add_bos_token,
  157. add_eos_token=add_eos_token,
  158. **kwargs,
  159. )
  160. @property
  161. def vocab_size(self):
  162. return len(self.encoder)
  163. @property
  164. def normalizer(self):
  165. if self._normalizer is None:
  166. self._normalizer = EnglishNormalizer()
  167. return self._normalizer
  168. def get_vocab(self):
  169. return dict(self.encoder, **self.added_tokens_encoder)
  170. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.bpe
  171. def bpe(self, token):
  172. if token in self.cache:
  173. return self.cache[token]
  174. word = tuple(token)
  175. pairs = get_pairs(word)
  176. if not pairs:
  177. return token
  178. while True:
  179. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  180. if bigram not in self.bpe_ranks:
  181. break
  182. first, second = bigram
  183. new_word = []
  184. i = 0
  185. while i < len(word):
  186. try:
  187. j = word.index(first, i)
  188. except ValueError:
  189. new_word.extend(word[i:])
  190. break
  191. else:
  192. new_word.extend(word[i:j])
  193. i = j
  194. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  195. new_word.append(first + second)
  196. i += 2
  197. else:
  198. new_word.append(word[i])
  199. i += 1
  200. new_word = tuple(new_word)
  201. word = new_word
  202. if len(word) == 1:
  203. break
  204. else:
  205. pairs = get_pairs(word)
  206. word = " ".join(word)
  207. self.cache[token] = word
  208. return word
  209. # Copied from transformers.models.llama.tokenization_llama.LlamaTokenizer.build_inputs_with_special_tokens
  210. def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
  211. bos_token_id = [self.bos_token_id] if self.add_bos_token else []
  212. eos_token_id = [self.eos_token_id] if self.add_eos_token else []
  213. output = bos_token_id + token_ids_0 + eos_token_id
  214. if token_ids_1 is not None:
  215. output = output + bos_token_id + token_ids_1 + eos_token_id
  216. return output
  217. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.get_special_tokens_mask
  218. def get_special_tokens_mask(
  219. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
  220. ) -> List[int]:
  221. """
  222. Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
  223. special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
  224. Args:
  225. token_ids_0 (`List[int]`):
  226. List of IDs.
  227. token_ids_1 (`List[int]`, *optional*):
  228. Optional second list of IDs for sequence pairs.
  229. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  230. Whether or not the token list is already formatted with special tokens for the model.
  231. Returns:
  232. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  233. """
  234. if already_has_special_tokens:
  235. return super().get_special_tokens_mask(
  236. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  237. )
  238. if not self.add_bos_token:
  239. return super().get_special_tokens_mask(
  240. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=False
  241. )
  242. if token_ids_1 is None:
  243. return [1] + ([0] * len(token_ids_0))
  244. return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
  245. def _tokenize(self, text):
  246. """Tokenize a string."""
  247. bpe_tokens = []
  248. text = self.normalizer(text)
  249. for token in re.findall(self.pat, text):
  250. token = "".join(
  251. self.byte_encoder[b] for b in token.encode("utf-8")
  252. ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
  253. # if the token is "Ġ" we replace it with "[SPACE]" (if "[SPACE]" is present in the vocab), otherwise we keep the "Ġ".
  254. bpe_tokens.extend(
  255. "[SPACE]" if bpe_token == "\u0120" and "[SPACE]" in self.encoder.keys() else bpe_token
  256. for bpe_token in self.bpe(token).split(" ")
  257. )
  258. return bpe_tokens
  259. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_token_to_id
  260. def _convert_token_to_id(self, token):
  261. """Converts a token (str) in an id using the vocab."""
  262. return self.encoder.get(token, self.encoder.get(self.unk_token))
  263. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_id_to_token
  264. def _convert_id_to_token(self, index):
  265. """Converts an index (integer) in a token (str) using the vocab."""
  266. return self.decoder.get(index)
  267. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.convert_tokens_to_string
  268. def convert_tokens_to_string(self, tokens):
  269. """Converts a sequence of tokens (string) in a single string."""
  270. text = "".join(tokens)
  271. text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
  272. return text
  273. def clean_up_tokenization(self, text):
  274. text = "".join(text)
  275. vocab_tokens = list(self.encoder.keys()) + list(self.added_tokens_encoder.keys())
  276. text = text.replace("[SPACE]", " ") if "[SPACE]" in vocab_tokens else text
  277. text = text.replace("[STOP]", " ") if "[STOP]" in vocab_tokens else text
  278. text = text.replace(self.unk_token, "").replace(" ", " ").replace(" ", " ")
  279. return text
  280. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.save_vocabulary
  281. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  282. if not os.path.isdir(save_directory):
  283. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  284. return
  285. vocab_file = os.path.join(
  286. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  287. )
  288. merge_file = os.path.join(
  289. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
  290. )
  291. with open(vocab_file, "w", encoding="utf-8") as f:
  292. f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  293. index = 0
  294. with open(merge_file, "w", encoding="utf-8") as writer:
  295. writer.write("#version: 0.2\n")
  296. for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
  297. if index != token_index:
  298. logger.warning(
  299. f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
  300. " Please check that the tokenizer is not corrupted!"
  301. )
  302. index = token_index
  303. writer.write(" ".join(bpe_tokens) + "\n")
  304. index += 1
  305. return vocab_file, merge_file