MCPcopy Create free account
hub / github.com/MiniMax-AI/VTP / bpe

Method bpe

vtp/tokenizers/text_tokenizer.py:208–248  ·  view source on GitHub ↗

Apply BPE encoding to a token.

(self, token)

Source from the content-addressed store, hash-verified

206 self.clean_fn = get_clean_fn(clean)
207
208 def bpe(self, token):
209 """Apply BPE encoding to a token."""
210 if token in self.cache:
211 return self.cache[token]
212 word = tuple(token[:-1]) + (token[-1] + '</w>',)
213 pairs = get_pairs(word)
214
215 if not pairs:
216 return token+'</w>'
217
218 while True:
219 bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float('inf')))
220 if bigram not in self.bpe_ranks:
221 break
222 first, second = bigram
223 new_word = []
224 i = 0
225 while i < len(word):
226 try:
227 j = word.index(first, i)
228 new_word.extend(word[i:j])
229 i = j
230 except Exception:
231 new_word.extend(word[i:])
232 break
233
234 if word[i] == first and i < len(word)-1 and word[i+1] == second:
235 new_word.append(first+second)
236 i += 2
237 else:
238 new_word.append(word[i])
239 i += 1
240 new_word = tuple(new_word)
241 word = new_word
242 if len(word) == 1:
243 break
244 else:
245 pairs = get_pairs(word)
246 word = ' '.join(word)
247 self.cache[token] = word
248 return word
249
250 def encode(self, text):
251 """Encode text to token IDs."""

Callers 1

encodeMethod · 0.95

Calls 1

get_pairsFunction · 0.85

Tested by

no test coverage detected