From 4398f78facf58c2b179ffe399ee3685ae8b3d8ca Mon Sep 17 00:00:00 2001 From: devmtnaing Date: Fri, 30 Oct 2026 10:34:15 +0630 Subject: [PATCH] =?UTF-8?q?Add=20an=20interactive=20Lesson=20step=20and=20?= =?UTF-8?q?notebook=20to=20Setup=20=C2=B7=20Step=201?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A step-by-step tutor between Concepts and Learn: short screens, each with a check question (hint on the first miss, answer and why on the second). The Build step links a Jupyter notebook with exercises: Open in Colab, download, or view on GitHub. Also a Step 1 quiz. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T85pZTr611HcS7wydhD4D7 --- .gitignore | 3 + CONTRIBUTING.md | 8 + course/00-setup/notebooks/step-1.ipynb | 774 ++++++++++++++++++ scripts/audit.mjs | 2 + src/components/ai/Session.tsx | 196 ++++- src/components/ai/Stepper.astro | 2 +- src/lib/ai/course.ts | 52 +- src/lib/ai/lessons.ts | 569 +++++++++++++ src/lib/ai/quizzes.ts | 46 ++ .../ai-engineer/[track]/[module]/[unit].astro | 4 +- src/pages/ai-engineer/notebooks/[file].ts | 11 + src/styles/ai.css | 18 + 12 files changed, 1676 insertions(+), 9 deletions(-) create mode 100644 course/00-setup/notebooks/step-1.ipynb create mode 100644 src/lib/ai/lessons.ts create mode 100644 src/pages/ai-engineer/notebooks/[file].ts diff --git a/.gitignore b/.gitignore index dd86789..4044b08 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,6 @@ __pycache__/ # Cloudflare Wrangler local state .wrangler/ + +# exercises folder: personal practice code, not part of the repo +exercises/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7dc6bad..5c887ca 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -258,6 +258,14 @@ under `/ai-engineer` are built from it at build time - **Quizzes and flashcards** are in `src/lib/ai/quizzes.ts` and `src/lib/ai/flashcards.ts`, keyed by module id (`t1-1.4`). A question names its correct option and says why. +- **Lessons** (the optional *Lesson* step) are in `src/lib/ai/lessons.ts`, + keyed by module id like quizzes: one small idea per screen in markdown, each + with a `choice`, `number` or `text` check that has a hint and a why. A lesson + can name a notebook under `course/` (e.g. `00-setup/notebooks/step-1.ipynb`). + The site links it to Colab and GitHub and serves it as a download from + `/ai-engineer/notebooks/`. Every exercise in a notebook needs a hidden + solution and an `assert` check cell, and the solutions should pass when run + top to bottom. - **Papers and projects** are `course/track-3-research-engineer/papers.md` and `course/projects/README.md`. - **A new section** (another course next to LeetCode and AI Engineer) is one diff --git a/course/00-setup/notebooks/step-1.ipynb b/course/00-setup/notebooks/step-1.ipynb new file mode 100644 index 0000000..284d88a --- /dev/null +++ b/course/00-setup/notebooks/step-1.ipynb @@ -0,0 +1,774 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Step 1 · Python for ML: NumPy, broadcasting and PyTorch basics\n", + "\n", + "This notebook goes with the **Lesson** step of [Setup · Step 1](https://learn.devmtnaing.com/ai-engineer/setup/step-1). Each section has:\n", + "\n", + "- a short example to run and look at,\n", + "- an **exercise**: replace the `...` with your code,\n", + "- a **check** cell with `assert`s. If it prints ✅, you got it.\n", + "\n", + "Stuck? Each exercise has a hidden **hint and solution** below it. Try first, then peek.\n", + "\n", + "**Run cells in order** (Shift+Enter). In Colab, *Runtime → Change runtime type → GPU* gives you a free NVIDIA GPU for the last section." + ], + "id": "c00" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import time\n", + "import numpy as np\n", + "import torch\n", + "\n", + "print(\"numpy\", np.__version__, \"| torch\", torch.__version__)" + ], + "id": "c01" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 1. NumPy arrays and shapes\n", + "\n", + "Math on a whole array at once, no loops. Every array has a `shape`: (rows, columns) for 2D." + ], + "id": "c02" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "prices = np.array([100, 200, 300])\n", + "print(prices * 2) # [200 400 600]\n", + "\n", + "x = np.arange(6).reshape(2, 3)\n", + "print(x)\n", + "print(\"shape:\", x.shape) # (2, 3)\n", + "\n", + "print(x[0]) # first row [0 1 2]\n", + "print(x[1, 2]) # row 1, col 2 5\n", + "print(x[:, 0]) # every row, col 0 [0 3]\n", + "print(x[0, 1:3]) # row 0, cols 1-2 [1 2]" + ], + "id": "c03" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 1 · indexing\n", + "\n", + "Using `x` from above, get:\n", + "- `col1`: the whole second column (`[1, 4]`)\n", + "- `last_row`: the last row (`[3, 4, 5]`)\n", + "- `corner`: the bottom-right number (`5`)" + ], + "id": "c04" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "col1 = ...\n", + "last_row = ...\n", + "corner = ..." + ], + "id": "c05" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
💡 Hint\n", + "\n", + "`:` means every row. Negative indexes count from the end: `x[-1]` is the last row.\n", + "\n", + "
\n", + "\n", + "
✅ Solution\n", + "\n", + "```python\n", + "col1 = x[:, 1]\n", + "last_row = x[1] # or x[-1]\n", + "corner = x[1, 2] # or x[-1, -1]\n", + "```\n", + "\n", + "
" + ], + "id": "c06" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "assert np.array_equal(col1, [1, 4]), col1\n", + "assert np.array_equal(last_row, [3, 4, 5]), last_row\n", + "assert corner == 5, corner\n", + "print(\"✅ indexing\")" + ], + "id": "c07" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. `sum` / `mean` along an axis\n", + "\n", + "`axis=0` collapses the **rows** (one value per column). `axis=1` collapses the **columns** (one value per row). `keepdims=True` keeps the collapsed axis as size 1." + ], + "id": "c08" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "data = np.array([[1., 2., 3.],\n", + " [4., 5., 6.],\n", + " [7., 8., 9.],\n", + " [10., 11., 12.]]) # 4 images × 3 colour channels\n", + "print(data.mean(axis=0), data.mean(axis=0).shape) # per channel → (3,)\n", + "print(data.mean(axis=1), data.mean(axis=1).shape) # per image → (4,)\n", + "print(data.mean(axis=1, keepdims=True).shape) # (4, 1)" + ], + "id": "c09" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 2 · axis\n", + "\n", + "- `row_sums`: the sum of each row of `data`, shape `(4,)`\n", + "- `col_max`: the largest value in each column, shape `(3,)`" + ], + "id": "c10" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "row_sums = ...\n", + "col_max = ..." + ], + "id": "c11" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
💡 Hint\n", + "\n", + "One value per row means collapsing the columns: `axis=1`. One value per column means `axis=0`.\n", + "\n", + "
\n", + "\n", + "
✅ Solution\n", + "\n", + "```python\n", + "row_sums = data.sum(axis=1)\n", + "col_max = data.max(axis=0)\n", + "```\n", + "\n", + "
" + ], + "id": "c12" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "assert row_sums.shape == (4,) and np.allclose(row_sums, [6, 15, 24, 33]), row_sums\n", + "assert col_max.shape == (3,) and np.allclose(col_max, [10, 11, 12]), col_max\n", + "print(\"✅ axis\")" + ], + "id": "c13" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. Broadcasting\n", + "\n", + "Line shapes up **from the right**: each pair must be equal, or one of them 1 (or missing).\n", + "\n", + "```\n", + "(4, 3) - (3,) → 3 vs 3 ✓ one value per COLUMN, stretched down the rows\n", + "(4, 3) - (4,) → 3 vs 4 ✗ ERROR\n", + "(4, 3) - (4, 1) → 3 vs 1 ✓, 4 vs 4 ✓ one value per ROW, stretched across\n", + "```" + ], + "id": "c14" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "channel_mean = data.mean(axis=0) # (3,)\n", + "print((data - channel_mean).shape) # (4, 3)\n", + "\n", + "try:\n", + " data - data.mean(axis=1) # (4, 3) - (4,)\n", + "except ValueError as e:\n", + " print(\"ERROR:\", e)\n", + "\n", + "image_mean = data.mean(axis=1, keepdims=True) # (4, 1)\n", + "print((data - image_mean).shape) # (4, 3)" + ], + "id": "c15" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 3 · centre each image\n", + "\n", + "Subtract **each image's own mean** (each row's mean) from `data`, so every row of `centered` averages to 0. Use broadcasting, no loops." + ], + "id": "c16" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "centered = ..." + ], + "id": "c17" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
💡 Hint\n", + "\n", + "You need one value per row, shape `(4, 1)`. `keepdims=True` gives you exactly that.\n", + "\n", + "
\n", + "\n", + "
✅ Solution\n", + "\n", + "```python\n", + "centered = data - data.mean(axis=1, keepdims=True)\n", + "```\n", + "\n", + "
" + ], + "id": "c18" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "assert centered.shape == (4, 3), centered.shape\n", + "assert np.allclose(centered.mean(axis=1), 0), centered.mean(axis=1)\n", + "assert np.allclose(centered[0], [-1, 0, 1]), centered[0]\n", + "print(\"✅ broadcasting\")" + ], + "id": "c19" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Quick check:** what shape is `np.ones((8, 1)) + np.ones((1, 5))`? Guess, then run it." + ], + "id": "c20" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print((np.ones((8, 1)) + np.ones((1, 5))).shape)" + ], + "id": "c21" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4. Build · matrix multiplication: loops vs `@`\n", + "\n", + "Shape rule: `[m, k] @ [k, n] → [m, n]`. The inner numbers must match.\n", + "\n", + "### Exercise 4 · write it with three loops\n", + "\n", + "Fill in `matmul_loops(A, B)`: `C[i, j]` is the sum over `k` of `A[i, k] * B[k, j]`. Use plain Python loops: that's the point." + ], + "id": "c22" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def matmul_loops(A, B):\n", + " m, k = A.shape\n", + " k2, n = B.shape\n", + " assert k == k2, \"inner dimensions must match\"\n", + " C = np.zeros((m, n))\n", + " ...\n", + " return C" + ], + "id": "c23" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
💡 Hint\n", + "\n", + "Loop `i` over rows of A, `j` over columns of B, and an inner loop that adds up `A[i, p] * B[p, j]`.\n", + "\n", + "
\n", + "\n", + "
✅ Solution\n", + "\n", + "```python\n", + "def matmul_loops(A, B):\n", + " m, k = A.shape\n", + " k2, n = B.shape\n", + " assert k == k2, \"inner dimensions must match\"\n", + " C = np.zeros((m, n))\n", + " for i in range(m):\n", + " for j in range(n):\n", + " total = 0.0\n", + " for p in range(k):\n", + " total += A[i, p] * B[p, j]\n", + " C[i, j] = total\n", + " return C\n", + "```\n", + "\n", + "
" + ], + "id": "c24" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "A = np.random.rand(3, 4)\n", + "B = np.random.rand(4, 2)\n", + "assert matmul_loops(A, B).shape == (3, 2)\n", + "assert np.allclose(matmul_loops(A, B), A @ B)\n", + "print(\"✅ matmul_loops matches A @ B\")" + ], + "id": "c25" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Time it\n", + "\n", + "Start at 128 × 128. The course asks for **512 × 512**: set `n = 512` once it works. In plain Python that takes roughly 15 seconds on an Apple Silicon Mac (longer on Colab's CPU), so be patient. That *is* the lesson." + ], + "id": "c26" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "n = 128 # then try 512\n", + "A = np.random.rand(n, n)\n", + "B = np.random.rand(n, n)\n", + "\n", + "t0 = time.perf_counter(); C1 = matmul_loops(A, B); t_loops = time.perf_counter() - t0\n", + "t0 = time.perf_counter(); C2 = A @ B; t_numpy = time.perf_counter() - t0\n", + "\n", + "assert np.allclose(C1, C2)\n", + "print(f\"{n}×{n} loops: {t_loops:.3f} s numpy: {t_numpy * 1000:.3f} ms → {t_loops / t_numpy:,.0f}× faster\")" + ], + "id": "c27" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 5. Build · numerically stable softmax\n", + "\n", + "`softmax(x) = exp(x) / sum(exp(x))`, applied to **each row** of a `[batch, classes]` array. Each row becomes probabilities that add up to 1.\n", + "\n", + "The naive version breaks on big numbers:" + ], + "id": "c28" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def softmax_naive(x):\n", + " e = np.exp(x)\n", + " return e / e.sum(axis=1, keepdims=True)\n", + "\n", + "print(softmax_naive(np.array([[2.0, 1.0, 0.1]]))) # fine\n", + "print(softmax_naive(np.array([[1000.0, 999.0]]))) # nan: exp(1000) overflows" + ], + "id": "c29" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 5 · make it stable\n", + "\n", + "Subtract each row's **max** before `exp`. The answer doesn't change (the shift cancels in the division), but the biggest number becomes `exp(0) = 1`, so nothing overflows." + ], + "id": "c30" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def softmax(x):\n", + " # x: shape (batch, classes)\n", + " ..." + ], + "id": "c31" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
💡 Hint\n", + "\n", + "`x.max(axis=1, keepdims=True)` has shape `(batch, 1)`, so `x - that` broadcasts across each row. Then do the naive version.\n", + "\n", + "
\n", + "\n", + "
✅ Solution\n", + "\n", + "```python\n", + "def softmax(x):\n", + " # x: shape (batch, classes)\n", + " x = x - x.max(axis=1, keepdims=True) # (batch, 1) broadcasts across the row\n", + " e = np.exp(x)\n", + " return e / e.sum(axis=1, keepdims=True)\n", + "```\n", + "\n", + "
" + ], + "id": "c32" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "logits = np.random.randn(4, 10) * 5\n", + "p = softmax(logits)\n", + "assert p.shape == (4, 10)\n", + "assert np.allclose(p.sum(axis=1), 1), \"each row must add up to 1\"\n", + "\n", + "big = softmax(np.array([[1000.0, 999.0], [-1000.0, -1000.0]]))\n", + "assert np.all(np.isfinite(big)), big\n", + "assert np.allclose(big[1], [0.5, 0.5])\n", + "\n", + "# matches PyTorch's own softmax\n", + "assert np.allclose(p, torch.softmax(torch.from_numpy(logits), dim=1).numpy())\n", + "print(\"✅ stable softmax matches torch.softmax\")" + ], + "id": "c33" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 6. PyTorch tensors\n", + "\n", + "Same ideas as NumPy, plus GPUs and autograd. `reshape` keeps the same numbers (rows × cols must equal the count), and `-1` means \"work it out\"." + ], + "id": "c34" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "t = torch.arange(6)\n", + "print(t, t.shape)\n", + "print(t.reshape(2, 3))\n", + "print(t.reshape(-1, 1).shape) # (6, 1)\n", + "\n", + "try:\n", + " t.reshape(4, 2)\n", + "except RuntimeError as e:\n", + " print(\"ERROR:\", e)" + ], + "id": "c35" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 6 · reshape\n", + "\n", + "From `torch.arange(12)`, make:\n", + "- `grid`: shape `(3, 4)`\n", + "- `col`: a single column, shape `(12, 1)`, using `-1` for the 12" + ], + "id": "c36" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "grid = ...\n", + "col = ..." + ], + "id": "c37" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
💡 Hint\n", + "\n", + "`.reshape(rows, cols)`. For the column, one column means the second number is 1.\n", + "\n", + "
\n", + "\n", + "
✅ Solution\n", + "\n", + "```python\n", + "grid = torch.arange(12).reshape(3, 4)\n", + "col = torch.arange(12).reshape(-1, 1)\n", + "```\n", + "\n", + "
" + ], + "id": "c38" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "assert grid.shape == (3, 4) and grid[1, 0] == 4, grid\n", + "assert col.shape == (12, 1), col.shape\n", + "print(\"✅ reshape\")" + ], + "id": "c39" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 7. NumPy ↔ PyTorch: shared memory\n", + "\n", + "`torch.from_numpy(a)` **shares** memory with `a`; `torch.tensor(a)` makes a **copy**. Predict both prints before you run it." + ], + "id": "c40" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "a = np.array([1, 2, 3])\n", + "shared = torch.from_numpy(a)\n", + "copied = torch.tensor(a)\n", + "a[0] = 100\n", + "print(\"shared:\", shared) # ?\n", + "print(\"copied:\", copied) # ?" + ], + "id": "c41" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 8. Devices\n", + "\n", + "Tensors live on `cpu`, `cuda` (NVIDIA, e.g. Colab GPU) or `mps` (Apple Silicon). Maths only works between tensors on the **same** device. Pick it once at the top." + ], + "id": "c42" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "device = \"cuda\" if torch.cuda.is_available() else \"mps\" if torch.backends.mps.is_available() else \"cpu\"\n", + "print(\"using\", device)\n", + "\n", + "x = torch.tensor([1.0, 2.0], device=device)\n", + "y = torch.tensor([3.0, 4.0], device=device)\n", + "print(x + y)" + ], + "id": "c43" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 9. Training: gradient descent with autograd\n", + "\n", + "The target is 5; `w` starts at 3; `loss = (w - 5) ** 2`. `loss.backward()` fills in `w.grad`, we step opposite it, then **zero** the gradient (it accumulates otherwise)." + ], + "id": "c44" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "w = torch.tensor(3.0, requires_grad=True)\n", + "lr = 0.1\n", + "for step in range(3):\n", + " loss = (w - 5) ** 2\n", + " loss.backward()\n", + " with torch.no_grad():\n", + " w -= lr * w.grad\n", + " w.grad.zero_()\n", + " print(step + 1, round(w.item(), 4)) # 3.4, 3.72, 3.976" + ], + "id": "c45" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 7 · train until it arrives\n", + "\n", + "Write `train_until(lr)`: start `w` at 3.0 **on `device`** (pass `device=device` to `torch.tensor`; `.to(device)` afterwards makes a copy with no `.grad`), loop with `while` until `w` is within `0.001` of 5, and **return the number of steps**.\n", + "\n", + "Then try different learning rates. What happens at `lr=1.0`? (Don't run that one without a step limit!)" + ], + "id": "c46" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def train_until(lr, target=5.0, tol=0.001):\n", + " w = ...\n", + " steps = 0\n", + " ...\n", + " return steps" + ], + "id": "c47" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
💡 Hint\n", + "\n", + "Start from the loop above. Swap `for` for `while abs(w.item() - target) > tol:` and add `steps += 1` inside.\n", + "\n", + "
\n", + "\n", + "
✅ Solution\n", + "\n", + "```python\n", + "def train_until(lr, target=5.0, tol=0.001):\n", + " w = torch.tensor(3.0, requires_grad=True, device=device)\n", + " steps = 0\n", + " while abs(w.item() - target) > tol:\n", + " loss = (w - target) ** 2\n", + " loss.backward()\n", + " with torch.no_grad():\n", + " w -= lr * w.grad\n", + " w.grad.zero_()\n", + " steps += 1\n", + " return steps\n", + "```\n", + "\n", + "
" + ], + "id": "c48" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "steps = train_until(0.1)\n", + "print(\"lr=0.1 →\", steps, \"steps\")\n", + "assert steps == 35, steps\n", + "assert train_until(0.3) < steps, \"a bigger (but not too big) learning rate should need fewer steps\"\n", + "print(\"✅ training loop\")" + ], + "id": "c49" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Done 🎉\n", + "\n", + "You've run everything in Step 1. Before the checkpoint, make sure you can:\n", + "\n", + "- predict the shape of a broadcast or a matmul **before** running it,\n", + "- write the stable softmax from memory,\n", + "- explain why `zero_()` matters and what a too-big learning rate does.\n", + "\n", + "Then do the **Quiz** and **Checkpoint** steps on the site." + ], + "id": "c50" + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + }, + "colab": { + "provenance": [] + }, + "accelerator": "GPU" + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/scripts/audit.mjs b/scripts/audit.mjs index 7d50c1d..154c743 100644 --- a/scripts/audit.mjs +++ b/scripts/audit.mjs @@ -359,6 +359,8 @@ async function main() { ['/ai-engineer/track-2', '.timeline'], ['/ai-engineer/track-2/2-7', '.guide-hero'], ['/ai-engineer/track-1/1-1/concepts', '.session-body h1'], + ['/ai-engineer/setup/step-1/lesson', '.lesson-check'], + ['/ai-engineer/setup/step-1/build', '.notebook'], ['/ai-engineer/track-1/1-4/learn', '.check'], ['/ai-engineer/track-2/2-7/quiz', '.option'], ['/ai-engineer/practice', '.grid-cards'], diff --git a/src/components/ai/Session.tsx b/src/components/ai/Session.tsx index a8dda1a..fe013d1 100644 --- a/src/components/ai/Session.tsx +++ b/src/components/ai/Session.tsx @@ -2,7 +2,7 @@ import type { ComponentChildren } from 'preact' import { useEffect, useMemo, useRef, useState } from 'preact/hooks' import type { Question } from '../../lib/ai/quizzes' -import type { BuildItem, Resource, UnitKind } from '../../lib/ai/course' +import type { BuildItem, Lesson as LessonData, LessonCheck, Notebook, Resource, UnitKind } from '../../lib/ai/course' import { addXp, markDone, toggleChecked, totalXp, touch, update, get } from '../../lib/progress' import { Icon, shuffle, useProgress, XP } from './ui' @@ -24,6 +24,8 @@ export type SessionProps = { module: SessionModule track: { id: string; short: string; subtitle: string } questions?: Question[] + lesson?: LessonData + notebook?: Notebook backUrl: string guideUrl: string } @@ -32,9 +34,7 @@ export type SessionProps = { function useEnter(fn: () => void, enabled = true) { const ref = useRef(fn) - useEffect(() => { - ref.current = fn - }) + ref.current = fn // during render, so an Enter right after typing sees the latest state useEffect(() => { if (!enabled) return const h = (e: KeyboardEvent) => { @@ -262,6 +262,7 @@ function Checklist({ s, exit, finish }: UnitProps) { ? 'Work through the core resources. Tick each one when finished. Links open in a new tab.' : 'Hands-on work. This is where the learning happens. Tick each build when it runs and you have written notes on it.'}

+ {s.notebook && }
{req.map((r) => item(r, isRes ? XP.coreResource : XP.build))}
{required.length > 0 && optional.length > 0 && ( <> @@ -396,6 +397,191 @@ export function Quiz({ questions, title, exit, onComplete }: { questions: Questi ) } +// ───────── lesson: one idea per screen, each with a check question ───────── + +/** "(2, 3)", "2,3" and "[2, 3]" all compare equal; so do "(3,)" and "3". */ +const normAnswer = (x: string) => x.toLowerCase().replace(/[\s()[\]]/g, '').replace(/,$/, '') +const parseNum = (x: string) => Number(x.trim().replace(/[−–]/g, '-')) + +function isRight(c: LessonCheck, sel: number | null, answer: string) { + if (c.kind === 'choice') return sel === c.a + if (c.kind === 'number') { + const n = parseNum(answer) + return answer.trim() !== '' && Number.isFinite(n) && Math.abs(n - c.a) <= (c.tol ?? 0.001) + } + return c.a.some((a) => normAnswer(a) === normAnswer(answer)) +} + +function answerHtml(c: LessonCheck) { + if (c.kind === 'choice') return c.oHtml![c.a] + return c.kind === 'number' ? String(c.a) : c.a[0] +} + +export function NotebookCard({ nb, label }: { nb: Notebook; label: string }) { + return ( +
+
+ + + + + {label} notebook + Exercises with self-checks. Runs in Colab (free GPU) or Jupyter on your machine. + +
+ +
+ ) +} + +type LessonStatus = 'ask' | 'hint' | 'right' | 'shown' + +function Lesson({ s, exit, finish }: UnitProps) { + const l = s.lesson! + const posKey = `lesson-pos:${s.unitId}` + // where you left off, so a long lesson can be done over several sittings + const [idx, setIdx] = useState(() => { + try { + const n = Number(localStorage.getItem(posKey)) + return n > 0 && n < l.screens.length ? n : 0 + } catch { + return 0 + } + }) + const [sel, setSel] = useState(null) + const [answer, setAnswer] = useState('') + const [status, setStatus] = useState('ask') + const sc = l.screens[idx] + const c = sc.check + const last = idx === l.screens.length - 1 + const answered = status === 'right' || status === 'shown' + const ready = !c || (c.kind === 'choice' ? sel !== null : answer.trim() !== '') + + useEffect(() => { + try { + localStorage.setItem(posKey, String(idx)) + } catch {} + }, [idx]) + + const go = (to: number) => { + setIdx(to) + setSel(null) + setAnswer('') + setStatus('ask') + window.scrollTo(0, 0) + } + const check = () => { + if (!c || answered || !ready) return + if (isRight(c, sel, answer)) { + if (status === 'ask') addXp(XP.quizCorrect) + setStatus('right') + } else setStatus(status === 'ask' ? 'hint' : 'shown') + } + const next = () => { + if (!last) return go(idx + 1) + try { + localStorage.removeItem(posKey) + } catch {} + markDone(s.unitId, XP.unitBonus) + finish('Lesson complete!', 'Next: run the notebook, then read the docs in the Learn step.') + } + useEnter(!c || answered ? next : check) + useEffect(() => { + const h = (e: KeyboardEvent) => { + const n = Number(e.key) + if (c?.kind === 'choice' && !answered && !(e.target instanceof HTMLInputElement) && n >= 1 && n <= c.o.length) setSel(n - 1) + } + window.addEventListener('keydown', h) + return () => window.removeEventListener('keydown', h) + }, [c, answered]) + + const backBtn = idx > 0 && ( + + ) + const footer = + status === 'right' ? ( +
Correct!}> + +
+ ) : status === 'shown' ? ( +
}> + +
+ ) : status === 'hint' ? ( +
Not quite. Try again.Hint: }> + +
+ ) : ( +
+ {backBtn} + +
+ ) + + return ( + + + Lesson · {s.module.label} · {idx + 1} / {l.screens.length} + +

{sc.title}

+
+ {c && ( +
+
Check
+

+ {c.kind === 'choice' ? ( +

+ {c.oHtml!.map((o, i) => { + const cls = ['option', !answered && sel === i && 'sel', answered && i === c.a && 'right', status === 'shown' && sel === i && 'wrong'].filter(Boolean).join(' ') + return ( + + ) + })} +
+ ) : ( + setAnswer((e.target as HTMLInputElement).value)} + /> + )} +
+ )} + {last && l.notebook && } + + ) +} + function Checkpoint({ s, exit, finish }: UnitProps) { const p = useProgress() const m = s.module @@ -457,6 +643,8 @@ export default function Session(s: SessionProps) { switch (s.kind) { case 'concepts': return + case 'lesson': + return case 'resources': case 'build': return diff --git a/src/components/ai/Stepper.astro b/src/components/ai/Stepper.astro index 81e92f6..85f50e3 100644 --- a/src/components/ai/Stepper.astro +++ b/src/components/ai/Stepper.astro @@ -6,7 +6,7 @@ import type { IconName } from '../../lib/icons'; interface Props { track: Track; module: Module } const { track, module: m } = Astro.props; -const KIND_ICON: Record = { concepts: 'bulb', resources: 'bookOpen', build: 'code', quiz: 'help', checkpoint: 'trophy' }; +const KIND_ICON: Record = { concepts: 'bulb', lesson: 'play', resources: 'bookOpen', build: 'code', quiz: 'help', checkpoint: 'trophy' }; ---
{unitKinds(m).map((k) => ( diff --git a/src/lib/ai/course.ts b/src/lib/ai/course.ts index 53a8eea..8b03f05 100644 --- a/src/lib/ai/course.ts +++ b/src/lib/ai/course.ts @@ -4,6 +4,7 @@ * the slices they need as props, so the markdown never ships to the browser. */ import { marked } from 'marked' import { quizzes } from './quizzes' +import { lessons, type Check } from './lessons' const files = import.meta.glob('/course/**/*.md', { query: '?raw', import: 'default', eager: true }) as Record const read = (p: string) => { @@ -34,7 +35,7 @@ export type Track = { id: string; slug: string; title: string; short: string; su export type Paper = { id: string; star: boolean; title: string; by: string; url: string | null } export type PaperSection = { title: string; papers: Paper[] } export type Project = { id: string; title: string; template: boolean; html: string } -export type UnitKind = 'concepts' | 'resources' | 'build' | 'quiz' | 'checkpoint' +export type UnitKind = 'concepts' | 'lesson' | 'resources' | 'build' | 'quiz' | 'checkpoint' const hash = (s: string) => { let h = 5381 @@ -204,8 +205,8 @@ export const projects = parseProjects() // ───────── units: the five steps of every module ───────── -export const UNIT_LABEL: Record = { concepts: 'Concepts', resources: 'Learn', build: 'Build', quiz: 'Quiz', checkpoint: 'Checkpoint' } -export const UNIT_SLUG: Record = { concepts: 'concepts', resources: 'learn', build: 'build', quiz: 'quiz', checkpoint: 'checkpoint' } +export const UNIT_LABEL: Record = { concepts: 'Concepts', lesson: 'Lesson', resources: 'Learn', build: 'Build', quiz: 'Quiz', checkpoint: 'Checkpoint' } +export const UNIT_SLUG: Record = { concepts: 'concepts', lesson: 'lesson', resources: 'learn', build: 'build', quiz: 'quiz', checkpoint: 'checkpoint' } export const BASE = '/ai-engineer' export const trackUrl = (t: Track) => `${BASE}/${t.slug}` @@ -214,6 +215,7 @@ export const unitUrl = (t: Track, m: Module, k: UnitKind) => `${moduleUrl(t, m)} export function unitKinds(m: Module): UnitKind[] { const k: UnitKind[] = ['concepts'] + if (lessons[m.id]) k.push('lesson') if (m.resources.length) k.push('resources') if (m.build.length) k.push('build') if (quizzes[m.id]?.length) k.push('quiz') @@ -247,3 +249,47 @@ export const trackColor = (trackId: string) => tracks.find((t) => t.id === track export const trackWeeks = (t: Track) => t.modules.reduce((a, m) => a + (Number(m.weeks?.split(/[–-]/).at(-1)) || 0), 0) /** Upper end of a module's estimate, in course weeks, or 0 when it has none. */ export const moduleWeeks = (m: Module) => Number(m.weeks?.split(/[–-]/).at(-1)) || 0 + +// ───────── lessons and notebooks ───────── + +const REPO = 'devmtnaing/learn' +const notebooks = import.meta.glob('/course/**/*.ipynb', { query: '?raw', import: 'default', eager: true }) as Record + +/** A notebook under /course: its raw JSON, plus where to open or download it. */ +export type Notebook = { file: string; colab: string; github: string; download: string } +export const notebookFile = (path: string) => path.replace('/notebooks/', '/').replace(/^\d+-/, '').replace(/\//g, '-') // '00-setup/notebooks/step-1.ipynb' → 'setup-step-1.ipynb' +export function notebookFor(path: string): Notebook { + if (notebooks[`/course/${path}`] == null) throw new Error(`notebook missing: course/${path}`) + const file = notebookFile(path) + return { + file, + colab: `https://colab.research.google.com/github/${REPO}/blob/main/course/${path}`, + github: `https://github.com/${REPO}/blob/main/course/${path}`, + download: `${BASE}/notebooks/${file}`, + } +} +export const allNotebooks = () => Object.entries(notebooks).map(([k, json]) => ({ file: notebookFile(k.replace('/course/', '')), json })) + +export type LessonCheck = Check & { qHtml: string; oHtml?: string[]; hintHtml: string; whyHtml: string } +export type LessonScreen = { title: string; html: string; check?: LessonCheck } +export type Lesson = { screens: LessonScreen[]; notebook?: Notebook } + +/** The module's lesson with its markdown rendered, or undefined if it has none. */ +export function lessonFor(m: Module): Lesson | undefined { + const l = lessons[m.id] + if (!l) return undefined + return { + notebook: l.notebook ? notebookFor(l.notebook) : undefined, + screens: l.screens.map((sc) => ({ + title: sc.title, + html: block(sc.md), + check: sc.check && { + ...sc.check, + qHtml: inline(sc.check.q), + oHtml: sc.check.kind === 'choice' ? sc.check.o.map(inline) : undefined, + hintHtml: inline(sc.check.hint), + whyHtml: inline(sc.check.why), + }, + })), + } +} diff --git a/src/lib/ai/lessons.ts b/src/lib/ai/lessons.ts new file mode 100644 index 0000000..b2c7550 --- /dev/null +++ b/src/lib/ai/lessons.ts @@ -0,0 +1,569 @@ +/* Interactive lessons: a module's ideas taught one small screen at a time, + * each followed by a check question with a hint. Keyed by module id, like + * quizzes.ts. Bodies are markdown and are rendered at build time by course.ts. + * + * A check is one of: + * choice pick an option; `a` is the index of the right one + * number type a number; right within `tol` (default 0.001) + * text type a short answer; compared ignoring spaces, case and brackets, + * so "(2, 3)", "2,3" and "[2, 3]" all match "(2, 3)" + * `hint` shows after the first miss, `why` once it is answered. */ + +export type Check = + | { kind: 'choice'; q: string; o: string[]; a: number; hint: string; why: string } + | { kind: 'number'; q: string; a: number; tol?: number; hint: string; why: string } + | { kind: 'text'; q: string; a: string[]; hint: string; why: string } +export type Screen = { title: string; md: string; check?: Check } +/** `notebook` is a path under /course: the notebook the lesson ends with. */ +export type LessonDef = { notebook?: string; screens: Screen[] } + +export const lessons: Record = { + 'setup-1': { + notebook: '00-setup/notebooks/step-1.ipynb', + screens: [ + // ───────── NumPy ───────── + { + title: 'AI data is just numbers', + md: `Every kind of data a model sees is turned into numbers first: + +| data | as numbers | +|---|---| +| an image | a grid of pixel brightness values | +| text | a list of token ids, one number per word piece | +| a table | rows and columns of numbers | + +So most of ML code is **math on big piles of numbers**. NumPy is the Python tool for that.`, + check: { + kind: 'choice', + q: 'A 28 × 28 grayscale image becomes…', + o: ['A grid of 28 × 28 numbers', 'A single number', 'A sentence describing it', 'A file name'], + a: 0, + hint: 'Each pixel has a brightness. How many pixels are there?', + why: 'One number per pixel, laid out in the same 28 × 28 grid.', + }, + }, + { + title: 'NumPy arrays: math without loops', + md: `A NumPy \`array\` lets you do math on every number at once: + +\`\`\`python +import numpy as np + +prices = np.array([100, 200, 300]) +prices * 2 # array([200, 400, 600]) +\`\`\` + +No \`for\` loop. It's also **much faster** than a Python loop: + +\`\`\` +Python loop: overhead paid once PER NUMBER (1,000,000 times) +NumPy: overhead paid once PER OPERATION, then a tight C loop +\`\`\` + +Writing the loop in C yourself would be about as fast, but NumPy gives you that speed while you write one line of Python.`, + check: { + kind: 'choice', + q: 'What is `np.array([1, 2, 3]) + 10`?', + o: ['`array([11, 12, 13])`', '`array([1, 2, 3, 10])`', 'An error', '`16`'], + a: 0, + hint: 'The `+ 10` is applied to every number in the array.', + why: 'Math on an array works element by element: 1+10, 2+10, 3+10.', + }, + }, + { + title: 'Shapes', + md: `Every array has a **shape**: how many numbers along each dimension. + +\`\`\` +5 shape () a scalar: one number +[1, 2, 3] shape (3,) 1D: 3 numbers +[[1, 2, 3], shape (2, 3) 2D: 2 rows, 3 columns + [4, 5, 6]] +\`\`\` + +Read a 2D shape as **(rows, columns)**. Shape bugs are the most common bugs in ML code, so get used to asking "what shape is this?"`, + check: { + kind: 'text', + q: 'What is the shape of `np.array([[1, 2], [3, 4], [5, 6]])`?', + a: ['(3, 2)'], + hint: 'Count the inner lists (rows), then the numbers in each (columns).', + why: '3 rows of 2 numbers each: shape (3, 2).', + }, + }, + { + title: 'Indexing and slicing', + md: `Pick out parts of an array with \`[rows, columns]\`. A \`:\` means "all of them". + +\`\`\`python +x = np.arange(6).reshape(2, 3) +# [[0, 1, 2], +# [3, 4, 5]] + +x[0] # [0, 1, 2] first row +x[1, 2] # 5 row 1, column 2 +x[:, 0] # [0, 3] every row, column 0 +x[0, 1:3] # [1, 2] row 0, columns 1 up to (not including) 3 +\`\`\` + +Counting starts at **0**, and a slice \`a:b\` stops *before* \`b\`.`, + check: { + kind: 'choice', + q: 'With the same `x`, what is `x[:, 1]`?', + o: ['`[1, 4]`', '`[3, 4, 5]`', '`[0, 1]`', '`4`'], + a: 0, + hint: '`:` means every row; `1` means column 1 (the second column).', + why: 'Column 1 holds 1 (row 0) and 4 (row 1).', + }, + }, + { + title: 'sum and mean along an axis', + md: `\`axis\` says which direction to collapse: + +\`\`\` +data (4, 3) data.mean(axis=0) → shape (3,) collapse the rows: +┌────┬────┬────┐ one value per COLUMN +│ │ │ │ ─┐ +│ │ │ │ │ data.mean(axis=1) → shape (4,) collapse the columns: +│ │ │ │ │ one value per ROW +│ │ │ │ ─┘ +└────┴────┴────┘ +\`\`\` + +Add \`keepdims=True\` to keep the collapsed dimension as size 1: \`data.mean(axis=1, keepdims=True)\` has shape **(4, 1)**. That shape is exactly what you need for broadcasting, coming next.`, + check: { + kind: 'text', + q: '`data` has shape (4, 3). What is the shape of `data.sum(axis=0)`?', + a: ['(3,)', '3'], + hint: 'axis=0 collapses the rows, so one value is left per column.', + why: 'Summing down the 4 rows leaves one number for each of the 3 columns: (3,).', + }, + }, + // ───────── Broadcasting ───────── + { + title: 'Broadcasting: the rule', + md: `Broadcasting lets arrays of **different shapes** work together by "stretching" the smaller one. + +**The rule:** line the shapes up **from the right**. Each pair must be **equal**, or one of them must be **1** (or missing). + +\`\`\` +images (4, 3) 4 images × 3 colour channels +means (3,) one mean per channel + ─── +compare: 3 vs 3 ✓ 4 vs (missing) ✓ → result (4, 3) +\`\`\` + +The \`(3,)\` row is copied **down all 4 rows**, so each column gets its own value subtracted.`, + check: { + kind: 'choice', + q: 'What does `(4, 3)` + `(3,)` give?', + o: ['Shape (4, 3)', 'Shape (3,)', 'An error', 'Shape (4,)'], + a: 0, + hint: 'Compare from the right: 3 vs 3, then 4 vs nothing.', + why: 'Both pairs are fine, so the (3,) stretches down the rows and the result is (4, 3).', + }, + }, + { + title: 'Broadcasting: one value per row', + md: `What if you want **one value per row** instead, like each image's own mean? + +\`\`\` +images (4, 3) +per_img (4,) compare from the right: 3 vs 4 ✗ → ERROR +\`\`\` + +Make it a column, shape **(4, 1)**, and it stretches **across** the columns: + +\`\`\`python +per_img = images.mean(axis=1, keepdims=True) # (4, 1) +# or: x.reshape(4, 1) or: x[:, None] +images - per_img # (4, 3) ✓ +\`\`\` + +The danger: when shapes *happen* to line up wrongly, NumPy doesn't error. It quietly computes the wrong thing. That's why broadcasting bugs are called **silent**.`, + check: { + kind: 'choice', + q: 'What does `(4, 3)` + `(4,)` give?', + o: ['An error', 'Shape (4, 3)', 'Shape (4, 4)', 'Shape (4,)'], + a: 0, + hint: 'Line them up from the right. What is the first pair you compare?', + why: 'From the right it is 3 vs 4: not equal and neither is 1, so it errors. Reshape to (4, 1) to get one value per row.', + }, + }, + { + title: 'Broadcasting both ways', + md: `Both arrays can stretch at once: + +\`\`\` +x (8, 1) a column of 8 +y (1, 5) a row of 5 + ────── + 1 vs 5 → stretch x across; 8 vs 1 → stretch y down +\`\`\` + +Every row of \`x\` gets combined with every column of \`y\`.`, + check: { + kind: 'text', + q: 'What is the shape of `x + y` when x is (8, 1) and y is (1, 5)?', + a: ['(8, 5)'], + hint: 'For each pair, the 1 stretches to match the other number.', + why: 'The 1s stretch to 5 and to 8, giving (8, 5).', + }, + }, + // ───────── Matmul and softmax ───────── + { + title: 'Matrix multiplication: @', + md: `Matrix multiplication is **the** operation of deep learning. Every layer of a neural network is mostly one. + +\`\`\`python +A @ B +\`\`\` + +**Shape rule:** \`[m, k] @ [k, n] → [m, n]\`. The two **inner** numbers must match, and they disappear. + +\`\`\` +[32, 64] @ [64, 10] + └──┬──┘ + must match → result [32, 10] +\`\`\` + +Each output number is a row of \`A\` "dotted" with a column of \`B\`: multiply pairs, then add them up.`, + check: { + kind: 'text', + q: 'What is the shape of `[32, 64] @ [64, 10]`?', + a: ['(32, 10)'], + hint: 'Keep the outer numbers; the inner 64s must match and disappear.', + why: '[m, k] @ [k, n] gives [m, n]: (32, 10).', + }, + }, + { + title: 'Why matmul needs NumPy', + md: `By hand, multiplying two n × n matrices takes **three nested loops**: + +\`\`\`python +for i in range(n): # each row of A + for j in range(n): # each column of B + for k in range(n): # add up the pairs + C[i, j] += A[i, k] * B[k, j] +\`\`\` + +For n = 512 that's 512 × 512 × 512 ≈ **134 million** multiply-adds. Measured on an Apple Silicon Mac: **about 14 seconds** with the loops, **under 1 millisecond** with \`A @ B\`. That's over 10,000× faster. + +You'll time both yourself in the notebook. It's the course's first Build exercise.`, + check: { + kind: 'choice', + q: 'Roughly why is `A @ B` so much faster than the 3-loop version?', + o: [ + 'It runs optimised compiled code instead of paying Python overhead on every multiply', + 'It skips some of the multiplications', + 'It uses less accurate numbers', + 'Python loops are broken', + ], + a: 0, + hint: 'Remember where the Python overhead is paid: per number, or per operation?', + why: 'The loops pay Python overhead 134 million times; @ hands the whole job to optimised C/BLAS code once.', + }, + }, + { + title: 'Softmax: scores into probabilities', + md: `A model's raw outputs ("scores", called **logits**) can be any numbers. **Softmax** turns them into probabilities that are all positive and add up to 1: + +\`\`\` +softmax(x) = exp(x) / sum(exp(x)) + +scores [2.0, 1.0, 0.1] +exp [7.39, 2.72, 1.11] sum = 11.22 +probs [0.66, 0.24, 0.10] sum = 1 ✓ +\`\`\` + +**Stable version:** \`exp(1000)\` overflows to \`inf\`. Subtract the max first. It gives the **same answer**, because shifting every score by the same amount cancels out in the division. + +\`\`\`python +def softmax(x): # x: (batch, classes) + x = x - x.max(axis=1, keepdims=True) # (batch, 1) broadcasts + e = np.exp(x) + return e / e.sum(axis=1, keepdims=True) +\`\`\` + +Look at the code: \`axis\`, \`keepdims\` and broadcasting, all from earlier screens.`, + check: { + kind: 'choice', + q: 'What is `softmax([3.0, 3.0])`?', + o: ['`[0.5, 0.5]`', '`[3.0, 3.0]`', '`[1.0, 1.0]`', '`[0.0, 0.0]`'], + a: 0, + hint: 'Equal scores get equal probabilities, and they must add up to 1.', + why: 'Both exps are equal, so each gets half: [0.5, 0.5].', + }, + }, + // ───────── PyTorch: tensors ───────── + { + title: 'PyTorch tensors', + md: `A **tensor** is the maths word for an array with any number of dimensions. A scalar is a 0D tensor, a list is 1D, a grid is 2D… + +\`torch.tensor\` is like a NumPy array, plus two superpowers: + +1. **It runs on a GPU**: fast for big models. +2. **Autograd**: it can compute gradients for you (coming up). + +\`\`\`python +import torch +x = torch.arange(6) # tensor([0, 1, 2, 3, 4, 5]) +x.shape # torch.Size([6]) +\`\`\` + +Shapes and broadcasting work **exactly** like NumPy. (TensorFlow is a different library from Google. PyTorch is from Meta and is the standard for research and most LLMs.)`, + check: { + kind: 'choice', + q: 'What do PyTorch tensors add on top of NumPy arrays?', + o: ['GPU support and automatic gradients', 'Different broadcasting rules', 'Only a different name', 'Support for strings'], + a: 0, + hint: 'There were two "superpowers".', + why: 'Same array ideas, plus GPUs and autograd. Broadcasting is identical.', + }, + }, + { + title: 'reshape', + md: `\`reshape\` puts the **same numbers** into a new shape, filling row by row: + +\`\`\` +torch.arange(6).reshape(2, 3) torch.arange(6).reshape(3, 2) +┌───┬───┬───┐ ┌───┬───┐ +│ 0 │ 1 │ 2 │ │ 0 │ 1 │ +├───┼───┼───┤ ├───┼───┤ +│ 3 │ 4 │ 5 │ │ 2 │ 3 │ +└───┴───┴───┘ ├───┼───┤ + │ 4 │ 5 │ + └───┴───┘ +\`\`\` + +**Rule:** reshape never adds or drops numbers, so rows × columns must equal the count. \`-1\` means "you work this one out": \`x.reshape(2, -1)\` → (2, 3).`, + check: { + kind: 'choice', + q: 'What does `torch.arange(6).reshape(4, 2)` do?', + o: ['Raises an error', 'Pads the last row with zeros', 'Leaves the last row empty', 'Drops the extra slots'], + a: 0, + hint: 'How many slots does (4, 2) have, and how many numbers are there?', + why: '4 × 2 = 8 slots but only 6 numbers: RuntimeError. Tensors can\'t have ragged or padded rows.', + }, + }, + { + title: 'NumPy ↔ PyTorch', + md: `Data usually starts in NumPy (loaded from files, images, pandas) and becomes a tensor for training: + +\`\`\`python +a = np.array([1, 2, 3]) +t = torch.from_numpy(a) # NumPy → tensor: SHARES memory +b = t.numpy() # tensor → NumPy: shares memory too +c = torch.tensor(a) # makes an independent COPY +\`\`\` + +\`\`\` +from_numpy: torch.tensor(a): + a ──┐ a ──► [1, 2, 3] + ├──► [1, 2, 3] c ──► [1, 2, 3] (separate copy) + t ──┘ +\`\`\``, + check: { + kind: 'choice', + q: '`t = torch.from_numpy(a)`, then `a[0] = 100`. What is `t`?', + o: ['`tensor([100, 2, 3])`', '`tensor([1, 2, 3])`', 'An error', '`tensor([100])`'], + a: 0, + hint: 'Do `a` and `t` point at the same box of numbers, or two boxes?', + why: 'from_numpy shares memory, so changing a changes t. With torch.tensor(a), t would stay [1, 2, 3].', + }, + }, + { + title: 'Devices: CPU and GPU', + md: `Every tensor lives on a **device**: + +| device | what | +|---|---| +| \`"cpu"\` | the default | +| \`"mps"\` | Apple Silicon Mac GPU | +| \`"cuda"\` | NVIDIA GPU (cloud, Colab) | + +\`\`\`python +device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" +x = torch.tensor([1., 2.], device=device) +\`\`\` + +**Rule:** maths only works between tensors on the **same device**. Pick the device once at the top and use it everywhere.`, + check: { + kind: 'choice', + q: '`x` is on `"mps"`, `y` is on the CPU. What does `x + y` do?', + o: ['Raises a "same device" error', 'Moves y automatically', 'Returns a CPU tensor', 'Returns zeros'], + a: 0, + hint: 'What is the rule about devices?', + why: 'RuntimeError: expected all tensors to be on the same device. Fix: create y on the same device too.', + }, + }, + // ───────── Training ───────── + { + title: 'Loss: how wrong is the guess?', + md: `Training is a guessing game. The simplest version has **one number** \`w\` (the model's guess) and a **target** (the right answer). Here the target is 5. + +\`\`\` + w = 3 target = 5 + 3 ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ► 5 +\`\`\` + +The **loss** measures how wrong the guess is: + +\`\`\`python +loss = (w - 5) ** 2 # 0 when w = 5; bigger the further away +\`\`\` + +In real models the target comes from data: the real house price, the photo's label, the actual next word.`, + check: { + kind: 'number', + q: 'What is the loss when `w = 3`?', + a: 4, + hint: 'Work out (3 − 5) first, then square it.', + why: '(3 − 5)² = (−2)² = 4.', + }, + }, + { + title: 'The gradient', + md: `The **gradient** says how the loss changes when \`w\` changes: which way is "uphill". For our loss it is: + +\`\`\` +grad = 2 * (w - 5) +\`\`\` + +- **negative** gradient → loss goes *down* if \`w\` goes **up** +- **positive** gradient → loss goes *down* if \`w\` goes **down** + +You don't usually work this out by hand. PyTorch does it for you, as you'll see in a moment.`, + check: { + kind: 'number', + q: 'What is the gradient when `w = 3`?', + a: -4, + hint: '2 × (3 − 5). Watch the sign.', + why: '2 × (−2) = −4. Negative, so increasing w lowers the loss.', + }, + }, + { + title: 'Gradient descent', + md: `Step **opposite** the gradient: + +\`\`\`python +w = w - learning_rate * grad # learning_rate = 0.1 +\`\`\` + +The **learning rate** is the step size. Subtracting a negative gradient makes \`w\` go **up**, toward 5.`, + check: { + kind: 'number', + q: 'With `w = 3`, `grad = -4`, `learning_rate = 0.1`: what is the new `w`?', + a: 3.4, + hint: '3 − 0.1 × (−4). Subtracting a negative is adding.', + why: '3 − (−0.4) = 3.4. Closer to 5.', + }, + }, + { + title: 'Step two: smaller steps', + md: `Repeat from \`w = 3.4\`. Break it into three lines so the signs stay straight: + +\`\`\` +1. grad = 2 * (3.4 - 5) +2. step = 0.1 * grad +3. w_new = 3.4 - step +\`\`\``, + check: { + kind: 'number', + q: 'What is the new `w` after step two?', + a: 3.72, + hint: 'grad = −3.2 and step = −0.32. Start from 3.4, not 3.', + why: '3.4 − (−0.32) = 3.72. The step (0.32) is smaller than the first (0.4) because the gradient shrinks as w nears 5, so training slows down as it arrives.', + }, + }, + { + title: 'The learning rate', + md: `\`\`\` +lr = 1.0: 3 ──────────► 7 grad flips sign every step: + ◄──────────── 3 it bounces forever (or explodes if bigger) + +lr = 0.1: 3 → 3.4 → 3.72 → … → 5 steady ✓ + +lr = 0.001: 3 → 3.004 → … thousands of steps 🐢 +\`\`\` + +| learning rate | result | +|---|---| +| too big | overshoots, bounces or blows up | +| about right | steady progress | +| too small | works, but painfully slow |`, + check: { + kind: 'number', + q: 'With `lr = 1.0` and `w = 3`, what is `w` after one step?', + a: 7, + hint: 'grad is still −4. Now the step is 1.0 × (−4).', + why: '3 − (−4) = 7. It jumped right over 5, and the next step jumps back to 3.', + }, + }, + { + title: 'Autograd: PyTorch computes the gradient', + md: `The same training loop in PyTorch. You never write \`2 * (w - 5)\`: + +\`\`\`python +w = torch.tensor(3.0, requires_grad=True) # track gradients for w +lr = 0.1 + +for step in range(10): + loss = (w - 5) ** 2 + loss.backward() # computes w.grad for you + + with torch.no_grad(): # the update itself isn't part of the maths to track + w -= lr * w.grad + + w.grad.zero_() # reset for the next step (next screen) + print(step + 1, round(w.item(), 4)) +\`\`\` + +Prints \`1 3.4\`, \`2 3.72\`, … the same numbers you just computed by hand. For a model with millions of numbers, autograd is what makes training possible.`, + check: { + kind: 'choice', + q: 'What does `loss.backward()` do?', + o: ['Computes the gradient of the loss for every tensor with requires_grad', 'Updates w', 'Resets the gradient', 'Undoes the last step'], + a: 0, + hint: 'Which line actually changes w? It isn\'t this one.', + why: 'backward() only fills in .grad. The update is the separate w -= lr * w.grad line (optimizer.step() in real code).', + }, + }, + { + title: 'Why zero the gradient?', + md: `\`backward()\` doesn't replace \`w.grad\`. It **adds** to it, like pouring into a bucket that is never emptied: + +\`\`\` +with zero_(): step 1: grad = −4 → w = 3.4 + step 2: grad = −3.2 → w = 3.72 ✓ + +without zero_(): step 1: grad = −4 → w = 3.4 + step 2: grad = −4 + (−3.2) = ? +\`\`\` + +Without it, \`w\` goes 3.4, 4.12, 5.02, 5.91, 6.62, 7.01, 6.99, 6.58 … swinging like a pendulum. In real code this is \`optimizer.zero_grad()\`, once every step.`, + check: { + kind: 'number', + q: 'Without `zero_()`, what is `w.grad` at step 2?', + a: -7.2, + hint: 'The old −4 is still in the bucket. Add the new −3.2 to it.', + why: '−4 + (−3.2) = −7.2, so the step is 0.72 instead of 0.32 and w overshoots.', + }, + }, + { + title: 'Your turn: the notebook', + md: `You've seen every idea in Step 1. Now **run it**. The notebook has a section for each screen, with small exercises and \`assert\` checks that tell you when you're right: + +1. NumPy arrays, indexing and \`axis\` +2. Broadcasting +3. **Build:** matmul with three loops vs \`@\`, timed at 512 × 512 +4. **Build:** a numerically stable softmax, checked against \`torch.softmax\` +5. Tensors, reshape, NumPy ↔ PyTorch, devices +6. A training loop that runs until \`w\` reaches 5 + +Open it in Colab (runs in your browser, free GPU) or download it for Jupyter on your machine. Stuck? Every exercise has a hidden hint and solution. Try first. + +The official docs are in the **Learn** step. Read them alongside the notebook.`, + }, + ], + }, +} diff --git a/src/lib/ai/quizzes.ts b/src/lib/ai/quizzes.ts index 061e55d..ba6cbe2 100644 --- a/src/lib/ai/quizzes.ts +++ b/src/lib/ai/quizzes.ts @@ -3,6 +3,52 @@ export type Question = { q: string; o: string[]; a: number; why: string } export const quizzes: Record = { + // ───────────── Setup ───────────── + 'setup-1': [ + { + q: 'data has shape (4, 3). What is the shape of data.mean(axis=1, keepdims=True)?', + o: ['(4, 1)', '(4,)', '(1, 3)', '(3,)'], + a: 0, + why: 'axis=1 collapses the columns (one value per row), and keepdims leaves that axis as size 1.', + }, + { + q: 'Which of these broadcasts without an error?', + o: ['(4, 3) + (3,)', '(4, 3) + (4,)', '(2, 3) + (3, 2)', '(5,) + (4,)'], + a: 0, + why: 'Compared from the right, 3 vs 3 matches and the missing dimension stretches. The others have a pair that is neither equal nor 1.', + }, + { + q: 'Why does a stable softmax subtract the row maximum first?', + o: ['To stop exp() overflowing; the result is unchanged', 'To make the outputs sum to 1', 'To make it faster', 'To turn the scores negative for the loss'], + a: 0, + why: 'A constant shift cancels in the division, but it keeps the largest exponent at exp(0) = 1.', + }, + { + q: 'torch.arange(6).reshape(3, -1) has shape…', + o: ['(3, 2)', '(3, 6)', '(2, 3)', 'Error'], + a: 0, + why: '-1 means "work it out": 6 numbers in 3 rows is 2 per row.', + }, + { + q: 'a = np.array([1, 2, 3]); t = torch.from_numpy(a); a[0] = 100. What is t?', + o: ['tensor([100, 2, 3])', 'tensor([1, 2, 3])', 'An error', 'tensor([100])'], + a: 0, + why: 'from_numpy shares memory with the array. torch.tensor(a) would make a copy.', + }, + { + q: 'w = 3, loss = (w - 5) ** 2, learning rate 0.1. After one gradient-descent step, w is…', + o: ['3.4', '2.6', '7', '3.04'], + a: 0, + why: 'grad = 2(w - 5) = -4, so w - 0.1 × (-4) = 3.4.', + }, + { + q: 'What happens if you forget w.grad.zero_() in the training loop?', + o: ['Gradients add up across steps, so the steps grow and w overshoots', 'Training crashes with an error', 'w stops changing', 'Nothing changes'], + a: 0, + why: 'backward() adds into .grad. Old gradients pile up and the updates get too big.', + }, + ], + // ───────────── Track 1 ───────────── 't1-1.1': [ { diff --git a/src/pages/ai-engineer/[track]/[module]/[unit].astro b/src/pages/ai-engineer/[track]/[module]/[unit].astro index b297150..a4df7f4 100644 --- a/src/pages/ai-engineer/[track]/[module]/[unit].astro +++ b/src/pages/ai-engineer/[track]/[module]/[unit].astro @@ -2,7 +2,7 @@ /* One lesson step, full screen. Built for every step of every module. */ import Base from '../../../../layouts/Base.astro'; import Session from '../../../../components/ai/Session'; -import { moduleUrl, tracks, trackUrl, unitKinds, UNIT_LABEL, UNIT_SLUG, type Module, type Track, type UnitKind } from '../../../../lib/ai/course'; +import { lessonFor, moduleUrl, tracks, trackUrl, unitKinds, UNIT_LABEL, UNIT_SLUG, type Module, type Track, type UnitKind } from '../../../../lib/ai/course'; import { quizzes } from '../../../../lib/ai/quizzes'; import { SITE_NAME } from '../../../../data/site'; import '../../../../styles/ai.css'; @@ -24,6 +24,8 @@ const label = UNIT_LABEL[kind]; module={{ id: m.id, label: m.label, title: m.title, why: m.why, concepts: m.concepts, notes: m.notes, guideHtml: kind === 'concepts' ? m.guideHtml : '', resources: m.resources, build: m.build, checkpoint: m.checkpoint }} track={{ id: track.id, short: track.short, subtitle: track.subtitle }} questions={kind === 'quiz' ? quizzes[m.id] : undefined} + lesson={kind === 'lesson' ? lessonFor(m) : undefined} + notebook={kind === 'build' ? lessonFor(m)?.notebook : undefined} backUrl={`${trackUrl(track)}#${m.slug}`} guideUrl={moduleUrl(track, m)} /> diff --git a/src/pages/ai-engineer/notebooks/[file].ts b/src/pages/ai-engineer/notebooks/[file].ts new file mode 100644 index 0000000..3639049 --- /dev/null +++ b/src/pages/ai-engineer/notebooks/[file].ts @@ -0,0 +1,11 @@ +/* Course notebooks as downloads: /ai-engineer/notebooks/00-setup-notebooks-step-1.ipynb. + * The notebook itself lives in /course next to the module it belongs to. */ +import type { APIRoute } from 'astro' +import { allNotebooks } from '../../../lib/ai/course' + +export function getStaticPaths() { + return allNotebooks().map((n) => ({ params: { file: n.file }, props: { json: n.json } })) +} + +export const GET: APIRoute = ({ props }) => + new Response(props.json as string, { headers: { 'Content-Type': 'application/x-ipynb+json' } }) diff --git a/src/styles/ai.css b/src/styles/ai.css index f710f18..2fadaa1 100644 --- a/src/styles/ai.css +++ b/src/styles/ai.css @@ -194,6 +194,7 @@ a.card.row, .card.row { display: flex; } .option.wrong { border-color: var(--bad); background: var(--bad-soft); box-shadow: 0 3px 0 var(--bad); } .option.wrong .k { background: var(--bad); color: var(--on-accent); } .option:disabled { cursor: default; } +.option { font-family: inherit; } .footer { position: fixed; left: 0; right: 0; bottom: 0; border-top: 1px solid var(--line); background: color-mix(in srgb, var(--bg) 88%, transparent); backdrop-filter: blur(10px); } .footer.ok { background: var(--ok-soft); border-color: color-mix(in srgb, var(--ok) 35%, transparent); } @@ -225,6 +226,23 @@ a.card.row, .card.row { display: flex; } .prose th { background: var(--bg-2); } .prose pre { background: var(--bg-2); border: 1px solid var(--line); padding: 14px; border-radius: 12px; overflow-x: auto; font-size: 13px; } .prose pre code { background: none; padding: 0; } +.prose :not(pre) > code { font-family: var(--mono); font-size: 0.9em; background: var(--bg-2); padding: 1px 5px; border-radius: 5px; } +/* ───────── lesson step ───────── */ +.lesson-body { max-width: 80ch; } +.lesson-body > * + * { margin-top: 14px; } +.lesson-body pre { line-height: 1.45; } +.lesson-check { max-width: 80ch; border-top: 1px solid var(--line); margin-top: 26px; } +.lesson-q { font-size: 18px; font-weight: 600; line-height: 1.5; margin: 0; } +.lesson-q code, .option code, .footer .msg code { font-family: var(--mono); font-size: 0.9em; background: var(--bg-2); padding: 1px 5px; border-radius: 5px; } +.lesson-check .options { margin-top: 16px; } +.answer-input { margin-top: 16px; width: min(320px, 100%); font: 600 17px var(--mono); color: var(--ink); background: var(--card); border: 1.5px solid var(--line); border-radius: 12px; padding: 12px 14px; box-shadow: 0 3px 0 var(--line); } +.answer-input:focus { outline: none; border-color: var(--c, var(--accent)); box-shadow: 0 3px 0 var(--c, var(--accent)); } +.answer-input.right { border-color: var(--ok); background: var(--ok-soft); box-shadow: 0 3px 0 var(--ok); } +.answer-input.wrong { border-color: var(--bad); background: var(--bad-soft); box-shadow: 0 3px 0 var(--bad); } +.notebook { margin: 22px 0 6px; max-width: 80ch; } +.notebook small { display: block; } +.notebook-actions { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 14px; } +.notebook-actions .btn { display: inline-flex; align-items: center; gap: 6px; text-decoration: none; } .prose ul, .prose ol { padding-left: 22px; } .prose input[type='checkbox'] { accent-color: var(--accent); } .guide-hero { border-radius: 22px; padding: 26px 28px; background: linear-gradient(135deg, var(--c), var(--ce)); color: var(--on-accent); margin: 10px 0 26px; }