{ "nbformat": 4, "nbformat_minor": 5, "metadata": { "kernelspec": { "name": "python3", "display_name": "Python 3", "language": "python" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lab 2.1 · Build a tokenizer\n", "\n", "**Goal:** build byte-pair encoding (BPE) from scratch in plain Python, train it on a slice of\n", "TinyStories, check that `decode(encode(text)) == text`, compare it with the tokenizers real models\n", "use (`tiktoken`), measure how many tokens the same content costs in English and in Indonesian, and\n", "break a tokenizer three ways.\n", "\n", "**Runs on:** any laptop, CPU only, a few minutes (the BPE training is plain Python); also Kaggle or\n", "Colab. Needs `tiktoken` and `matplotlib`; the notebook downloads its own data (about 3 MB of\n", "TinyStories from huggingface.co, cached after the first run).\n", "\n", "**Versions tested:** see the last cell's output (it prints them).\n", "\n", "The data: the first 3 MB of the TinyStories validation file (Eldan and Li, licence\n", "CDLA-Sharing-1.0), cut into stories. The first 2,500 stories train the tokenizer; the next 1,000\n", "are held out and never seen in training." ], "id": "lab-2-1-tokens-00" }, { "cell_type": "code", "metadata": {}, "source": [ "import csv\n", "import json\n", "import importlib.metadata\n", "import math\n", "import pathlib\n", "import platform\n", "import re\n", "import time\n", "import urllib.request\n", "from collections import Counter\n", "\n", "try:\n", " import tiktoken\n", "except ImportError: # e.g. a fresh Colab runtime\n", " import subprocess\n", " import sys\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"tiktoken\"])\n", " import tiktoken\n", "\n", "\n", "def data_root():\n", " for candidate in (pathlib.Path(\"data\"), pathlib.Path(\"../data\")):\n", " if candidate.is_dir():\n", " return candidate\n", " return None\n", "\n", "\n", "def out_dir():\n", " root = data_root()\n", " if root is None:\n", " return pathlib.Path(\".\")\n", " d = root / \"lab-2-1-tokens\"\n", " d.mkdir(parents=True, exist_ok=True)\n", " return d\n", "\n", "\n", "def cache_dir():\n", " root = data_root()\n", " d = (root.parent / \".work\") if root is not None else pathlib.Path(\".\")\n", " d.mkdir(parents=True, exist_ok=True)\n", " return d\n", "\n", "\n", "URL = \"https://huggingface.co/datasets/roneneldan/TinyStories/resolve/main/TinyStoriesV2-GPT4-valid.txt\"\n", "N_BYTES = 3_000_000\n", "EOT = \"<|endoftext|>\"\n", "\n", "\n", "def load_stories():\n", " path = cache_dir() / \"tinystories-valid-head.txt\"\n", " if not path.exists():\n", " with urllib.request.urlopen(URL, timeout=120) as response:\n", " path.write_bytes(response.read(N_BYTES))\n", " text = path.read_bytes().decode(\"utf-8\", errors=\"ignore\")\n", " parts = text.split(EOT)\n", " # parts[0] starts mid-story and parts[-1] is cut off at the byte limit: drop both\n", " return [p.strip() for p in parts[1:-1] if p.strip()]\n", "\n", "\n", "STORIES = load_stories()\n", "TRAIN, HELD = STORIES[:2500], STORIES[2500:3500]\n", "train_bytes = sum(len(s.encode(\"utf-8\")) for s in TRAIN)\n", "held_bytes = sum(len(s.encode(\"utf-8\")) for s in HELD)\n", "print(f\"{len(STORIES)} stories in the slice; train {len(TRAIN)} stories ({train_bytes:,} bytes), \"\n", " f\"held out {len(HELD)} stories ({held_bytes:,} bytes)\")\n", "print(\"first held-out story starts:\", repr(HELD[0][:70]))" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-01" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 · Predict first\n", "\n", "Before running the cells below, write down your answers:\n", "\n", "1. How many bytes does UTF-8 use for `a`, `é`, `日` and the emoji 😀?\n", "2. About how many tokens will GPT-2's tokenizer need for a 100-word English paragraph? For the\n", " same paragraph in Indonesian? (Within 20 % is a good guess.)\n", "3. Your tokenizer will start with 256 byte tokens and add 500 merges. On stories it has never\n", " seen, about how many **bytes per token** will it reach? (1 means no compression at all.)\n", "4. Will 2,000 merges compress twice as well as 500? More than twice? Less?" ], "id": "lab-2-1-tokens-02" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 · From characters to bytes\n", "\n", "A string is a list of **code points** (one number per character, set by Unicode). To store or send\n", "it, a computer turns each code point into 1 to 4 **bytes**; the standard way is **UTF-8**. A byte\n", "is a number from 0 to 255, so 256 symbols can write *any* text in any language." ], "id": "lab-2-1-tokens-03" }, { "cell_type": "code", "metadata": {}, "source": [ "print(f\"{'char':>5} {'code point':>10} {'UTF-8 bytes (hex)':<20} {'(decimal)':<16} count\")\n", "for ch in [\"a\", \"é\", \"日\", \"\\U0001F600\"]:\n", " b = ch.encode(\"utf-8\")\n", " print(f\"{ch:>5} U+{ord(ch):04X} {b.hex(' '):<20} {str(list(b)):<16} {len(b)}\")\n", "\n", "word = \"tokenization\"\n", "print(\"\\nbytes of 'tokenization':\", list(word.encode(\"utf-8\")))\n", "print(\"round trip:\", bytes(word.encode(\"utf-8\")).decode(\"utf-8\") == word)" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-04" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 · Three ways to cut text, on the same data\n", "\n", "- **Characters (here: bytes):** the vocabulary is tiny and nothing is unknown, but sequences are long.\n", "- **Words:** sequences are short, but the vocabulary is huge and a new word is a problem. We build a\n", " word vocabulary from the training stories and see how many words in the held-out stories it does\n", " not know.\n", "- **Subwords (BPE):** in between, built next." ], "id": "lab-2-1-tokens-05" }, { "cell_type": "code", "metadata": {}, "source": [ "sentence = \"Once upon a time, a little girl named Lily found a shiny red ball.\"\n", "print(\"sentence:\", sentence)\n", "print(\" characters:\", len(sentence), \"| bytes:\", len(sentence.encode(\"utf-8\")),\n", " \"| words (and punctuation marks):\", len(re.findall(r\"\\w+|[^\\w\\s]\", sentence)))\n", "\n", "WORD = re.compile(r\"\\w+|[^\\w\\s]\")\n", "train_words = Counter(w for s in TRAIN for w in WORD.findall(s))\n", "held_words = [w for s in HELD for w in WORD.findall(s)]\n", "known = set(train_words)\n", "unknown_tokens = sum(1 for w in held_words if w not in known)\n", "unknown_types = len({w for w in held_words if w not in known})\n", "print(f\"\\nword vocabulary from training: {len(train_words):,} different words/marks \"\n", " f\"in {sum(train_words.values()):,} running words\")\n", "print(f\"held out: {len(held_words):,} running words, {unknown_tokens:,} not in the vocabulary \"\n", " f\"({100 * unknown_tokens / len(held_words):.2f} %), {unknown_types:,} different unknown words\")\n", "print(\"some unknown words:\", sorted({w for w in held_words if w not in known})[:12])\n", "print(\"different characters in the training stories:\", len(set(\"\".join(TRAIN))))" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-06" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 · Byte-pair encoding, by hand first\n", "\n", "BPE starts with every byte as its own token and repeats one step: **count every pair of\n", "neighbouring tokens, merge the most frequent pair into a new token.** The first merge makes token 256,\n", "the second token 257, and so on. We merge inside \"pieces\" (words, with their leading space) so a merge\n", "never crosses a word boundary; the next section does that for real text. Ties are broken by taking\n", "the pair with the smaller IDs, so the result is deterministic.\n", "\n", "First on a four-word toy corpus (a classic example from the BPE paper): `low` 5 times, `lower`\n", "2 times, `newest` 6 times, `widest` 3 times." ], "id": "lab-2-1-tokens-07" }, { "cell_type": "code", "metadata": {}, "source": [ "def merge_ids(ids, pair, new_id):\n", " \"\"\"Replace every adjacent occurrence of `pair` in the list `ids` by `new_id`.\"\"\"\n", " out, i = [], 0\n", " while i < len(ids):\n", " if i < len(ids) - 1 and ids[i] == pair[0] and ids[i + 1] == pair[1]:\n", " out.append(new_id)\n", " i += 2\n", " else:\n", " out.append(ids[i])\n", " i += 1\n", " return out\n", "\n", "\n", "def train_bpe(piece_counts, n_merges):\n", " \"\"\"piece_counts: Counter {bytes piece: how often it occurs}. Returns (merges, counts at merge time).\"\"\"\n", " words = [[list(piece), freq] for piece, freq in piece_counts.items()]\n", " pairs = Counter()\n", " for ids, freq in words:\n", " for p in zip(ids, ids[1:]):\n", " pairs[p] += freq\n", " merges, counts = [], []\n", " for rank in range(n_merges):\n", " if not pairs:\n", " break\n", " # most frequent pair; on a tie the smaller (first id, second id)\n", " (a, b), count = max(pairs.items(), key=lambda kv: (kv[1], -kv[0][0], -kv[0][1]))\n", " new_id = 256 + rank\n", " merges.append((a, b))\n", " counts.append(count)\n", " for w in words:\n", " ids, freq = w\n", " if a not in ids or b not in ids:\n", " continue\n", " merged = merge_ids(ids, (a, b), new_id)\n", " if len(merged) == len(ids):\n", " continue\n", " for p in zip(ids, ids[1:]): # take the old pairs out of the counts ...\n", " pairs[p] -= freq\n", " if pairs[p] == 0:\n", " del pairs[p]\n", " for p in zip(merged, merged[1:]): # ... and put the new ones in\n", " pairs[p] += freq\n", " w[0] = merged\n", " return merges, counts\n", "\n", "\n", "def vocab_of(merges):\n", " vocab = {i: bytes([i]) for i in range(256)}\n", " for rank, (a, b) in enumerate(merges):\n", " vocab[256 + rank] = vocab[a] + vocab[b]\n", " return vocab\n", "\n", "\n", "def show(b):\n", " return repr(b.decode(\"utf-8\", errors=\"replace\"))\n", "\n", "\n", "toy = Counter({b\"low\": 5, b\"lower\": 2, b\"newest\": 6, b\"widest\": 3})\n", "toy_merges, toy_counts = train_bpe(toy, 8)\n", "toy_vocab = vocab_of(toy_merges)\n", "print(\"start:\", {p.decode(): list(p) for p in toy})\n", "print(f\"\\n{'merge':>5} {'pair':<16} {'count':>5} new token\")\n", "for rank, ((a, b), count) in enumerate(zip(toy_merges, toy_counts)):\n", " print(f\"{rank + 1:>5} {show(toy_vocab[a]) + ' + ' + show(toy_vocab[b]):<16} {count:>5} \"\n", " f\"{256 + rank} = {show(toy_vocab[256 + rank])}\")" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-08" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Encoding a *new* word means applying the merges **in the order they were learned**. Decoding is\n", "the reverse and needs no rules at all: look up each token's bytes and join them." ], "id": "lab-2-1-tokens-09" }, { "cell_type": "code", "metadata": {}, "source": [ "def encode_piece(piece, merges, limit=None):\n", " \"\"\"Encode one string with the first `limit` merges (default: all of them).\"\"\"\n", " rank = {p: i for i, p in enumerate(merges)}\n", " limit = len(merges) if limit is None else limit\n", " ids = list(piece.encode(\"utf-8\"))\n", " while len(ids) > 1:\n", " pair = min(set(zip(ids, ids[1:])), key=lambda p: rank.get(p, math.inf))\n", " r = rank.get(pair)\n", " if r is None or r >= limit:\n", " break\n", " ids = merge_ids(ids, pair, 256 + r)\n", " return ids\n", "\n", "\n", "for w in [\"lowest\", \"newer\", \"wider\"]:\n", " ids = encode_piece(w, toy_merges)\n", " print(f\"{w!r:9} -> {ids} = {[toy_vocab[i].decode() for i in ids]}\")" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-10" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 · Train on TinyStories\n", "\n", "The same function, on real text. Step one is **pre-splitting**: a regular expression cuts the text\n", "into pieces (a word with its leading space, a run of digits, a run of punctuation, whitespace) and\n", "merges happen inside a piece only. We count how often each distinct piece occurs, and train on the\n", "counts (a 2 MB text has only a few thousand different words)." ], "id": "lab-2-1-tokens-11" }, { "cell_type": "code", "metadata": {}, "source": [ "PATTERN = r\" ?[^\\W\\d_]+| ?\\d+| ?(?:[^\\s\\w]|_)+|\\s+(?!\\S)|\\s+\"\n", "SPLIT = re.compile(PATTERN)\n", "\n", "print(SPLIT.findall(\"Once upon a time, Tom had 12 red balls!\"))\n", "\n", "piece_counts = Counter(p.encode(\"utf-8\") for s in TRAIN for p in SPLIT.findall(s))\n", "print(f\"\\n{sum(piece_counts.values()):,} pieces, {len(piece_counts):,} different\")\n", "\n", "t0 = time.time()\n", "MERGES, MERGE_COUNTS = train_bpe(piece_counts, 2000)\n", "print(f\"trained 2000 merges in {time.time() - t0:.1f} s\")\n", "\n", "VOCAB = vocab_of(MERGES)\n", "print(f\"\\n{'merge':>5} {'new token':<12} {'pair':<24} count\")\n", "for rank in list(range(10)) + [49, 99, 199, 499, 999, 1999]:\n", " a, b = MERGES[rank]\n", " print(f\"{rank + 1:>5} {show(VOCAB[256 + rank]):<12} {show(VOCAB[a]) + ' + ' + show(VOCAB[b]):<24} {MERGE_COUNTS[rank]:,}\")" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-12" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Merge `k` is only ever built from tokens that exist before merge `k`, so **training with 500\n", "merges gives exactly the first 500 merges of training with 2,000**. We train once and reuse prefixes.\n", "Now wrap it in a tokenizer class with `encode` and `decode`, plus one special token." ], "id": "lab-2-1-tokens-13" }, { "cell_type": "code", "metadata": {}, "source": [ "class BPE:\n", " def __init__(self, merges):\n", " self.merges = list(merges)\n", " self.rank = {p: i for i, p in enumerate(self.merges)}\n", " self.vocab = vocab_of(self.merges)\n", " self.eot_id = 256 + len(self.merges)\n", " self.vocab[self.eot_id] = EOT.encode(\"utf-8\")\n", " self.cache = {}\n", "\n", " @property\n", " def vocab_size(self):\n", " return len(self.vocab)\n", "\n", " def encode_piece(self, piece, limit):\n", " key = (piece, limit)\n", " if key not in self.cache:\n", " self.cache[key] = encode_piece(piece, self.merges, limit)\n", " return self.cache[key]\n", "\n", " def encode(self, text, n_merges=None):\n", " limit = len(self.merges) if n_merges is None else n_merges\n", " ids = []\n", " for part in re.split(\"(\" + re.escape(EOT) + \")\", text):\n", " if part == EOT:\n", " ids.append(self.eot_id)\n", " else:\n", " for piece in SPLIT.findall(part):\n", " ids.extend(self.encode_piece(piece, limit))\n", " return ids\n", "\n", " def decode(self, ids):\n", " return b\"\".join(self.vocab[i] for i in ids).decode(\"utf-8\", errors=\"replace\")\n", "\n", "\n", "tok500 = BPE(MERGES[:500])\n", "tok2000 = BPE(MERGES)\n", "print(f\"vocabulary: 256 bytes + 500 merges + 1 special token = {tok500.vocab_size} entries\")\n", "print(f\"end-of-text token id: {tok500.eot_id}\")\n", "\n", "demo = \"Once upon a time, a little girl named Lily found a shiny red ball.\"\n", "ids = tok500.encode(demo)\n", "print(\"\\n\", demo)\n", "print(len(ids), \"tokens:\", ids)\n", "print([tok500.vocab[i].decode() for i in ids])\n", "print(\"sentence in bytes:\", len(demo.encode(\"utf-8\")), \"-> bytes per token:\",\n", " round(len(demo.encode(\"utf-8\")) / len(ids), 2))" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-14" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 · Does it round-trip?\n", "\n", "The promise of a byte-level tokenizer: **any** string encodes, and decoding gives back exactly what\n", "you put in. Check on the 1,000 held-out stories, and on text the tokenizer was never meant for." ], "id": "lab-2-1-tokens-15" }, { "cell_type": "code", "metadata": {}, "source": [ "bad = [i for i, s in enumerate(HELD) if tok500.decode(tok500.encode(s)) != s]\n", "print(f\"round trip on {len(HELD)} held-out stories: {len(HELD) - len(bad)} exact, {len(bad)} different\")\n", "\n", "joined = EOT.join(HELD[:20])\n", "print(\"with end-of-text tokens between stories:\", tok500.decode(tok500.encode(joined)) == joined)\n", "\n", "odd = \"Halo, apa kabar? 日本語のテキスト 😀 café 12345\"\n", "odd_ids = tok500.encode(odd)\n", "print(f\"\\n{odd!r}\\n -> {len(odd_ids)} tokens, round trip exact: {tok500.decode(odd_ids) == odd}\")\n", "print(\" never an 'unknown' token; ids above 255 used:\", sum(1 for i in odd_ids if i > 255), \"of\", len(odd_ids))\n", "\n", "# the pre-splitting pattern must cover every character, or encode would silently drop text\n", "weird = [\"snake_case_name\", \"tab\\tand\\r\\nCRLF\", \"x\\u00b2 + y\\u2082 = z\", \"e\\u0301 combining\", \"\", \" \", \"\\n\\n \\n\",\n", " \"family \\U0001F468\\u200d\\U0001F469\\u200d\\U0001F467\", \"a__b\", \"\\x00\\x1f control\", \"\\u00a0no-break space\"]\n", "ok = [tok500.decode(tok500.encode(t)) == t and \"\".join(SPLIT.findall(t)) == t for t in weird]\n", "print(f\"{sum(ok)} of {len(weird)} odd strings (underscores, tabs, CRLF, combining marks, control characters) round-trip\")" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-16" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7 · Compare with the tokenizers real models use\n", "\n", "`tiktoken` ships the tokenizers of GPT-2 (50,257 entries), GPT-4-era models (`cl100k_base`) and\n", "newer OpenAI models (`o200k_base`). The first call downloads each vocabulary file once. We measure\n", "**bytes per token** on the same held-out stories: more bytes per token means shorter sequences." ], "id": "lab-2-1-tokens-17" }, { "cell_type": "code", "metadata": {}, "source": [ "ENC = {name: tiktoken.get_encoding(name) for name in [\"gpt2\", \"cl100k_base\", \"o200k_base\"]}\n", "for name, e in ENC.items():\n", " print(f\"{name:12} vocabulary {e.n_vocab:,} entries\")\n", "\n", "held_text = EOT.join(HELD)\n", "rows = []\n", "\n", "\n", "def measure(name, count_tokens, vocab_size):\n", " n = sum(count_tokens(s) for s in HELD)\n", " rows.append((name, vocab_size, n))\n", " print(f\"{name:22} vocab {vocab_size:>7,} tokens {n:>8,} bytes/token {held_bytes / n:5.2f} \"\n", " f\"tokens/story {n / len(HELD):6.1f}\")\n", "\n", "\n", "measure(\"bytes (no merges)\", lambda s: len(s.encode(\"utf-8\")), 256)\n", "measure(\"lab BPE, 500 merges\", lambda s: len(tok500.encode(s)), tok500.vocab_size)\n", "measure(\"lab BPE, 2000 merges\", lambda s: len(tok2000.encode(s)), tok2000.vocab_size)\n", "for name, e in ENC.items():\n", " measure(name, lambda s, e=e: len(e.encode(s)), e.n_vocab)" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-18" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Spaces, capitals and special tokens\n", "\n", "`\" the\"` (with a space) and `\"the\"` are different tokens, `\"The\"` is a third one, and the text\n", "`<|endoftext|>` is a *special* token with its own ID that the encoder refuses to produce from plain\n", "user text unless you allow it." ], "id": "lab-2-1-tokens-19" }, { "cell_type": "code", "metadata": {}, "source": [ "gpt2 = ENC[\"gpt2\"]\n", "for s in [\" the\", \"the\", \"The\", \" The\", \" the\"]:\n", " print(f\"{s!r:8} -> {gpt2.encode(s)}\")\n", "print(\"end-of-text id in GPT-2:\", gpt2.encode(EOT, allowed_special={EOT}))\n", "try:\n", " gpt2.encode(\"please stop <|endoftext|> now\")\n", "except ValueError as e:\n", " print(\"default encode refuses the special text:\", str(e).splitlines()[0])\n", "print(\"allowed:\", gpt2.encode(\"please stop <|endoftext|> now\", allowed_special={EOT}))" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-20" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### What tokenization does to letters, digits and spaces\n", "\n", "A model never sees letters, only token IDs. Print how three real tokenizers cut a few strings." ], "id": "lab-2-1-tokens-21" }, { "cell_type": "code", "metadata": {}, "source": [ "def pieces(e, s):\n", " return [e.decode([t]) for t in e.encode(s)]\n", "\n", "\n", "for s in [\"strawberry\", \" strawberry\", \"12345678\", \"1234567890123\", \"ice cream\", \"ice cream \"]:\n", " print(f\"{s!r}\")\n", " for name, e in ENC.items():\n", " print(f\" {name:12} {len(e.encode(s))} tokens {pieces(e, s)}\")" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-22" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8 · Measure: tokens per word, English versus Indonesian\n", "\n", "Three short passages, each written in English and in Indonesian with the same content (about 100\n", "words each; written for this book, not copied). We count tokens with every tokenizer above.\n", "Words are whitespace-separated." ], "id": "lab-2-1-tokens-23" }, { "cell_type": "code", "metadata": {}, "source": [ "EN = {\n", " \"story\": (\n", " \"Rina lived in a small village near the sea. Every morning she walked to the market with her \"\n", " \"grandmother to buy fresh fish and vegetables. One day it began to rain very hard, and the road \"\n", " \"turned into mud. A kind farmer saw them and offered a ride on his cart. They laughed all the way \"\n", " \"home, wet but happy. That evening, Rina's grandmother cooked a hot soup, and the whole family sat \"\n", " \"together at the table. Rina thought it was the best day of the whole year, because nobody was in \"\n", " \"a hurry and everyone had time to talk.\"\n", " ),\n", " \"notice\": (\n", " \"The city council announced on Monday that the main bridge will be closed for repairs for three \"\n", " \"weeks. Drivers are advised to use the northern road, which is longer but has less traffic in the \"\n", " \"morning. Buses will run every ten minutes between the station and the university. The council said \"\n", " \"the work is necessary because engineers found small cracks in the concrete last month. Residents \"\n", " \"who live near the bridge can ask for a free parking permit at the town hall. The mayor thanked \"\n", " \"everyone for their patience and promised to finish the repairs before the school holidays begin.\"\n", " ),\n", " \"science\": (\n", " \"Rain forms when water vapour in the air cools and turns into tiny drops. These drops collect \"\n", " \"around specks of dust and join together inside clouds. When they become heavy enough, they can no \"\n", " \"longer float, so they fall to the ground. In warm weather the drops stay liquid all the way down. \"\n", " \"In very cold weather they freeze and fall as snow or hail. Farmers watch the sky carefully because \"\n", " \"too little rain dries the fields, while too much rain can wash the seeds away. Scientists measure \"\n", " \"rain in millimetres using a simple tool that is shaped like a tall glass.\"\n", " ),\n", "}\n", "ID = {\n", " \"story\": (\n", " \"Rina tinggal di sebuah desa kecil dekat laut. Setiap pagi ia berjalan ke pasar bersama neneknya \"\n", " \"untuk membeli ikan dan sayuran segar. Suatu hari hujan turun sangat deras, dan jalanan berubah \"\n", " \"menjadi lumpur. Seorang petani yang baik hati melihat mereka dan menawarkan tumpangan di atas \"\n", " \"gerobaknya. Mereka tertawa sepanjang jalan pulang, basah tetapi bahagia. Malam itu, nenek Rina \"\n", " \"memasak sup hangat, dan seluruh keluarga duduk bersama di meja makan. Rina merasa itu hari \"\n", " \"terbaik sepanjang tahun, karena tidak ada yang terburu-buru dan semua orang punya waktu untuk \"\n", " \"berbincang.\"\n", " ),\n", " \"notice\": (\n", " \"Dewan kota mengumumkan pada hari Senin bahwa jembatan utama akan ditutup untuk perbaikan selama \"\n", " \"tiga minggu. Pengemudi disarankan memakai jalan utara, yang lebih jauh tetapi lebih sepi pada \"\n", " \"pagi hari. Bus akan berjalan setiap sepuluh menit antara stasiun dan universitas. Dewan \"\n", " \"menyampaikan bahwa pekerjaan ini diperlukan karena para insinyur menemukan retakan kecil pada \"\n", " \"beton bulan lalu. Warga yang tinggal dekat jembatan dapat meminta izin parkir gratis di balai \"\n", " \"kota. Wali kota berterima kasih kepada semua orang atas kesabaran mereka dan berjanji \"\n", " \"menyelesaikan perbaikan sebelum libur sekolah dimulai.\"\n", " ),\n", " \"science\": (\n", " \"Hujan terbentuk ketika uap air di udara mendingin dan berubah menjadi tetesan kecil. Tetesan ini \"\n", " \"berkumpul di sekitar butiran debu dan bergabung di dalam awan. Ketika sudah cukup berat, tetesan \"\n", " \"tidak bisa lagi melayang, sehingga jatuh ke tanah. Pada cuaca hangat, tetesan tetap berupa cairan \"\n", " \"sampai ke bawah. Pada cuaca yang sangat dingin, tetesan membeku dan turun sebagai salju atau \"\n", " \"hujan es. Para petani memperhatikan langit dengan saksama karena hujan yang terlalu sedikit \"\n", " \"membuat ladang kering, sedangkan hujan yang terlalu banyak dapat menghanyutkan benih. Para \"\n", " \"ilmuwan mengukur hujan dalam milimeter memakai alat sederhana yang bentuknya seperti gelas tinggi.\"\n", " ),\n", "}\n", "for lang, passages in [(\"English\", EN), (\"Indonesian\", ID)]:\n", " print(lang, {k: len(v.split()) for k, v in passages.items()}, \"words\")\n", "\n", "TOKENIZERS = {\n", " \"lab BPE, 500 merges\": (lambda t: len(tok500.encode(t)), tok500.vocab_size),\n", " \"lab BPE, 2000 merges\": (lambda t: len(tok2000.encode(t)), tok2000.vocab_size),\n", " \"gpt2\": (lambda t: len(ENC[\"gpt2\"].encode(t)), ENC[\"gpt2\"].n_vocab),\n", " \"cl100k_base\": (lambda t: len(ENC[\"cl100k_base\"].encode(t)), ENC[\"cl100k_base\"].n_vocab),\n", " \"o200k_base\": (lambda t: len(ENC[\"o200k_base\"].encode(t)), ENC[\"o200k_base\"].n_vocab),\n", "}\n", "\n", "tpw_rows = []\n", "for tname, (count, vsize) in TOKENIZERS.items():\n", " for lang, passages in [(\"English\", EN), (\"Indonesian\", ID)]:\n", " for passage, text in list(passages.items()) + [(\"all\", \" \".join(passages.values()))]:\n", " n_words, n_bytes, n_tokens = len(text.split()), len(text.encode(\"utf-8\")), count(text)\n", " tpw_rows.append({\n", " \"language\": lang, \"passage\": passage, \"tokenizer\": tname, \"vocab_size\": vsize,\n", " \"words\": n_words, \"bytes\": n_bytes, \"tokens\": n_tokens,\n", " \"tokens_per_word\": round(n_tokens / n_words, 3),\n", " \"bytes_per_token\": round(n_bytes / n_tokens, 3),\n", " })\n", "\n", "print(f\"\\n{'tokenizer':22} {'English':>22} {'Indonesian':>22} ratio (same content, tokens id/en)\")\n", "print(f\"{'':22} {'tokens (per word)':>22} {'tokens (per word)':>22}\")\n", "for tname in TOKENIZERS:\n", " en = next(r for r in tpw_rows if r[\"tokenizer\"] == tname and r[\"language\"] == \"English\" and r[\"passage\"] == \"all\")\n", " idn = next(r for r in tpw_rows if r[\"tokenizer\"] == tname and r[\"language\"] == \"Indonesian\" and r[\"passage\"] == \"all\")\n", " print(f\"{tname:22} {en['tokens']:>6} ({en['tokens_per_word']:.2f}){'':>8} \"\n", " f\"{idn['tokens']:>6} ({idn['tokens_per_word']:.2f}){'':>8} {idn['tokens'] / en['tokens']:.2f}\")\n", "\n", "with open(out_dir() / \"tokens-per-word.csv\", \"w\", newline=\"\", encoding=\"utf-8\") as f:\n", " w = csv.DictWriter(f, fieldnames=list(tpw_rows[0]))\n", " w.writeheader()\n", " w.writerows(tpw_rows)\n", "print(\"\\nsaved\", out_dir() / \"tokens-per-word.csv\")" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-24" }, { "cell_type": "markdown", "metadata": {}, "source": [ "One passage at a time (so you can see the spread), with GPT-2 and the lab tokenizer:" ], "id": "lab-2-1-tokens-25" }, { "cell_type": "code", "metadata": {}, "source": [ "print(f\"{'passage':8} {'language':11} {'words':>5} {'gpt2 tokens':>11} {'per word':>9} {'lab-500 tokens':>15} {'per word':>9}\")\n", "for passage in EN:\n", " for lang in [\"English\", \"Indonesian\"]:\n", " g = next(r for r in tpw_rows if r[\"tokenizer\"] == \"gpt2\" and r[\"language\"] == lang and r[\"passage\"] == passage)\n", " m = next(r for r in tpw_rows if r[\"tokenizer\"] == \"lab BPE, 500 merges\" and r[\"language\"] == lang and r[\"passage\"] == passage)\n", " print(f\"{passage:8} {lang:11} {g['words']:>5} {g['tokens']:>11} {g['tokens_per_word']:>9.2f} \"\n", " f\"{m['tokens']:>15} {m['tokens_per_word']:>9.2f}\")" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-26" }, { "cell_type": "markdown", "metadata": {}, "source": [ "What does the extra cost look like word by word? The first Indonesian sentence under GPT-2:" ], "id": "lab-2-1-tokens-27" }, { "cell_type": "code", "metadata": {}, "source": [ "first_id = ID[\"story\"].split(\". \")[0] + \".\"\n", "first_en = EN[\"story\"].split(\". \")[0] + \".\"\n", "for label, s in [(\"English\", first_en), (\"Indonesian\", first_id)]:\n", " pieces = [gpt2.decode([t]) for t in gpt2.encode(s)]\n", " print(f\"{label:11} {len(s.split())} words -> {len(pieces)} gpt2 tokens\")\n", " print(\" \", pieces)" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-28" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 9 · Measure: compression against the number of merges\n", "\n", "Because the first `k` merges of the 2,000 are the training result for `k` merges, one tokenizer\n", "can be evaluated at every `k`. We use the 1,000 held-out stories, and also the English and Indonesian\n", "passages from section 8, to see who benefits from more merges." ], "id": "lab-2-1-tokens-29" }, { "cell_type": "code", "metadata": {}, "source": [ "K_LIST = [0, 50, 100, 200, 300, 500, 750, 1000, 1500, 2000]\n", "en_all, id_all = \" \".join(EN.values()), \" \".join(ID.values())\n", "merge_rows = []\n", "for k in K_LIST:\n", " n_tokens = sum(len(tok2000.encode(s, n_merges=k)) for s in HELD)\n", " en_t = len(tok2000.encode(en_all, n_merges=k))\n", " id_t = len(tok2000.encode(id_all, n_merges=k))\n", " merge_rows.append({\n", " \"merges\": k, \"vocab_size\": 257 + k, \"tokens\": n_tokens, \"bytes\": held_bytes,\n", " \"bytes_per_token\": round(held_bytes / n_tokens, 3),\n", " \"en_tokens_per_word\": round(en_t / len(en_all.split()), 3),\n", " \"id_tokens_per_word\": round(id_t / len(id_all.split()), 3),\n", " })\n", "print(f\"{'merges':>6} {'vocab':>6} {'tokens':>9} {'bytes/token':>11} {'en tok/word':>12} {'id tok/word':>12}\")\n", "for r in merge_rows:\n", " print(f\"{r['merges']:>6} {r['vocab_size']:>6} {r['tokens']:>9,} {r['bytes_per_token']:>11.3f} \"\n", " f\"{r['en_tokens_per_word']:>12.3f} {r['id_tokens_per_word']:>12.3f}\")\n", "\n", "with open(out_dir() / \"merges.csv\", \"w\", newline=\"\", encoding=\"utf-8\") as f:\n", " w = csv.DictWriter(f, fieldnames=list(merge_rows[0]))\n", " w.writeheader()\n", " w.writerows(merge_rows)\n", "print(\"\\nsaved\", out_dir() / \"merges.csv\")" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-30" }, { "cell_type": "markdown", "metadata": {}, "source": [ "The three options of section 3, side by side, with the real tokenizers (the table behind the chapter's trade-off):" ], "id": "lab-2-1-tokens-31" }, { "cell_type": "code", "metadata": {}, "source": [ "option_rows = [\n", " {\"option\": \"bytes\", \"vocab_size\": 256, \"tokens\": held_bytes, \"unknown_tokens\": 0},\n", " {\"option\": \"words and punctuation (training vocabulary)\", \"vocab_size\": len(train_words),\n", " \"tokens\": len(held_words), \"unknown_tokens\": unknown_tokens},\n", "]\n", "for k in (500, 2000):\n", " n = next(r[\"tokens\"] for r in merge_rows if r[\"merges\"] == k)\n", " option_rows.append({\"option\": f\"BPE, {k} merges\", \"vocab_size\": 257 + k, \"tokens\": n, \"unknown_tokens\": 0})\n", "for name in ENC:\n", " option_rows.append({\"option\": name, \"vocab_size\": ENC[name].n_vocab,\n", " \"tokens\": next(n for nm, _, n in rows if nm == name), \"unknown_tokens\": 0})\n", "print(f\"{'option':46} {'vocab':>8} {'tokens':>10} {'unknown':>8}\")\n", "for r in option_rows:\n", " print(f\"{r['option']:46} {r['vocab_size']:>8,} {r['tokens']:>10,} {r['unknown_tokens']:>8,}\")\n", "with open(out_dir() / \"options.csv\", \"w\", newline=\"\", encoding=\"utf-8\") as f:\n", " w = csv.DictWriter(f, fieldnames=list(option_rows[0]))\n", " w.writeheader()\n", " w.writerows(option_rows)" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-32" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Plots" ], "id": "lab-2-1-tokens-33" }, { "cell_type": "code", "metadata": {}, "source": [ "try:\n", " import matplotlib.pyplot as plt\n", "\n", " fig, ax = plt.subplots(1, 2, figsize=(11, 3.6))\n", " ax[0].plot([r[\"vocab_size\"] for r in merge_rows], [r[\"bytes_per_token\"] for r in merge_rows], \"o-\")\n", " ax[0].axhline(held_bytes / next(n for name, _, n in rows if name == \"gpt2\"), ls=\"--\", c=\"grey\", label=\"gpt2\")\n", " ax[0].set(xlabel=\"vocabulary size (257 + merges)\", ylabel=\"bytes per token\", title=\"compression vs merges\")\n", " ax[0].legend()\n", " names = list(TOKENIZERS)\n", " for j, lang in enumerate([\"English\", \"Indonesian\"]):\n", " vals = [next(r[\"tokens_per_word\"] for r in tpw_rows if r[\"tokenizer\"] == n and r[\"language\"] == lang and r[\"passage\"] == \"all\") for n in names]\n", " ax[1].bar([i + 0.4 * j for i in range(len(names))], vals, width=0.4, label=lang)\n", " ax[1].set_xticks([i + 0.2 for i in range(len(names))])\n", " ax[1].set_xticklabels(names, rotation=25, ha=\"right\")\n", " ax[1].set(ylabel=\"tokens per word\", title=\"same content, two languages\")\n", " ax[1].legend()\n", " plt.tight_layout()\n", " plt.show()\n", "except ImportError:\n", " print(\"matplotlib not installed: skipping the plots\")" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-34" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 10 · Export the merge table (for the book's tokenizer explorer)\n", "\n", "The explorer in Ch 2.1 runs the same encoder in your browser. It needs the pre-splitting pattern,\n", "the 500 merges, the bytes of every token, and a few test strings with the IDs this notebook produced,\n", "so the browser version can prove it agrees." ], "id": "lab-2-1-tokens-35" }, { "cell_type": "code", "metadata": {}, "source": [ "golden = [\n", " \"Once upon a time, a little girl named Lily found a shiny red ball.\",\n", " \"The cat sat on the mat. The cats sat on the mats.\",\n", " \"Halo, apa kabar? Saya sedang belajar.\",\n", " \"café 日本語 😀\",\n", " \"12345 + 678 = 13023\",\n", " \"snake_case_name = 1\",\n", " \" two spaces and\\nnewline\",\n", "]\n", "export = {\n", " \"description\": \"Lab 2.1 byte-pair encoder: 256 byte tokens + 500 merges + one special token, trained on \"\n", " \"2,500 TinyStories validation stories. Encode = split with `pattern`, turn each piece into \"\n", " \"UTF-8 bytes, then repeatedly apply the lowest-rank merge present (merge i makes id 256+i).\",\n", " \"pattern_python\": PATTERN,\n", " \"pattern_js\": r\" ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+\",\n", " \"pattern_js_flags\": \"gu\",\n", " \"n_merges\": 500,\n", " \"special\": {EOT: tok500.eot_id},\n", " \"merges\": [list(m) for m in MERGES[:500]],\n", " \"vocab_hex\": [tok500.vocab[i].hex() for i in range(256 + 500)],\n", " \"golden\": [{\"text\": s, \"ids\": tok500.encode(s)} for s in golden],\n", "}\n", "path = out_dir() / \"tokenizer-merges.json\"\n", "path.write_text(json.dumps(export, ensure_ascii=False, indent=1) + \"\\n\", encoding=\"utf-8\")\n", "print(\"saved\", path, f\"({path.stat().st_size:,} bytes)\")\n", "for g in export[\"golden\"]:\n", " print(f\"{len(g['ids']):>3} tokens {g['text']!r}\")" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-36" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 11 · Checkpoint\n", "\n", "Your run prints these lines (the data is fixed, so they should match exactly; only training times differ):\n", "\n", "```text\n", "3686 stories in the slice; train 2500 stories (1,991,971 bytes), held out 1000 stories (797,839 bytes)\n", "held out: 193,286 running words, 1,226 not in the vocabulary (0.63 %), 581 different unknown words\n", " 1 'e' + 's' 9 256 = 'es' <- toy corpus, merge 1\n", " 8 'd' + 'est' 3 263 = 'dest' <- toy corpus, merge 8\n", " 1 'he' 'h' + 'e' 57,896 <- TinyStories, merge 1\n", " 6 ' the' ' t' + 'he' 26,365\n", "vocabulary: 256 bytes + 500 merges + 1 special token = 757 entries\n", "round trip on 1000 held-out stories: 1000 exact, 0 different\n", "lab BPE, 500 merges vocab 757 tokens 277,779 bytes/token 2.87\n", "lab BPE, 2000 merges vocab 2,257 tokens 215,722 bytes/token 3.70\n", "gpt2 vocab 50,257 tokens 196,213 bytes/token 4.07\n", "gpt2 342 (1.13) 706 (2.59) ratio 2.06 <- English / Indonesian tokens (per word), same content\n", "```\n", "\n", "You are done with the build part when the round trip is exact on all 1,000 stories, your 500-merge\n", "tokenizer lands near 2.87 bytes per token, and you can say in one sentence why the Indonesian\n", "passages cost about twice the tokens of the English ones under GPT-2." ], "id": "lab-2-1-tokens-37" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 12 · Explore\n", "\n", "| Knob | Try | Question |\n", "| --- | --- | --- |\n", "| Number of merges | edit `K_LIST` in section 9 (try 20, 3000) | Where does the gain per merge flatten? Does the Indonesian curve move as much as the English one? |\n", "| Training corpus | the next cell trains on stories plus a little Indonesian | How much does a small share of Indonesian lower its tokens per word, and what happens to English? |\n", "| Pre-splitting | the cell after it trains with and without the regex | Which merges appear without pre-splitting that the pre-split run can never make? |\n", "| The tie-break rule | change `-kv[0][0], -kv[0][1]` in `train_bpe` | Do the merge counts change? Does the final compression? |" ], "id": "lab-2-1-tokens-38" }, { "cell_type": "code", "metadata": {}, "source": [ "# Explore 1: a tokenizer trained on stories plus a little Indonesian (a toy: the same short Indonesian\n", "# text counted REPEAT times, about 5 % of the training bytes). Measured on the section 8 passages.\n", "ID_TRAIN = (\n", " \"Pagi itu Budi bangun lebih awal dari biasanya. Ia mencuci muka, memakai seragam sekolah, lalu sarapan \"\n", " \"nasi goreng bersama ibu dan adiknya. Di halaman rumah, ayam-ayam berlarian mencari makanan. Budi \"\n", " \"mengambil tasnya dan berjalan kaki ke sekolah bersama teman-temannya. Di jalan mereka melihat seorang \"\n", " \"bapak sedang menjual buah-buahan di pinggir jalan. Budi membeli dua buah jeruk dan membaginya dengan \"\n", " \"temannya. Sesampainya di sekolah, guru sudah menunggu di depan kelas. Hari ini mereka belajar menulis \"\n", " \"cerita tentang keluarga. Budi menulis tentang ibunya yang selalu memasak dengan penuh cinta. Siang \"\n", " \"hari, hujan turun dan anak-anak bermain di bawah atap sekolah. Setelah pulang, Budi membantu ayahnya \"\n", " \"membersihkan kebun. Mereka menanam sayuran dan menyiram tanaman sampai sore. Malam itu keluarga makan \"\n", " \"bersama di meja, dan semua orang bercerita tentang harinya. Budi tidur dengan senang karena besok \"\n", " \"adalah hari libur dan ia ingin pergi ke pantai bersama kakeknya.\"\n", ")\n", "REPEAT = 120\n", "id_pieces = Counter(p.encode(\"utf-8\") for p in SPLIT.findall(ID_TRAIN))\n", "mixed_counts = piece_counts + Counter({p: c * REPEAT for p, c in id_pieces.items()})\n", "id_bytes_share = REPEAT * len(ID_TRAIN.encode(\"utf-8\")) / (train_bytes + REPEAT * len(ID_TRAIN.encode(\"utf-8\")))\n", "print(f\"ID_TRAIN: {len(ID_TRAIN.split())} words; Indonesian share of training bytes: {100 * id_bytes_share:.1f} %\")\n", "\n", "mixed_merges, _ = train_bpe(mixed_counts, 500)\n", "tok_mixed = BPE(mixed_merges)\n", "for name, t in [(\"English-only, 500 merges\", tok500), (\"English + 5 % Indonesian, 500 merges\", tok_mixed)]:\n", " en_n, id_n = len(t.encode(en_all)), len(t.encode(id_all))\n", " held_n = sum(len(t.encode(s)) for s in HELD)\n", " print(f\"{name:40} English {en_n / len(en_all.split()):.3f} tok/word | Indonesian {id_n / len(id_all.split()):.3f} tok/word \"\n", " f\"| held-out stories {held_bytes / held_n:.3f} bytes/token\")" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-39" }, { "cell_type": "code", "metadata": {}, "source": [ "# Explore 2: pre-splitting on and off. Without it, each whole story is one piece, so merges can cross\n", "# word boundaries. Small slice (100 stories, 200 merges) because the \"off\" run is much slower.\n", "small_train, small_eval = TRAIN[:100], HELD[:100]\n", "small_bytes = sum(len(s.encode(\"utf-8\")) for s in small_eval)\n", "\n", "t0 = time.time()\n", "on_merges, _ = train_bpe(Counter(p.encode(\"utf-8\") for s in small_train for p in SPLIT.findall(s)), 200)\n", "t_on = time.time() - t0\n", "t0 = time.time()\n", "off_merges, _ = train_bpe(Counter(s.encode(\"utf-8\") for s in small_train), 200)\n", "t_off = time.time() - t0\n", "\n", "on_tokens = sum(len(BPE(on_merges).encode(s)) for s in small_eval)\n", "t0 = time.time()\n", "off_tok = BPE(off_merges)\n", "off_tokens = sum(len(encode_piece(s, off_merges)) for s in small_eval)\n", "print(f\"pre-split ON : train {t_on:5.1f} s, {on_tokens:,} tokens, {small_bytes / on_tokens:.3f} bytes/token on held-out\")\n", "print(f\"pre-split OFF: train {t_off:5.1f} s, {off_tokens:,} tokens, {small_bytes / off_tokens:.3f} bytes/token on held-out\")\n", "for label, merges in [(\"ON \", on_merges), (\"OFF\", off_merges)]:\n", " v = vocab_of(merges)\n", " print(label, \"first 12 merged tokens:\", [v[256 + i].decode(\"utf-8\", errors=\"replace\") for i in range(12)])\n", "cross = [v for v in (vocab_of(off_merges)[256 + i] for i in range(200))\n", " if len(SPLIT.findall(v.decode(\"utf-8\", errors=\"replace\"))) > 1]\n", "print(f\"OFF: {len(cross)} of its 200 merged tokens span two or more pre-split pieces, e.g.\",\n", " [c.decode(\"utf-8\", errors=\"replace\") for c in cross[:8]])" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-40" }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 13 · Failure playground\n", "\n", "Three things that go wrong with tokenizers in practice. For each: run it, read the symptom, find the\n", "cause, and fix it. Hints are in Review 2.1; answers are not." ], "id": "lab-2-1-tokens-41" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 13a · The bill that was twice as big as the estimate\n", "\n", "A team plans to translate 1,000,000 words of Indonesian documents with an API that bills per token.\n", "They use the rule of thumb they remember for English text: **1.3 tokens per word**." ], "id": "lab-2-1-tokens-42" }, { "cell_type": "code", "metadata": {}, "source": [ "words_to_process = 1_000_000\n", "assumed_tokens_per_word = 1.3\n", "estimate = int(words_to_process * assumed_tokens_per_word)\n", "print(f\"estimate: {estimate:,} tokens\")\n", "\n", "sample = \" \".join(ID.values())\n", "actual_per_word = len(ENC[\"gpt2\"].encode(sample)) / len(sample.split())\n", "print(f\"actual (gpt2 tokenizer on an Indonesian sample): {int(words_to_process * actual_per_word):,} tokens\")\n", "context = 4096\n", "print(f\"a {context}-token window holds about {int(context / assumed_tokens_per_word):,} words of English \"\n", " f\"by the rule of thumb, and {int(context / actual_per_word):,} words of this Indonesian sample\")" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-43" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: the invoice is far higher than the estimate, and long documents no longer fit the context\n", "window the team planned for. Where did the rule of thumb come from, why does it not transfer, and\n", "how should the team estimate cost *before* sending the job? (Do the same estimate with `o200k_base`.)" ], "id": "lab-2-1-tokens-44" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 13b · A streamed answer with replacement characters\n", "\n", "A chat server sends the model's output to the browser one token at a time, decoding each ID on its own." ], "id": "lab-2-1-tokens-45" }, { "cell_type": "code", "metadata": {}, "source": [ "text = \"Halo 日本語 😀\"\n", "ids = ENC[\"gpt2\"].encode(text)\n", "print(\"ids:\", ids)\n", "streamed = \"\".join(ENC[\"gpt2\"].decode([i]) for i in ids)\n", "print(\"decoded all at once: \", ENC[\"gpt2\"].decode(ids))\n", "print(\"decoded token by token:\", streamed)\n", "print(\"lab tokenizer, per token:\", [tok500.decode([i]) for i in tok500.encode(\"日😀\")])" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-46" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: `�` appears in the streamed text, although decoding all the IDs at once is perfect. Look at\n", "the bytes behind each token (`ENC[\"gpt2\"].decode_single_token_bytes(i)`). What is a token boundary\n", "allowed to cut, and what must a streaming decoder do before it shows text?" ], "id": "lab-2-1-tokens-47" }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 13c · The wrong tokenizer" ], "id": "lab-2-1-tokens-48" }, { "cell_type": "code", "metadata": {}, "source": [ "text = \"Once upon a time there was a little girl.\"\n", "mine = tok500.encode(text)\n", "print(\"encoded with the lab tokenizer:\", mine)\n", "print(\"decoded with GPT-2's tokenizer:\", repr(ENC[\"gpt2\"].decode(mine)))\n", "theirs = ENC[\"gpt2\"].encode(text)\n", "print(\"encoded with GPT-2's tokenizer:\", theirs)\n", "try:\n", " print(\"decoded with the lab tokenizer:\", repr(tok500.decode(theirs)))\n", "except KeyError as e:\n", " print(\"decoding with the lab tokenizer failed: KeyError\", e)" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-49" }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symptom: garbage text in one direction, a crash in the other, and no error at all if the IDs happen\n", "to be in range. Why does a token ID mean nothing without its tokenizer, and what must always be\n", "stored or shipped together with a model's weights?" ], "id": "lab-2-1-tokens-50" }, { "cell_type": "code", "metadata": {}, "source": [ "print(\n", " \"Versions tested:\",\n", " f\"Python {platform.python_version()},\",\n", " f\"tiktoken {importlib.metadata.version('tiktoken')},\",\n", " end=\" \",\n", ")\n", "try:\n", " import matplotlib\n", " print(f\"matplotlib {matplotlib.__version__},\", end=\" \")\n", "except ImportError:\n", " pass\n", "print(f\"{platform.system()} {platform.machine()}\")" ], "execution_count": null, "outputs": [], "id": "lab-2-1-tokens-51" } ] }