{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "49s7rxTFRQ4b",
    "outputId": "da7e5891-b0c3-4b39-ee57-0c6112e045d0"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('the-verdict.txt', <http.client.HTTPMessage at 0x7a3072aefd90>)"
      ]
     },
     "execution_count": 184,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import urllib.request\n",
    "url = (\"https://raw.githubusercontent.com/rasbt/\"\n",
    "       \"LLMs-from-scratch/main/ch02/01_main-chapter-code/\"\n",
    "       \"the-verdict.txt\")\n",
    "file_path = \"the-verdict.txt\"\n",
    "urllib.request.urlretrieve(url, file_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "HfcdLopwR7k9",
    "outputId": "d7357c48-bb83-4d41-eece-a80cafda1408"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Length of text: 20479\n",
      "I HAD always thought Jack Gisburn rather a cheap genius--though a good fellow enough--so it was no \n"
     ]
    }
   ],
   "source": [
    "with open(file_path, 'r', encoding='utf8') as f:\n",
    "  raw_file = f.read()\n",
    "print(\"Length of text:\", len(raw_file))\n",
    "print(raw_file[:99])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "3r4G4xAjSjE4",
    "outputId": "aa105451-3f73-44f0-ba14-52828c37713c"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Hello,', ' ', 'world.', ' ', 'This,', ' ', 'is', ' ', 'a', ' ', 'test.']\n"
     ]
    }
   ],
   "source": [
    "# naive tokenization with regex splitting on space\n",
    "import re\n",
    "text = \"Hello, world. This, is a test.\"\n",
    "result = re.split(r'(\\s)', text)\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "5v-Gvm5Og62B",
    "outputId": "27112c19-23e4-48f4-e398-0ec643b64347"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Hello', ',', '', ' ', 'world', '.', '', ' ', 'This', ',', '', ' ', 'is', ' ', 'a', ' ', 'test', '.', '']\n"
     ]
    }
   ],
   "source": [
    "# split on space, commas, periods\n",
    "result = re.split(r'([,.\\s])', text)\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "O19VkRWAiSpa",
    "outputId": "fa3b2e77-6f22-4631-cccf-3ddc6018fcd1"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello\n",
      ",\n",
      "world\n",
      ".\n",
      "This\n",
      ",\n",
      "is\n",
      "a\n",
      "test\n",
      ".\n"
     ]
    }
   ],
   "source": [
    "# We don't actually want the whitespace, note that we can easily strip that out.\n",
    "for item in result:\n",
    "  if item.strip():\n",
    "    print(item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "TRy-BAeQij3m",
    "outputId": "3912bdcb-002d-4552-8f8d-f0f06ce2ec54"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Hello', ',', 'world', '.', 'This', ',', 'is', 'a', 'test', '.']"
      ]
     },
     "execution_count": 189,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Strip out whitespace.\n",
    "items = [item for item in result if item.strip()]\n",
    "items"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "ml7jB2b9i5dw",
    "outputId": "c9b2ee98-15da-43ff-f061-c2eea69cbb6c"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Hello', ',', 'world', '.', 'Is', 'this', '--', 'a', 'test', '?']"
      ]
     },
     "execution_count": 190,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Handle more characters and therefore more complex input text.\n",
    "text = \"Hello, world. Is this-- a test?\"\n",
    "result = re.split(r'([,.:;?_!\"()\\']|--|\\s)', text)\n",
    "tokens = [item for item in result if item.strip()]\n",
    "tokens"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "eOJB1BcLjRRe",
    "outputId": "64730924-d263-43d3-a1c8-75c898512d81"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "# tokens: 4690\n",
      "First 33 tokens: ['I', 'HAD', 'always', 'thought', 'Jack', 'Gisburn', 'rather', 'a', 'cheap', 'genius', '--', 'though', 'a', 'good', 'fellow', 'enough', '--', 'so', 'it', 'was', 'no', 'great', 'surprise', 'to', 'me', 'to', 'hear', 'that', ',', 'in', 'the', 'height', 'of']\n"
     ]
    }
   ],
   "source": [
    "# Now apply it to our full sample text.\n",
    "result = re.split(r'([,.:;?_!\"()\\']|--|\\s)', raw_file)\n",
    "tokens = [item for item in result if item.strip()]\n",
    "print(\"# tokens:\", len(tokens))\n",
    "print(\"First 33 tokens:\", tokens[:33])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "40CAjW2-kekP",
    "outputId": "5b8f698a-f42f-4ced-d879-1a97a47e5ab6"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "# unique tokens: 1130\n",
      "First 10 unique tokens: ['!', '\"', \"'\", '(', ')', ',', '--', '.', ':', ';']\n"
     ]
    }
   ],
   "source": [
    "# But how many *unique* tokens are there?\n",
    "unique_tokens = sorted(set(tokens))\n",
    "num_unique_tokens = len(unique_tokens)\n",
    "print(\"# unique tokens:\", num_unique_tokens)\n",
    "print(\"First 10 unique tokens:\", list(unique_tokens)[:10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "BpRLNSG3W0Bl",
    "outputId": "bfbfdc8c-bc14-4902-c4a5-c4326e03a71d"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "! - 0\n",
      "\" - 1\n",
      "' - 2\n",
      "( - 3\n",
      ") - 4\n",
      ", - 5\n",
      "-- - 6\n",
      ". - 7\n",
      ": - 8\n",
      "; - 9\n",
      "? - 10\n",
      "A - 11\n",
      "Ah - 12\n",
      "Among - 13\n",
      "And - 14\n",
      "Are - 15\n",
      "Arrt - 16\n",
      "As - 17\n",
      "At - 18\n",
      "Be - 19\n",
      "Begin - 20\n",
      "Burlington - 21\n",
      "But - 22\n",
      "By - 23\n",
      "Carlo - 24\n",
      "Chicago - 25\n",
      "Claude - 26\n",
      "Come - 27\n",
      "Croft - 28\n",
      "Destroyed - 29\n",
      "Devonshire - 30\n",
      "Don - 31\n",
      "Dubarry - 32\n",
      "Emperors - 33\n",
      "Florence - 34\n",
      "For - 35\n",
      "Gallery - 36\n",
      "Gideon - 37\n",
      "Gisburn - 38\n",
      "Gisburns - 39\n",
      "Grafton - 40\n",
      "Greek - 41\n",
      "Grindle - 42\n",
      "Grindles - 43\n",
      "HAD - 44\n",
      "Had - 45\n",
      "Hang - 46\n",
      "Has - 47\n",
      "He - 48\n",
      "Her - 49\n",
      "Hermia - 50\n",
      "His - 51\n"
     ]
    }
   ],
   "source": [
    "# Now create a dict mapping integers to tokens.\n",
    "vocab = {token:id for id, token in enumerate(unique_tokens)}\n",
    "for token, id in vocab.items():\n",
    "  print(f'{token} - {id}')\n",
    "  if (id > 50):\n",
    "    break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "c_isIkmVbBiE"
   },
   "outputs": [],
   "source": [
    "# Now make a basic tokenizer class.\n",
    "\n",
    "class SimpleTokenizerV1:\n",
    "  def __init__(self, vocab):\n",
    "    self.str_to_int = vocab\n",
    "    self.int_to_str = {id:token for token, id in vocab.items()}\n",
    "\n",
    "  def encode(self, text):\n",
    "    tokens = re.split(r'([,.:;?_!\"()\\']|--|\\s)', text)\n",
    "    tokens = [token.strip() for token in tokens if token.strip()]\n",
    "    ids = [self.str_to_int[token] for token in tokens]\n",
    "    return ids\n",
    "\n",
    "  def decode(self, ids):\n",
    "    tokens = [self.int_to_str[id] for id in ids]\n",
    "    text = \" \".join(tokens)\n",
    "    text = re.sub(r'\\s+([,.:;?_!\"()\\']|--)', r'\\1', text)\n",
    "    return text\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "E-yoqJYjdLTp",
    "outputId": "aaeeb090-4352-4cf4-a647-42b632f6d4aa"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 56, 2, 850, 988, 602, 533, 746, 5, 1126, 596, 5, 1, 67, 7, 38, 851, 1108, 754, 793, 7]\n"
     ]
    }
   ],
   "source": [
    "tokenizer = SimpleTokenizerV1(vocab)\n",
    "text = \"\"\"\"It's the last he painted, you know,\"\n",
    "       Mrs. Gisburn said with pardonable pride.\"\"\"\n",
    "ids = tokenizer.encode(text)\n",
    "print(ids)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "6c6ZF2Xrd2bg",
    "outputId": "a4af7070-becd-41a4-8bac-9d67b4694d43"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\" It' s the last he painted, you know,\" Mrs. Gisburn said with pardonable pride.\n"
     ]
    }
   ],
   "source": [
    "print(tokenizer.decode(ids))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "9E9DRGV4fL87"
   },
   "outputs": [],
   "source": [
    "# It works, overlooking some minor issues with spaces in decoding.\n",
    "# But it easily breaks on new vocab.\n",
    "\n",
    "text = \"Hello, do you like tea?\"\n",
    "#print(tokenizer.encode(text))\n",
    "\n",
    "# This will obtain:\n",
    "# KeyError: 'Hello'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "frEeo25ciLDM",
    "outputId": "8a9e2395-cd76-4e2a-a0d0-5ff2baf127af"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1132\n"
     ]
    }
   ],
   "source": [
    "# Let's handle unknown tokens and end of text.\n",
    "unique_tokens.extend([\"<|endoftext|>\", \"<|unk|>\"])\n",
    "vocab = {token:id for id, token in enumerate(unique_tokens)}\n",
    "print(len(vocab))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "Izoa9FzDiZBe",
    "outputId": "7a3c1b51-6da2-44b4-c1a6-32d68589404a"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "younger, 1127\n",
      "your, 1128\n",
      "yourself, 1129\n",
      "<|endoftext|>, 1130\n",
      "<|unk|>, 1131\n"
     ]
    }
   ],
   "source": [
    "for token, id in list(vocab.items())[-5:]:\n",
    "  print(f\"{token}, {id}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "M9lwn93LjBvW"
   },
   "outputs": [],
   "source": [
    "# Now enhance our tokenizer class to handle unknown words.\n",
    "\n",
    "class SimpleTokenizerV2:\n",
    "  def __init__(self, vocab):\n",
    "    self.str_to_int = vocab\n",
    "    self.int_to_str = {id:token for token, id in vocab.items()}\n",
    "\n",
    "  def encode(self, text):\n",
    "    tokens = re.split(r'([,.:;?_!\"()\\']|--|\\s)', text)\n",
    "    tokens = [token.strip() for token in tokens if token.strip()]\n",
    "    tokens = [token if token in self.str_to_int else \"<|unk|>\" for token in tokens]\n",
    "    ids = [self.str_to_int[token] for token in tokens]\n",
    "    return ids\n",
    "\n",
    "  def decode(self, ids):\n",
    "    tokens = [self.int_to_str[id] for id in ids]\n",
    "    text = \" \".join(tokens)\n",
    "    text = re.sub(r'\\s+([,.:;?_!\"()\\']|--)', r'\\1', text)\n",
    "    return text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "aZaGOJ-_jmsT",
    "outputId": "e5050f08-9728-4a18-be2f-ed8aba1f77b2"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, do you like tea? <|endoftext|> In the sunlit terraces of the palace.\n"
     ]
    }
   ],
   "source": [
    "# Try the new tokenizer out.\n",
    "\n",
    "text1 = \"Hello, do you like tea?\"\n",
    "text2 = \"In the sunlit terraces of the palace.\"\n",
    "text = \" <|endoftext|> \".join((text1, text2))\n",
    "print(text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "qbBmtLSmjxoX",
    "outputId": "2ea3c993-e53e-4ad1-f94a-3b07ef129a7a"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1131, 5, 355, 1126, 628, 975, 10, 1130, 55, 988, 956, 984, 722, 988, 1131, 7]\n"
     ]
    }
   ],
   "source": [
    "tokenizer = SimpleTokenizerV2(vocab)\n",
    "print(tokenizer.encode(text))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "ByWO70Q8kF4f",
    "outputId": "1ad83ebf-bf7a-4f0b-cf8a-636f76bc688e"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<|unk|>, do you like tea? <|endoftext|> In the sunlit terraces of the <|unk|>.\n"
     ]
    }
   ],
   "source": [
    "print(tokenizer.decode(tokenizer.encode(text)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 36
    },
    "id": "hIGHayfe8Exm",
    "outputId": "e453dab6-b6c6-4b5c-f555-45dae59adeec"
   },
   "outputs": [
    {
     "data": {
      "application/vnd.google.colaboratory.intrinsic+json": {
       "type": "string"
      },
      "text/plain": [
       "'0.14.0'"
      ]
     },
     "execution_count": 204,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from importlib.metadata import version\n",
    "import tiktoken\n",
    "version(\"tiktoken\") # should be > 0.7.0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "wDFsNiV48VKy"
   },
   "outputs": [],
   "source": [
    "# instantiate a byte-pair-encoding (BPE) tokenizer\n",
    "tokenizer = tiktoken.get_encoding(\"gpt2\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "kKXiv3RJ8nQE",
    "outputId": "a7aaad3b-bbf4-4263-99f5-064a1ba43ad4"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[15496, 11, 466, 345, 588, 8887, 30, 220, 50256, 554, 262, 4252, 18250, 8812, 2114, 1659, 617, 34680, 27271, 13]\n"
     ]
    }
   ],
   "source": [
    "# test out encoding\n",
    "text = (\n",
    "    \"Hello, do you like tea? <|endoftext|> In the sunlit terraces\"\n",
    "    \"of someunknownPlace.\"\n",
    ")\n",
    "integers = tokenizer.encode(text, allowed_special={\"<|endoftext|>\"})\n",
    "print(integers)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "uW5_we5C9G-C",
    "outputId": "851302cf-bd7d-4907-d863-307ce3a38c2d"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, do you like tea? <|endoftext|> In the sunlit terracesof someunknownPlace.\n"
     ]
    }
   ],
   "source": [
    "# now decoding\n",
    "strings = tokenizer.decode(integers)\n",
    "print(strings)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "TwiFDv2m9e8j"
   },
   "source": [
    "#### Exercise 2.1 Byte pair encoding of unknown words\n",
    "Try the BPE tokenizer from the tiktoken library on the unknown words “Akwirw ier” and print the individual token IDs. Then, call the decode function on each of the resulting integers in this list to reproduce the mapping shown in figure 2.11. Lastly, call the decode method on the token IDs to check whether it can reconstruct the original input, “Akwirw ier.”"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "r6vbNwgI9kDv",
    "outputId": "8d1c190e-8e27-4cbc-caf0-62dba3e1c9eb"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[33901, 86, 343, 86, 220, 959]\n",
      "['Ak', 'w', 'ir', 'w', ' ', 'ier']\n",
      "33901 = \"Ak\"\n",
      "   86 = \"w\"\n",
      "  343 = \"ir\"\n",
      "   86 = \"w\"\n",
      "  220 = \" \"\n",
      "  959 = \"ier\"\n",
      "Akwirw ier\n"
     ]
    }
   ],
   "source": [
    "text = \"Akwirw ier\"\n",
    "integers = tokenizer.encode(text, allowed_special={\"<|endoftext|>\"})\n",
    "print(integers)\n",
    "\n",
    "strings = []\n",
    "for integer in integers:\n",
    "  strings.append(tokenizer.decode([integer]))\n",
    "print(strings)\n",
    "\n",
    "for string, integer in zip(strings, integers):\n",
    "  print(f'{integer:5} = \"{string}\"')\n",
    "\n",
    "print(tokenizer.decode(integers))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "QTYgrI7tgLVO",
    "outputId": "7a900a65-01e8-4d48-f907-a5856b7738a6"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5145"
      ]
     },
     "execution_count": 209,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Now load and encode the sample text\n",
    "with open(file_path, 'r', encoding='utf8') as f:\n",
    "  raw_file = f.read()\n",
    "\n",
    "tokens = tokenizer.encode(raw_file)\n",
    "len(tokens)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "wy-tqpeXg4ML",
    "outputId": "9f2c68e7-c506-4f77-bd95-86b805c9755e"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "x: [290, 4920, 2241, 287]\n",
      "y:      [4920, 2241, 287, 257]\n"
     ]
    }
   ],
   "source": [
    "# demonstrate what next token prediction looks like\n",
    "enc_sample = tokens[50:]\n",
    "context_size = 4\n",
    "x = enc_sample[:context_size]\n",
    "y = enc_sample[1:context_size+1]\n",
    "print(f'x: {x}')\n",
    "print(f'y:      {y}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "9Rn1BBvDhqu6",
    "outputId": "e373781f-bc5a-4b5c-be08-3c5265d7802f"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[290] -> 4920\n",
      "[290, 4920] -> 2241\n",
      "[290, 4920, 2241] -> 287\n",
      "[290, 4920, 2241, 287] -> 257\n"
     ]
    }
   ],
   "source": [
    "# more generally\n",
    "for i in range(1, context_size+1):\n",
    "  context = enc_sample[:i]\n",
    "  desired = enc_sample[i]\n",
    "  print(context, \"->\", desired)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "zf6nBb1cibjH",
    "outputId": "ad742461-40bd-4051-b0e9-1bbd237e69e9"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " and ->  established\n",
      " and established ->  himself\n",
      " and established himself ->  in\n",
      " and established himself in ->  a\n"
     ]
    }
   ],
   "source": [
    "# as text\n",
    "for i in range(1, context_size+1):\n",
    "  context = enc_sample[:i]\n",
    "  desired = enc_sample[i]\n",
    "  print(tokenizer.decode(context), \"->\", tokenizer.decode([desired]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "WT6Fyl_kkT8q",
    "outputId": "79cfc819-e26d-466e-95c3-b8f93acb604e"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First batch: (tensor([  40,  367, 2885, 1464]), tensor([ 367, 2885, 1464, 1807]))\n",
      "Length: 5145\n"
     ]
    }
   ],
   "source": [
    "# Build a tokenizer dataset based on PyTorch datasets\n",
    "import torch\n",
    "from torch.utils.data import Dataset, DataLoader\n",
    "\n",
    "class GPTDatasetV1(Dataset):\n",
    "  def __init__(self, txt, tokenizer, max_length, stride):\n",
    "    self.input_ids = []\n",
    "    self.target_ids = []\n",
    "\n",
    "    tokens = tokenizer.encode(txt)\n",
    "    self.num_tokens = len(tokens)\n",
    "    for i in range(1, self.num_tokens - max_length, stride):\n",
    "      input_batch = tokens[i-1:i-1+max_length]\n",
    "      target_batch = tokens[i:i+max_length]\n",
    "      self.input_ids.append(torch.tensor(input_batch))\n",
    "      self.target_ids.append(torch.tensor(target_batch))\n",
    "\n",
    "  def __len__(self):\n",
    "    return self.num_tokens\n",
    "\n",
    "  def __getitem__(self, idx):\n",
    "    return self.input_ids[idx], self.target_ids[idx]\n",
    "\n",
    "ds = GPTDatasetV1(raw_file, tokenizer, 4, 2)\n",
    "print(\"First batch:\", ds[0])\n",
    "print(\"Length:\", len(ds))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "5O3PZxeTpokC"
   },
   "outputs": [],
   "source": [
    "# create a PyTorch dataloader builder\n",
    "\n",
    "def create_dataloader_v1(txt, batch_size=4, max_length=256,\n",
    "                         stride=128, shuffle=True, drop_last=True,\n",
    "                         num_workers=0):\n",
    "    tokenizer = tiktoken.get_encoding(\"gpt2\")\n",
    "    dataset = GPTDatasetV1(txt, tokenizer, max_length, stride)\n",
    "    dataloader = DataLoader(\n",
    "        dataset=dataset,\n",
    "        batch_size=batch_size,\n",
    "        shuffle=shuffle,\n",
    "        drop_last=drop_last,\n",
    "        num_workers=num_workers\n",
    "    )\n",
    "\n",
    "    return dataloader"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "iTbO4HcgqgUh",
    "outputId": "86d61909-8fe7-4e87-becb-66b47e717a20"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[tensor([[  40,  367, 2885, 1464]]), tensor([[ 367, 2885, 1464, 1807]])]\n"
     ]
    }
   ],
   "source": [
    "# uset the dataloader\n",
    "with open('the-verdict.txt', 'r', encoding='utf-8') as f:\n",
    "  raw_text = f.read()\n",
    "\n",
    "dataloader = create_dataloader_v1(raw_text, batch_size=1, max_length=4, stride=1, shuffle=False)\n",
    "data_iter = iter(dataloader)\n",
    "first_batch = next(data_iter)\n",
    "print(first_batch)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "cgA7jkLRq_m-",
    "outputId": "1b47c85b-c429-4955-8da0-c92505fd838f"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[tensor([[ 367, 2885, 1464, 1807]]), tensor([[2885, 1464, 1807, 3619]])]\n"
     ]
    }
   ],
   "source": [
    "# observe the meaning of the `stride` parameter\n",
    "second_batch = next(data_iter)\n",
    "print(second_batch)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "s-bOB0jfrP8U"
   },
   "source": [
    "#### Exercise 2.2 Data loaders with different strides and context sizes\n",
    "\n",
    "To develop more intuition for how the data loader works, try to run it with different settings such as max_length=2 and stride=2, and max_length=8 and stride=2."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "ErdEfw3HrhL6",
    "outputId": "686a9d52-4f56-4ede-add9-a2bb0fe68c8b"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "max_length=2 and stride=2\n",
      "[tensor([[ 40, 367]]), tensor([[ 367, 2885]])]\n",
      "[tensor([[2885, 1464]]), tensor([[1464, 1807]])]\n"
     ]
    }
   ],
   "source": [
    "print('max_length=2 and stride=2')\n",
    "dataloader = create_dataloader_v1(raw_text, batch_size=1, max_length=2, stride=2, shuffle=False)\n",
    "data_iter = iter(dataloader)\n",
    "first_batch = next(data_iter)\n",
    "print(first_batch)\n",
    "second_batch = next(data_iter)\n",
    "print(second_batch)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "UW9e8vAers_N",
    "outputId": "af5ae171-8f43-4581-dcb6-c20827eff134"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "max_length=8 and stride=8\n",
      "[tensor([[  40,  367, 2885, 1464, 1807, 3619,  402,  271]]), tensor([[  367,  2885,  1464,  1807,  3619,   402,   271, 10899]])]\n",
      "[tensor([[10899,  2138,   257,  7026, 15632,   438,  2016,   257]]), tensor([[ 2138,   257,  7026, 15632,   438,  2016,   257,   922]])]\n"
     ]
    }
   ],
   "source": [
    "print('max_length=8 and stride=8')\n",
    "dataloader = create_dataloader_v1(raw_text, batch_size=1, max_length=8, stride=8, shuffle=False)\n",
    "data_iter = iter(dataloader)\n",
    "first_batch = next(data_iter)\n",
    "print(first_batch)\n",
    "second_batch = next(data_iter)\n",
    "print(second_batch)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "029XHr3bsEBV",
    "outputId": "ecbc6f7f-fccd-41fa-a535-39fab91191ca"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[   40,   367,  2885,  1464],\n",
      "        [ 1807,  3619,   402,   271],\n",
      "        [10899,  2138,   257,  7026],\n",
      "        [15632,   438,  2016,   257],\n",
      "        [  922,  5891,  1576,   438],\n",
      "        [  568,   340,   373,   645],\n",
      "        [ 1049,  5975,   284,   502],\n",
      "        [  284,  3285,   326,    11]])\n",
      "tensor([[  367,  2885,  1464,  1807],\n",
      "        [ 3619,   402,   271, 10899],\n",
      "        [ 2138,   257,  7026, 15632],\n",
      "        [  438,  2016,   257,   922],\n",
      "        [ 5891,  1576,   438,   568],\n",
      "        [  340,   373,   645,  1049],\n",
      "        [ 5975,   284,   502,   284],\n",
      "        [ 3285,   326,    11,   287]])\n"
     ]
    }
   ],
   "source": [
    "# observe a batch size greater than 1, as is typical for real world use\n",
    "\n",
    "dataloader = create_dataloader_v1(raw_text, batch_size=8, max_length=4, stride=4, shuffle=False)\n",
    "data_iter = iter(dataloader)\n",
    "inputs, targets = next(data_iter)\n",
    "print(inputs)\n",
    "print(targets)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "mzEArfjHaRaU",
    "outputId": "ba12f1cc-8935-4755-be3e-07b269ab29b1"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Parameter containing:\n",
       "tensor([[ 0.3374, -0.1778, -0.1690],\n",
       "        [ 0.9178,  1.5810,  1.3010],\n",
       "        [ 1.2753, -0.2010, -0.1606],\n",
       "        [-0.4015,  0.9666, -1.1481],\n",
       "        [-1.1589,  0.3255, -0.6315],\n",
       "        [-2.8400, -0.7849, -1.4096]], requires_grad=True)"
      ]
     },
     "execution_count": 220,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# demonstrate token ID to embedding vector conversion\n",
    "\n",
    "input_ids = torch.tensor([2, 3, 5, 1])\n",
    "vocab_size = 6\n",
    "output_dim = 3\n",
    "\n",
    "torch.manual_seed(123)\n",
    "embedding_layer = torch.nn.Embedding(vocab_size, output_dim)\n",
    "embedding_layer.weight\n",
    "\n",
    "# We will get a 6x3 matrix, one row per possible vocabulary term\n",
    "# and a column for each embedding dimension"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "4xTqiwbsazRJ",
    "outputId": "e3fa2cff-9917-44d7-bf6a-c21034f74018"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([3])\n",
      "tensor([[-0.4015,  0.9666, -1.1481]], grad_fn=<EmbeddingBackward0>)\n"
     ]
    }
   ],
   "source": [
    "# Let's obtain an embedding vector.\n",
    "print(torch.tensor([3]))\n",
    "print(embedding_layer(torch.tensor([3])))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "V5-wQx4JblNz",
    "outputId": "099847cc-0389-402c-de19-a9e50de3e597"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[ 1.2753, -0.2010, -0.1606],\n",
      "        [-0.4015,  0.9666, -1.1481],\n",
      "        [-2.8400, -0.7849, -1.4096],\n",
      "        [ 0.9178,  1.5810,  1.3010]], grad_fn=<EmbeddingBackward0>)\n"
     ]
    }
   ],
   "source": [
    "# And all embeddings for our vocab:\n",
    "print(embedding_layer(input_ids))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "zME5e__2dJbD"
   },
   "source": [
    "Ultimately this matrix will be part of the neural network which implements our language model. In the course of training that model to accurately predict the next token in the sequence, the embedding layer will tend to assume weights such that semantically similar token wind up closer together in the embedding space."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "yvADnGqqfiRo"
   },
   "outputs": [],
   "source": [
    "# Now a more realistic example\n",
    "vocab_size = 50257 # The vocabulary size of the BPE tokenizer we use\n",
    "output_dim = 256\n",
    "token_embedding_layer = torch.nn.Embedding(vocab_size, output_dim)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "ymwZnK0Nga55",
    "outputId": "fbbf250b-bbab-4f08-8b29-cb140e4a4ba9"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Input token ID's:\n",
      " tensor([[   40,   367,  2885,  1464],\n",
      "        [ 1807,  3619,   402,   271],\n",
      "        [10899,  2138,   257,  7026],\n",
      "        [15632,   438,  2016,   257],\n",
      "        [  922,  5891,  1576,   438],\n",
      "        [  568,   340,   373,   645],\n",
      "        [ 1049,  5975,   284,   502],\n",
      "        [  284,  3285,   326,    11]])\n",
      "Input shape:\n",
      " torch.Size([8, 4])\n"
     ]
    }
   ],
   "source": [
    "# Instantiate a dataloader with 8 samples in a batch\n",
    "# and up to 4 tokens per batch.\n",
    "max_length = 4\n",
    "dataloader = create_dataloader_v1(\n",
    "    raw_text, batch_size=8, max_length=max_length,\n",
    "    stride=max_length, shuffle=False)\n",
    "data_iter = iter(dataloader)\n",
    "inputs, targets = next(data_iter)\n",
    "print(\"Input token ID's:\\n\", inputs)\n",
    "print(\"Input shape:\\n\", inputs.shape)\n",
    "\n",
    "# Prints an 8x4 matrix of (samples)x(tokens) for a batch.\n",
    "# Each batch has eight text samples, and each text\n",
    "# sample has four tokens."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "M8ZhlpSMiK6S"
   },
   "source": [
    "When we embed the preceding batch of tokens, we replace each cell in the matrix with a vector of 256 elements, corresponding to the appropriate row in the 50,257x256 embedding matrix."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "t-j0L6Bhj4kt",
    "outputId": "f6b51203-7b0a-4280-dd00-93c85c01e4cf"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Batch embeddings shape: torch.Size([8, 4, 256])\n",
      "Sample embeddings shape: torch.Size([4, 256])\n",
      "Token embeddings shape: torch.Size([256])\n"
     ]
    }
   ],
   "source": [
    "token_embeddings = token_embedding_layer(inputs)\n",
    "print(\"Batch embeddings shape:\", token_embeddings.shape)\n",
    "print(\"Sample embeddings shape:\", token_embeddings[0].shape)\n",
    "print(\"Token embeddings shape:\", token_embeddings[0][0].shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "V10v5ILOpi-U"
   },
   "source": [
    "Now we need a way to account for token position within each sample. For this we will create a positional embedding layer with the same shape as a sample embedding: that is, the number of rows is the number of tokens, and the number of columns is the embedding dimension.\n",
    "\n",
    "We can then retrieve the positional embedding vector that corresponds to the first token position, the second token position, and so on. Each token embedding can then be summed with its corresponding position embedding to produce a combined embedding that represents both a token and its position within the sample."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "rktrJS45tjae",
    "outputId": "e5cab3a6-074f-4500-8656-8b79bd9ffd02"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Seq: tensor([0, 1, 2, 3])\n",
      "tensor([[ 1.7375, -0.5620, -0.6303,  ..., -0.2277,  1.5748,  1.0345],\n",
      "        [ 1.6423, -0.7201,  0.2062,  ...,  0.4118,  0.1498, -0.4628],\n",
      "        [-0.4651, -0.7757,  0.5806,  ...,  1.4335, -0.4963,  0.8579],\n",
      "        [-0.6754, -0.4628,  1.4323,  ...,  0.8139, -0.7088,  0.4827]],\n",
      "       grad_fn=<EmbeddingBackward0>)\n",
      "torch.Size([4, 256])\n"
     ]
    }
   ],
   "source": [
    "# The context length represents how much our model can handle,\n",
    "# while the max_length represents the length of the raw input text.\n",
    "# In the real world it's possible for max_length > context_length,\n",
    "# and that has to be engineered around, but for our simple purposes\n",
    "# here we will assume they are the same.\n",
    "context_length = max_length\n",
    "pos_embedding_layer = torch.nn.Embedding(context_length, output_dim)\n",
    "seq = torch.arange(context_length)\n",
    "print(\"Seq:\", seq)\n",
    "pos_embeddings = pos_embedding_layer(seq)\n",
    "print(pos_embeddings)\n",
    "print(pos_embeddings.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "E-K0sOCfuj4A",
    "outputId": "94441372-476f-47cb-c6ff-63ea767f2790"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[ 1.7375, -0.5620, -0.6303,  ..., -0.2277,  1.5748,  1.0345],\n",
      "        [ 1.6423, -0.7201,  0.2062,  ...,  0.4118,  0.1498, -0.4628],\n",
      "        [-0.4651, -0.7757,  0.5806,  ...,  1.4335, -0.4963,  0.8579],\n",
      "        [-0.6754, -0.4628,  1.4323,  ...,  0.8139, -0.7088,  0.4827]],\n",
      "       grad_fn=<EmbeddingBackward0>)\n",
      "torch.Size([4, 256])\n"
     ]
    }
   ],
   "source": [
    "# Note that subsequent calls to pos_embedding_layer() with\n",
    "# the same input produce the same results.\n",
    "pos_embeddings = pos_embedding_layer(seq)\n",
    "print(pos_embeddings)\n",
    "print(pos_embeddings.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "W4_GUIvYvC11",
    "outputId": "02971cfc-2281-4552-bed3-d15d1f6356b2"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[ 1.6423, -0.7201,  0.2062,  ...,  0.4118,  0.1498, -0.4628],\n",
      "        [-0.6754, -0.4628,  1.4323,  ...,  0.8139, -0.7088,  0.4827],\n",
      "        [-0.4651, -0.7757,  0.5806,  ...,  1.4335, -0.4963,  0.8579],\n",
      "        [ 1.6423, -0.7201,  0.2062,  ...,  0.4118,  0.1498, -0.4628],\n",
      "        [-0.4651, -0.7757,  0.5806,  ...,  1.4335, -0.4963,  0.8579]],\n",
      "       grad_fn=<EmbeddingBackward0>)\n",
      "torch.Size([5, 256])\n"
     ]
    }
   ],
   "source": [
    "# Calls with different input produce different results.\n",
    "seq = torch.tensor([1, 3, 2, 1, 2])\n",
    "pos_embeddings = pos_embedding_layer(seq)\n",
    "print(pos_embeddings)\n",
    "print(pos_embeddings.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "MMllHJH_vl7F",
    "outputId": "cefeaa27-f95f-410e-fb08-0965211bda97"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Error: index out of range in self\n"
     ]
    }
   ],
   "source": [
    "# Trying to retrieve the embedding for something beyond the bounds\n",
    "# of our embedding layer produces an error\n",
    "seq = torch.tensor([4])\n",
    "try:\n",
    "  pos_embeddings = pos_embedding_layer(seq)\n",
    "  print(pos_embeddings)\n",
    "  print(pos_embeddings.shape)\n",
    "except Exception as e:\n",
    "  print(\"Error:\", e)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "9Y6PW7aiyFpW",
    "outputId": "d64134b8-5001-47db-90a8-1e750192e9af"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Token embeddings shape: torch.Size([8, 4, 256])\n",
      "Position embeddings shape: torch.Size([4, 256])\n",
      "Input embeddings shape: torch.Size([8, 4, 256])\n"
     ]
    }
   ],
   "source": [
    "# We can broadcast the position embeddings tensor to\n",
    "# each row in the token_embeddings tensor because they have\n",
    "# the same shape, which makes it convenient and efficient\n",
    "# to produce the combined token + position embedding for each\n",
    "# token, aka the input embedding.\n",
    "seq = torch.arange(context_length)\n",
    "pos_embeddings = pos_embedding_layer(seq)\n",
    "print(\"Token embeddings shape:\", token_embeddings.shape)\n",
    "print(\"Position embeddings shape:\", pos_embeddings.shape)\n",
    "input_embeddings = token_embeddings + pos_embeddings\n",
    "print(\"Input embeddings shape:\", input_embeddings.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "brRdRyIn3UWe"
   },
   "source": [
    "Why is it valid to just straight up add the token and position embeddings together? Intuitively, this makes more sense to me as an engineering thing than a math thing. We have input tokens with certain characteristics, and it just so happens that these tokens have both semantic meaning, and also their position is meaningful. Just as a low-resolution image devolves into pixel art while a high resolution image can be lifelike, if I embed these tokens into a low dimensional space, I probably will capture very little of both the semantic and positional information. But if I use a stupidly high dimensional embedding space, there will be more than enough room to store both pieces of information — and there will also be a lot of waste. So the trick is to find the sweet spot, and in practice that's a matter of enlightened trial-and-error.\n",
    "\n",
    "Coming at it from a DSP angle: insufficient dimensionality in the embedding space is a lot like a too-low sampling rate, e.g. real-world recordings captured at 8khz are just inevitably going to alias like crazy. So with both embedding space dimensionality and sample rates, you want to crank things up high enough so that you don't have \"aliasing\" (information getting not just lost but garbled and bounced around in weird ways), but not so high that you're wasting resources.\n",
    "\n",
    "What we call \"aliasing\" in the world of audio signals goes by the name \"crosstalk\" in neural networks, and they both represent the same essential phenomenon of \"a system which can't accomodate its input information.\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "93_lt9HG3_BY"
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "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.14.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
