{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "NXou6U-PVITq"
      },
      "source": [
        "# Luyện tập PyTorch: tự viết, không nhờ LLM\n",
        "\n",
        "29 bài tập chia thành 7 phần. Mỗi bài gồm ba thứ: **đề** (ô này), **ô để bạn viết** (có `# TODO`) và **ô kiểm tra** (`assert`). Chạy ô kiểm tra: qua hết thì in ✅.\n",
        "\n",
        "**Quy tắc**\n",
        "- Tắt autocomplete (Copilot, Cursor) và đóng tab chat LLM khi làm.\n",
        "- Viết từ ô trống. Kẹt thì tự debug ít nhất 20 phút (đọc traceback từ dưới lên, `print(x.shape, x.dtype, x.device)`), rồi mới mở docs: `help(torch.gather)` hoặc docs.pytorch.org.\n",
        "- Chỉ hỏi LLM sau khi bài đã qua, và chỉ để review code của bạn.\n",
        "- Các ô kiểm tra chạy trên CPU. Khi `Restart & Run All`, các ô chưa làm sẽ báo `NotImplementedError`: bình thường.\n",
        "- Ô helper ở đầu notebook có hàm `_ref_*`: đó là đáp án nội bộ cho Phần 7, đừng mở trước khi tự làm.\n",
        "\n",
        "Tiến độ xem ở ô cuối notebook."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "8qI5rs5aVITs",
        "outputId": "80d9c9b7-0a26-40c8-87aa-ec9093422f50"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "torch 2.8.0+cu126 | device: cuda\n"
          ]
        }
      ],
      "source": [
        "import copy\n",
        "import math\n",
        "import os\n",
        "import random\n",
        "import tempfile\n",
        "\n",
        "import numpy as np\n",
        "import torch\n",
        "import torch.nn as nn\n",
        "import torch.nn.functional as F\n",
        "from torch.utils.data import DataLoader, Dataset, random_split\n",
        "\n",
        "\n",
        "def set_seed(seed=0):\n",
        "    random.seed(seed)\n",
        "    np.random.seed(seed)\n",
        "    torch.manual_seed(seed)\n",
        "\n",
        "\n",
        "set_seed(0)\n",
        "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
        "print(\"torch\", torch.__version__, \"| device:\", device)\n",
        "\n",
        "_DONE = set()\n",
        "\n",
        "\n",
        "def done(tag):\n",
        "    _DONE.add(tag)\n",
        "    print(f\"✅ Bài {tag} qua ({len(_DONE)}/29)\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "id": "pVryXApMVITs"
      },
      "outputs": [],
      "source": [
        "# Dữ liệu tổng hợp dùng cho các bài sau (không cần tải gì)\n",
        "def make_circle_data(n, seed):\n",
        "    # 2 lớp: điểm nằm trong / ngoài hình tròn bán kính 1 (cần phi tuyến)\n",
        "    g = torch.Generator().manual_seed(seed)\n",
        "    X = torch.randn(n, 2, generator=g)\n",
        "    y = (X.pow(2).sum(dim=1) > 1.0).long()\n",
        "    return X, y\n",
        "\n",
        "\n",
        "def make_pattern_images(n, seed, size=16, noise=0.1):\n",
        "    # ảnh xám size x size, 3 lớp: 0 = đường ngang, 1 = đường dọc, 2 = đường chéo\n",
        "    g = torch.Generator().manual_seed(seed)\n",
        "    labels = torch.randint(0, 3, (n,), generator=g)\n",
        "    imgs = torch.zeros(n, 1, size, size)\n",
        "    for i in range(n):\n",
        "        c = int(labels[i])\n",
        "        if c == 0:\n",
        "            r = int(torch.randint(2, size - 2, (1,), generator=g))\n",
        "            imgs[i, 0, r, :] = 1.0\n",
        "        elif c == 1:\n",
        "            col = int(torch.randint(2, size - 2, (1,), generator=g))\n",
        "            imgs[i, 0, :, col] = 1.0\n",
        "        else:\n",
        "            off = int(torch.randint(-3, 4, (1,), generator=g))\n",
        "            for r in range(size):\n",
        "                col = r + off\n",
        "                if 0 <= col < size:\n",
        "                    imgs[i, 0, r, col] = 1.0\n",
        "    imgs = imgs + noise * torch.randn(n, 1, size, size, generator=g)\n",
        "    return imgs, labels"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "id": "41zp8UalVITt"
      },
      "outputs": [],
      "source": [
        "# Đáp án nội bộ cho Phần 7. Đừng mở ô này trước khi tự làm xong Phần 7.\n",
        "def _ref_train_linear(X, y, steps=50, lr=0.1):\n",
        "    torch.manual_seed(0)\n",
        "    model = nn.Linear(X.shape[1], 1)\n",
        "    opt = torch.optim.SGD(model.parameters(), lr=lr)\n",
        "    for _ in range(steps):\n",
        "        opt.zero_grad()\n",
        "        pred = model(X).squeeze(-1)\n",
        "        loss = F.mse_loss(pred, y)\n",
        "        loss.backward()\n",
        "        opt.step()\n",
        "    return model, loss.item()\n",
        "\n",
        "\n",
        "def _ref_epoch_loss(model, loader, opt):\n",
        "    total, count = 0.0, 0\n",
        "    for xb, yb in loader:\n",
        "        opt.zero_grad()\n",
        "        loss = F.cross_entropy(model(xb), yb)\n",
        "        loss.backward()\n",
        "        opt.step()\n",
        "        total += loss.item() * len(xb)\n",
        "        count += len(xb)\n",
        "    return total / count"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "o0N5OVOzVITt"
      },
      "source": [
        "## Phần 1. Tensor và broadcasting (6 bài)\n",
        "\n",
        "Mục tiêu: nhìn một phép toán là đoán được shape kết quả, và viết được không cần vòng lặp."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BkrLP-1jVITt"
      },
      "source": [
        "### Bài 1.1. Bảng nhân bằng broadcasting\n",
        "Viết `make_table(n)` trả về tensor `float32` shape `(n, n)` với `[i, j] = i * j`. Không dùng vòng lặp.\n",
        "\n",
        "Tra cứu: `torch.arange`, indexing với `None`, quy tắc broadcasting."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "TQHx691DVITt",
        "outputId": "9a828e9d-bfac-4bff-d5f2-0a03dbcff4a7"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "tensor([[ 0.,  0.,  0.,  0.,  0.],\n",
              "        [ 0.,  1.,  2.,  3.,  4.],\n",
              "        [ 0.,  2.,  4.,  6.,  8.],\n",
              "        [ 0.,  3.,  6.,  9., 12.],\n",
              "        [ 0.,  4.,  8., 12., 16.]])"
            ]
          },
          "execution_count": 4,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "def make_table(n):\n",
        "    # TODO\n",
        "    v = torch.arange(n, dtype=torch.float32)\n",
        "    b = torch.reshape(v, (-1, 1))\n",
        "    return v * b\n",
        "make_table(5)\n",
        "\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "5lOo5aRiVITu",
        "outputId": "cba0a1cb-ebc7-481c-a9fc-fa613fc5632c"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "✅ Bài 1.1 qua (1/29)\n"
          ]
        }
      ],
      "source": [
        "t = make_table(4)\n",
        "expected = torch.tensor([[i * j for j in range(4)] for i in range(4)], dtype=torch.float32)\n",
        "assert t.shape == (4, 4), f\"shape sai: {tuple(t.shape)}\"\n",
        "assert t.dtype == torch.float32, f\"dtype sai: {t.dtype}\"\n",
        "assert torch.equal(t, expected)\n",
        "assert make_table(1).shape == (1, 1)\n",
        "done(\"1.1\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "y7t_AaUCVITu"
      },
      "source": [
        "### Bài 1.2. Khoảng cách từng cặp\n",
        "Viết `pairwise_sq_dist(a, b)` với `a: (N, D)`, `b: (M, D)` trả về `(N, M)`, phần tử `[i, j] = ||a[i] - b[j]||²`. Không vòng lặp, không dùng `torch.cdist`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "id": "xgnSMSsJVITu"
      },
      "outputs": [],
      "source": [
        "def pairwise_sq_dist(a, b):\n",
        "    # TODO\n",
        "    a_new = b[None,:,:]\n",
        "    b_new = a[:,None,:]\n",
        "    diff =  abs(a_new - b_new)\n",
        "    print(diff.shape)\n",
        "    n = diff**2\n",
        "\n",
        "    return n.sum(-1)\n",
        "    ##raise NotImplementedError\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "zSZ10VPVVITu",
        "outputId": "06045b4c-938d-478e-8877-70351549a8fa"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "torch.Size([5, 7, 3])\n",
            "✅ Bài 1.2 qua (2/29)\n"
          ]
        }
      ],
      "source": [
        "set_seed(0)\n",
        "a, b = torch.randn(5, 3), torch.randn(7, 3)\n",
        "d = pairwise_sq_dist(a, b)\n",
        "assert d.shape == (5, 7), f\"shape sai: {tuple(d.shape)}\"\n",
        "assert torch.allclose(d, torch.cdist(a, b) ** 2, atol=1e-4)\n",
        "assert (d >= -1e-5).all()\n",
        "done(\"1.2\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XWt111pxVITu"
      },
      "source": [
        "### Bài 1.3. Chọn một phần tử mỗi hàng\n",
        "Viết `pick_per_row(x, idx)` với `x: (N, C)`, `idx: (N,)` kiểu `long`, trả về `(N,)` có phần tử `i` là `x[i, idx[i]]`. Không vòng lặp.\n",
        "\n",
        "Tra cứu: `torch.gather`, advanced indexing."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "5ZVj-DU6VITv",
        "outputId": "2f9b7098-4ec9-40c6-ac5c-f8e125e8ce2e"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "torch.Size([6])\n",
            "torch.Size([6, 4])\n"
          ]
        }
      ],
      "source": [
        "def pick_per_row(x, idx):\n",
        "    # TODO\n",
        "\n",
        "    idx[:, None]\n",
        "\n",
        "    result = torch.gather(x, dim=1, index=idx[:, None])\n",
        "    result = result.squeeze(1)\n",
        "    return result\n",
        "\n",
        "    raise NotImplementedError\n",
        "idx = torch.tensor([0, 3, 1, 2, 2, 0])\n",
        "print(idx.shape)\n",
        "x = torch.randn(6, 4)\n",
        "print(x.shape)\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "6E588_cGVITv",
        "outputId": "947b9065-4258-4d0e-f112-e4567e9b56fb"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "True\n",
            "✅ Bài 1.3 qua (3/29)\n"
          ]
        }
      ],
      "source": [
        "set_seed(0)\n",
        "x = torch.randn(6, 4)\n",
        "idx = torch.tensor([0, 3, 1, 2, 2, 0])\n",
        "\n",
        "out = pick_per_row(x, idx)\n",
        "assert out.shape == (6,), f\"shape sai: {tuple(out.shape)}\"\n",
        "assert torch.equal(out, torch.stack([x[i, idx[i]] for i in range(6)]))\n",
        "print(torch.equal(out, torch.stack([x[i, idx[i]] for i in range(6)])))\n",
        "done(\"1.3\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nDmG2tbKVITv"
      },
      "source": [
        "### Bài 1.4. Softmax ổn định số học\n",
        "Viết `stable_softmax(x, dim)` tự cài, không dùng `F.softmax`, `torch.softmax` hay `x.softmax`. Phải không ra `nan` khi giá trị rất lớn."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "qaZY9g7bVITv",
        "outputId": "af673008-304a-42b6-deec-4f405d65d379"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "tensor([[0.1311, 0.0774, 0.2856, 0.2110, 0.2948],\n",
              "        [0.4691, 0.1667, 0.0556, 0.0568, 0.2518],\n",
              "        [0.3273, 0.3915, 0.0241, 0.0888, 0.1683],\n",
              "        [0.6531, 0.0340, 0.1002, 0.1074, 0.1053]])"
            ]
          },
          "execution_count": 10,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "def stable_softmax(x, dim=-1):\n",
        "    # TODO\n",
        "    max_x, _ = torch.max(x, dim=dim, keepdim=True)\n",
        "    ezi = torch.exp(x - max_x)\n",
        "\n",
        "    sumezi = torch.sum(ezi ,dim = dim, keepdim=True)\n",
        "\n",
        "    g = ezi/sumezi\n",
        "    return g\n",
        "\n",
        "\n",
        "    raise NotImplementedError\n",
        "x = torch.randn(4, 5)\n",
        "stable_softmax(x, dim = -1)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "3i3Mir_aVITv",
        "outputId": "10d35a02-72b0-4ac2-f188-e95cdea7e387"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "✅ Bài 1.4 qua (4/29)\n"
          ]
        }
      ],
      "source": [
        "set_seed(0)\n",
        "x = torch.randn(4, 5)\n",
        "for dim in (-1, 0, 1):\n",
        "    assert torch.allclose(stable_softmax(x, dim), F.softmax(x, dim=dim), atol=1e-6), f\"sai với dim={dim}\"\n",
        "big = torch.tensor([[1000.0, 1001.0, 1002.0]])\n",
        "out = stable_softmax(big, dim=-1)\n",
        "assert torch.isfinite(out).all(), \"bị nan/inf khi giá trị lớn: nhớ trừ max\"\n",
        "assert torch.allclose(out, F.softmax(big, dim=-1), atol=1e-6)\n",
        "assert torch.allclose(out.sum(dim=-1), torch.ones(1))\n",
        "done(\"1.4\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0KTgN1DRVITv"
      },
      "source": [
        "### Bài 1.5. Dạng song tuyến tính theo batch\n",
        "Viết `batched_bilinear(x, W, y)` với `x: (B, N)`, `W: (N, M)`, `y: (B, M)` trả về `(B,)`, phần tử `b` là `x[b] @ W @ y[b]`. Dùng đúng một lần `torch.einsum`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "bhf1dRI6VITv",
        "outputId": "7d37c607-e9c9-4699-ebc2-253d1f82fc17"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "tensor([[ 1.5410, -0.2934, -2.1788],\n",
            "        [ 0.5684, -1.0845, -1.3986],\n",
            "        [ 0.4033,  0.8380, -0.7193],\n",
            "        [-0.4033, -0.5966,  0.1820],\n",
            "        [-0.8567,  1.1006, -1.0712]])\n"
          ]
        }
      ],
      "source": [
        "def batched_bilinear(x, W, y):\n",
        "    # TODO\n",
        "\n",
        "    a = torch.einsum(\"bn,nm,bm -> b\", x,W,y)\n",
        "    return a\n",
        "    raise NotImplementedError\n",
        "\n",
        "print(a)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Q9dKD5hvVITw",
        "outputId": "357ec2d2-e7c2-4919-9f6e-ddece70d1b51"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "✅ Bài 1.5 qua (5/29)\n"
          ]
        }
      ],
      "source": [
        "set_seed(0)\n",
        "x, W, y = torch.randn(6, 4), torch.randn(4, 3), torch.randn(6, 3)\n",
        "out = batched_bilinear(x, W, y)\n",
        "assert out.shape == (6,), f\"shape sai: {tuple(out.shape)}\"\n",
        "expected = torch.stack([x[b] @ W @ y[b] for b in range(6)])\n",
        "assert torch.allclose(out, expected, atol=1e-5)\n",
        "done(\"1.5\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RMg47oE0VITw"
      },
      "source": [
        "### Bài 1.6. Trung bình có mask\n",
        "Viết `masked_mean(x, mask)` với `x: (B, T)` float, `mask: (B, T)` bool (`True` = phần tử hợp lệ). Trả về `(B,)`: trung bình các phần tử hợp lệ của từng hàng. Mỗi hàng có ít nhất một phần tử hợp lệ. Giá trị ở vị trí bị che không được ảnh hưởng kết quả."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "metadata": {
        "id": "xN53nyoGVITw"
      },
      "outputs": [],
      "source": [
        "def masked_mean(x, mask):\n",
        "\n",
        "    # TODO\n",
        "    count = tensor.sum(mask, dim = 1)\n",
        "    sum = tensor.sum(x * mask, dim = 1)\n",
        "    \n",
        "\n",
        "    raise NotImplementedError"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 211
        },
        "id": "7v2CuhpnVITw",
        "outputId": "cffadeb9-a546-419e-8cef-810b2d1defdc"
      },
      "outputs": [],
      "source": [
        "x = torch.tensor([[1.0, 2.0, 3.0, 4.0],\n",
        "                  [10.0, 20.0, 30.0, 40.0]])\n",
        "mask = torch.tensor([[True, True, False, False],\n",
        "                     [True, True, True, False]])\n",
        "\n",
        "out = masked_mean(x, mask)\n",
        "assert out.shape == (2,)\n",
        "assert torch.allclose(out, torch.tensor([1.5, 20.0]))\n",
        "x_dirty = x.clone()\n",
        "x_dirty[~mask] = 1e9\n",
        "assert torch.allclose(masked_mean(x_dirty, mask), torch.tensor([1.5, 20.0])), \"giá trị ở vị trí bị che đang ảnh hưởng kết quả\"\n",
        "done(\"1.6\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4h7Y6XvQVITw"
      },
      "source": [
        "## Phần 2. Autograd (4 bài)\n",
        "\n",
        "Mục tiêu: hiểu gradient được tạo ra, cộng dồn và bị tắt như thế nào."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Q19gZlE9VITw"
      },
      "source": [
        "### Bài 2.1. Gradient bằng autograd\n",
        "Viết `grad_of(f, x)`: `f` nhận tensor và trả về scalar; trả về `df/dx` cùng shape với `x`. Không làm thay đổi `x` của người gọi. Không dùng `torch.autograd.functional`.\n",
        "\n",
        "Tra cứu: `detach`, `requires_grad_`, `backward`, `torch.autograd.grad`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "irAIVcgHVITw"
      },
      "outputs": [],
      "source": [
        "def grad_of(f, x):\n",
        "    # TODO\n",
        "    raise NotImplementedError"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IEJX2fJCVITw"
      },
      "outputs": [],
      "source": [
        "def numeric_grad(f, x, eps=1e-6):\n",
        "    x = x.detach().double()\n",
        "    g = torch.zeros_like(x)\n",
        "    for i in range(x.numel()):\n",
        "        e = torch.zeros_like(x)\n",
        "        e.view(-1)[i] = eps\n",
        "        g.view(-1)[i] = (f(x + e) - f(x - e)).item() / (2 * eps)\n",
        "    return g\n",
        "\n",
        "\n",
        "set_seed(0)\n",
        "x = torch.randn(5, dtype=torch.float64)\n",
        "fs = [\n",
        "    lambda t: (t ** 3).sum() + (2 * t).sum(),\n",
        "    lambda t: torch.sin(t).sum() * t.pow(2).mean(),\n",
        "]\n",
        "for f in fs:\n",
        "    g = grad_of(f, x)\n",
        "    assert g.shape == x.shape\n",
        "    assert torch.allclose(g, numeric_grad(f, x), atol=1e-5), \"gradient sai\"\n",
        "assert not x.requires_grad and x.grad is None, \"bạn đã làm thay đổi x của người gọi\"\n",
        "done(\"2.1\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-xB79dL_VITw"
      },
      "source": [
        "### Bài 2.2. Hồi quy tuyến tính thủ công\n",
        "Viết `fit_linear_manual(X, y, lr, steps)` học `w` shape `(D,)` và `b` scalar bằng gradient descent thủ công:\n",
        "- khởi tạo `w`, `b` bằng zeros có `requires_grad=True`;\n",
        "- loss là MSE trung bình;\n",
        "- cập nhật tham số trong `torch.no_grad()` và tự xoá gradient sau mỗi bước;\n",
        "- không dùng `torch.optim`, không dùng `nn.Module`.\n",
        "\n",
        "Trả về `(w, b)`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Lo0EP6iDVITw"
      },
      "outputs": [],
      "source": [
        "def fit_linear_manual(X, y, lr=0.1, steps=200):\n",
        "    # TODO\n",
        "    raise NotImplementedError"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ITNrQEl9VITw"
      },
      "outputs": [],
      "source": [
        "set_seed(0)\n",
        "true_w = torch.tensor([2.0, -3.0, 0.5])\n",
        "true_b = 1.0\n",
        "X = torch.randn(200, 3)\n",
        "y = X @ true_w + true_b + 0.01 * torch.randn(200)\n",
        "w_fit, b_fit = fit_linear_manual(X, y, lr=0.1, steps=200)\n",
        "w_fit, b_fit = w_fit.detach(), b_fit.detach()\n",
        "assert w_fit.shape == (3,), f\"shape của w sai: {tuple(w_fit.shape)}\"\n",
        "assert torch.allclose(w_fit, true_w, atol=0.05), f\"w = {w_fit}\"\n",
        "assert abs(b_fit.item() - true_b) < 0.05, f\"b = {b_fit.item()}\"\n",
        "done(\"2.2\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "e0Yde1GYVITx"
      },
      "source": [
        "### Bài 2.3. Gradient cộng dồn\n",
        "Đoạn code dưới gọi `backward()` hai lần trên cùng một biểu thức. **Trước khi in `w23.grad`**, dự đoán giá trị của nó và ghi vào `answer_2_3`. Sau đó viết `backward_twice_clean(w, x)`: gọi `backward()` cho `w * x` hai lần nhưng không để gradient cộng dồn, và trả về **bản sao** của `w.grad` sau lần thứ hai."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "OJ8oNrRfVITx"
      },
      "outputs": [],
      "source": [
        "w23 = torch.tensor(2.0, requires_grad=True)\n",
        "x23 = torch.tensor(3.0)\n",
        "(w23 * x23).backward()\n",
        "(w23 * x23).backward()\n",
        "# print(w23.grad)   # chỉ bỏ comment sau khi đã dự đoán xong\n",
        "\n",
        "answer_2_3 = None   # TODO: điền dự đoán của bạn (một số)\n",
        "\n",
        "\n",
        "def backward_twice_clean(w, x):\n",
        "    # TODO\n",
        "    raise NotImplementedError"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "INy5l7Y9VITy"
      },
      "outputs": [],
      "source": [
        "assert answer_2_3 is not None, \"hãy điền dự đoán vào answer_2_3 trước\"\n",
        "assert float(answer_2_3) == w23.grad.item(), f\"dự đoán {answer_2_3} chưa khớp w23.grad thật\"\n",
        "w2 = torch.tensor(2.0, requires_grad=True)\n",
        "out = backward_twice_clean(w2, torch.tensor(3.0))\n",
        "assert out.item() == 3.0, f\"kỳ vọng 3.0, nhận {out.item()}\"\n",
        "assert out is not w2.grad, \"hãy trả về bản sao (clone), không phải chính w.grad\"\n",
        "done(\"2.3\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RZzI18FYVITy"
      },
      "source": [
        "### Bài 2.4. Cập nhật EMA không qua autograd\n",
        "Viết `ema_update(target, source, tau)`: với mỗi cặp tham số, `p_t = tau * p_s + (1 - tau) * p_t`, cập nhật tại chỗ. `target` và `source` là hai `nn.Module` cùng kiến trúc. Autograd không được ghi lại phép cập nhật, `source` không đổi, và tham số của `target` vẫn phải là leaf có `requires_grad=True`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WGxeaRh9VITy"
      },
      "outputs": [],
      "source": [
        "def ema_update(target, source, tau):\n",
        "    # TODO\n",
        "    raise NotImplementedError"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UAOS4mjoVITy"
      },
      "outputs": [],
      "source": [
        "set_seed(0)\n",
        "t, s = nn.Linear(3, 2), nn.Linear(3, 2)\n",
        "wt0, bt0 = t.weight.detach().clone(), t.bias.detach().clone()\n",
        "ws, bs = s.weight.detach().clone(), s.bias.detach().clone()\n",
        "ema_update(t, s, 0.1)\n",
        "assert torch.allclose(t.weight.detach(), 0.1 * ws + 0.9 * wt0, atol=1e-6)\n",
        "assert torch.allclose(t.bias.detach(), 0.1 * bs + 0.9 * bt0, atol=1e-6)\n",
        "assert torch.equal(s.weight.detach(), ws) and torch.equal(s.bias.detach(), bs), \"source không được thay đổi\"\n",
        "for p in t.parameters():\n",
        "    assert p.requires_grad and p.is_leaf and p.grad_fn is None\n",
        "done(\"2.4\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1asLpuaNVITz"
      },
      "source": [
        "## Phần 3. `nn.Module` và vòng lặp huấn luyện (4 bài)\n",
        "\n",
        "Mục tiêu: viết được vòng lặp huấn luyện, đánh giá và lưu/nạp checkpoint mà không nhìn tài liệu."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "h2abfPpzVITz"
      },
      "source": [
        "### Bài 3.1. MLP có độ sâu tuỳ chỉnh\n",
        "Viết `class MLP(nn.Module)` với `__init__(self, in_dim, hidden, out_dim, n_hidden_layers=1)`:\n",
        "- `n_hidden_layers` (>= 1) lớp ẩn `Linear` + `ReLU`; lớp ẩn đầu nhận `in_dim`, các lớp sau nhận `hidden`;\n",
        "- một `Linear(hidden, out_dim)` ở cuối, không activation.\n",
        "\n",
        "Tra cứu: `nn.ModuleList`, `nn.Sequential`. Nếu tham số không được đăng ký, số tham số sẽ sai."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "XyoRM0iwVITz"
      },
      "outputs": [],
      "source": [
        "class MLP(nn.Module):\n",
        "    # TODO: __init__ và forward\n",
        "    pass"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Sqy2955MVITz"
      },
      "outputs": [],
      "source": [
        "set_seed(0)\n",
        "\n",
        "\n",
        "def n_params(m):\n",
        "    return sum(p.numel() for p in m.parameters())\n",
        "\n",
        "\n",
        "m1 = MLP(2, 16, 3, n_hidden_layers=1)\n",
        "m2 = MLP(2, 16, 3, n_hidden_layers=2)\n",
        "assert isinstance(m1, nn.Module)\n",
        "assert n_params(m1) == 2 * 16 + 16 + 16 * 3 + 3, f\"số tham số m1 = {n_params(m1)}\"\n",
        "assert n_params(m2) == (2 * 16 + 16 + 16 * 3 + 3) + (16 * 16 + 16), f\"số tham số m2 = {n_params(m2)}\"\n",
        "assert m2(torch.randn(5, 2)).shape == (5, 3)\n",
        "a, b0, z = torch.randn(1, 2), torch.randn(1, 2), torch.zeros(1, 2)\n",
        "with torch.no_grad():\n",
        "    lhs = m2(a + b0)\n",
        "    rhs = m2(a) + m2(b0) - m2(z)\n",
        "assert not torch.allclose(lhs, rhs, atol=1e-5), \"mạng đang là hàm affine: thiếu ReLU?\"\n",
        "done(\"3.1\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nApSh-zMVITz"
      },
      "source": [
        "### Bài 3.2. Vòng lặp huấn luyện full-batch\n",
        "Viết `train_classifier(model, X, y, lr, epochs)`: huấn luyện bằng `Adam` + `CrossEntropyLoss`, mỗi epoch là một bước cập nhật trên toàn bộ dữ liệu. Trả về list các loss (kiểu `float`) theo epoch."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "PEDeuRjWVITz"
      },
      "outputs": [],
      "source": [
        "def train_classifier(model, X, y, lr=1e-2, epochs=400):\n",
        "    # TODO\n",
        "    raise NotImplementedError"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "zABXSGhtVITz"
      },
      "outputs": [],
      "source": [
        "set_seed(0)\n",
        "Xtr, ytr = make_circle_data(512, seed=1)\n",
        "Xte, yte = make_circle_data(512, seed=2)\n",
        "m = nn.Sequential(nn.Linear(2, 32), nn.ReLU(), nn.Linear(32, 2))\n",
        "losses = train_classifier(m, Xtr, ytr, lr=1e-2, epochs=400)\n",
        "assert len(losses) == 400, f\"len(losses) = {len(losses)}\"\n",
        "assert all(isinstance(l, float) for l in losses), \"loss phải là float (dùng .item())\"\n",
        "assert losses[-1] < 0.5 * losses[0], \"loss chưa giảm đủ\"\n",
        "m = m.cpu().eval()\n",
        "with torch.no_grad():\n",
        "    acc = (m(Xte).argmax(dim=1) == yte).float().mean().item()\n",
        "print(f\"accuracy test = {acc:.3f}\")\n",
        "assert acc > 0.92, f\"accuracy test = {acc:.3f}\"\n",
        "done(\"3.2\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aO0_vHVnVIT0"
      },
      "source": [
        "### Bài 3.3. Hàm đánh giá\n",
        "Viết `evaluate(model, X, y)` trả về `(loss, accuracy)`, cả hai là `float`; loss là cross entropy trung bình. Phải đặt model ở chế độ đánh giá và tắt tính gradient."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "8NtS5lByVIT0"
      },
      "outputs": [],
      "source": [
        "def evaluate(model, X, y):\n",
        "    # TODO\n",
        "    raise NotImplementedError"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-DVuMt0zVIT0"
      },
      "outputs": [],
      "source": [
        "set_seed(0)\n",
        "Xe, ye = make_circle_data(200, seed=3)\n",
        "net = nn.Sequential(nn.Linear(2, 16), nn.ReLU(), nn.Dropout(0.5), nn.Linear(16, 2))\n",
        "grad_flags = []\n",
        "hook = net.register_forward_hook(lambda mod, inp, out: grad_flags.append(torch.is_grad_enabled()))\n",
        "loss1, acc1 = evaluate(net, Xe, ye)\n",
        "loss2, acc2 = evaluate(net, Xe, ye)\n",
        "hook.remove()\n",
        "assert all(isinstance(v, float) for v in (loss1, acc1)), \"trả về float, không phải tensor (dùng .item())\"\n",
        "assert (loss1, acc1) == (loss2, acc2), \"kết quả đổi giữa hai lần gọi: quên model.eval() (Dropout)?\"\n",
        "assert grad_flags and not any(grad_flags), \"chưa tắt gradient: dùng torch.no_grad()\"\n",
        "net.eval()\n",
        "with torch.no_grad():\n",
        "    logits = net(Xe)\n",
        "assert abs(loss1 - F.cross_entropy(logits, ye).item()) < 1e-5\n",
        "assert abs(acc1 - (logits.argmax(dim=1) == ye).float().mean().item()) < 1e-6\n",
        "done(\"3.3\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BI5zWOzzVIT0"
      },
      "source": [
        "### Bài 3.4. Lưu và nạp checkpoint\n",
        "Viết hai hàm:\n",
        "- `save_checkpoint(path, model, optimizer, epoch)`: lưu `state_dict` của model, của optimizer và `epoch` vào một file;\n",
        "- `load_checkpoint(path, model, optimizer)`: nạp lại vào model và optimizer (tại chỗ), trả về `epoch` đã lưu.\n",
        "\n",
        "Mục tiêu là huấn luyện tiếp được như chưa từng dừng, nên trạng thái optimizer (động lượng của Adam) cũng phải được khôi phục."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "f8HEfWFZVIT0"
      },
      "outputs": [],
      "source": [
        "def save_checkpoint(path, model, optimizer, epoch):\n",
        "    # TODO\n",
        "    raise NotImplementedError\n",
        "\n",
        "\n",
        "def load_checkpoint(path, model, optimizer):\n",
        "    # TODO\n",
        "    raise NotImplementedError"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "61AjLpClVIT0"
      },
      "outputs": [],
      "source": [
        "set_seed(0)\n",
        "Xc, yc = make_circle_data(64, seed=4)\n",
        "\n",
        "\n",
        "def make_net():\n",
        "    return nn.Sequential(nn.Linear(2, 8), nn.ReLU(), nn.Linear(8, 2))\n",
        "\n",
        "\n",
        "net_a = make_net()\n",
        "opt_a = torch.optim.Adam(net_a.parameters(), lr=1e-2)\n",
        "for _ in range(5):\n",
        "    opt_a.zero_grad()\n",
        "    F.cross_entropy(net_a(Xc), yc).backward()\n",
        "    opt_a.step()\n",
        "\n",
        "with tempfile.TemporaryDirectory() as tmp:\n",
        "    path = os.path.join(tmp, \"ckpt.pt\")\n",
        "    save_checkpoint(path, net_a, opt_a, epoch=5)\n",
        "    assert os.path.exists(path)\n",
        "    set_seed(123)\n",
        "    net_b = make_net()\n",
        "    opt_b = torch.optim.Adam(net_b.parameters(), lr=1e-2)\n",
        "    epoch = load_checkpoint(path, net_b, opt_b)\n",
        "\n",
        "assert epoch == 5\n",
        "for pa, pb in zip(net_a.parameters(), net_b.parameters()):\n",
        "    assert torch.equal(pa, pb), \"tham số chưa khớp\"\n",
        "sa, sb = opt_a.state_dict()[\"state\"], opt_b.state_dict()[\"state\"]\n",
        "assert len(sb) == len(sa) > 0, \"chưa nạp trạng thái optimizer\"\n",
        "for k in sa:\n",
        "    assert torch.equal(sa[k][\"exp_avg\"], sb[k][\"exp_avg\"]), \"exp_avg chưa khớp\"\n",
        "    assert torch.equal(sa[k][\"exp_avg_sq\"], sb[k][\"exp_avg_sq\"]), \"exp_avg_sq chưa khớp\"\n",
        "done(\"3.4\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "peQG3_e-VIT0"
      },
      "source": [
        "## Phần 4. `Dataset` và `DataLoader` (3 bài)\n",
        "\n",
        "Mục tiêu: tự đóng gói dữ liệu, gộp batch có độ dài khác nhau, chia train/val tái lập được."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7ZRUxsOfVIT0"
      },
      "source": [
        "### Bài 4.1. Dataset tuỳ chỉnh\n",
        "Viết `class PairsDataset(Dataset)` với `__init__(self, X, y, transform=None)`, `__len__`, `__getitem__(i)` trả về `(x, y)`. Nếu có `transform` thì chỉ áp dụng cho `x`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "5an8zyW0VIT1"
      },
      "outputs": [],
      "source": [
        "class PairsDataset(Dataset):\n",
        "    # TODO\n",
        "    pass"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "KWrl5e9rVIT1"
      },
      "outputs": [],
      "source": [
        "set_seed(0)\n",
        "X, y = torch.randn(100, 4), torch.arange(100)\n",
        "ds = PairsDataset(X, y)\n",
        "assert len(ds) == 100\n",
        "xi, yi = ds[7]\n",
        "assert torch.equal(xi, X[7]) and int(yi) == 7\n",
        "ds2 = PairsDataset(X, y, transform=lambda t: t * 2)\n",
        "assert torch.equal(ds2[7][0], X[7] * 2) and int(ds2[7][1]) == 7\n",
        "batches = list(DataLoader(ds, batch_size=16, shuffle=False))\n",
        "assert len(batches) == 7\n",
        "assert batches[0][0].shape == (16, 4) and batches[0][1].shape == (16,)\n",
        "assert batches[-1][0].shape == (4, 4)\n",
        "assert len(list(DataLoader(ds, batch_size=16, drop_last=True))) == 6\n",
        "done(\"4.1\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LliNgWMCVIT1"
      },
      "source": [
        "### Bài 4.2. `collate_fn` cho chuỗi độ dài khác nhau\n",
        "Viết `pad_collate(batch)`; `batch` là list các `(seq, label)` với `seq: LongTensor (T_i,)` và `label: int`. Trả về `(padded, lengths, labels)`:\n",
        "- `padded`: `(B, T_max)` kiểu `long`, đệm số 0 ở cuối;\n",
        "- `lengths`: `(B,)` kiểu `long`, độ dài thật;\n",
        "- `labels`: `(B,)` kiểu `long`.\n",
        "\n",
        "Tra cứu: `torch.nn.utils.rnn.pad_sequence` (hoặc tự làm)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "pWXfrBAiVIT1"
      },
      "outputs": [],
      "source": [
        "def pad_collate(batch):\n",
        "    # TODO\n",
        "    raise NotImplementedError"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Zs7M-5RSVIT1"
      },
      "outputs": [],
      "source": [
        "class VarLenDataset(Dataset):\n",
        "    def __init__(self):\n",
        "        g = torch.Generator().manual_seed(0)\n",
        "        self.items = []\n",
        "        for i, L in enumerate([3, 5, 2, 4, 1, 6, 3]):\n",
        "            self.items.append((torch.randint(1, 50, (L,), generator=g), i % 2))\n",
        "\n",
        "    def __len__(self):\n",
        "        return len(self.items)\n",
        "\n",
        "    def __getitem__(self, i):\n",
        "        return self.items[i]\n",
        "\n",
        "\n",
        "vds = VarLenDataset()\n",
        "loader = DataLoader(vds, batch_size=4, shuffle=False, collate_fn=pad_collate)\n",
        "batches = list(loader)\n",
        "padded, lengths, labels = batches[0]\n",
        "assert padded.shape == (4, 5), f\"padded.shape = {tuple(padded.shape)}\"\n",
        "assert padded.dtype == torch.long and lengths.dtype == torch.long and labels.dtype == torch.long\n",
        "assert lengths.tolist() == [3, 5, 2, 4]\n",
        "assert labels.tolist() == [0, 1, 0, 1]\n",
        "for i in range(4):\n",
        "    seq = vds.items[i][0]\n",
        "    assert torch.equal(padded[i, : len(seq)], seq)\n",
        "    assert (padded[i, len(seq):] == 0).all()\n",
        "assert batches[1][0].shape == (3, 6)\n",
        "assert batches[1][1].tolist() == [1, 6, 3]\n",
        "done(\"4.2\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OnxdO-E4VIT1"
      },
      "source": [
        "### Bài 4.3. Chia train/val tái lập được\n",
        "Viết `split_and_loaders(dataset, val_frac, batch_size, seed)`: chia bằng `random_split` với `torch.Generator` có seed (cùng seed cho cùng cách chia). Trả về `(train_loader, val_loader)`; train xáo trộn, val không xáo trộn."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "vlyN2c3HVIT2"
      },
      "outputs": [],
      "source": [
        "def split_and_loaders(dataset, val_frac, batch_size, seed):\n",
        "    # TODO\n",
        "    raise NotImplementedError"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "G0_QEGCGVIT5"
      },
      "outputs": [],
      "source": [
        "set_seed(0)\n",
        "base = torch.utils.data.TensorDataset(torch.randn(200, 4), torch.arange(200))\n",
        "tl, vl = split_and_loaders(base, val_frac=0.25, batch_size=32, seed=7)\n",
        "assert len(tl.dataset) == 150 and len(vl.dataset) == 50\n",
        "tl2, vl2 = split_and_loaders(base, val_frac=0.25, batch_size=32, seed=7)\n",
        "assert list(vl.dataset.indices) == list(vl2.dataset.indices), \"cùng seed phải cho cùng cách chia\"\n",
        "tl3, vl3 = split_and_loaders(base, val_frac=0.25, batch_size=32, seed=8)\n",
        "assert list(vl.dataset.indices) != list(vl3.dataset.indices), \"khác seed phải cho cách chia khác\"\n",
        "tr_idx, va_idx = set(tl.dataset.indices), set(vl.dataset.indices)\n",
        "assert not (tr_idx & va_idx) and (tr_idx | va_idx) == set(range(200))\n",
        "assert isinstance(tl.sampler, torch.utils.data.RandomSampler), \"train_loader phải shuffle\"\n",
        "assert isinstance(vl.sampler, torch.utils.data.SequentialSampler), \"val_loader không được shuffle\"\n",
        "done(\"4.3\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2CwlxwawVIT5"
      },
      "source": [
        "## Phần 5. CNN (3 bài)\n",
        "\n",
        "Mục tiêu: tính được shape qua các lớp conv, thiết kế một CNN nhỏ và huấn luyện bằng mini-batch."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9UNeXPFNVIT5"
      },
      "source": [
        "### Bài 5.1. Output shape của `Conv2d`\n",
        "Viết `conv_out_size(h, w, kernel, stride=1, padding=0, dilation=1)` trả về `(h_out, w_out)` cho kernel vuông, bằng công thức (không tạo layer). Công thức có trong docs của `nn.Conv2d`; tự suy ra thì tốt hơn."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "XSzuFzM3VIT5"
      },
      "outputs": [],
      "source": [
        "def conv_out_size(h, w, kernel, stride=1, padding=0, dilation=1):\n",
        "    # TODO\n",
        "    raise NotImplementedError"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UqC2KhFZVIT5"
      },
      "outputs": [],
      "source": [
        "configs = [\n",
        "    (16, 16, 3, 1, 1, 1),\n",
        "    (16, 16, 3, 1, 0, 1),\n",
        "    (28, 20, 5, 2, 2, 1),\n",
        "    (15, 17, 3, 2, 0, 1),\n",
        "    (32, 32, 3, 1, 2, 2),\n",
        "    (10, 13, 4, 3, 1, 1),\n",
        "]\n",
        "for h, w, k, s, p, d in configs:\n",
        "    real = nn.Conv2d(1, 1, k, stride=s, padding=p, dilation=d)(torch.zeros(1, 1, h, w)).shape[-2:]\n",
        "    got = conv_out_size(h, w, k, s, p, d)\n",
        "    assert tuple(got) == tuple(real), f\"{(h, w, k, s, p, d)}: nhận {got}, thực tế {tuple(real)}\"\n",
        "done(\"5.1\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-hvInad_VIT5"
      },
      "source": [
        "### Bài 5.2. Một CNN nhỏ\n",
        "Viết `class SmallCNN(nn.Module)` với `__init__(self, n_classes=3)`; `forward(x)` nhận `(B, 1, 16, 16)` trả về logits `(B, n_classes)`. Yêu cầu: ít nhất 2 lớp `Conv2d`, tổng tham số không quá 20 000. Tính kích thước trước lớp `Linear` bằng tay (dùng bài 5.1), đừng thử sai."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "6dR6tGmIVIT6"
      },
      "outputs": [],
      "source": [
        "class SmallCNN(nn.Module):\n",
        "    # TODO\n",
        "    pass"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "U1t31K0ZVIT6"
      },
      "outputs": [],
      "source": [
        "net = SmallCNN(3)\n",
        "n = sum(p.numel() for p in net.parameters())\n",
        "assert n <= 20_000, f\"{n} tham số, nhiều quá\"\n",
        "assert sum(isinstance(m, nn.Conv2d) for m in net.modules()) >= 2, \"cần ít nhất 2 lớp Conv2d\"\n",
        "assert net(torch.randn(4, 1, 16, 16)).shape == (4, 3)\n",
        "assert SmallCNN(5)(torch.randn(2, 1, 16, 16)).shape == (2, 5)\n",
        "done(\"5.2\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6p3PIUK9VIT6"
      },
      "source": [
        "### Bài 5.3. Huấn luyện CNN theo mini-batch\n",
        "Viết `train_cnn(model, loader, epochs, lr)`: `Adam` + `CrossEntropyLoss`, lặp qua `loader` mỗi epoch. Trả về list loss trung bình (`float`) của từng epoch. Dùng `SmallCNN` của bạn ở bài 5.2.\n",
        "\n",
        "Tuỳ chọn: thử đưa model và batch lên `device` (GPU) rồi so tốc độ; ô kiểm tra tự đưa model về CPU."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WWMhRyoBVIT6"
      },
      "outputs": [],
      "source": [
        "def train_cnn(model, loader, epochs, lr):\n",
        "    # TODO\n",
        "    raise NotImplementedError"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "E3R9ldJyVIT6"
      },
      "outputs": [],
      "source": [
        "set_seed(0)\n",
        "Xi, yi = make_pattern_images(600, seed=10)\n",
        "Xt, yt = make_pattern_images(300, seed=11)\n",
        "train_loader = DataLoader(torch.utils.data.TensorDataset(Xi, yi), batch_size=64, shuffle=True)\n",
        "net = SmallCNN(3)\n",
        "hist = train_cnn(net, train_loader, epochs=20, lr=5e-3)\n",
        "assert len(hist) == 20 and all(isinstance(v, float) for v in hist), \"trả về list 20 float\"\n",
        "assert hist[-1] < hist[0], \"loss chưa giảm\"\n",
        "net = net.cpu().eval()\n",
        "with torch.no_grad():\n",
        "    acc = (net(Xt).argmax(dim=1) == yt).float().mean().item()\n",
        "print(f\"accuracy test = {acc:.3f}\")\n",
        "assert acc > 0.93, f\"accuracy test = {acc:.3f}\"\n",
        "done(\"5.3\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FFtRGq8YVIT7"
      },
      "source": [
        "## Phần 6. Attention (3 bài)\n",
        "\n",
        "Mục tiêu: tự cài attention và một Transformer block, kiểm tra được tính nhân quả (causal)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zNp3jo9lVIT7"
      },
      "source": [
        "### Bài 6.1. Scaled dot-product attention\n",
        "Viết `scaled_dot_product_attention(q, k, v, mask=None)` với `q: (B, T, d)`, `k: (B, S, d)`, `v: (B, S, dv)`. `mask` là `None` hoặc `bool` shape `(T, S)` hay `(B, T, S)`, `True` = được phép attend. Trả về `(out, attn)` với `out: (B, T, dv)` và `attn: (B, T, S)`. Không dùng `F.scaled_dot_product_attention`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "BTyFP045VIT7"
      },
      "outputs": [],
      "source": [
        "def scaled_dot_product_attention(q, k, v, mask=None):\n",
        "    # TODO\n",
        "    raise NotImplementedError"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "sWsSdYycVIT8"
      },
      "outputs": [],
      "source": [
        "set_seed(0)\n",
        "B, T, S, d, dv = 2, 5, 5, 8, 6\n",
        "q, k, v = torch.randn(B, T, d), torch.randn(B, S, d), torch.randn(B, S, dv)\n",
        "out, attn = scaled_dot_product_attention(q, k, v)\n",
        "assert out.shape == (B, T, dv) and attn.shape == (B, T, S)\n",
        "assert torch.allclose(attn.sum(dim=-1), torch.ones(B, T), atol=1e-5)\n",
        "assert torch.allclose(out, F.scaled_dot_product_attention(q, k, v), atol=1e-5)\n",
        "causal = torch.tril(torch.ones(T, S, dtype=torch.bool))\n",
        "out_c, attn_c = scaled_dot_product_attention(q, k, v, mask=causal)\n",
        "assert torch.allclose(out_c, F.scaled_dot_product_attention(q, k, v, attn_mask=causal), atol=1e-5)\n",
        "assert attn_c[:, ~causal].abs().max() < 1e-8, \"vị trí bị che phải có trọng số 0\"\n",
        "batch_mask = causal.unsqueeze(0).expand(B, T, S)\n",
        "out_b, _ = scaled_dot_product_attention(q, k, v, mask=batch_mask)\n",
        "assert torch.allclose(out_b, out_c, atol=1e-6)\n",
        "done(\"6.1\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ecMP7PbuVIT8"
      },
      "source": [
        "### Bài 6.2. Multi-head self-attention\n",
        "Viết `class MultiHeadSelfAttention(nn.Module)` với `__init__(self, d_model, n_heads, causal=False)`:\n",
        "- `raise ValueError` nếu `d_model` không chia hết cho `n_heads`;\n",
        "- bốn lớp `Linear(d_model, d_model)` có bias (chiếu q, k, v và chiếu đầu ra); dùng một `Linear(d_model, 3 * d_model)` cho q, k, v cũng được vì tổng tham số như nhau;\n",
        "- `forward(x)`: `x (B, T, d_model)` → `(B, T, d_model)`; nếu `causal=True`, vị trí `t` chỉ nhìn các vị trí `<= t`.\n",
        "\n",
        "Bạn có thể dùng lại `scaled_dot_product_attention` của bài 6.1."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "OA-ON9irVIT8"
      },
      "outputs": [],
      "source": [
        "class MultiHeadSelfAttention(nn.Module):\n",
        "    # TODO\n",
        "    pass"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "f1o707n9VIT8"
      },
      "outputs": [],
      "source": [
        "set_seed(0)\n",
        "d, h = 32, 4\n",
        "try:\n",
        "    MultiHeadSelfAttention(30, 4)\n",
        "except ValueError:\n",
        "    pass\n",
        "else:\n",
        "    raise AssertionError(\"cần ValueError khi d_model không chia hết cho n_heads\")\n",
        "mha = MultiHeadSelfAttention(d, h)\n",
        "assert sum(p.numel() for p in mha.parameters()) == 4 * d * d + 4 * d, \"số tham số không khớp: 4 Linear d x d có bias?\"\n",
        "x = torch.randn(2, 10, d)\n",
        "assert mha(x).shape == (2, 10, d)\n",
        "\n",
        "x2 = x.clone()\n",
        "x2[:, 5:] = torch.randn(2, 5, d)\n",
        "with torch.no_grad():\n",
        "    mha_c = MultiHeadSelfAttention(d, h, causal=True)\n",
        "    o1, o2 = mha_c(x), mha_c(x2)\n",
        "    assert torch.allclose(o1[:, :5], o2[:, :5], atol=1e-5), \"causal: đầu ra ở quá khứ bị ảnh hưởng bởi tương lai\"\n",
        "    assert not torch.allclose(o1[:, 5:], o2[:, 5:], atol=1e-5)\n",
        "    n1, n2 = mha(x), mha(x2)\n",
        "    assert not torch.allclose(n1[:, :5], n2[:, :5], atol=1e-5), \"non-causal: các vị trí đầu phải nhìn được tương lai\"\n",
        "done(\"6.2\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pHfs8ETpVIT8"
      },
      "source": [
        "### Bài 6.3. Transformer block (pre-norm)\n",
        "Viết `class TransformerBlock(nn.Module)` với `__init__(self, d_model, n_heads, causal=True)` và `forward(self, x)`:\n",
        "\n",
        "`x = x + attn(ln1(x))`, rồi `x = x + mlp(ln2(x))`, với `ln1`, `ln2` là `LayerNorm(d_model)` và `mlp = Linear(d, 4d) → GELU → Linear(4d, d)`. Dùng `MultiHeadSelfAttention` ở bài 6.2."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "LmoztiWXVIT8"
      },
      "outputs": [],
      "source": [
        "class TransformerBlock(nn.Module):\n",
        "    # TODO\n",
        "    pass"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "On7vxpbvVIT8"
      },
      "outputs": [],
      "source": [
        "set_seed(0)\n",
        "d, h = 32, 4\n",
        "blk = TransformerBlock(d, h, causal=True)\n",
        "assert sum(p.numel() for p in blk.parameters()) == 12 * d * d + 13 * d, \"số tham số không khớp\"\n",
        "x = torch.randn(2, 10, d)\n",
        "assert blk(x).shape == x.shape\n",
        "x2 = x.clone()\n",
        "x2[:, 6:] = torch.randn(2, 4, d)\n",
        "with torch.no_grad():\n",
        "    assert torch.allclose(blk(x)[:, :6], blk(x2)[:, :6], atol=1e-5), \"block không còn causal\"\n",
        "    for p in blk.parameters():\n",
        "        p.zero_()\n",
        "    assert torch.allclose(blk(x), x, atol=1e-6), \"khi mọi tham số bằng 0 block phải là phép đồng nhất: kiểm tra đường residual và pre-norm\"\n",
        "done(\"6.3\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_mg_toFRVIT8"
      },
      "source": [
        "## Phần 7. Debug lab (6 bài)\n",
        "\n",
        "Mỗi bài có một hàm **bị lỗi**. Chạy ô kiểm tra trước, đọc thông báo lỗi, tìm nguyên nhân, sửa hàm ở ô code rồi chạy lại. Đây là kỹ năng khó thay thế nhất khi tự làm việc với PyTorch."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Tbp0DJwjVIT9"
      },
      "source": [
        "### Bài 7.1. Kết quả khác bản đúng\n",
        "Hàm này huấn luyện hồi quy tuyến tính nhưng trọng số khác bản đúng. Sửa lỗi; giữ nguyên `torch.manual_seed(0)` và thứ tự khởi tạo."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ZzDn0AubVIT9"
      },
      "outputs": [],
      "source": [
        "def train_linear_buggy(X, y, steps=50, lr=0.1):\n",
        "    torch.manual_seed(0)\n",
        "    model = nn.Linear(X.shape[1], 1)\n",
        "    opt = torch.optim.SGD(model.parameters(), lr=lr)\n",
        "    for _ in range(steps):\n",
        "        pred = model(X).squeeze(-1)\n",
        "        loss = F.mse_loss(pred, y)\n",
        "        loss.backward()\n",
        "        opt.step()\n",
        "    return model, loss.item()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "sJf0sQk1VIT9"
      },
      "outputs": [],
      "source": [
        "set_seed(0)\n",
        "X71 = torch.randn(100, 3)\n",
        "y71 = X71 @ torch.tensor([1.0, -2.0, 0.5]) + 0.3\n",
        "m_ref, l_ref = _ref_train_linear(X71, y71)\n",
        "m_fix, l_fix = train_linear_buggy(X71, y71)\n",
        "assert torch.allclose(m_fix.weight, m_ref.weight, atol=1e-5), \"trọng số khác bản đúng\"\n",
        "assert abs(l_fix - l_ref) < 1e-6\n",
        "done(\"7.1\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Dm4W73XNVIT_"
      },
      "source": [
        "### Bài 7.2. Loss sai âm thầm\n",
        "`mse_buggy` không báo lỗi nhưng cho kết quả sai với một số kiểu shape. Sửa để đúng với cả ba cặp shape được thử trong ô kiểm tra."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WqF8fJ3FVIT_"
      },
      "outputs": [],
      "source": [
        "def mse_buggy(pred, target):\n",
        "    return ((pred - target) ** 2).mean()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "CpbkouSDVIT_"
      },
      "outputs": [],
      "source": [
        "set_seed(0)\n",
        "p, t = torch.randn(8, 1), torch.randn(8)\n",
        "expected = F.mse_loss(p.squeeze(-1), t)\n",
        "for pp, tt in [(p, t), (p.squeeze(-1), t), (p, t.unsqueeze(-1))]:\n",
        "    got = mse_buggy(pp, tt)\n",
        "    assert torch.allclose(got, expected, atol=1e-6), (\n",
        "        f\"shapes {tuple(pp.shape)} và {tuple(tt.shape)}: nhận {got.item():.4f}, kỳ vọng {expected.item():.4f}\"\n",
        "    )\n",
        "done(\"7.2\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LCysmv3uVIT_"
      },
      "source": [
        "### Bài 7.3. Dự đoán không ổn định\n",
        "`predict_buggy` dùng model có `Dropout` và `BatchNorm`. Sửa để: kết quả lặp lại được; không đổi thống kê của BatchNorm; không tạo đồ thị gradient; và sau khi gọi, model ở đúng chế độ train/eval như trước khi gọi."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "nFu6h22iVIT_"
      },
      "outputs": [],
      "source": [
        "def predict_buggy(model, X):\n",
        "    logits = model(X)\n",
        "    return logits.argmax(dim=1)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "k2JAfJiAVIUA"
      },
      "outputs": [],
      "source": [
        "set_seed(0)\n",
        "net73 = nn.Sequential(nn.Linear(4, 16), nn.BatchNorm1d(16), nn.ReLU(), nn.Dropout(0.5), nn.Linear(16, 3))\n",
        "X73 = torch.randn(32, 4)\n",
        "net73.train()\n",
        "bn = net73[1]\n",
        "mean_before = bn.running_mean.clone()\n",
        "steps_before = bn.num_batches_tracked.clone()\n",
        "flags = []\n",
        "hk = net73.register_forward_hook(lambda m, i, o: flags.append(torch.is_grad_enabled()))\n",
        "p1 = predict_buggy(net73, X73)\n",
        "p2 = predict_buggy(net73, X73)\n",
        "hk.remove()\n",
        "assert torch.equal(p1, p2), \"dự đoán đổi giữa hai lần gọi: Dropout còn bật?\"\n",
        "assert torch.equal(bn.running_mean, mean_before) and torch.equal(bn.num_batches_tracked, steps_before), \"BatchNorm bị cập nhật thống kê\"\n",
        "assert flags and not any(flags), \"gradient chưa được tắt\"\n",
        "assert not p1.requires_grad\n",
        "assert net73.training is True, \"hàm phải trả model về chế độ train như ban đầu\"\n",
        "net73.eval()\n",
        "with torch.no_grad():\n",
        "    assert torch.equal(p1, net73(X73).argmax(dim=1))\n",
        "done(\"7.3\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DsZqezpXVIUA"
      },
      "source": [
        "### Bài 7.4. Hàm loss phân loại\n",
        "Hàm nhận logits `(N, C)` và nhãn đọc từ file CSV nên có dtype `float`. Sửa để kết quả đúng bằng cross entropy chuẩn."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gt3cZK5kVIUA"
      },
      "outputs": [],
      "source": [
        "def ce_loss_buggy(logits, labels):\n",
        "    probs = F.softmax(logits, dim=1)\n",
        "    return F.cross_entropy(probs, labels.float())"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "EUkY40Z6VIUA"
      },
      "outputs": [],
      "source": [
        "set_seed(0)\n",
        "logits = torch.randn(8, 5)\n",
        "labels_f = torch.tensor([0., 4., 2., 1., 3., 3., 0., 2.])\n",
        "expected = F.cross_entropy(logits, labels_f.long())\n",
        "got = ce_loss_buggy(logits, labels_f)\n",
        "assert torch.allclose(got, expected, atol=1e-6), f\"nhận {got.item():.4f}, kỳ vọng {expected.item():.4f}\"\n",
        "done(\"7.4\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QWW-ILmKVIUA"
      },
      "source": [
        "### Bài 7.5. Lỗi khi `backward()`\n",
        "`forward_buggy` báo lỗi lúc tính gradient. Sửa mà không đổi toán học: giá trị trả về và gradient phải đúng."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "13K_KjOPVIUA"
      },
      "outputs": [],
      "source": [
        "def forward_buggy(w, x):\n",
        "    h = w * x\n",
        "    h += 1\n",
        "    out = torch.sigmoid(h)\n",
        "    out *= 2\n",
        "    return out.sum()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Yz-RsvflVIUA"
      },
      "outputs": [],
      "source": [
        "set_seed(0)\n",
        "w75 = torch.randn(4, requires_grad=True)\n",
        "x75 = torch.randn(4)\n",
        "loss = forward_buggy(w75, x75)\n",
        "loss.backward()\n",
        "s = torch.sigmoid(w75.detach() * x75 + 1)\n",
        "assert torch.allclose(loss.detach(), 2 * s.sum(), atol=1e-6)\n",
        "assert torch.allclose(w75.grad, 2 * s * (1 - s) * x75, atol=1e-6)\n",
        "done(\"7.5\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "18V7QntTVIUA"
      },
      "source": [
        "### Bài 7.6. Loss trung bình theo epoch\n",
        "`epoch_loss_buggy` trả về loss trung bình của epoch nhưng (1) giữ đồ thị tính toán của mọi batch trong bộ nhớ, và (2) tính trung bình theo batch thay vì theo mẫu. Sửa để trả về `float` là trung bình theo mẫu."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "TdlgUDkCVIUA"
      },
      "outputs": [],
      "source": [
        "def epoch_loss_buggy(model, loader, opt):\n",
        "    total = 0\n",
        "    for xb, yb in loader:\n",
        "        opt.zero_grad()\n",
        "        loss = F.cross_entropy(model(xb), yb)\n",
        "        loss.backward()\n",
        "        opt.step()\n",
        "        total += loss\n",
        "    return total / len(loader)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "abeYJbwFVIUA"
      },
      "outputs": [],
      "source": [
        "set_seed(0)\n",
        "X76, y76 = make_circle_data(100, seed=5)\n",
        "loader76 = DataLoader(torch.utils.data.TensorDataset(X76, y76), batch_size=32, shuffle=False)\n",
        "base_net = nn.Sequential(nn.Linear(2, 8), nn.ReLU(), nn.Linear(8, 2))\n",
        "m_a, m_b = copy.deepcopy(base_net), copy.deepcopy(base_net)\n",
        "opt_a = torch.optim.SGD(m_a.parameters(), lr=0.1)\n",
        "opt_b = torch.optim.SGD(m_b.parameters(), lr=0.1)\n",
        "ref = _ref_epoch_loss(m_a, loader76, opt_a)\n",
        "got = epoch_loss_buggy(m_b, loader76, opt_b)\n",
        "assert isinstance(got, float), f\"kiểu trả về {type(got).__name__}, cần float (dùng .item())\"\n",
        "assert abs(got - ref) < 1e-6, f\"nhận {got:.6f}, kỳ vọng {ref:.6f}: đã trung bình theo mẫu chưa?\"\n",
        "done(\"7.6\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Dk9P0B6jVIUB"
      },
      "source": [
        "## Tiến độ và bước tiếp theo"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "n6r0Jva9VIUB"
      },
      "outputs": [],
      "source": [
        "parts = [(1, 6), (2, 4), (3, 4), (4, 3), (5, 3), (6, 3), (7, 6)]\n",
        "missing = [f\"{p}.{i}\" for p, n in parts for i in range(1, n + 1) if f\"{p}.{i}\" not in _DONE]\n",
        "print(f\"Đã qua {len(_DONE)}/29 bài\")\n",
        "print(\"Còn lại:\", \", \".join(missing) if missing else \"không còn bài nào\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KylV2vYqVIUB"
      },
      "source": [
        "**Sau khi qua hết 29 bài**, ba việc nên làm (không có `assert`, tự đặt tiêu chí):\n",
        "1. Viết lại từ trí nhớ vòng lặp huấn luyện + đánh giá + checkpoint trong 10 phút, không nhìn notebook.\n",
        "2. Huấn luyện một CNN trên MNIST hoặc CIFAR-10 (`torchvision.datasets`), vẽ đường loss/accuracy, cố đạt trên 98% (MNIST) hoặc trên 80% (CIFAR-10).\n",
        "3. Dựng mini-GPT mức ký tự từ `TransformerBlock` ở bài 6.3 và huấn luyện trên một file văn bản nhỏ."
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "gpuType": "T4",
      "provenance": []
    },
    "kernelspec": {
      "display_name": "base",
      "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.13.5"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
