Question about Encoder Logic
Author: JackxTongCreated Jul 20, 2024Updated Dec 10, 2024
I noticed the encode() method has extra logic with a while loop to find the lowest merge index:
def encode(self, text):
text_bytes = text.encode("utf-8") # raw bytes
ids = list(text_bytes) # list of integers in range 0..255
while len(ids) >= 2:
stats = get_stats(ids)
pair = min(stats, key=lambda p: self.merges.get(p, float("inf")))
if pair not in self.merges:
break # nothing else can be merged anymore
idx = self.merges[pair]
ids = merge(ids, pair, idx)
return idsCan we simplify it like this:
def encode(self, text):
tokens = text.encode("utf-8")
tokens = list(map(int, tokens))
for pair, index in self.merges.items():
tokens = merge(tokens, pair, index)
return tokensSince merge() merges all occurrences, it seems a simple for loop suffices. Is there a reason for the more complex logic? I have trained my tokenizer vs the basictokenizer on some text data, and achieved the exact same vocab & encoder. Maybe I missed something. Could you clarify?
Thanks!
Update: I made a pytest from my forked repo just to show mine is also correct: For anyone interested to try out
Source: karpathy/minbpe