TheDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/itsubaki/gpt/llms.txt
Use this file to discover all available pages before exploring further.
tokenizer package implements Byte Pair Encoding (BPE) training from scratch, building a vocabulary of merged subword tokens from raw text. Starting from 256 raw byte tokens, the algorithm iteratively merges the most frequent adjacent pair until the target vocabulary size is reached. The resulting merge rules are serialized to a .gob file and reused by both the pre-training and fine-tuning pipelines, while the encoded token sequence is written to a .bin file ready for the data loader.
% make dl
curl -fs -o testdata/tiny_codes.txt https://raw.githubusercontent.com/oreilly-japan/deep-learning-from-scratch-6/refs/heads/main/codebot/tiny_codes.txt
curl -fs -o testdata/tiny_codes_sft.json https://raw.githubusercontent.com/oreilly-japan/deep-learning-from-scratch-6/refs/heads/main/codebot/tiny_codes_sft.json
This downloads approximately 6.5 MB of Python code snippets (
tiny_codes.txt) and a corresponding instruction-response dataset (tiny_codes_sft.json).-ftestdata/tiny_codes.txt-rtestdata/merge_rules.gob-vocab-size1000Training BPE 100%|██████████████████████████████| 743/743
saved merge rules to testdata/merge_rules.gob
...
995 -> "are"
996 -> ")."
997 -> " my"
998 -> "emain"
999 -> "<|endoftext|>"
byte count: 6487033
token count: 2640742
compression ratio: 2.456519038967078
encoding time: 1.459157917s
saved tokens to testdata/tiny_codes.bin
How BPE training works
TheTrainBPE() function implements the BPE algorithm over a pre-tokenized corpus:
- Initialise with 256 base byte tokens (one per byte value 0–255).
- Count all adjacent token pairs across the pre-tokenized corpus.
- Merge the most frequent pair into a new token ID (
256 + step). - Repeat until
vocabSize - 256 - 1merges have been performed. - Append the special
<|endoftext|>token at ID256 + numMerges.
Vocabulary composition
--vocab-size 1000, this gives 256 base bytes + 743 merge rules + 1 end token = 1000 tokens.
Compression ratio
After training, the tokenizer encodes the full corpus and reports the compression ratio — how many fewer tokens are needed compared to raw bytes:Pre-tokenization
Before byte encoding, text is split into words and punctuation using a GPT-2-style regular expression. This prevents merges from spanning word boundaries:'s, 'll, 're), optional-space letter runs, optional-space digit runs, optional-space punctuation clusters, and whitespace-only chunks. Each chunk is encoded independently into byte IDs before BPE merges are applied.
Serialization
Merge rules are stored in insertion order inside aDefaultDict[Pair] and serialized with the standard encoding/gob package:
NewBPETokenizerFrom(), ensuring the vocabulary is identical between training and generation.