{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a43e4fc9",
   "metadata": {},
   "source": [
    "# 01 · Text, Unicode, and bytes\n",
    "**Start here · about 15 minutes**\n",
    "\n",
    "The letter A can be written three ways: `A ↔ U+0041 ↔ 01000001`. This notebook makes every arrow observable in Python, then tests examples where one displayed character takes more than one byte.\n",
    "\n",
    "**You will be able to:** distinguish a code point from a byte; inspect UTF-8; explain why 256 byte values cover far more than 256 characters.\n",
    "\n",
    "Use **Shift+Enter** to run a cell. Change the experiment inputs, then use **Kernel → Restart Kernel and Run All Cells** to check the whole story. Every unit runs independently. Markdown cells are editable too: double-click one to write down what you observe."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "30472c8d",
   "metadata": {},
   "source": [
    "## 1 · One letter, three representations\n",
    "`ord()` returns a code point as an integer. `U+0041` writes that integer in hexadecimal. `.encode(\"utf-8\")` produces a Python `bytes` object. Iterating over it gives integers, one per byte.\n",
    "\n",
    "**Predict:** will the code point and byte value still match if you replace `A` with `猫`?\n",
    "\n",
    "**Python:** `repr()` shows a diagnostic representation. F-strings interpolate `{expr}`; `:04X` and `:08b` mean zero-padded hex/binary with minimum widths 4/8. `[expr for x in iterable]` is a list comprehension."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "b70959ec",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Text: 'A'\n",
      "Code point: U+0041\n",
      "Python bytes: b'A'\n",
      "Byte values: [65]\n",
      "Hex: ['41']\n",
      "Bits: ['01000001']\n"
     ]
    }
   ],
   "source": [
    "text = \"A\"\n",
    "print(\"Text:\", repr(text))\n",
    "for character in text:\n",
    "    print(\"Code point:\", f\"U+{ord(character):04X}\")\n",
    "raw = text.encode(\"utf-8\")\n",
    "print(\"Python bytes:\", raw)\n",
    "print(\"Byte values:\", list(raw))\n",
    "print(\"Hex:\", [f\"{value:02X}\" for value in raw])\n",
    "print(\"Bits:\", [f\"{value:08b}\" for value in raw])\n",
    "assert raw.decode(\"utf-8\") == text"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f717182",
   "metadata": {},
   "source": [
    "## 2 · Count different representations\n",
    "A byte takes **256 values**, so its inclusive range is **0–255**, not `[0, 256]`. Individual bits are 0 or 1.\n",
    "\n",
    "Also distinguish a Unicode code point from a *grapheme cluster*: a unit perceived as one displayed character, which can contain several code points. Python `len(str)` counts code points. The installed `regex` library can count grapheme clusters with `\\X`.\n",
    "\n",
    "**Predict:** will `é` and `e` followed by a combining accent have the same counts?\n",
    "\n",
    "**Python:** Raw strings (`r\"...\"`) preserve backslashes. In f-strings, `!r` applies `repr()` and `>N` right-aligns. `range(256)` excludes its stop value, 256."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "9b407a08",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "text            graphemes  code points  UTF-8 bytes\n",
      "'A'                     1            1            1\n",
      "'猫'                     1            1            3\n",
      "'🙂'                     1            1            4\n",
      "'é'                     1            1            2\n",
      "'é'                    1            2            3\n",
      "'👩\\u200d💻'              1            3           11\n",
      "Smallest byte: 0\n",
      "Largest byte: 255\n"
     ]
    }
   ],
   "source": [
    "import regex\n",
    "\n",
    "samples = [\"A\", \"猫\", \"🙂\", \"é\", \"é\", \"👩‍💻\"]\n",
    "print(f'{\"text\":14} {\"graphemes\":>10} {\"code points\":>12} {\"UTF-8 bytes\":>12}')\n",
    "for text in samples:\n",
    "    print(f'{text!r:14} {len(regex.findall(r\"\\X\", text)):>10} {len(text):>12} {len(text.encode(\"utf-8\")):>12}')\n",
    "print(\"Smallest byte:\", min(bytes(range(256))))\n",
    "print(\"Largest byte:\", max(bytes(range(256))))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c7b3b44f",
   "metadata": {},
   "source": [
    "## 3 · More than one byte can represent one code point\n",
    "A byte vocabulary contains the possible **pieces**, not a separate entry for every complete character. UTF-8 combines those pieces into sequences of one to four bytes per Unicode scalar value.\n",
    "\n",
    "**Try:** replace the text below with any short phrase, ideally in more than one script. Watch where the character boundaries and byte boundaries differ.\n",
    "\n",
    "**Python:** `all(condition for x in iterable)` evaluates a generator, stopping at the first false result."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "740523ae",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:32.541902Z",
     "iopub.status.busy": "2026-11-15T02:04:32.541810Z",
     "iopub.status.idle": "2026-11-15T02:04:32.544101Z",
     "shell.execute_reply": "2026-11-15T02:04:32.543712Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "'A' U+0041 [65]\n",
      "'猫' U+732B [231, 140, 171]\n",
      "'🙂' U+1F642 [240, 159, 153, 130]\n"
     ]
    }
   ],
   "source": [
    "my_text = \"A猫🙂\"\n",
    "for character in my_text:\n",
    "    print(repr(character), f\"U+{ord(character):04X}\", list(character.encode(\"utf-8\")))\n",
    "assert all(0 <= value <= 255 for value in my_text.encode(\"utf-8\"))\n",
    "assert my_text.encode(\"utf-8\").decode(\"utf-8\") == my_text"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e4a8e3b3",
   "metadata": {},
   "source": [
    "## 4 · A piece of valid UTF-8 need not be valid UTF-8\n",
    "**Predict:** what happens if we decode just the first byte of `猫`? This matters later because a tokenizer can split a character's bytes across tokens.\n",
    "\n",
    "**Python:** `raw[:n]` selects the first `n` bytes. `except UnicodeDecodeError` handles that exception type."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c2e73cea",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:32.545286Z",
     "iopub.status.busy": "2026-11-15T02:04:32.545208Z",
     "iopub.status.idle": "2026-11-15T02:04:32.547220Z",
     "shell.execute_reply": "2026-11-15T02:04:32.546759Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[231] → incomplete UTF-8 sequence\n",
      "[231, 140] → incomplete UTF-8 sequence\n",
      "[231, 140, 171] → 猫\n"
     ]
    }
   ],
   "source": [
    "raw = \"猫\".encode(\"utf-8\")\n",
    "for length in range(1, len(raw) + 1):\n",
    "    piece = raw[:length]\n",
    "    try:\n",
    "        print(list(piece), \"→\", piece.decode(\"utf-8\"))\n",
    "    except UnicodeDecodeError:\n",
    "        print(list(piece), \"→ incomplete UTF-8 sequence\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "485b2768",
   "metadata": {},
   "source": [
    "## 5 · Similar appearance does not imply identical text\n",
    "Normalizing text can change its code points and bytes. A tokenizer does not automatically normalize just because it uses UTF-8. Exact reconstruction and normalization are separate choices."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "ca18d746",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:32.548087Z",
     "iopub.status.busy": "2026-11-15T02:04:32.548026Z",
     "iopub.status.idle": "2026-11-15T02:04:32.550558Z",
     "shell.execute_reply": "2026-11-15T02:04:32.550110Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Same string: False\n",
      "First bytes: [195, 169]\n",
      "Second bytes: [101, 204, 129]\n",
      "Equal after NFC normalization: True\n"
     ]
    }
   ],
   "source": [
    "import unicodedata\n",
    "\n",
    "first = \"é\"\n",
    "second = \"é\"\n",
    "print(\"Same string:\", first == second)\n",
    "print(\"First bytes:\", list(first.encode(\"utf-8\")))\n",
    "print(\"Second bytes:\", list(second.encode(\"utf-8\")))\n",
    "print(\"Equal after NFC normalization:\", unicodedata.normalize(\"NFC\", first) == unicodedata.normalize(\"NFC\", second))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9160625d",
   "metadata": {},
   "source": [
    "## Your experiment\n",
    "Edit `candidate`, predict all three counts before running, then check exact reconstruction. Empty text is also a useful input."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "bedf38a9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:32.551547Z",
     "iopub.status.busy": "2026-11-15T02:04:32.551480Z",
     "iopub.status.idle": "2026-11-15T02:04:32.553601Z",
     "shell.execute_reply": "2026-11-15T02:04:32.553286Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Graphemes: 24\n",
      "Code points: 24\n",
      "Bytes: 27\n"
     ]
    }
   ],
   "source": [
    "candidate = \"Your own example: café 猫\"\n",
    "print(\"Graphemes:\", len(regex.findall(r\"\\X\", candidate)))\n",
    "print(\"Code points:\", len(candidate))\n",
    "print(\"Bytes:\", len(candidate.encode(\"utf-8\")))\n",
    "assert candidate.encode(\"utf-8\").decode(\"utf-8\") == candidate"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3b44f784",
   "metadata": {},
   "source": [
    "## What you found\n",
    "- My example and prediction:\n",
    "- What happened:\n",
    "- My revised explanation of character / code point / byte:\n",
    "- Why 256 byte values can represent multilingual text:\n",
    "\n",
    "**Toward the CS336 tokenizer:** you now know how to inspect the input representation and check lossless conversion before thinking about BPE.\n",
    "\n",
    "**References:** [Python Unicode HOWTO](https://docs.python.org/3/howto/unicode.html), [Python bytes](https://docs.python.org/3/library/stdtypes.html#bytes)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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
}
