{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cbcbbb68",
   "metadata": {},
   "source": [
    "# 04 · Inspect a real tokenizer\n",
    "**About 15–20 minutes · independent of other units**\n",
    "\n",
    "A BPE vocabulary is learned from data, so its tokens are chunks that were frequent in that data, and some of them look like meaningful words. Here we inspect the outputs of the already-installed `tiktoken` library as a measuring instrument. We use its API, not its implementation.\n",
    "\n",
    "**You will be able to:** distinguish bytes from token IDs on real inputs; measure bytes per token; check exact reconstruction; observe how whitespace and text changes affect segmentation.\n",
    "\n",
    "The fixed encoding is **GPT-2**, so the vocabulary does not change when you edit the examples. Loading its encoding may download a cached vocabulary file on the first run. There is no model inference or API key involved."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d84c56fd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:35.129431Z",
     "iopub.status.busy": "2026-11-15T02:04:35.129273Z",
     "iopub.status.idle": "2026-11-15T02:04:35.228732Z",
     "shell.execute_reply": "2026-11-15T02:04:35.228417Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Encoding: gpt2\n",
      "Vocabulary size: 50257\n"
     ]
    }
   ],
   "source": [
    "import tiktoken\n",
    "\n",
    "encoding = tiktoken.get_encoding(\"gpt2\")\n",
    "print(\"Encoding:\", encoding.name)\n",
    "print(\"Vocabulary size:\", encoding.n_vocab)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd4e4c17",
   "metadata": {},
   "source": [
    "## 1 · Inspect token IDs and the bytes they identify\n",
    "**Predict:** does the leading space belong to a token? Does one token always decode cleanly on its own?\n",
    "\n",
    "The display uses UTF-8 replacement characters only for readability. Those replacement characters are not changes to the token's actual bytes.\n",
    "\n",
    "**Python:** `encode_ordinary()` returns IDs; `decode_single_token_bytes()` retrieves one token’s byte payload."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "14b33e13",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:35.229685Z",
     "iopub.status.busy": "2026-11-15T02:04:35.229633Z",
     "iopub.status.idle": "2026-11-15T02:04:35.231814Z",
     "shell.execute_reply": "2026-11-15T02:04:35.231530Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Text: 'hello world! 猫🙂'\n",
      "IDs: [31373, 995, 0, 13328, 234, 104, 8582, 25081]\n",
      "      ID  bytes                           display only\n",
      "   31373  b'hello'                        'hello'\n",
      "     995  b' world'                       ' world'\n",
      "       0  b'!'                            '!'\n",
      "   13328  b' \\xe7'                        ' �'\n",
      "     234  b'\\x8c'                         '�'\n",
      "     104  b'\\xab'                         '�'\n",
      "    8582  b'\\xf0\\x9f'                     '�'\n",
      "   25081  b'\\x99\\x82'                     '��'\n",
      "Exact reconstruction: PASS\n"
     ]
    }
   ],
   "source": [
    "text = \"hello world! 猫🙂\"\n",
    "ids = encoding.encode_ordinary(text)\n",
    "print(\"Text:\", repr(text))\n",
    "print(\"IDs:\", ids)\n",
    "print(f'{\"ID\":>8}  {\"bytes\":30}  display only')\n",
    "for token_id in ids:\n",
    "    payload = encoding.decode_single_token_bytes(token_id)\n",
    "    print(f'{token_id:>8}  {str(payload):30}  {payload.decode(\"utf-8\", errors=\"replace\")!r}')\n",
    "payload = b\"\".join(encoding.decode_single_token_bytes(i) for i in ids)\n",
    "assert payload == text.encode(\"utf-8\")\n",
    "assert encoding.decode(ids) == text\n",
    "print(\"Exact reconstruction: PASS\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f6b08916",
   "metadata": {},
   "source": [
    "## 2 · Compare byte length and token length\n",
    "Bytes per token is an observable compression measure here, not a score of how meaningful the words are. These examples are not matched translations, so they cannot establish a language ranking.\n",
    "\n",
    "**Predict:** will repeating a letter, changing case, or adding spaces preserve the token count?\n",
    "\n",
    "**Python:** Empty lists are falsey. `x if condition else y` selects a value; `:.2f` displays two decimal places."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "2ef2b4ea",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:35.232608Z",
     "iopub.status.busy": "2026-11-15T02:04:35.232565Z",
     "iopub.status.idle": "2026-11-15T02:04:35.234627Z",
     "shell.execute_reply": "2026-11-15T02:04:35.234322Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "text                              bytes  tokens  bytes/token\n",
      "'hello'                               5       1         5.00\n",
      "' hello'                              6       1         6.00\n",
      "'Hello'                               5       1         5.00\n",
      "'HELLO'                               5       3         1.67\n",
      "'tokenization'                       12       2         6.00\n",
      "'tokenization tokenization'          25       4         6.25\n",
      "'猫喜欢阳光。'                             18      14         1.29\n",
      "'🙂🙂🙂'                                12       6         2.00\n",
      "'aaaaaaaaaaaa'                       12       3         4.00\n",
      "'   '                                 3       3         1.00\n",
      "''                                    0       0          n/a\n"
     ]
    }
   ],
   "source": [
    "samples = [\n",
    "    \"hello\", \" hello\", \"Hello\", \"HELLO\",\n",
    "    \"tokenization\", \"tokenization tokenization\",\n",
    "    \"猫喜欢阳光。\", \"🙂🙂🙂\", \"aaaaaaaaaaaa\", \"   \", \"\",\n",
    "]\n",
    "print(f'{\"text\":32} {\"bytes\":>6} {\"tokens\":>7} {\"bytes/token\":>12}')\n",
    "for sample in samples:\n",
    "    token_ids = encoding.encode_ordinary(sample)\n",
    "    byte_count = len(sample.encode(\"utf-8\"))\n",
    "    ratio = f\"{byte_count / len(token_ids):.2f}\" if token_ids else \"n/a\"\n",
    "    print(f'{sample!r:32} {byte_count:>6} {len(token_ids):>7} {ratio:>12}')\n",
    "    assert encoding.decode(token_ids) == sample"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d20a1468",
   "metadata": {},
   "source": [
    "## 3 · Encoding parts separately can change segmentation\n",
    "A tokenizer can be lossless while `encode(left) + encode(right)` differs from `encode(left + right)`. A boundary can prevent merges that would otherwise be available.\n",
    "\n",
    "**Predict:** what happens if a stream splits `hello` into `hel` and `lo`?\n",
    "\n",
    "**Python:** `+` concatenates strings and lists; it does not add the IDs elementwise."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "244b1101",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:35.235349Z",
     "iopub.status.busy": "2026-11-15T02:04:35.235301Z",
     "iopub.status.idle": "2026-11-15T02:04:35.236988Z",
     "shell.execute_reply": "2026-11-15T02:04:35.236732Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Separate: [2978, 5439]\n",
      "Together: [31373]\n",
      "Same token IDs: False\n"
     ]
    }
   ],
   "source": [
    "left, right = \"hel\", \"lo\"\n",
    "separate = encoding.encode_ordinary(left) + encoding.encode_ordinary(right)\n",
    "together = encoding.encode_ordinary(left + right)\n",
    "print(\"Separate:\", separate)\n",
    "print(\"Together:\", together)\n",
    "print(\"Same token IDs:\", separate == together)\n",
    "assert encoding.decode(separate) == left + right\n",
    "assert encoding.decode(together) == left + right"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a33b9cc",
   "metadata": {},
   "source": [
    "## 4 · Special-token policy is explicit\n",
    "The string `<|endoftext|>` can mean literal text or a reserved marker, depending on the encoding policy. Here we deliberately compare both interpretations. We are only observing GPT-2's convention, not prescribing the assignment's implementation.\n",
    "\n",
    "**Python:** `{marker}` is a set literal, passed through the keyword argument `allowed_special`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "383fffed",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:35.237734Z",
     "iopub.status.busy": "2026-11-15T02:04:35.237690Z",
     "iopub.status.idle": "2026-11-15T02:04:35.239043Z",
     "shell.execute_reply": "2026-11-15T02:04:35.238779Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "As literal text: [27, 91, 437, 1659, 5239, 91, 29]\n",
      "As allowed special marker: [50256]\n"
     ]
    }
   ],
   "source": [
    "marker = \"<|endoftext|>\"\n",
    "literal_ids = encoding.encode_ordinary(marker)\n",
    "marker_ids = encoding.encode(marker, allowed_special={marker})\n",
    "print(\"As literal text:\", literal_ids)\n",
    "print(\"As allowed special marker:\", marker_ids)\n",
    "assert encoding.decode(literal_ids) == marker\n",
    "assert encoding.decode(marker_ids) == marker"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1895c34e",
   "metadata": {},
   "source": [
    "## Your experiment · use a line of your own\n",
    "Paste a short line into `my_text`. Predict the tricky boundaries, then inspect every token's bytes. Change only one thing and compare again: case, a space, punctuation, or a multilingual character."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "8ec928a1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:35.239690Z",
     "iopub.status.busy": "2026-11-15T02:04:35.239650Z",
     "iopub.status.idle": "2026-11-15T02:04:35.241339Z",
     "shell.execute_reply": "2026-11-15T02:04:35.241014Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "IDs: [33, 11401, 34175, 257, 25818, 27571, 284, 1366, 13]\n",
      "Token bytes: [b'B', b'PE', b' constructs', b' a', b' vocabulary', b' tailored', b' to', b' data', b'.']\n",
      "Characters: 45 Bytes: 45 Tokens: 9\n"
     ]
    }
   ],
   "source": [
    "my_text = \"BPE constructs a vocabulary tailored to data.\"\n",
    "my_ids = encoding.encode_ordinary(my_text)\n",
    "print(\"IDs:\", my_ids)\n",
    "print(\"Token bytes:\", [encoding.decode_single_token_bytes(i) for i in my_ids])\n",
    "print(\"Characters:\", len(my_text), \"Bytes:\", len(my_text.encode(\"utf-8\")), \"Tokens:\", len(my_ids))\n",
    "assert encoding.decode(my_ids) == my_text"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f59ded39",
   "metadata": {},
   "source": [
    "## What you found\n",
    "- My text and prediction:\n",
    "- A surprising boundary I observed:\n",
    "- What my bytes-per-token measurement does and does not tell me:\n",
    "- A round-trip property I would want my own tokenizer to satisfy:\n",
    "- Why a single token's byte payload need not be valid UTF-8:\n",
    "\n",
    "**Toward the CS336 tokenizer:** inspect bytes instead of guessing from printed text; measure actual sequence lengths; distinguish round-trip correctness from a particular segmentation. With these four notebooks done, the assignment's tokenizer section reads against concrete examples.\n",
    "\n",
    "**Reference:** [tiktoken public API and overview](https://github.com/openai/tiktoken)."
   ]
  }
 ],
 "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
}
