tokenizer.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. # Copyright 2021 The OpenAI Team Authors.
  2. # Copyright 2021-2022 The Alibaba Fundamental Vision Team Authors. All rights reserved.
  3. #
  4. # The implementation here is modified based on OpenAI CLIP,
  5. # originally MIT License, Copyright (c) 2021 OpenAI,
  6. # and publicly available at https://github.com/openai/CLIP/.
  7. """ CLIP Tokenizer."""
  8. import gzip
  9. import html
  10. import os
  11. from functools import lru_cache
  12. import ftfy
  13. import regex as re
  14. import torch
  15. @lru_cache()
  16. def default_bpe():
  17. return os.path.join(
  18. os.path.dirname(os.path.abspath(__file__)),
  19. 'bpe_simple_vocab_16e6.txt.gz')
  20. @lru_cache()
  21. def bytes_to_unicode():
  22. """
  23. Returns list of utf-8 byte and a corresponding list of unicode strings.
  24. The reversible bpe codes work on unicode strings.
  25. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
  26. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
  27. This is a significant percentage of your normal, say, 32K bpe vocab.
  28. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
  29. And avoids mapping to whitespace/control characters the bpe code barfs on.
  30. """
  31. bs = list(range(ord('!'),
  32. ord('~') + 1)) + list(range(
  33. ord('¡'),
  34. ord('¬') + 1)) + list(range(ord('®'),
  35. ord('ÿ') + 1))
  36. cs = bs[:]
  37. n = 0
  38. for b in range(2**8):
  39. if b not in bs:
  40. bs.append(b)
  41. cs.append(2**8 + n)
  42. n += 1
  43. cs = [chr(n) for n in cs]
  44. return dict(zip(bs, cs))
  45. def get_pairs(word):
  46. """Return set of symbol pairs in a word.
  47. Word is represented as tuple of symbols (symbols being variable-length strings).
  48. """
  49. pairs = set()
  50. prev_char = word[0]
  51. for char in word[1:]:
  52. pairs.add((prev_char, char))
  53. prev_char = char
  54. return pairs
  55. def basic_clean(text):
  56. text = ftfy.fix_text(text)
  57. text = html.unescape(html.unescape(text))
  58. return text.strip()
  59. def whitespace_clean(text):
  60. text = re.sub(r'\s+', ' ', text)
  61. text = text.strip()
  62. return text
  63. class SimpleTokenizer(object):
  64. def __init__(self, bpe_path: str = default_bpe()):
  65. self.byte_encoder = bytes_to_unicode()
  66. self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
  67. merges = gzip.open(bpe_path).read().decode('utf-8').split('\n')
  68. merges = merges[1:49152 - 256 - 2 + 1]
  69. merges = [tuple(merge.split()) for merge in merges]
  70. vocab = list(bytes_to_unicode().values())
  71. vocab = vocab + [v + '</w>' for v in vocab]
  72. for merge in merges:
  73. vocab.append(''.join(merge))
  74. vocab.extend(['<|startoftext|>', '<|endoftext|>'])
  75. self.encoder = dict(zip(vocab, range(len(vocab))))
  76. self.decoder = {v: k for k, v in self.encoder.items()}
  77. self.bpe_ranks = dict(zip(merges, range(len(merges))))
  78. self.cache = {
  79. '<|startoftext|>': '<|startoftext|>',
  80. '<|endoftext|>': '<|endoftext|>'
  81. }
  82. self.pat = re.compile(
  83. r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""",
  84. re.IGNORECASE)
  85. def bpe(self, token):
  86. if token in self.cache:
  87. return self.cache[token]
  88. word = tuple(token[:-1]) + (token[-1] + '</w>', )
  89. pairs = get_pairs(word)
  90. if not pairs:
  91. return token + '</w>'
  92. error_list = []
  93. while True:
  94. bigram = min(
  95. pairs, key=lambda pair: self.bpe_ranks.get(pair, float('inf')))
  96. if bigram not in self.bpe_ranks:
  97. break
  98. first, second = bigram
  99. new_word = []
  100. i = 0
  101. while i < len(word):
  102. try:
  103. j = word.index(first, i)
  104. new_word.extend(word[i:j])
  105. i = j
  106. except Exception as err:
  107. error_list.append(err)
  108. new_word.extend(word[i:])
  109. break
  110. if word[i] == first and i < len(word) - 1 and word[
  111. i + 1] == second:
  112. new_word.append(first + second)
  113. i += 2
  114. else:
  115. new_word.append(word[i])
  116. i += 1
  117. new_word = tuple(new_word)
  118. word = new_word
  119. if len(word) == 1:
  120. break
  121. else:
  122. pairs = get_pairs(word)
  123. if len(error_list) > 100:
  124. print(error_list[-1])
  125. word = ' '.join(word)
  126. self.cache[token] = word
  127. return word
  128. def encode(self, text):
  129. bpe_tokens = []
  130. text = whitespace_clean(basic_clean(text)).lower()
  131. for token in re.findall(self.pat, text):
  132. token = ''.join(self.byte_encoder[b]
  133. for b in token.encode('utf-8'))
  134. bpe_tokens.extend(self.encoder[bpe_token]
  135. for bpe_token in self.bpe(token).split(' '))
  136. return bpe_tokens
  137. def decode(self, tokens):
  138. text = ''.join([self.decoder[token] for token in tokens])
  139. text = bytearray([self.byte_decoder[c] for c in text]).decode(
  140. 'utf-8', errors='replace').replace('</w>', ' ')
  141. return text
  142. def clip_tokenize(tokenizer, texts, context_length=77, truncate=True):
  143. """
  144. Returns the tokenized representation of given input string(s)
  145. Parameters
  146. ----------
  147. texts : Union[str, List[str]]
  148. An input string or a list of input strings to tokenize
  149. context_length : int
  150. The context length to use; all CLIP models use 77 as the context length
  151. truncate: bool
  152. Whether to truncate the text in case its encoding is longer than the context length
  153. Returns
  154. -------
  155. A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length].
  156. We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long.
  157. """
  158. if isinstance(texts, str):
  159. texts = [texts]
  160. sot_token = tokenizer.encoder['<|startoftext|>']
  161. eot_token = tokenizer.encoder['<|endoftext|>']
  162. all_tokens = [[sot_token] + tokenizer.encode(text) + [eot_token]
  163. for text in texts]
  164. result = torch.zeros(len(all_tokens), context_length, dtype=torch.int)
  165. for i, tokens in enumerate(all_tokens):
  166. if len(tokens) > context_length:
  167. if truncate:
  168. tokens = tokens[:context_length]
  169. tokens[-1] = eot_token
  170. else:
  171. raise RuntimeError(
  172. f'Input {texts[i]} is too long for context length {context_length}'
  173. )
  174. result[i, :len(tokens)] = torch.tensor(tokens)
  175. return result