Create tiny_byte_tokenizer.py
Browse files- tiny_byte_tokenizer.py +38 -0
tiny_byte_tokenizer.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Tiny byte-level tokenizer:
|
| 4 |
+
- Vocab: 0..255 (raw bytes) + 256:[PAD], 257:[EOS]
|
| 5 |
+
- UTF-8 in/out
|
| 6 |
+
- Deterministic, license-clean, zero deps
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
PAD_ID = 256
|
| 10 |
+
EOS_ID = 257
|
| 11 |
+
VOCAB_SIZE = 258
|
| 12 |
+
|
| 13 |
+
class TinyByteTokenizer:
|
| 14 |
+
def __init__(self, pad_id=PAD_ID, eos_id=EOS_ID):
|
| 15 |
+
self.pad_id = pad_id
|
| 16 |
+
self.eos_id = eos_id
|
| 17 |
+
|
| 18 |
+
def encode(self, text: str, add_eos=True):
|
| 19 |
+
b = text.encode("utf-8", errors="replace")
|
| 20 |
+
ids = list(b)
|
| 21 |
+
if add_eos:
|
| 22 |
+
ids.append(self.eos_id)
|
| 23 |
+
return ids
|
| 24 |
+
|
| 25 |
+
def decode(self, ids):
|
| 26 |
+
# drop special tokens
|
| 27 |
+
bytes_out = bytearray()
|
| 28 |
+
for t in ids:
|
| 29 |
+
if t == self.eos_id or t == self.pad_id:
|
| 30 |
+
continue
|
| 31 |
+
if 0 <= t <= 255:
|
| 32 |
+
bytes_out.append(t)
|
| 33 |
+
return bytes(bytes_out).decode("utf-8", errors="replace")
|
| 34 |
+
|
| 35 |
+
def pad(self, ids, max_len):
|
| 36 |
+
if len(ids) >= max_len:
|
| 37 |
+
return ids[:max_len]
|
| 38 |
+
return ids + [self.pad_id] * (max_len - len(ids))
|