Download src/tokenizer.py from mlvar/tinystories-gpt-124m: direct link, hf CLI and curl.
- Browser
- Download file 1.02 kB
-
https://huggingface.co/mlvar/tinystories-gpt-124m/resolve/main/src/tokenizer.py
- Command line
-
hf download hf://mlvar/tinystories-gpt-124m/src/tokenizer.py
-
curl -L -o tokenizer.py https://huggingface.co/mlvar/tinystories-gpt-124m/resolve/main/src/tokenizer.py
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})" | |