simple_tokenizer.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import gzip
  2. import html
  3. import os
  4. from functools import lru_cache
  5. import ftfy
  6. import regex as re
  7. @lru_cache()
  8. def default_bpe():
  9. return os.path.join(os.path.dirname(os.path.abspath(__file__)), "../data/bpe_simple_vocab_16e6.txt.gz")
  10. @lru_cache()
  11. def bytes_to_unicode():
  12. """
  13. Returns list of utf-8 byte and a corresponding list of unicode strings.
  14. The reversible bpe codes work on unicode strings.
  15. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
  16. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
  17. This is a signficant percentage of your normal, say, 32K bpe vocab.
  18. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
  19. And avoids mapping to whitespace/control characters the bpe code barfs on.
  20. """
  21. bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
  22. cs = bs[:]
  23. n = 0
  24. for b in range(2**8):
  25. if b not in bs:
  26. bs.append(b)
  27. cs.append(2**8+n)
  28. n += 1
  29. cs = [chr(n) for n in cs]
  30. return dict(zip(bs, cs))
  31. def get_pairs(word):
  32. """Return set of symbol pairs in a word.
  33. Word is represented as tuple of symbols (symbols being variable-length strings).
  34. """
  35. pairs = set()
  36. prev_char = word[0]
  37. for char in word[1:]:
  38. pairs.add((prev_char, char))
  39. prev_char = char
  40. return pairs
  41. def basic_clean(text):
  42. text = ftfy.fix_text(text)
  43. text = html.unescape(html.unescape(text))
  44. return text.strip()
  45. def whitespace_clean(text):
  46. text = re.sub(r'\s+', ' ', text)
  47. text = text.strip()
  48. return text
  49. class SimpleTokenizer(object):
  50. def __init__(self, bpe_path: str = default_bpe()):
  51. self.byte_encoder = bytes_to_unicode()
  52. self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
  53. merges = gzip.open(bpe_path).read().decode("utf-8").split('\n')
  54. merges = merges[1:49152-256-2+1]
  55. merges = [tuple(merge.split()) for merge in merges]
  56. vocab = list(bytes_to_unicode().values())
  57. vocab = vocab + [v+'</w>' for v in vocab]
  58. for merge in merges:
  59. vocab.append(''.join(merge))
  60. vocab.pop(-1) # remove last one in vocab(jekyll) to keep vocab_size unchanged
  61. vocab.extend(['<|mask|>', '<|startoftext|>', '<|endoftext|>']) # vocab_size 49408
  62. # vocab.extend(['<|startoftext|>', '<|endoftext|>']) # vocab_size 49408
  63. self.encoder = dict(zip(vocab, range(len(vocab))))
  64. self.decoder = {v: k for k, v in self.encoder.items()}
  65. self.bpe_ranks = dict(zip(merges, range(len(merges))))
  66. self.cache = {'<|startoftext|>': '<|startoftext|>', '<|mask|>': '<|mask|>', '<|endoftext|>': '<|endoftext|>'}
  67. self.pat = re.compile(r"""<\|startoftext\|>|<\|mask\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE)
  68. def bpe(self, token):
  69. if token in self.cache:
  70. return self.cache[token]
  71. word = tuple(token[:-1]) + ( token[-1] + '</w>',)
  72. pairs = get_pairs(word)
  73. if not pairs:
  74. return token+'</w>'
  75. while True:
  76. bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf')))
  77. if bigram not in self.bpe_ranks:
  78. break
  79. first, second = bigram
  80. new_word = []
  81. i = 0
  82. while i < len(word):
  83. try:
  84. j = word.index(first, i)
  85. new_word.extend(word[i:j])
  86. i = j
  87. except:
  88. new_word.extend(word[i:])
  89. break
  90. if word[i] == first and i < len(word)-1 and word[i+1] == second:
  91. new_word.append(first+second)
  92. i += 2
  93. else:
  94. new_word.append(word[i])
  95. i += 1
  96. new_word = tuple(new_word)
  97. word = new_word
  98. if len(word) == 1:
  99. break
  100. else:
  101. pairs = get_pairs(word)
  102. word = ' '.join(word)
  103. self.cache[token] = word
  104. return word
  105. def encode(self, text):
  106. bpe_tokens = []
  107. text = whitespace_clean(basic_clean(text)).lower()
  108. for token in re.findall(self.pat, text):
  109. token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
  110. bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
  111. return bpe_tokens
  112. def decode(self, tokens):
  113. text = ''.join([self.decoder[token] for token in tokens])
  114. text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ')
  115. return text