bpe_openai_gpt2.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. # Source: https://github.com/openai/gpt-2/blob/master/src/encoder.py
  2. # License:
  3. # Modified MIT License
  4. # Software Copyright (c) 2019 OpenAI
  5. # We don’t claim ownership of the content you create with GPT-2, so it is yours to do with as you please.
  6. # We only ask that you use GPT-2 responsibly and clearly indicate your content was created using GPT-2.
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
  8. # associated documentation files (the "Software"), to deal in the Software without restriction,
  9. # including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
  10. # and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
  11. # subject to the following conditions:
  12. # The above copyright notice and this permission notice shall be included
  13. # in all copies or substantial portions of the Software.
  14. # The above copyright notice and this permission notice need not be included
  15. # with content created by the Software.
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  17. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  19. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  20. # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
  21. # OR OTHER DEALINGS IN THE SOFTWARE.
  22. import os
  23. import json
  24. import regex as re
  25. import requests
  26. from tqdm import tqdm
  27. from functools import lru_cache
  28. @lru_cache()
  29. def bytes_to_unicode():
  30. """
  31. Returns list of utf-8 byte and a corresponding list of unicode strings.
  32. The reversible bpe codes work on unicode strings.
  33. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
  34. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
  35. This is a significant percentage of your normal, say, 32K bpe vocab.
  36. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
  37. And avoids mapping to whitespace/control characters the bpe code barfs on.
  38. """
  39. bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
  40. cs = bs[:]
  41. n = 0
  42. for b in range(2**8):
  43. if b not in bs:
  44. bs.append(b)
  45. cs.append(2**8 + n)
  46. n += 1
  47. cs = [chr(n) for n in cs]
  48. return dict(zip(bs, cs))
  49. def get_pairs(word):
  50. """
  51. Return set of symbol pairs in a word.
  52. Word is represented as tuple of symbols (symbols being variable-length strings).
  53. """
  54. pairs = set()
  55. prev_char = word[0]
  56. for char in word[1:]:
  57. pairs.add((prev_char, char))
  58. prev_char = char
  59. return pairs
  60. class Encoder:
  61. def __init__(self, encoder, bpe_merges, errors='replace'):
  62. self.encoder = encoder
  63. self.decoder = {v: k for k, v in self.encoder.items()}
  64. self.errors = errors # how to handle errors in decoding
  65. self.byte_encoder = bytes_to_unicode()
  66. self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
  67. self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
  68. self.cache = {}
  69. # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
  70. self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
  71. def bpe(self, token):
  72. if token in self.cache:
  73. return self.cache[token]
  74. word = tuple(token)
  75. pairs = get_pairs(word)
  76. if not pairs:
  77. return token
  78. while True:
  79. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float('inf')))
  80. if bigram not in self.bpe_ranks:
  81. break
  82. first, second = bigram
  83. new_word = []
  84. i = 0
  85. while i < len(word):
  86. try:
  87. j = word.index(first, i)
  88. new_word.extend(word[i:j])
  89. i = j
  90. except ValueError:
  91. new_word.extend(word[i:])
  92. break
  93. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  94. new_word.append(first + second)
  95. i += 2
  96. else:
  97. new_word.append(word[i])
  98. i += 1
  99. new_word = tuple(new_word)
  100. word = new_word
  101. if len(word) == 1:
  102. break
  103. else:
  104. pairs = get_pairs(word)
  105. word = ' '.join(word)
  106. self.cache[token] = word
  107. return word
  108. def encode(self, text):
  109. bpe_tokens = []
  110. for token in re.findall(self.pat, text):
  111. token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
  112. bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
  113. return bpe_tokens
  114. def decode(self, tokens):
  115. text = ''.join([self.decoder[token] for token in tokens])
  116. text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors=self.errors)
  117. return text
  118. def get_encoder(model_name, models_dir):
  119. with open(os.path.join(models_dir, model_name, 'encoder.json'), 'r') as f:
  120. encoder = json.load(f)
  121. with open(os.path.join(models_dir, model_name, 'vocab.bpe'), 'r', encoding="utf-8") as f:
  122. bpe_data = f.read()
  123. bpe_merges = [tuple(merge_str.split()) for merge_str in bpe_data.split('\n')[1:-1]]
  124. return Encoder(encoder=encoder, bpe_merges=bpe_merges)
  125. def download_vocab():
  126. # Modified code from
  127. subdir = 'gpt2_model'
  128. if not os.path.exists(subdir):
  129. os.makedirs(subdir)
  130. subdir = subdir.replace('\\', '/') # needed for Windows
  131. for filename in ['encoder.json', 'vocab.bpe']:
  132. r = requests.get("https://openaipublic.blob.core.windows.net/gpt-2/models/117M/" + filename, stream=True)
  133. with open(os.path.join(subdir, filename), 'wb') as f:
  134. file_size = int(r.headers["content-length"])
  135. chunk_size = 1000
  136. with tqdm(ncols=100, desc="Fetching " + filename, total=file_size, unit_scale=True) as pbar:
  137. # 1k for chunk_size, since Ethernet packet size is around 1500 bytes
  138. for chunk in r.iter_content(chunk_size=chunk_size):
  139. f.write(chunk)
  140. pbar.update(chunk_size)