Skip to content

The best ChatGPT that $100 can buy.

Python

fix token_bytes calculation to use raw token bytes instead of round-tripping through str, which corrupts tokens that are not valid standalone UTF-8 (e.g. bytes >= 0x80 became 3-byte U+FFFD). 193/32768 tokens were affected, so bpb of new runs will read ~0.05% higher than old runs. Thank you @ellenjxu #693

Andrej Karpathy2ce972a3696b
diff --git a/nanochat/tokenizer.py b/nanochat/tokenizer.py
index a2146c2..e604602 100644
--- a/nanochat/tokenizer.py
+++ b/nanochat/tokenizer.py
@@ -255,6 +255,9 @@ class RustBPETokenizer:
def decode(self, ids):
return self.enc.decode(ids)
+ def decode_single_token_bytes(self, token_id):
+ return self.enc.decode_single_token_bytes(token_id)
+
def save(self, tokenizer_dir):
# save the encoding object to disk
os.makedirs(tokenizer_dir, exist_ok=True)
diff --git a/scripts/tok_train.py b/scripts/tok_train.py
index e08cd10..13d8f85 100644
--- a/scripts/tok_train.py
+++ b/scripts/tok_train.py
@@ -74,16 +74,16 @@ assert decoded == test_text
# allows us to report a loss that is invariant to the vocab size of the tokenizer.
# The bits per byte on the validation set is then one of the primary metrics we care about.
vocab_size = tokenizer.get_vocab_size()
-special_set = set(tokenizer.get_special_tokens())
-token_strings = [tokenizer.decode([token_id]) for token_id in range(vocab_size)]
+special_ids = set(tokenizer.encode_special(s) for s in tokenizer.get_special_tokens())
token_bytes = []
for token_id in range(vocab_size):
- token_str = token_strings[token_id] # the Python string representation of this token
- if token_str in special_set:
- token_bytes.append(0) # special characters are not counted
+ if token_id in special_ids:
+ token_bytes.append(0) # special tokens are not counted
else:
- id_bytes = len(token_str.encode("utf-8")) # number of bytes that make up this token
- token_bytes.append(id_bytes)
+ # use the raw bytes of the token: decoding to a string first corrupts
+ # tokens that are not valid standalone UTF-8 (e.g. the raw bytes >= 0x80)
+ num_bytes = len(tokenizer.decode_single_token_bytes(token_id))
+ token_bytes.append(num_bytes)
token_bytes = torch.tensor(token_bytes, dtype=torch.int32, device='cpu')
token_bytes_path = os.path.join(tokenizer_dir, "token_bytes.pt")
with open(token_bytes_path, "wb") as f: