tinystories-gpt-124m / src /tokenizer.py
mlvar's picture
Upload model weights, training code, and model card
7f1e014 verified
Raw History Blame Contribute Delete
1.02 kB
"""Thin wrapper around tiktoken's GPT-2 BPE tokenizer."""
import tiktoken
class Tokenizer:
"""GPT-2 BPE tokenizer via tiktoken.
Vocabulary size: 50257
Lossless for ASCII text (which TinyStories overwhelmingly is).
"""
def __init__(self):
self._enc = tiktoken.get_encoding("gpt2")
# GPT-2 uses 50256 as the actual token count but reserves 50257 slots.
# We use the full 50257 to match convention.
self.vocab_size = self._enc.n_vocab # 50257
self.eot_token = self._enc.eot_token # End-of-text token (<|endoftext|>)
def encode(self, text: str) -> list[int]:
"""Encode a string into a list of token IDs."""
return self._enc.encode(text, allowed_special={"<|endoftext|>"})
def decode(self, tokens: list[int]) -> str:
"""Decode a list of token IDs back into a string."""
return self._enc.decode(tokens)
def __repr__(self) -> str:
return f"Tokenizer(vocab_size={self.vocab_size}, eot_token={self.eot_token})"