{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8ad9a538",
   "metadata": {},
   "source": [
    "# 02 · Vocabulary, token IDs, and embeddings\n",
    "**About 10–15 minutes · independent of unit 01**\n",
    "\n",
    "A language model reads its input along `raw text → token IDs → embedding vector`. This notebook isolates the last two arrows. An ID is a label used for lookup; an embedding is a vector associated with that label.\n",
    "\n",
    "**You will be able to:** inspect a vocabulary in both directions; reconstruct text from token bytes; look up vectors without interpreting token IDs as meaningful numerical quantities."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b64c649",
   "metadata": {},
   "source": [
    "## 1 · A tiny vocabulary you can inspect\n",
    "This is a deliberately small **lookup example**, not a complete tokenizer or a 256-byte vocabulary. Its token IDs are invented. The keys label entries; the values are byte strings of different lengths.\n",
    "\n",
    "**Predict:** do all four entries represent the same number of bytes?\n",
    "\n",
    "**Python:** `b\"...\"` is a bytes literal. `dict.items()` yields `(key, value)` pairs; `{k: v for ...}` is a dictionary comprehension."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "e5965a0d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:33.276651Z",
     "iopub.status.busy": "2026-11-15T02:04:33.276534Z",
     "iopub.status.idle": "2026-11-15T02:04:33.282142Z",
     "shell.execute_reply": "2026-11-15T02:04:33.281532Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ID: 0 bytes: b'h' byte length: 1\n",
      "ID: 1 bytes: b'i' byte length: 1\n",
      "ID: 2 bytes: b'hi' byte length: 2\n",
      "ID: 3 bytes: b' hi' byte length: 3\n"
     ]
    }
   ],
   "source": [
    "id_to_bytes = {0: b\"h\", 1: b\"i\", 2: b\"hi\", 3: b\" hi\"}\n",
    "bytes_to_id = {piece: token_id for token_id, piece in id_to_bytes.items()}\n",
    "for token_id, piece in id_to_bytes.items():\n",
    "    print(\"ID:\", token_id, \"bytes:\", repr(piece), \"byte length:\", len(piece))\n",
    "assert bytes_to_id[b\"hi\"] == 2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3f9fb65",
   "metadata": {},
   "source": [
    "## 2 · Reconstruct text from a chosen sequence\n",
    "We supply the sequence explicitly to focus on lookup. Choosing which pieces an encoder emits is a separate problem.\n",
    "\n",
    "`b\"\".join(...)` concatenates byte strings. Decode the **combined** bytes as UTF-8, rather than assuming each token must contain a complete character."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "75d58c84",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:33.283841Z",
     "iopub.status.busy": "2026-11-15T02:04:33.283621Z",
     "iopub.status.idle": "2026-11-15T02:04:33.286532Z",
     "shell.execute_reply": "2026-11-15T02:04:33.285883Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "IDs: [2, 3]\n",
      "Pieces: [b'hi', b' hi']\n",
      "Text: 'hi hi'\n"
     ]
    }
   ],
   "source": [
    "token_ids = [2, 3]\n",
    "pieces = [id_to_bytes[token_id] for token_id in token_ids]\n",
    "restored_bytes = b\"\".join(pieces)\n",
    "print(\"IDs:\", token_ids)\n",
    "print(\"Pieces:\", pieces)\n",
    "print(\"Text:\", repr(restored_bytes.decode(\"utf-8\")))\n",
    "assert restored_bytes == b\"hi hi\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7a1e6e58",
   "metadata": {},
   "source": [
    "## 3 · IDs label rows in an embedding table\n",
    "Here each row has three made-up numbers. A real language model learns its embedding parameters during model training. This table is fixed demonstration data.\n",
    "\n",
    "PyTorch indexing `table[indices]` selects the indicated rows. **Predict:** what shape will two token IDs produce?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "bc090686",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:33.287924Z",
     "iopub.status.busy": "2026-11-15T02:04:33.287819Z",
     "iopub.status.idle": "2026-11-15T02:04:33.872129Z",
     "shell.execute_reply": "2026-11-15T02:04:33.871796Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Table shape: (4, 3)\n",
      "ID sequence shape: (2,)\n",
      "Selected vector shape: (2, 3)\n",
      "tensor([[0.2000, 0.4000, 0.6000],\n",
      "        [0.8000, 0.3000, 0.1000]])\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "\n",
    "embedding_table = torch.tensor([\n",
    "    [1.0, 0.0, 0.0],\n",
    "    [0.0, 1.0, 0.0],\n",
    "    [0.2, 0.4, 0.6],\n",
    "    [0.8, 0.3, 0.1],\n",
    "])\n",
    "indices = torch.tensor(token_ids)\n",
    "vectors = embedding_table[indices]\n",
    "print(\"Table shape:\", tuple(embedding_table.shape))\n",
    "print(\"ID sequence shape:\", tuple(indices.shape))\n",
    "print(\"Selected vector shape:\", tuple(vectors.shape))\n",
    "print(vectors)\n",
    "assert vectors.shape == (len(token_ids), 3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "70365437",
   "metadata": {},
   "source": [
    "## 4 · Renaming IDs does not change the represented text\n",
    "An ID being numerically close to another ID does not establish semantic similarity. If we consistently reorder both the vocabulary and embedding rows, lookup still yields the same text and vectors.\n",
    "\n",
    "Inspect the mapping below: old ID 2 becomes new ID 0, for example.\n",
    "\n",
    "**Python:** `enumerate(seq)` yields `(index, value)` pairs, starting at index 0."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "d4231ce3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:33.873101Z",
     "iopub.status.busy": "2026-11-15T02:04:33.873025Z",
     "iopub.status.idle": "2026-11-15T02:04:33.876963Z",
     "shell.execute_reply": "2026-11-15T02:04:33.876583Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Old IDs: [2, 3] New IDs: [0, 2]\n",
      "Same text and same selected vectors\n"
     ]
    }
   ],
   "source": [
    "new_to_old = [2, 0, 3, 1]\n",
    "old_to_new = {old: new for new, old in enumerate(new_to_old)}\n",
    "renamed_vocabulary = {new: id_to_bytes[old] for new, old in enumerate(new_to_old)}\n",
    "renamed_table = embedding_table[new_to_old]\n",
    "renamed_ids = [old_to_new[token_id] for token_id in token_ids]\n",
    "print(\"Old IDs:\", token_ids, \"New IDs:\", renamed_ids)\n",
    "assert b\"\".join(renamed_vocabulary[i] for i in renamed_ids) == restored_bytes\n",
    "torch.testing.assert_close(renamed_table[renamed_ids], vectors)\n",
    "print(\"Same text and same selected vectors\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4b097fcb",
   "metadata": {},
   "source": [
    "## Your experiment\n",
    "Change only `my_ids` to a different sequence of valid IDs. Predict the resulting text and vector shape. Repeating an ID repeats the same row at this lookup stage; contextual processing comes later."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "9bbf867e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-15T02:04:33.877690Z",
     "iopub.status.busy": "2026-11-15T02:04:33.877638Z",
     "iopub.status.idle": "2026-11-15T02:04:33.879688Z",
     "shell.execute_reply": "2026-11-15T02:04:33.879334Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Text: 'hi hihi'\n",
      "Vectors: tensor([[1.0000, 0.0000, 0.0000],\n",
      "        [0.0000, 1.0000, 0.0000],\n",
      "        [0.8000, 0.3000, 0.1000],\n",
      "        [0.2000, 0.4000, 0.6000]])\n"
     ]
    }
   ],
   "source": [
    "my_ids = [0, 1, 3, 2]\n",
    "print(\"Text:\", repr(b\"\".join(id_to_bytes[i] for i in my_ids).decode(\"utf-8\")))\n",
    "print(\"Vectors:\", embedding_table[my_ids])\n",
    "assert embedding_table[my_ids].shape == (len(my_ids), 3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c0e71758",
   "metadata": {},
   "source": [
    "## What you found\n",
    "- My prediction and observation:\n",
    "- What belongs to the tokenizer vocabulary:\n",
    "- What belongs to the language model:\n",
    "- Why token ID 257 says nothing about the size or content of its vector:\n",
    "\n",
    "**Toward the CS336 tokenizer:** separate byte payloads, integer labels, and learned parameters. Debugging becomes easier when you print each representation independently.\n",
    "\n",
    "**Reference:** [PyTorch indexing](https://docs.pytorch.org/docs/2.11/notes/tensor_indexing.html)."
   ]
  }
 ],
 "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
}
