Replacing the Shakespeare GPT's 65 characters with a byte-level BPE tokenizer trained on the same text leaves the Transformer unchanged and changes four things. On tiny-shakespeare the merges stop at 12,715 tokens, not the 50,257 requested, and the text becomes 306,651 tokens, about 0.27 per character (tokenizers 0.23.3). The model then has $769\,V + 10{,}738{,}944$ parameters, 20,516,779 for this vocabulary, 48% of them in the embedding table and LM head. A context of 256 tokens reaches several times further back than 256 characters. And per-token losses are not comparable with the character model's 1.48 until multiplied by tokens per character. A reloaded tokenizer also lost its special tokens until they were registered again, a fix made in 2026.
The character-level model built in the walkthrough spends its capacity learning to spell: every word must be assembled one letter at a time, and a context of 256 characters holds only a few lines of verse. Large language models instead read subword tokens, frequent words and pieces of words, so that common words cost one token and rare ones a few. A later version of the program in the same repository, train_gpt_tokenized.py, swaps the character vocabulary for a byte-level byte-pair-encoding (BPE) tokenizer trained on the same text and keeps the Transformer unchanged. This article describes what changes and what the change implies. The walkthrough itself does not cover this version, so everything here is read from the code. No model was trained for this article; the tokenizer was trained once for this edition, with version 0.23.3 of the tokenizers library, to check the statements about it below (the script is tools/experiments/gpt/bpe_check.py in this site's repository).
The code is in the same folder as the character-level program, gpt_text_model. The code blocks are excerpts of the unified diff from train_gpt.py to train_gpt_tokenized.py, generated from the files.
Byte-pair encoding in brief
Byte-pair encoding builds a vocabulary by merging. It starts from single symbols, counts which adjacent pair occurs most often in the training text, adds that pair to the vocabulary as a new symbol, and repeats until the vocabulary reaches the requested size. Frequent words end up as single tokens; rare words remain split into several. The method, its origin as a compression algorithm, and its adaptation to neural machine translation by Sennrich, Haddow and Birch (2016) are explained in the subword section of Tokenization.
GPT-2 made the method byte-level: the starting symbols are the 256 possible byte values rather than Unicode characters, so that any string at all can be encoded without an "unknown" token, from a base vocabulary of only 256 (Radford et al., 2019, Section 2.2). GPT-2 also prevented merges across character categories, so that variants such as "dog." and "dog!" do not each consume a vocabulary slot, with an exception for spaces; its vocabulary has 50,257 tokens (Sections 2.2 and 2.3). In GPT-2's tokenizer a space is attached to the beginning of the word that follows it: the pattern that splits text before merging includes ?\p{L}+, an optional space followed by letters, in its released encoder.py. The tokenizer used here is the ByteLevelBPETokenizer of the Hugging Face tokenizers library, an implementation of the same byte-level scheme.
Training the tokenizer on the text
The character vocabulary and the stoi/itos dictionaries are replaced by a tokenizer that is trained on the dataset the first time the program runs and then saved, as vocab.json and merges.txt, so later runs reload it:
--- train_gpt.py
+++ train_gpt_tokenized.py
@@ -7,17 +7,23 @@
import torch.nn.functional as F
-# The Gutenberg datasets contain characters (Greek, Hebrew, ...) that a narrower output encoding cannot show.
-# Print them as "?" rather than crash when output goes to a file or pipe.
+# Import the ByteLevelBPETokenizer from Hugging Face's tokenizers library
+try:
+ from tokenizers import ByteLevelBPETokenizer
+except ImportError:
+ raise ImportError("Please install the tokenizers library with: pip install tokenizers")
+
+# A sampled sequence of byte-level tokens need not be valid UTF-8, and decodes to text containing U+FFFD.
+# Print such characters as "?" rather than crash when output goes to a file or pipe in a narrower encoding.
if hasattr(sys.stdout, 'reconfigure'): # Not every stdout has it (IDLE, Jupyter)
sys.stdout.reconfigure(errors='replace')
# Updated Hyperparameters
-batch_size = 64 # Increased batch size
-block_size = 256 # Increased block size for more context
-C = 384 # Increased embedding dimension
-learning_rate = 3e-4 # Lowered learning rate for stable training
-n_layer = 6 # Increased number of layers
-num_heads = 6 # Increased number of attention heads
-dropout_rate = 0.2 # Dropout rate for regularization
+batch_size = 64 # Increased batch size
+block_size = 256 # Increased block size for more context (block_size now counts tokens)
+C = 384 # Increased embedding dimension
+learning_rate = 3e-4 # Lowered learning rate for stable training
+n_layer = 6 # Increased number of layers
+num_heads = 6 # Increased number of attention heads
+dropout_rate = 0.2 # Dropout rate for regularization
eval_interval = 100
eval_iters = 100
@@ -73,24 +71,44 @@
####################################################################################################
-# Load the Dataset and Create Vocabulary
-
+# GPT-2 Style BPE Tokenization Setup
+
+# Define a directory to store (or load) the BPE tokenizer files
+bpe_dir = os.path.join(data_dir, "bpe")
+vocab_file = os.path.join(bpe_dir, "vocab.json")
+merges_file = os.path.join(bpe_dir, "merges.txt")
+special_tokens = ["<|pad|>", "<|unk|>", "<|bos|>", "<|eos|>"]
+
+# If the BPE model files do not exist, train a new tokenizer on the dataset.
+if not os.path.exists(vocab_file) or not os.path.exists(merges_file):
+ os.makedirs(bpe_dir, exist_ok=True)
+ print("Training new BPE tokenizer...")
+ tokenizer = ByteLevelBPETokenizer()
+ # You can adjust vocab_size as needed; GPT-2 used 50,257 tokens by default.
+ tokenizer.train(files=[data_file], vocab_size=50257, min_frequency=2, special_tokens=special_tokens)
+ tokenizer.save_model(bpe_dir)
+ print(f"Tokenizer saved to {bpe_dir}.")
+else:
+ print("Loading existing BPE tokenizer...")
+ tokenizer = ByteLevelBPETokenizer(vocab_file, merges_file)
+ # The saved files do not mark the special tokens as special, so register them again
+ tokenizer.add_special_tokens(special_tokens)
+
+# Get the vocabulary size from the tokenizer
+vocab_size = tokenizer.get_vocab_size()
+
+# Define encode and decode functions that work with tokens rather than characters
+def encode(s):
+ # Returns a list of token IDs
+ return tokenizer.encode(s).ids
+
+def decode(token_ids):
+ # Converts a list of token IDs back into a string
+ return tokenizer.decode(token_ids)
+
+# Read the dataset and encode it into token IDs
with open(data_file, 'r', encoding='utf-8') as f:
text = f.read()
-chars = sorted(list(set(text)))
-vocab_size = len(chars)
-
-####################################################################################################
-# Encode and Decode Text
-
-stoi = {ch: i for i, ch in enumerate(chars)}
-itos = {i: ch for i, ch in enumerate(chars)}
-
-def encode(s):
- return [stoi[c] for c in s]
-
-def decode(l):
- return ''.join([itos[i] for i in l])
-
+# Encode the entire text; note that this produces a long list of token IDs.
data = torch.tensor(encode(text), dtype=torch.long)
The training call asks for vocab_size=50257, GPT-2's size, with min_frequency=2, so that a pair must occur at least twice to be merged, and four special tokens, <|pad|>, <|unk|>, <|bos|> and <|eos|>. The requested size is an upper limit rather than a guarantee: merges stop when no remaining pair is frequent enough, and on a text of about a million characters that can happen before 50,257 is reached. The program does not print the resulting vocabulary size, but vocab_size = tokenizer.get_vocab_size() passes whatever it is to the model. On tiny-shakespeare the merges stop at 12,715 tokens, a quarter of the requested size, and the whole text becomes 306,651 tokens, about 0.27 per character.
The special_tokens list and the call to add_special_tokens in the else branch were added in 2026 for this edition. On the first run, the freshly trained tokenizer treats the four special tokens as special: the string <|bos|> encodes as the single token 2. On every later run the tokenizer is rebuilt from vocab.json and merges.txt. Those files keep the special tokens' IDs but not the fact that they are special, so in the original version the reloaded tokenizer split <|bos|> into six ordinary tokens, [31, 95, 69, 1040, 95, 33], the pieces <, |, b, os, | and >. The <|bos|> sample prompt therefore meant one thing on the first run and another on every run after it, and nothing reported an error. A program run once from a clean folder, as an experiment with a new tokenizer, never meets this; it appears only when the saved tokenizer is reused. Registering the tokens again with add_special_tokens after loading restores the first run's behavior; they keep their IDs, and the vocabulary is unchanged. The general point is that a saved tokenizer is only as complete as the format it is saved in. save_model writes only the vocabulary and the merges, while the library's save method writes a single tokenizer.json with the whole configuration, special tokens included, which a tokenizer loaded with Tokenizer.from_file keeps. Encoding a few test strings before saving and again after reloading, and comparing the results, catches this class of problem.
encode and decode keep their names and roles, so the rest of the program is unaffected: the whole text is still encoded into one long tensor, now of token IDs, and split 90/10 into training and validation by position, now counted in tokens. The text is read and written as UTF-8, as in the character-level program (Tiny Shakespeare Data Pipeline explains why).
What the vocabulary size does to the model
The Transformer is untouched; only vocab_size changes. But two layers scale with it: the token embedding table ($V \times C$ weights) and the LM head ($C \times V$ weights plus $V$ biases). With $C = 384$, every other layer together has 10,738,944 parameters, so the model has
$$769\,V + 10{,}738{,}944$$
parameters, where 769 = 384 + 384 + 1. With the 65-character vocabulary this gives the familiar 10,788,929. The counts for some other vocabulary sizes, computed with tools/experiments/gpt/param_counts.py in this site's repository:
| Vocabulary size $V$ | Parameters | Share in embedding and LM head |
|---|---|---|
| 65 (characters) | 10,788,929 | 0.5% |
| 5,000 | 14,583,944 | 26% |
| 12,715 (reached on tiny-shakespeare) | 20,516,779 | 48% |
| 20,000 | 26,118,944 | 59% |
| 50,257 (if reached) | 49,386,577 | 78% |
With the vocabulary actually reached, almost half the parameters are in these two layers, and the model is nearly twice the size of the character-level one. At GPT-2's full vocabulary size, more than three quarters of the parameters would sit in the two vocabulary-sized layers, and the model would have about 49 million parameters to fit on about a megabyte of text. Each token's embedding row is trained only when that token appears, so rows for tokens that occur a handful of times receive few updates. The program prints the actual parameter count when training starts, which reveals the vocabulary size indirectly. This is one reason models trained on small corpora use smaller vocabularies, and why vocab_size is the first setting worth reducing in experiments with this program.
What the context length now means
block_size is still 256, but it now counts tokens. Since a typical English word is one or a few BPE tokens, 256 tokens cover several times as much text as 256 characters, so each prediction can draw on a longer stretch of the play. The cost of attention depends on the number of positions, not on how much text they represent, so this longer reach comes at no extra cost per step. The trade is that each prediction is harder: the model must choose among thousands of possible tokens instead of 65 characters.
Comparing losses across tokenizations
The training loop reports the same cross-entropy loss as before, but the loss is now per token, not per character, and the two are not comparable. A model that predicts whole words faces a harder choice at each step and has fewer steps per line, so a per-token loss is naturally higher than a per-character loss for the same quality of prediction. Vaswani et al. (2017) make the same caution about their own results: the perplexities in their Table 3 are "per-wordpiece, according to our byte-pair encoding, and should not be compared to per-word perplexities" (Table 3, caption).
The fair comparison converts both to the same unit. The total loss over a validation text, in nats, is the per-token loss times the number of tokens; dividing by the number of characters gives nats per character, comparable with the character-level model's 1.48 from the run described in Scaling the Shakespeare GPT:
$$\text{loss per character} = \text{loss per token} \times \frac{\text{number of tokens}}{\text{number of characters}}.$$
For example, if the tokenizer turned the validation text into a quarter as many tokens as it has characters (for the whole text the ratio is 0.27), a per-token loss of 5.0 would correspond to 1.25 nats per character, better than the character model, while a per-token loss of 6.4 would correspond to 1.6, worse. (These figures illustrate the conversion; they are not results from this program.) The same issue arises with perplexity, discussed for topic models in Evaluating Topic Models: perplexity per token and perplexity per word or per character measure uncertainty over different units. Perplexity and Source Coding works the conversion in a worked problem, with the ratio measured for this tokenizer on the validation text.
Prompts for generation
The sample prompts change to suit tokens:
--- train_gpt.py
+++ train_gpt_tokenized.py
@@ -326,7 +340,6 @@
scenarios = {
- "Start with 'A'": "A",
- "Start with 'The'": "The",
+ "Start with '<|bos|>'": "<|bos|> ",
+ "Start with 'The'": "The ",
"Start with 'To be, or not to be, that is the '": "To be, or not to be, that is the "
}
-
for description, start_text in scenarios.items():
Two details deserve care. The prompt <|bos|> uses one of the special tokens as a "beginning of sequence" marker, but the training text contains no such marker anywhere, so the model has never seen it in context and has no learned statistics for what follows it; it starts from a token sequence unlike anything in its training data. And the prompts The and To be, or not to be, that is the end with a space. In GPT-2's scheme the space belongs to the start of the next word's token, so a prompt that ends in a bare space ends with a token that, in the training text, almost always occurs fused with a following word; dropping the trailing space usually gives a more natural continuation. (As Scaling the Shakespeare GPT notes, Hamlet is not in tiny-shakespeare, so the third prompt is unfamiliar in any tokenization.)
Other changes in this version
The tokenized program was written after the character-level one, and several of its changes are improvements that the character-level one could use as well: torch.load with map_location, a start-up that survives a missing checkpoint folder, whole prompts for the generate command, and an explicit UTF-8 encoding. For this edition, in 2026, those improvements were carried back to train_gpt.py, as Scaling the Shakespeare GPT describes, so they no longer appear in the diff between the two programs. What remains is specific to this version.
A clearer local name. Inside the attention head and compute_loss, B, T, C = x.shape reused the name of the global embedding size C. That was harmless, since the local value equals the global one in the head, but confusing; the new version calls it C_:
--- train_gpt.py
+++ train_gpt_tokenized.py
@@ -119,3 +137,3 @@
def forward(self, x):
- B, T, C = x.shape
+ B, T, C_ = x.shape
Clearer progress reports. Training prints the parameter count and configuration at the start, and formats each evaluation as a progress report:
--- train_gpt.py
+++ train_gpt_tokenized.py
@@ -345,4 +357,12 @@
-# Update the training loop to call the generate_text_scenarios function at each checkpoint
def train_model(start_step=0):
+ print(f"\n[+] Starting training from step {start_step}")
+ print(f"[+] Model parameters: {sum(p.numel() for p in model.parameters()):,}")
+ print(f"[+] Training configuration:")
+ print(f" - Batch size: {batch_size}")
+ print(f" - Learning rate: {learning_rate}")
+ print(f" - Number of layers: {n_layer}")
+ print(f" - Number of heads: {num_heads}")
+ print(f" - Embedding dimension: {C}")
+
for step in range(start_step, num_train_steps):
@@ -357,6 +377,10 @@
losses = estimate_loss()
- print(f"Step {step}, Train Loss: {losses['train']}, Val Loss: {losses['val']}")
- # Save checkpoint at each evaluation interval
+ print(f"\n[+] Step {step}/{num_train_steps} ({step/num_train_steps*100:.1f}%)")
+ print(f" - Train Loss: {losses['train']:.4f}")
+ print(f" - Val Loss: {losses['val']:.4f}")
+ print(f" - Learning rate: {optimizer.param_groups[0]['lr']:.2e}")
+
+ # Save checkpoint and generate sample
save_checkpoint(model, optimizer, step)
- # Generate text after saving the checkpoint
+ print("\n[+] Generating sample text...")
generate_text()
The original version of this program also left out the save after the training loop that the character-level program makes, so the last 99 steps of a run, those after the checkpoint at step 9,900, were not kept when the program exited; the samples printed during training were unaffected. The save was restored for this edition and no longer shows in the diff.
A checkpoint folder of its own. In the original version both programs saved to the same checkpoints folder under the same file names, and each loads the latest checkpoint it finds at start-up. Each works on its own; run one after the other in the same working directory, the tokenized program stops at start-up with a "size mismatch" error from load_state_dict: a character-level checkpoint has an embedding table and LM head with 65 rows, and the BPE model needs one per token. The tokenized program now keeps its checkpoints in checkpoints_bpe:
--- train_gpt.py
+++ train_gpt_tokenized.py
@@ -298,5 +312,4 @@
-def save_checkpoint(model, optimizer, epoch, checkpoint_dir='checkpoints'):
- if not os.path.exists(checkpoint_dir):
- os.makedirs(checkpoint_dir)
+def save_checkpoint(model, optimizer, epoch, checkpoint_dir='checkpoints_bpe'): # Kept apart from the character model's checkpoints
+ os.makedirs(checkpoint_dir, exist_ok=True)
checkpoint_path = os.path.join(checkpoint_dir, f'model_epoch_{epoch}.pth')
@@ -367,7 +391,5 @@
def get_path_to_latest_checkpoint():
- """Return the path to the latest checkpoint file"""
- checkpoint_dir = 'checkpoints'
+ checkpoint_dir = 'checkpoints_bpe'
if not os.path.exists(checkpoint_dir):
return None
-
# Only files named like model_epoch_<step>.pth, so other files in the folder are ignored
@@ -424,3 +444,3 @@
print(f"Loading model from epoch {epoch}")
- checkpoint_path = f'checkpoints/model_epoch_{epoch}.pth'
+ checkpoint_path = f'checkpoints_bpe/model_epoch_{epoch}.pth'
if os.path.exists(checkpoint_path):
A checkpoint's file name here records a step but not which model the file belongs to, so two models that share a folder can load each other's files. Separate folders are the simplest remedy. A sturdier one, used by nanoGPT, saves the model's configuration in the checkpoint and builds the model from it when resuming (Karpathy, 2022), so that the weights and the model they are loaded into always match.
No vocabulary check on prompts. The character-level generate refuses a prompt containing a character outside its 65-character vocabulary. The tokenized one needs no such check, because a byte-level tokenizer can encode any string:
--- train_gpt.py
+++ train_gpt_tokenized.py
@@ -429,9 +449,4 @@
print(f"Checkpoint not found: {checkpoint_path}")
- pass
def generate(prompt="The", max_tokens=256):
- unknown = sorted(set(prompt) - set(stoi))
- if unknown:
- print(f"Not in the vocabulary, cannot encode: {unknown}")
- return
print(f"Generating text from prompt: {prompt}")
Printing what the model writes. The first lines of the first diff above set sys.stdout.reconfigure(errors='replace') in both programs, with a different reason in each comment. The tokens of a byte-level model stand for sequences of bytes, not characters, and a sampled sequence of them need not be valid UTF-8; decode replaces each invalid sequence with U+FFFD, the Unicode replacement character. When the output went to a file or a pipe, Python on Windows (before version 3.15, which defaults to UTF-8) encoded it in the locale's code page, here cp1252, which has no code for U+FFFD, so a test run for this edition, with its output redirected, stopped partway through training with a UnicodeEncodeError while printing a sample. This happens only when the output is redirected, which the program's interactive use does not do. With errors='replace', a character the output encoding cannot represent is printed as ? instead. The character-level program received the same line, because the Project Gutenberg texts in its catalog contain Greek and Hebrew characters, which cp1252 cannot encode either, and a model trained on them can reproduce them. Output generated by a model is text the program has not seen before, and code that prints it has to cope with anything the model can produce, which for a byte-level model includes byte sequences that are not text at all.
What the switch does and does not change
Switching from characters to subword tokens changes what the model has to learn, not how it learns. The Transformer, the training loop, the loss and the sampling are the same code; only the mapping between text and integers is different. The model no longer has to learn spelling, and a context of 256 tokens reaches much further back. In exchange, it must learn a far larger output distribution from the same small text, with most of its parameters in vocabulary-sized tables. Whether that trade pays off on tiny-shakespeare is an empirical question that the per-character comparison above is designed to answer.
References
- Karpathy, A. (2022). nanoGPT [Software repository, MIT license]. https://github.com/karpathy/nanoGPT. Cited:
train.py(the model configuration saved in each checkpoint). record · 3 pages - Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., and Sutskever, I. (2019). Language models are unsupervised multitask learners. OpenAI technical report. Cited: Section 2.2 (byte-level BPE, base vocabulary of 256, no merges across character categories), Section 2.3 (vocabulary of 50,257). Tokenizer code: https://github.com/openai/gpt-2/blob/master/src/encoder.py record · 3 pages
- Sennrich, R., Haddow, B., and Birch, A. (2016). Neural machine translation of rare words with subword units. In Proceedings of ACL 2016, 1715–1725. record · 2 pages
- Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., and Polosukhin, I. (2017). Attention is all you need. In Advances in Neural Information Processing Systems 30. arXiv:1706.03762. Cited: Table 3 caption (per-wordpiece perplexities). record · 9 pages
- Code for this article: train_gpt_tokenized.py and train_gpt.py in github.com/mdb42/ml-demos.
Reviewed: editorial review, 23 Nov 2026 · 6 revisions