You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

simple_tokenizer.py 5.0 kB

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

冻结ViT-B/32版本的CLIP模型中的全部图像层,用Adan优化器训练模型,训练100个epoch,每隔5个epoch对模型进行保存;完成CLIP模型训练后,运行test_clip.py用测试集中的数据和自定义的提示词对保存的模型进行测试,选取测试精度最好的模型和对应的提示词,运行predict.py文件,选择“min_loss.pth”模型,提交官方系统测试,top1的精度是0.6788。

Contributors (1)