37 / 90

Day 37: Text to Tokens — Unicode, Byte Encodings, and Vocabularies

Turn raw text into token ids: distinguish characters, Unicode code points, and UTF-8 bytes; build a deterministic vocabulary; and reproduce the text_tools train/val/test artifacts that every language-model baseline consumes. All work counts inside the 480-minute ledger.

Models & Training 480 active minutes (8 hours focused study)
01 120 min

From characters to bytes: code points and UTF-8

Agent-Assisted Engineering Check

Prerequisites

Complete Day 36. If blocked, use the Day 35 recovery link for probability and Python review.

Learning Objective

Distinguish a visible character, its Unicode code point, and its UTF-8 byte sequence; predict byte counts before measuring; record a prediction-versus-observation comparison for empty, ASCII, accented, CJK, and emoji text.

Instructions

A character is what a reader sees; a code point is its Unicode number (written U+XXXX); an encoding turns code points into bytes. Required work: predict then run python3 -c "s='猫aé😀'; print(len(s), [hex(ord(c)) for c in s], list(s.encode('utf-8')))" and compare each prediction. Optional work: encode the same string as UTF-16 and compare byte counts.

Practice & Prediction Log

Predict len(s), the code points, and the UTF-8 byte list for s='猫aé😀' and for the empty string ''. Then verify in Python and explain why the byte count differs from the code-point count.

Independent Mastery Criterion

Your written predictions match the observed ord() and encode() outputs for all probe strings (including empty), and you can state the rule mapping code-point ranges to UTF-8 byte counts.

Authoritative Source Resources & Provenance

linking PSF License Version 2

Python Unicode HOWTO

Author: Python Software Foundation | Original Source Link ↗

Relevant Section / Range: Sections: Definitions of Character, Code Point, and Encodings (UTF-8)

Verified Version & Date: Python 3.12 documentation (Verified: 2026-10-30)

Selection Rationale:

Normative reference for Python 3 code points, encodings, and variable-length UTF-8 byte behavior used in every tokenization step.

Source Prerequisites:

Basic Python strings and byte literals

Safe Fallback (Offline Resilience):

The lesson defines every required Unicode concept locally and all commands run offline.

Compared Candidate Sources & Selection Analysis (2)
Unicode Standard (unicode.org) official documentation ↗ compared_alternative [Unicode License Agreement / Terms of Use]

Exhaustive normative standard but far too deep for a first contact; the Python HOWTO teaches the same code point/encoding distinction in executable form.

Strong motivation and history but pre-Python-3 and not runnable; retained as optional background reading only.

linking MIT License (repository) / Standard YouTube License (video, subtitle rights unknown) Video subtitles have unknown distribution rights and are not imported

minbpe: Minimal Byte-Pair Encoding tokenizer (Let's build the GPT Tokenizer)

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: README exercise flow and minbpe/base.py; lecture segment on Unicode code points vs raw bytes

Verified Version & Date: commit 1acefe9 (Verified: 2026-10-30)

Selection Rationale:

Standard teaching reference connecting Unicode code points, UTF-8 bytes, and subword token ids for GPT-style tokenizers.

Source Prerequisites:

Basic Python and strings

Safe Fallback (Offline Resilience):

The lesson re-implements the same algorithms locally in pure Python with verified outputs.

Compared Candidate Sources & Selection Analysis (3)
OpenAI tiktoken ↗ compared_alternative [MIT]

Production BPE with Rust core and regex pre-tokenization; selected as the production contrast source rather than the primary teaching implementation.

Hugging Face tokenizers + NLP course chapter 6 ↗ compared_alternative [Apache-2.0 (library) / CC BY-NC-SA? (course text varies)]

High-quality BPE coverage but frames tokenization through library APIs; minbpe exposes the raw merge loop for hand tracing.

Google SentencePiece ↗ compared_alternative [Apache-2.0]

Industrial tokenizer trainer supporting BPE and unigram models; C++ core hides the teaching mechanics.

02 120 min

Vocabularies and token-id mappings

Independent Mastery Check (no AI assistance)

Prerequisites

Complete the previous activity; use the listed recovery link if blocked.

Learning Objective

Build a deterministic vocabulary mapping every distinct symbol to a stable integer id, encode and decode text losslessly, and choose an explicit policy for symbols never seen in training.

Instructions

A tokenizer needs two tables: stoi (symbol→id) and itos (id→symbol). Required work: assign ids 0..V-1 in sorted order over the distinct symbols of the training text, reserve len(vocab) as the id, then encode and decode a probe string. Optional work: contrast with a byte-level vocabulary of 256 entries that needs no .

Practice & Prediction Log

For training text 'banana': build the sorted character vocab, encode 'banana' and 'cab', decode the first result, and encode 'banana!' using . Then encode 'é猫' as UTF-8 bytes and state why byte-level input never hits .

Independent Mastery Criterion

Given any short training text, you can write the vocab table, encode/decode a probe string correctly by hand, and explain when <unk> is required versus when byte-level coverage removes it.

Authoritative Source Resources & Provenance

linking MIT License (repository) / Standard YouTube License (video, subtitle rights unknown) Video subtitles have unknown distribution rights and are not imported

minbpe: Minimal Byte-Pair Encoding tokenizer (Let's build the GPT Tokenizer)

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: minbpe/base.py: vocab dict, ids<->bytes mapping, encode/decode contract

Verified Version & Date: commit 1acefe9 (Verified: 2026-10-30)

Selection Rationale:

Shows the exact vocab, merges, and encode/decode invariants a teaching tokenizer must satisfy.

Source Prerequisites:

Basic Python dicts and lists

Safe Fallback (Offline Resilience):

All mapping exercises are re-implemented locally with verified expected ids.

Compared Candidate Sources & Selection Analysis (3)
OpenAI tiktoken ↗ compared_alternative [MIT]

Production BPE with Rust core and regex pre-tokenization; selected as the production contrast source rather than the primary teaching implementation.

Hugging Face tokenizers + NLP course chapter 6 ↗ compared_alternative [Apache-2.0 (library) / CC BY-NC-SA? (course text varies)]

High-quality BPE coverage but frames tokenization through library APIs; minbpe exposes the raw merge loop for hand tracing.

Google SentencePiece ↗ compared_alternative [Apache-2.0]

Industrial tokenizer trainer supporting BPE and unigram models; C++ core hides the teaching mechanics.

linking MIT License

tiktoken: Fast byte-pair encoding tokenizer used by OpenAI models

Author: OpenAI | Original Source Link ↗

Relevant Section / Range: README: encoding.get_encoding("cl100k_base"), encode/decode API, special token policy

Verified Version & Date: Verified 2026-10-30

Selection Rationale:

Production reference that contrasts a teaching tokenizer's explicit vocab dict with industrial byte-level BPE ranks and special tokens.

Source Prerequisites:

Basic Python

Safe Fallback (Offline Resilience):

The lesson's vocabulary/id exercises run entirely on a local Python dict with fixed expected values.

Compared Candidate Sources & Selection Analysis (2)
Hugging Face tokenizers library ↗ compared_alternative [Apache-2.0]

Broad production tokenizer framework with training APIs; tiktoken is a cleaner contrast for GPT-style compatibility claims.

Google SentencePiece ↗ compared_alternative [Apache-2.0]

Widely used trainer/tokenizer for open models; treated as further production context rather than the contrast reference.

03 120 min

Deterministic train/val/test splits and provenance

Agent-Assisted Engineering Check

Prerequisites

Complete the previous activity; use the listed recovery link if blocked.

Learning Objective

Reproduce the text_tools deterministic split artifacts and read the manifest, so every downstream model fits counts on train only, selects on val, and leaves test untouched.

Instructions

Required work: run python3 projects/text_tools/cli.py --input data/names.txt --split --output-dir /tmp/lm-data (defaults: seed 42, ratios 0.8/0.1/0.1), then open /tmp/lm-data/manifest.json and locate split_counts, split_sha256, and leakage_check. Re-run into a second directory and confirm identical hashes. Optional work: repeat with --seed 99 and observe the counts stay the same while membership changes.

Practice & Prediction Log

Predict train/val/test line counts for the 32,033-line corpus before running, then verify. For a 10-line file predict the same split. State which manifest fields prove determinism and that no index appears in two splits.

Independent Mastery Criterion

You can regenerate the artifacts, cite the exact split counts and the manifest fields that prove determinism and disjointness, and state why counts, vocab, and merges may be fit only on train.

Authoritative Source Resources & Provenance

linking MIT License (repository) / Standard YouTube License (video, subtitle rights unknown) Video subtitles have unknown distribution rights and are not imported

makemore: Character-level language models on names.txt

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: README and notebook part 1: names.txt corpus, 90% train / 5% dev / 5% test split rationale

Verified Version & Date: Verified 2026-10-30

Selection Rationale:

Uses the same data/names.txt corpus family and demonstrates why model fitting must see only the training split while dev/test remain held out.

Source Prerequisites:

Basic Python

Safe Fallback (Offline Resilience):

Local projects/text_tools/cli.py produces the deterministic splits and manifest offline.

Compared Candidate Sources & Selection Analysis (2)
Stanford CS336: Language Modeling from Scratch ↗ compared_alternative [No license declared (the repository has no LICENSE file, so all rights are reserved by default)]

More rigorous and comprehensive but assumes PyTorch fluency; retained as the systems-rigor companion source.

Karpathy nanoGPT ↗ compared_deferred [MIT]

Strong Transformer training reference but beyond the count-based baseline scope; deferred to later pretraining days.

linking MIT

CS336 Assignment 1: Basics (Spring 2025 tagged release)

Author: Stanford University CS336 Staff | Original Source Link ↗

Relevant Section / Range: README setup; tests/adapters.py; tests/test_optimizer.py; tests/test_nn_utils.py; tests/test_serialization.py

Verified Version & Date: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01

Selection Rationale:

Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.

Source Prerequisites:

Python systems programming

Safe Fallback (Offline Resilience):

Local projects/text_tools deterministic artifacts provide the complete pipeline offline.

Compared Candidate Sources & Selection Analysis (2)
Karpathy nanoGPT ↗ compared_alternative [MIT]

Simpler code layout, useful complementary reference for minimal PyTorch Transformer.

Hugging Face Transformers Course ↗ compared_alternative [Apache-2.0]

High-level API focus rather than building from raw tensor fundamentals.

04 120 min

Independent mastery check: bytes, ids, and split evidence

Independent Mastery Check (no AI assistance)

Prerequisites

Complete the previous activities; use the listed recovery link if blocked.

Learning Objective

Unaided, reproduce the code-point/byte computation, a vocab encode/decode, the split counts, and the malformed-input policy — then record an honest recovery plan for anything missed.

Instructions

Do not consult answers or AI during this check. Required work: predict all four answers in the draft log, then verify each with Python and the CLI. Optional work: describe one legitimate use of --errors ignore for noisy corpora.

Practice & Prediction Log

Closed-book: (a) How many code points and UTF-8 bytes does 'é猫' have? (b) With vocab {a:0,b:1,c:2}, what is encode('cab')? (c) How do 10 lines split at 0.8/0.1/0.1? (d) For a file containing invalid byte 0xFF: what exit code does --errors strict give, and which character appears under replace?

Independent Mastery Criterion

All four predictions match observed output without assistance, and any miss is logged together with the recovery link (Day 35 review or the matching Day 37 activity) that will repair it.

Authoritative Source Resources & Provenance

linking PSF License Version 2

Python Unicode HOWTO

Author: Python Software Foundation | Original Source Link ↗

Relevant Section / Range: Sections: Encodings, UTF-8 rules, and error handling strategies

Verified Version & Date: Python 3.12 documentation (Verified: 2026-10-30)

Selection Rationale:

Normative reference for the strict/replace decoding behavior verified in the mastery check.

Source Prerequisites:

Basic Python strings and byte literals

Safe Fallback (Offline Resilience):

All mastery-check answers are computable with a local Python interpreter.

Compared Candidate Sources & Selection Analysis (2)
Unicode Standard (unicode.org) official documentation ↗ compared_alternative [Unicode License Agreement / Terms of Use]

Exhaustive normative standard but far too deep for a first contact; the Python HOWTO teaches the same code point/encoding distinction in executable form.

Strong motivation and history but pre-Python-3 and not runnable; retained as optional background reading only.

linking MIT License (repository) / Standard YouTube License (video, subtitle rights unknown) Video subtitles have unknown distribution rights and are not imported

makemore: Character-level language models on names.txt

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: Corpus-to-tensor pipeline: stoi/itos lookup tables built from the training split only

Verified Version & Date: Verified 2026-10-30

Selection Rationale:

Reinforces that vocabulary tables and counts are fit on training data only, the rule assessed in this check.

Source Prerequisites:

Basic Python

Safe Fallback (Offline Resilience):

The local deterministic artifacts in projects/text_tools provide all required evidence offline.

Compared Candidate Sources & Selection Analysis (2)
Stanford CS336: Language Modeling from Scratch ↗ compared_alternative [No license declared (the repository has no LICENSE file, so all rights are reserved by default)]

More rigorous and comprehensive but assumes PyTorch fluency; retained as the systems-rigor companion source.

Karpathy nanoGPT ↗ compared_deferred [MIT]

Strong Transformer training reference but beyond the count-based baseline scope; deferred to later pretraining days.