{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a2e9dc2c",
   "metadata": {},
   "source": [
    "# 03 · BPE: merge order and corpus frequencies\n",
    "**About 20 minutes · independent of other units**\n",
    "\n",
    "Take `abab`. Merging `a` with `b` gives `[ab, ab]`, and merging `ab` with `ab` gives `[abab]`, with new IDs 256 and 257. This notebook reproduces that example, then changes one condition at a time.\n",
    "\n",
    "**You will be able to:** distinguish rules from vocabulary entries; explain merge priority; observe how corpus frequencies affect candidate merges.\n",
    "\n",
    "This notebook is a small laboratory. It does not contain an assignment tokenizer class or a BPE training loop."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "122b4bbc",
   "metadata": {},
   "source": [
    "## 1 · Start with bytes and supply two learned rules\n",
    "Here IDs 0–255 are explicitly assigned to their matching single-byte values. We then add two entries. This is a **toy convention**, not a promise about every tokenizer's ID assignment.\n",
    "\n",
    "The rules are supplied, as if training had already finished. Their position in the list is the priority.\n",
    "\n",
    "**Python:** `bytes([n])` constructs one byte; `bytes(n)` constructs `n` zero bytes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "34ea20c0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:34.544078Z",
     "iopub.status.busy": "2026-11-15T02:04:34.543927Z",
     "iopub.status.idle": "2026-11-15T02:04:34.549510Z",
     "shell.execute_reply": "2026-11-15T02:04:34.548975Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initial pieces: [b'a', b'b', b'a', b'b']\n",
      "Rules in priority order: [(b'a', b'b'), (b'ab', b'ab')]\n"
     ]
    }
   ],
   "source": [
    "vocabulary = {value: bytes([value]) for value in range(256)}\n",
    "vocabulary[256] = b\"ab\"\n",
    "vocabulary[257] = b\"abab\"\n",
    "rules = [(b\"a\", b\"b\"), (b\"ab\", b\"ab\")]\n",
    "text = \"abab\"\n",
    "initial_pieces = [bytes([value]) for value in text.encode(\"utf-8\")]\n",
    "print(\"Initial pieces:\", initial_pieces)\n",
    "print(\"Rules in priority order:\", rules)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "032b1761",
   "metadata": {},
   "source": [
    "## 2 · Inspect one merge pass\n",
    "This function handles just one chosen pair in a list of byte pieces. Reading left to right, a matched pair is replaced by its concatenation and those two positions are consumed. The same piece cannot participate in two overlapping merges in that pass.\n",
    "\n",
    "Read the function, then predict each displayed stage for `abab`.\n",
    "\n",
    "**Python:** `list.copy()` is shallow; `append(x)` adds one element. Byte strings are immutable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "41c6151b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:34.551260Z",
     "iopub.status.busy": "2026-11-15T02:04:34.551119Z",
     "iopub.status.idle": "2026-11-15T02:04:34.555213Z",
     "shell.execute_reply": "2026-11-15T02:04:34.554579Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Rule 1 (b'a', b'b') → [b'ab', b'ab']\n",
      "Rule 2 (b'ab', b'ab') → [b'abab']\n",
      "Final IDs: [257]\n"
     ]
    }
   ],
   "source": [
    "def merge_one_pair(pieces, pair):\n",
    "    result = []\n",
    "    position = 0\n",
    "    while position < len(pieces):\n",
    "        if position + 1 < len(pieces) and (pieces[position], pieces[position + 1]) == pair:\n",
    "            result.append(pieces[position] + pieces[position + 1])\n",
    "            position += 2\n",
    "        else:\n",
    "            result.append(pieces[position])\n",
    "            position += 1\n",
    "    return result\n",
    "\n",
    "pieces = initial_pieces.copy()\n",
    "for rank, pair in enumerate(rules, start=1):\n",
    "    pieces = merge_one_pair(pieces, pair)\n",
    "    print(\"Rule\", rank, pair, \"→\", pieces)\n",
    "    assert b\"\".join(pieces) == text.encode(\"utf-8\")\n",
    "bytes_to_id = {piece: token_id for token_id, piece in vocabulary.items()}\n",
    "print(\"Final IDs:\", [bytes_to_id[piece] for piece in pieces])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eab170b4",
   "metadata": {},
   "source": [
    "## 3 · Vocabulary membership alone does not determine segmentation\n",
    "Consider `abc` and a vocabulary containing both `ab` and `bc`. Two rule priority orders lead to different pieces, while reconstructing the same original bytes. We compare two hypothetical learned tokenizers; arbitrary rule reorderings are not necessarily valid training histories.\n",
    "\n",
    "**Predict:** which rule prevents the other rule from matching in each case?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "608edb1b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:34.556416Z",
     "iopub.status.busy": "2026-11-15T02:04:34.556337Z",
     "iopub.status.idle": "2026-11-15T02:04:34.559044Z",
     "shell.execute_reply": "2026-11-15T02:04:34.558376Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[(b'a', b'b'), (b'b', b'c')] → [b'ab', b'c']\n",
      "[(b'b', b'c'), (b'a', b'b')] → [b'a', b'bc']\n"
     ]
    }
   ],
   "source": [
    "start = [b\"a\", b\"b\", b\"c\"]\n",
    "for ordered_rules in [\n",
    "    [(b\"a\", b\"b\"), (b\"b\", b\"c\")],\n",
    "    [(b\"b\", b\"c\"), (b\"a\", b\"b\")],\n",
    "]:\n",
    "    pieces = start.copy()\n",
    "    for pair in ordered_rules:\n",
    "        pieces = merge_one_pair(pieces, pair)\n",
    "    print(ordered_rules, \"→\", pieces)\n",
    "    assert b\"\".join(pieces) == b\"abc\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aa6168e8",
   "metadata": {},
   "source": [
    "## 4 · Overlapping observations versus actual replacements\n",
    "The sequence `aaa` contains two adjacent `aa` windows. But a single non-overlapping replacement pass can only merge one of them.\n",
    "\n",
    "This is an important distinction between **counting candidate windows** and **applying a merge**.\n",
    "\n",
    "**Python:** `zip()` pairs iterables up to the shorter length; `Counter` counts the resulting tuple keys."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "a999502c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:34.560089Z",
     "iopub.status.busy": "2026-11-15T02:04:34.560016Z",
     "iopub.status.idle": "2026-11-15T02:04:34.562407Z",
     "shell.execute_reply": "2026-11-15T02:04:34.561954Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Adjacent windows: Counter({(b'a', b'a'): 2})\n",
      "After one pass: [b'aa', b'a']\n"
     ]
    }
   ],
   "source": [
    "from collections import Counter\n",
    "\n",
    "pieces = [b\"a\", b\"a\", b\"a\"]\n",
    "counts = Counter(zip(pieces, pieces[1:]))\n",
    "print(\"Adjacent windows:\", counts)\n",
    "merged = merge_one_pair(pieces, (b\"a\", b\"a\"))\n",
    "print(\"After one pass:\", merged)\n",
    "assert b\"\".join(merged) == b\"aaa\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "033fb5b0",
   "metadata": {},
   "source": [
    "## 5 · Where do the rules come from?\n",
    "During training, pair counts depend on the corpus and on earlier merges. To isolate just the first choice, the next experiment counts adjacent raw-byte pairs separately inside short documents. Document boundaries are deliberately preserved.\n",
    "\n",
    "**Predict:** will changing the mix of documents change the most frequent pair?\n",
    "\n",
    "**Python:** `Counter.update()` adds occurrences; `most_common(n)` returns the highest counts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "9abd3186",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:34.563554Z",
     "iopub.status.busy": "2026-11-15T02:04:34.563488Z",
     "iopub.status.idle": "2026-11-15T02:04:34.565916Z",
     "shell.execute_reply": "2026-11-15T02:04:34.565369Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mostly ab → [((b'a', b'b'), 5), ((b'b', b'a'), 3), ((b'x', b'y'), 1)]\n",
      "mostly xy → [((b'x', b'y'), 5), ((b'y', b'x'), 3), ((b'a', b'b'), 1)]\n"
     ]
    }
   ],
   "source": [
    "corpora = {\n",
    "    \"mostly ab\": [b\"ababab\", b\"abab\", b\"xy\"],\n",
    "    \"mostly xy\": [b\"xyxyxy\", b\"xyxy\", b\"ab\"],\n",
    "}\n",
    "for name, documents in corpora.items():\n",
    "    counts = Counter()\n",
    "    for document in documents:\n",
    "        pieces = [bytes([value]) for value in document]\n",
    "        counts.update(zip(pieces, pieces[1:]))\n",
    "    print(name, \"→\", counts.most_common(3))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9a50b628",
   "metadata": {},
   "source": [
    "## Your experiment · propose one next merge\n",
    "Edit `documents`. Inspect the pair counts, then choose `chosen_pair` yourself and rerun the following cell. Equal counts require a tie-breaking convention; do not infer a universal one from this toy display."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "90acd8ec",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:34.566814Z",
     "iopub.status.busy": "2026-11-15T02:04:34.566748Z",
     "iopub.status.idle": "2026-11-15T02:04:34.568735Z",
     "shell.execute_reply": "2026-11-15T02:04:34.568275Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Candidate pairs: [((b'a', b'n'), 6), ((b'n', b'a'), 5), ((b'b', b'a'), 3), ((b'n', b'd'), 1), ((b'd', b'a'), 1)]\n"
     ]
    }
   ],
   "source": [
    "documents = [b\"banana\", b\"banana\", b\"bandana\"]\n",
    "counts = Counter()\n",
    "for document in documents:\n",
    "    parts = [bytes([value]) for value in document]\n",
    "    counts.update(zip(parts, parts[1:]))\n",
    "print(\"Candidate pairs:\", counts.most_common())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "192d6886",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:34.569708Z",
     "iopub.status.busy": "2026-11-15T02:04:34.569641Z",
     "iopub.status.idle": "2026-11-15T02:04:34.571905Z",
     "shell.execute_reply": "2026-11-15T02:04:34.571434Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b'banana' → [b'b', b'an', b'an', b'a'] pieces: 6 → 4\n",
      "b'banana' → [b'b', b'an', b'an', b'a'] pieces: 6 → 4\n",
      "b'bandana' → [b'b', b'an', b'd', b'an', b'a'] pieces: 7 → 5\n"
     ]
    }
   ],
   "source": [
    "chosen_pair = (b\"a\", b\"n\")\n",
    "for document in documents:\n",
    "    parts = [bytes([value]) for value in document]\n",
    "    after = merge_one_pair(parts, chosen_pair)\n",
    "    print(document, \"→\", after, \"pieces:\", len(parts), \"→\", len(after))\n",
    "    assert b\"\".join(after) == document"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd3d91f6",
   "metadata": {},
   "source": [
    "## What you found\n",
    "- My corpus, selected pair, and observations:\n",
    "- What changes during tokenizer training:\n",
    "- What stays fixed when encoding new text:\n",
    "- Why a frequent token need not be a meaningful word:\n",
    "- Why a vocabulary and an ordered merge list are different information:\n",
    "\n",
    "**Toward the CS336 tokenizer:** you can now reason about byte preservation, overlapping pairs, and deterministic rule priority on examples small enough to inspect by hand. A full tokenizer must additionally handle boundaries, special tokens, efficiency, and arbitrary inputs.\n",
    "\n",
    "**Reference:** [CS336 lecture 1](https://cs336.stanford.edu/lectures/?trace=lecture_01)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (CS336 environment)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
