{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1d6ec053",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "# Module 06: Optimizers - Sophisticated Learning Algorithms\n",
    "\n",
    "Welcome to Module 06! You'll build optimizers that enable neural networks to learn from gradients using sophisticated algorithms.\n",
    "\n",
    "## 🔗 Prerequisites & Progress\n",
    "**You've Built**: Tensor with gradients (Modules 01-05)\n",
    "**You'll Build**: SGD, Adam, and AdamW optimizers with sophisticated momentum and adaptive learning\n",
    "**You'll Enable**: Modern optimization algorithms that power state-of-the-art neural networks\n",
    "\n",
    "**Connection Map**:\n",
    "```\n",
    "Gradients → Optimizers → Training\n",
    "(Module 05)  (Module 06)  (Module 07)\n",
    "```\n",
    "\n",
    "## Learning Objectives\n",
    "By the end of this module, you will:\n",
    "1. Implement SGD with momentum for stable gradient descent\n",
    "2. Build Adam optimizer with adaptive learning rates\n",
    "3. Create AdamW optimizer with decoupled weight decay\n",
    "4. Understand memory and computational trade-offs in optimization algorithms\n",
    "\n",
    "Let's get started!\n",
    "\n",
    "## 📦 Where This Code Lives in the Final Package\n",
    "\n",
    "**Learning Side:** You work in `modules/06_optimizers/optimizers_dev.py`  \n",
    "**Building Side:** Code exports to `tinytorch.core.optimizers`\n",
    "\n",
    "```python\n",
    "# How to use this module:\n",
    "from tinytorch.core.optimizers import SGD, Adam, AdamW\n",
    "```\n",
    "\n",
    "**Why this matters:**\n",
    "- **Learning:** Complete optimization system for modern neural network training\n",
    "- **Production:** Proper organization like PyTorch's torch.optim with all optimization algorithms together\n",
    "- **Consistency:** All optimization logic and parameter updating in core.optimizers\n",
    "- **Integration:** Works seamlessly with gradients from Module 05 for complete training capability"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d0a451b",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "imports",
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "#| default_exp core.optimizers\n",
    "#| export\n",
    "\n",
    "import numpy as np\n",
    "from typing import List, Union, Optional, Dict, Any\n",
    "\n",
    "# Import Tensor from Module 01 (now with gradient support from Module 05)\n",
    "from tinytorch.core.tensor import Tensor"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1439f0d3",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "## 1. Introduction: What are Optimizers?\n",
    "\n",
    "Optimizers are the engines that drive neural network learning. They take gradients computed from your loss function and use them to update model parameters toward better solutions. Think of optimization as navigating a complex landscape where you're trying to find the lowest valley (minimum loss).\n",
    "\n",
    "### The Optimization Challenge\n",
    "\n",
    "Imagine you're hiking in dense fog, trying to reach the bottom of a valley. You can only feel the slope under your feet (the gradient), but you can't see where you're going. Different optimization strategies are like different hiking approaches:\n",
    "\n",
    "```\n",
    "Loss Landscape (2D visualization):\n",
    "       🏔️\n",
    "      /  \\\\\n",
    "   🚶 /    \\\\\n",
    "    /      \\\\\n",
    "   /   🎯   \\\\  ← Global minimum (goal)\n",
    "  /          \\\\\n",
    " 🏔️          🏔️\n",
    "\n",
    "Challenge: Navigate to 🎯 using only local slope information!\n",
    "```\n",
    "\n",
    "### Our Optimizer Toolkit\n",
    "\n",
    "**SGD (Stochastic Gradient Descent)**\n",
    "- Strategy: Always step downhill\n",
    "- Problem: Can get stuck oscillating in narrow valleys\n",
    "- Solution: Add momentum to \"coast\" through oscillations\n",
    "\n",
    "**Adam (Adaptive Moment Estimation)**\n",
    "- Strategy: Adapt step size for each parameter individually\n",
    "- Advantage: Different learning rates for different dimensions\n",
    "- Key Insight: Some directions need big steps, others need small steps\n",
    "\n",
    "**AdamW (Adam with Weight Decay)**\n",
    "- Strategy: Adam + proper regularization\n",
    "- Fix: Separates optimization from regularization\n",
    "- Result: Better generalization and training stability\n",
    "\n",
    "### The Mathematics Behind Movement\n",
    "\n",
    "At its core, optimization follows: **θ_new = θ_old - α * direction**\n",
    "\n",
    "Where:\n",
    "- `θ` = parameters (your position in the landscape)\n",
    "- `α` = step size (learning rate)\n",
    "- `direction` = where to step (gradient-based)\n",
    "\n",
    "But sophisticated optimizers do much more than basic gradient descent!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f4517727",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "## 2. Foundations: Mathematical Background\n",
    "\n",
    "### Understanding Momentum: The Physics of Optimization\n",
    "\n",
    "Momentum in optimization works like momentum in physics. A ball rolling down a hill doesn't immediately change direction when it hits a small bump - it has momentum that carries it forward.\n",
    "\n",
    "```\n",
    "Without Momentum (SGD):           With Momentum:\n",
    "     ↓                                ↘️\n",
    "  ←  •  →  ← oscillation           →  •  → smooth path\n",
    "     ↑                                ↙️\n",
    "\n",
    "Narrow valley problem:            Momentum solution:\n",
    "|\\     /|                        |\\     /|\n",
    "| \\ • / | ← ping-pong             | \\ •→/ | ← smoother\n",
    "|  \\ /  |   motion                |  \\ /  |   descent\n",
    "|   ●   |                        |   ●   |\n",
    "```\n",
    "\n",
    "**SGD with Momentum Formula:**\n",
    "```\n",
    "velocity = β * previous_velocity + (1-β) * current_gradient\n",
    "parameter = parameter - learning_rate * velocity\n",
    "\n",
    "Where β ≈ 0.9 means \"90% memory of previous direction\"\n",
    "```\n",
    "\n",
    "### Adam: Adaptive Learning for Each Parameter\n",
    "\n",
    "Adam solves a key problem: different parameters need different learning rates. Imagine adjusting the focus and zoom on a camera - you need fine control for focus but coarse control for zoom.\n",
    "\n",
    "```\n",
    "Parameter Landscape (2 dimensions):\n",
    "\n",
    "   param2\n",
    "     ^\n",
    "     |\n",
    "   😞|    steep gradient\n",
    "     |    (needs small steps)\n",
    "     |\n",
    "  ---+--●--→ param1\n",
    "     |     \\\\\n",
    "     |      \\\\ gentle gradient\n",
    "     |       \\\\ (needs big steps)\n",
    "\n",
    "Adam Solution: Automatic step size per parameter!\n",
    "```\n",
    "\n",
    "**Adam's Two-Memory System:**\n",
    "\n",
    "1. **First Moment (m)**: \"Which direction am I usually going?\"\n",
    "   - `m = β₁ * old_m + (1-β₁) * gradient`\n",
    "   - Like momentum, but for direction\n",
    "\n",
    "2. **Second Moment (v)**: \"How big are my gradients usually?\"\n",
    "   - `v = β₂ * old_v + (1-β₂) * gradient²`\n",
    "   - Tracks gradient magnitude\n",
    "\n",
    "3. **Adaptive Update**:\n",
    "   - `step_size = m / √v`\n",
    "   - Big gradients → smaller steps\n",
    "   - Small gradients → relatively bigger steps\n",
    "\n",
    "### AdamW: Fixing Weight Decay\n",
    "\n",
    "Adam has a subtle bug in how it applies weight decay (regularization). AdamW fixes this:\n",
    "\n",
    "```\n",
    "Adam (incorrect):               AdamW (correct):\n",
    "gradient += weight_decay * param    [compute gradient update]\n",
    "update_param_with_gradient()        param -= learning_rate * gradient_update\n",
    "                                   param *= (1 - weight_decay)  ← separate!\n",
    "\n",
    "Why it matters:\n",
    "- Adam: Weight decay affected by adaptive learning rates\n",
    "- AdamW: Weight decay is consistent regardless of gradients\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c0eadfbd",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## 3. Implementation: Building Optimizers\n",
    "\n",
    "Now we'll implement each optimizer step by step, following the pattern: understand the algorithm → implement it → test it immediately. Each optimizer builds on the foundation of the previous one.\n",
    "\n",
    "### Implementation Strategy\n",
    "\n",
    "```\n",
    "Optimizer Base Class\n",
    "    ↓\n",
    "SGD (foundation algorithm)\n",
    "    ↓\n",
    "SGD + Momentum (reduce oscillations)\n",
    "    ↓\n",
    "Adam (adaptive learning rates)\n",
    "    ↓\n",
    "AdamW (proper weight decay)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d9ffcd40",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": false,
     "grade_id": "optimizer-base",
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "#| export\n",
    "class Optimizer:\n",
    "    \"\"\"\n",
    "    Base class for all optimizers.\n",
    "\n",
    "    This class defines the common interface that all optimizers must implement:\n",
    "    - zero_grad(): Clear gradients from parameters\n",
    "    - step(): Update parameters based on gradients\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, params: List[Tensor]):\n",
    "        \"\"\"\n",
    "        Initialize optimizer with parameters to optimize.\n",
    "\n",
    "        TODO: Set up the parameter list for optimization\n",
    "\n",
    "        APPROACH:\n",
    "        1. Store parameters as a list for iteration\n",
    "        2. Validate that all parameters require gradients\n",
    "        3. Initialize step counter for algorithms that need it\n",
    "\n",
    "        EXAMPLE:\n",
    "        >>> linear = Linear(784, 128)\n",
    "        >>> optimizer = SGD(linear.parameters(), lr=0.01)\n",
    "\n",
    "        HINT: Check that each parameter has requires_grad=True\n",
    "        \"\"\"\n",
    "        ### BEGIN SOLUTION\n",
    "        # Validate and store parameters\n",
    "        if not isinstance(params, list):\n",
    "            params = list(params)\n",
    "\n",
    "        # Check that parameters require gradients\n",
    "        for i, param in enumerate(params):\n",
    "            if not isinstance(param, Tensor):\n",
    "                raise TypeError(f\"Parameter {i} must be a Tensor, got {type(param)}\")\n",
    "            if not param.requires_grad:\n",
    "                raise ValueError(f\"Parameter {i} does not require gradients. Set requires_grad=True.\")\n",
    "\n",
    "        self.params = params\n",
    "        self.step_count = 0  # For algorithms that need step counting\n",
    "        ### END SOLUTION\n",
    "\n",
    "    def zero_grad(self):\n",
    "        \"\"\"\n",
    "        Clear gradients from all parameters.\n",
    "\n",
    "        TODO: Reset all parameter gradients to None\n",
    "\n",
    "        APPROACH:\n",
    "        1. Iterate through all parameters\n",
    "        2. Set each parameter's grad to None\n",
    "\n",
    "        EXAMPLE:\n",
    "        >>> optimizer.zero_grad()  # Clears all gradients\n",
    "        >>> assert param.grad is None for param in optimizer.params\n",
    "\n",
    "        WHY: Gradients accumulate by default, so we need to clear them between batches\n",
    "        \"\"\"\n",
    "        ### BEGIN SOLUTION\n",
    "        for param in self.params:\n",
    "            param.grad = None\n",
    "        ### END SOLUTION\n",
    "\n",
    "    def step(self):\n",
    "        \"\"\"\n",
    "        Update parameters based on gradients.\n",
    "\n",
    "        This is abstract - each optimizer implements its own update rule.\n",
    "        \"\"\"\n",
    "        raise NotImplementedError(\"Subclasses must implement step()\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a8759d8d",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### 🔬 Unit Test: Base Optimizer\n",
    "This test validates our base Optimizer class works correctly.\n",
    "**What we're testing**: Parameter validation and zero_grad functionality\n",
    "**Why it matters**: Foundation for all specific optimizer implementations\n",
    "**Expected**: Proper parameter storage and gradient clearing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "387b0722",
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "test-optimizer-base",
     "locked": true,
     "points": 10
    }
   },
   "outputs": [],
   "source": [
    "def test_unit_optimizer_base():\n",
    "    \"\"\"🔬 Test base Optimizer functionality.\"\"\"\n",
    "    print(\"🔬 Unit Test: Base Optimizer...\")\n",
    "\n",
    "    # Create test parameters\n",
    "    param1 = Tensor([1.0, 2.0], requires_grad=True)\n",
    "    param2 = Tensor([[3.0, 4.0], [5.0, 6.0]], requires_grad=True)\n",
    "\n",
    "    # Add some gradients\n",
    "    param1.grad = Tensor([0.1, 0.2])\n",
    "    param2.grad = Tensor([[0.3, 0.4], [0.5, 0.6]])\n",
    "\n",
    "    # Create optimizer\n",
    "    optimizer = Optimizer([param1, param2])\n",
    "\n",
    "    # Test parameter storage\n",
    "    assert len(optimizer.params) == 2\n",
    "    assert optimizer.params[0] is param1\n",
    "    assert optimizer.params[1] is param2\n",
    "    assert optimizer.step_count == 0\n",
    "\n",
    "    # Test zero_grad\n",
    "    optimizer.zero_grad()\n",
    "    assert param1.grad is None\n",
    "    assert param2.grad is None\n",
    "\n",
    "    # Test error handling\n",
    "    try:\n",
    "        bad_param = Tensor([1.0], requires_grad=False)\n",
    "        Optimizer([bad_param])\n",
    "        assert False, \"Should have raised ValueError\"\n",
    "    except ValueError as e:\n",
    "        assert \"does not require gradients\" in str(e)\n",
    "\n",
    "    print(\"✅ Base Optimizer works correctly!\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    test_unit_optimizer_base()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4421916c",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## SGD - Stochastic Gradient Descent\n",
    "\n",
    "SGD is the foundation of neural network optimization. It implements the simple but powerful idea: \"move in the direction opposite to the gradient.\"\n",
    "\n",
    "### Why SGD Works\n",
    "\n",
    "Gradients point uphill (toward higher loss). To minimize loss, we go downhill:\n",
    "\n",
    "```\n",
    "Loss Surface (side view):\n",
    "\n",
    "    Loss\n",
    "     ^\n",
    "     |\n",
    "  📈 |     current position\n",
    "     |    /\n",
    "     |   • ← you are here\n",
    "     |  / \\\n",
    "     | /   \\ gradient points uphill\n",
    "     |/     \\\n",
    "     ●-------\\--→ parameters\n",
    "      \\        \\\n",
    "       \\        ↘️ SGD steps downhill\n",
    "        \\        (opposite to gradient)\n",
    "         \\⭐ ← goal (minimum loss)\n",
    "```\n",
    "\n",
    "### The Oscillation Problem\n",
    "\n",
    "Pure SGD can get trapped oscillating in narrow valleys:\n",
    "\n",
    "```\n",
    "Narrow valley (top view):\n",
    "  \\     /\n",
    "   \\   /   ← steep sides\n",
    "    \\ /\n",
    "  4← • →2  ← SGD bounces back and forth\n",
    "    / \\\n",
    "   1   3   instead of going down the valley\n",
    "  /     \\\n",
    " ●       \\\n",
    " goal     \\\n",
    "```\n",
    "\n",
    "### Momentum Solution\n",
    "\n",
    "Momentum remembers the direction you were going and continues in that direction:\n",
    "\n",
    "```\n",
    "With momentum:\n",
    "  \\     /\n",
    "   \\   /\n",
    "    \\ /\n",
    "     •  ← smooth path down the valley\n",
    "    / ↓\n",
    "   /   ↓\n",
    "  ●    ↓  momentum carries us through oscillations\n",
    " goal\n",
    "```\n",
    "\n",
    "**Implementation:** SGD keeps a \"velocity\" buffer that accumulates momentum."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee1072b1",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": false,
     "grade_id": "sgd-optimizer",
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "#| export\n",
    "class SGD(Optimizer):\n",
    "    \"\"\"\n",
    "    Stochastic Gradient Descent with momentum.\n",
    "\n",
    "    SGD is the foundational optimization algorithm that moves parameters\n",
    "    in the direction opposite to gradients. With momentum, it remembers\n",
    "    previous updates to reduce oscillations and accelerate convergence.\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, params: List[Tensor], lr: float = 0.01, momentum: float = 0.0, weight_decay: float = 0.0):\n",
    "        \"\"\"\n",
    "        Initialize SGD optimizer.\n",
    "\n",
    "        TODO: Set up SGD with momentum and weight decay\n",
    "\n",
    "        APPROACH:\n",
    "        1. Call parent constructor to set up parameters\n",
    "        2. Store learning rate, momentum, and weight decay\n",
    "        3. Initialize momentum buffers for each parameter\n",
    "\n",
    "        EXAMPLE:\n",
    "        >>> optimizer = SGD(model.parameters(), lr=0.01, momentum=0.9)\n",
    "\n",
    "        HINTS:\n",
    "        - Momentum buffers should be initialized as None\n",
    "        - They'll be created lazily on first step\n",
    "        \"\"\"\n",
    "        ### BEGIN SOLUTION\n",
    "        super().__init__(params)\n",
    "\n",
    "        self.lr = lr\n",
    "        self.momentum = momentum\n",
    "        self.weight_decay = weight_decay\n",
    "\n",
    "        # Initialize momentum buffers (created lazily)\n",
    "        self.momentum_buffers = [None for _ in self.params]\n",
    "        ### END SOLUTION\n",
    "\n",
    "    def step(self):\n",
    "        \"\"\"\n",
    "        Perform SGD update step with momentum.\n",
    "\n",
    "        TODO: Implement SGD parameter update with momentum\n",
    "\n",
    "        APPROACH:\n",
    "        1. For each parameter with gradients:\n",
    "           a. Apply weight decay if specified\n",
    "           b. Update momentum buffer\n",
    "           c. Update parameter using momentum\n",
    "\n",
    "        FORMULA:\n",
    "        - With weight decay: grad = grad + weight_decay * param\n",
    "        - Momentum: v = momentum * v_prev + grad\n",
    "        - Update: param = param - lr * v\n",
    "\n",
    "        HINTS:\n",
    "        - Skip parameters without gradients\n",
    "        - Initialize momentum buffers on first use\n",
    "        - Use in-place operations to save memory\n",
    "        \"\"\"\n",
    "        ### BEGIN SOLUTION\n",
    "        for i, param in enumerate(self.params):\n",
    "            if param.grad is None:\n",
    "                continue\n",
    "\n",
    "            # Get gradient (param.grad is already a numpy array)\n",
    "            grad = param.grad\n",
    "\n",
    "            # Apply weight decay\n",
    "            if self.weight_decay != 0:\n",
    "                grad = grad + self.weight_decay * param.data\n",
    "\n",
    "            # Update momentum buffer\n",
    "            if self.momentum != 0:\n",
    "                if self.momentum_buffers[i] is None:\n",
    "                    # Initialize momentum buffer\n",
    "                    self.momentum_buffers[i] = np.zeros_like(param.data)\n",
    "\n",
    "                # Update momentum: v = momentum * v_prev + grad\n",
    "                self.momentum_buffers[i] = self.momentum * self.momentum_buffers[i] + grad\n",
    "                grad = self.momentum_buffers[i]\n",
    "\n",
    "            # Update parameter: param = param - lr * grad\n",
    "            param.data = param.data - self.lr * grad\n",
    "\n",
    "        # Increment step counter\n",
    "        self.step_count += 1\n",
    "        ### END SOLUTION"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c6ed86d3",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### 🔬 Unit Test: SGD Optimizer\n",
    "This test validates our SGD implementation works correctly.\n",
    "**What we're testing**: SGD updates with and without momentum\n",
    "**Why it matters**: Core optimization algorithm used in neural network training\n",
    "**Expected**: Correct parameter updates following SGD formulas"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "901e6d56",
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "test-sgd",
     "locked": true,
     "points": 15
    }
   },
   "outputs": [],
   "source": [
    "def test_unit_sgd_optimizer():\n",
    "    \"\"\"🔬 Test SGD optimizer implementation.\"\"\"\n",
    "    print(\"🔬 Unit Test: SGD Optimizer...\")\n",
    "\n",
    "    # Test basic SGD without momentum\n",
    "    param = Tensor([1.0, 2.0], requires_grad=True)\n",
    "    param.grad = Tensor([0.1, 0.2])\n",
    "\n",
    "    optimizer = SGD([param], lr=0.1)\n",
    "    original_data = param.data.copy()\n",
    "\n",
    "    optimizer.step()\n",
    "\n",
    "    # Expected: param = param - lr * grad = [1.0, 2.0] - 0.1 * [0.1, 0.2] = [0.99, 1.98]\n",
    "    expected = original_data - 0.1 * param.grad.data\n",
    "    assert np.allclose(param.data, expected)\n",
    "    assert optimizer.step_count == 1\n",
    "\n",
    "    # Test SGD with momentum\n",
    "    param2 = Tensor([1.0, 2.0], requires_grad=True)\n",
    "    param2.grad = Tensor([0.1, 0.2])\n",
    "\n",
    "    optimizer_momentum = SGD([param2], lr=0.1, momentum=0.9)\n",
    "\n",
    "    # First step: v = 0.9 * 0 + [0.1, 0.2] = [0.1, 0.2]\n",
    "    optimizer_momentum.step()\n",
    "    expected_first = np.array([1.0, 2.0]) - 0.1 * np.array([0.1, 0.2])\n",
    "    assert np.allclose(param2.data, expected_first)\n",
    "\n",
    "    # Second step with same gradient\n",
    "    param2.grad = Tensor([0.1, 0.2])\n",
    "    optimizer_momentum.step()\n",
    "    # v = 0.9 * [0.1, 0.2] + [0.1, 0.2] = [0.19, 0.38]\n",
    "    expected_momentum = np.array([0.19, 0.38])\n",
    "    expected_second = expected_first - 0.1 * expected_momentum\n",
    "    assert np.allclose(param2.data, expected_second, rtol=1e-5)\n",
    "\n",
    "    # Test weight decay\n",
    "    param3 = Tensor([1.0, 2.0], requires_grad=True)\n",
    "    param3.grad = Tensor([0.1, 0.2])\n",
    "\n",
    "    optimizer_wd = SGD([param3], lr=0.1, weight_decay=0.01)\n",
    "    optimizer_wd.step()\n",
    "\n",
    "    # grad_with_decay = [0.1, 0.2] + 0.01 * [1.0, 2.0] = [0.11, 0.22]\n",
    "    expected_wd = np.array([1.0, 2.0]) - 0.1 * np.array([0.11, 0.22])\n",
    "    assert np.allclose(param3.data, expected_wd)\n",
    "\n",
    "    print(\"✅ SGD optimizer works correctly!\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    test_unit_sgd_optimizer()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a4325f45",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## Adam - Adaptive Moment Estimation\n",
    "\n",
    "Adam solves a fundamental problem with SGD: different parameters often need different learning rates. Think of tuning a complex system where some knobs need gentle adjustments and others need bold changes.\n",
    "\n",
    "### The Parameter Scaling Problem\n",
    "\n",
    "Consider a neural network with both embedding weights and output weights:\n",
    "\n",
    "```\n",
    "Parameter Sensitivity Landscape:\n",
    "\n",
    "  output_weight                 embedding_weight\n",
    "       ↑                              ↑\n",
    "       |                              |\n",
    "    😱 |  steep cliff                  |  🐌 gentle slope\n",
    "       |  (needs tiny steps)          |  (needs big steps)\n",
    "       |                              |\n",
    "    ━━━●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━●━━━→\n",
    "\n",
    "Same learning rate = disaster!\n",
    "• Small LR: output weights learn fast, embeddings crawl\n",
    "• Large LR: embeddings learn well, output weights explode\n",
    "```\n",
    "\n",
    "### Adam's Adaptive Solution\n",
    "\n",
    "Adam automatically adjusts learning rates by tracking two statistics:\n",
    "\n",
    "```\n",
    "1. MOMENTUM (first moment): \"Which way am I usually going?\"\n",
    "   m = 0.9 * old_direction + 0.1 * current_gradient\n",
    "\n",
    "   Visualization:\n",
    "   old: →→→→\n",
    "   new:     ↗️\n",
    "   m:   →→→↗️  (weighted average)\n",
    "\n",
    "2. SCALE (second moment): \"How big are my steps usually?\"\n",
    "   v = 0.999 * old_scale + 0.001 * (current_gradient)²\n",
    "\n",
    "   Big gradients → bigger v → smaller effective steps\n",
    "   Small gradients → smaller v → bigger effective steps\n",
    "\n",
    "3. ADAPTIVE UPDATE:\n",
    "   step = momentum / √scale\n",
    "   param = param - learning_rate * step\n",
    "```\n",
    "\n",
    "### Bias Correction: The Cold Start Problem\n",
    "\n",
    "Adam starts with m=0 and v=0, which creates a bias toward zero initially:\n",
    "\n",
    "```\n",
    "Without bias correction:    With bias correction:\n",
    "\n",
    "Step 1: m = 0.9*0 + 0.1*g    Step 1: m̂ = m / (1-0.9¹) = m / 0.1\n",
    "       = 0.1*g (too small!)           = g (correct!)\n",
    "\n",
    "Step 2: m = 0.9*0.1*g + 0.1*g Step 2: m̂ = m / (1-0.9²) = m / 0.19\n",
    "       = 0.19*g (still small)         ≈ g (better!)\n",
    "```\n",
    "\n",
    "**Key Insight:** Adam is like having an automatic transmission that adjusts gear ratios for each parameter individually."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8c58d0d8",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": false,
     "grade_id": "adam-optimizer",
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "#| export\n",
    "class Adam(Optimizer):\n",
    "    \"\"\"\n",
    "    Adam optimizer with adaptive learning rates.\n",
    "\n",
    "    Adam computes individual adaptive learning rates for different parameters\n",
    "    from estimates of first and second moments of the gradients.\n",
    "    This makes it effective for problems with sparse gradients or noisy data.\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, params: List[Tensor], lr: float = 0.001, betas: tuple = (0.9, 0.999), eps: float = 1e-8, weight_decay: float = 0.0):\n",
    "        \"\"\"\n",
    "        Initialize Adam optimizer.\n",
    "\n",
    "        TODO: Set up Adam with adaptive learning rates\n",
    "\n",
    "        APPROACH:\n",
    "        1. Call parent constructor\n",
    "        2. Store hyperparameters (lr, betas, eps, weight_decay)\n",
    "        3. Initialize first and second moment buffers\n",
    "\n",
    "        PARAMETERS:\n",
    "        - lr: Learning rate (default: 0.001)\n",
    "        - betas: Coefficients for computing running averages (default: (0.9, 0.999))\n",
    "        - eps: Small constant for numerical stability (default: 1e-8)\n",
    "        - weight_decay: L2 penalty coefficient (default: 0.0)\n",
    "\n",
    "        EXAMPLE:\n",
    "        >>> optimizer = Adam(model.parameters(), lr=0.001, betas=(0.9, 0.999))\n",
    "        \"\"\"\n",
    "        ### BEGIN SOLUTION\n",
    "        super().__init__(params)\n",
    "\n",
    "        self.lr = lr\n",
    "        self.beta1, self.beta2 = betas\n",
    "        self.eps = eps\n",
    "        self.weight_decay = weight_decay\n",
    "\n",
    "        # Initialize moment buffers (created lazily)\n",
    "        self.m_buffers = [None for _ in self.params]  # First moment (mean)\n",
    "        self.v_buffers = [None for _ in self.params]  # Second moment (variance)\n",
    "        ### END SOLUTION\n",
    "\n",
    "    def step(self):\n",
    "        \"\"\"\n",
    "        Perform Adam update step.\n",
    "\n",
    "        TODO: Implement Adam parameter update with adaptive learning rates\n",
    "\n",
    "        APPROACH:\n",
    "        1. For each parameter with gradients:\n",
    "           a. Apply weight decay if specified\n",
    "           b. Update first moment estimate (momentum of gradient)\n",
    "           c. Update second moment estimate (momentum of squared gradient)\n",
    "           d. Compute bias-corrected moments\n",
    "           e. Update parameter using adaptive learning rate\n",
    "\n",
    "        FORMULAS:\n",
    "        - m_t = β₁ * m_{t-1} + (1-β₁) * g_t\n",
    "        - v_t = β₂ * v_{t-1} + (1-β₂) * g_t²\n",
    "        - m̂_t = m_t / (1-β₁^t)\n",
    "        - v̂_t = v_t / (1-β₂^t)\n",
    "        - θ_t = θ_{t-1} - lr * m̂_t / (√v̂_t + ε)\n",
    "\n",
    "        HINTS:\n",
    "        - Initialize buffers as zeros on first use\n",
    "        - Use step_count for bias correction\n",
    "        - Square gradients element-wise for second moment\n",
    "        \"\"\"\n",
    "        ### BEGIN SOLUTION\n",
    "        # Increment step counter first (needed for bias correction)\n",
    "        self.step_count += 1\n",
    "\n",
    "        for i, param in enumerate(self.params):\n",
    "            if param.grad is None:\n",
    "                continue\n",
    "\n",
    "            # Get gradient (param.grad is already a numpy array)\n",
    "            grad = param.grad\n",
    "\n",
    "            # Apply weight decay\n",
    "            if self.weight_decay != 0:\n",
    "                grad = grad + self.weight_decay * param.data\n",
    "\n",
    "            # Initialize buffers if needed\n",
    "            if self.m_buffers[i] is None:\n",
    "                self.m_buffers[i] = np.zeros_like(param.data)\n",
    "                self.v_buffers[i] = np.zeros_like(param.data)\n",
    "\n",
    "            # Update biased first moment estimate\n",
    "            self.m_buffers[i] = self.beta1 * self.m_buffers[i] + (1 - self.beta1) * grad\n",
    "\n",
    "            # Update biased second moment estimate\n",
    "            self.v_buffers[i] = self.beta2 * self.v_buffers[i] + (1 - self.beta2) * (grad ** 2)\n",
    "\n",
    "            # Compute bias correction\n",
    "            bias_correction1 = 1 - self.beta1 ** self.step_count\n",
    "            bias_correction2 = 1 - self.beta2 ** self.step_count\n",
    "\n",
    "            # Compute bias-corrected moments\n",
    "            m_hat = self.m_buffers[i] / bias_correction1\n",
    "            v_hat = self.v_buffers[i] / bias_correction2\n",
    "\n",
    "            # Update parameter\n",
    "            param.data = param.data - self.lr * m_hat / (np.sqrt(v_hat) + self.eps)\n",
    "        ### END SOLUTION"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1db08255",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### 🔬 Unit Test: Adam Optimizer\n",
    "This test validates our Adam implementation works correctly.\n",
    "**What we're testing**: Adam updates with adaptive learning rates and bias correction\n",
    "**Why it matters**: Most popular optimizer for modern neural networks\n",
    "**Expected**: Correct parameter updates following Adam formulas"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c3a8c1a0",
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "test-adam",
     "locked": true,
     "points": 20
    }
   },
   "outputs": [],
   "source": [
    "def test_unit_adam_optimizer():\n",
    "    \"\"\"🔬 Test Adam optimizer implementation.\"\"\"\n",
    "    print(\"🔬 Unit Test: Adam Optimizer...\")\n",
    "\n",
    "    # Test basic Adam functionality\n",
    "    param = Tensor([1.0, 2.0], requires_grad=True)\n",
    "    param.grad = Tensor([0.1, 0.2])\n",
    "\n",
    "    optimizer = Adam([param], lr=0.01, betas=(0.9, 0.999), eps=1e-8)\n",
    "    original_data = param.data.copy()\n",
    "\n",
    "    # First step\n",
    "    optimizer.step()\n",
    "\n",
    "    # Manually compute expected values\n",
    "    grad = np.array([0.1, 0.2])\n",
    "\n",
    "    # First moment: m = 0.9 * 0 + 0.1 * grad = 0.1 * grad\n",
    "    m = 0.1 * grad\n",
    "\n",
    "    # Second moment: v = 0.999 * 0 + 0.001 * grad^2 = 0.001 * grad^2\n",
    "    v = 0.001 * (grad ** 2)\n",
    "\n",
    "    # Bias correction\n",
    "    bias_correction1 = 1 - 0.9 ** 1  # = 0.1\n",
    "    bias_correction2 = 1 - 0.999 ** 1  # = 0.001\n",
    "\n",
    "    m_hat = m / bias_correction1  # = grad\n",
    "    v_hat = v / bias_correction2  # = grad^2\n",
    "\n",
    "    # Update\n",
    "    expected = original_data - 0.01 * m_hat / (np.sqrt(v_hat) + 1e-8)\n",
    "\n",
    "    assert np.allclose(param.data, expected, rtol=1e-6)\n",
    "    assert optimizer.step_count == 1\n",
    "\n",
    "    # Test second step to verify moment accumulation\n",
    "    param.grad = Tensor([0.1, 0.2])\n",
    "    optimizer.step()\n",
    "\n",
    "    # Should have updated moments\n",
    "    assert optimizer.m_buffers[0] is not None\n",
    "    assert optimizer.v_buffers[0] is not None\n",
    "    assert optimizer.step_count == 2\n",
    "\n",
    "    # Test with weight decay\n",
    "    param2 = Tensor([1.0, 2.0], requires_grad=True)\n",
    "    param2.grad = Tensor([0.1, 0.2])\n",
    "\n",
    "    optimizer_wd = Adam([param2], lr=0.01, weight_decay=0.01)\n",
    "    optimizer_wd.step()\n",
    "\n",
    "    # Weight decay should modify the effective gradient\n",
    "    # grad_with_decay = [0.1, 0.2] + 0.01 * [1.0, 2.0] = [0.11, 0.22]\n",
    "    # The exact computation is complex, but we can verify parameter changed\n",
    "    assert not np.array_equal(param2.data, np.array([1.0, 2.0]))\n",
    "\n",
    "    print(\"✅ Adam optimizer works correctly!\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    test_unit_adam_optimizer()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dde08823",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## AdamW - Adam with Decoupled Weight Decay\n",
    "\n",
    "AdamW fixes a subtle but important bug in Adam's weight decay implementation. The bug affects how regularization interacts with adaptive learning rates.\n",
    "\n",
    "### The Adam Weight Decay Bug\n",
    "\n",
    "In standard Adam, weight decay is added to gradients before the adaptive scaling:\n",
    "\n",
    "```\n",
    "Adam's approach (problematic):\n",
    "1. gradient = computed_gradient + weight_decay * parameter\n",
    "2. m = β₁ * m + (1-β₁) * gradient\n",
    "3. v = β₂ * v + (1-β₂) * gradient²\n",
    "4. step = m / √v\n",
    "5. parameter = parameter - learning_rate * step\n",
    "\n",
    "Problem: Weight decay gets \"adapted\" by the learning rate scaling!\n",
    "```\n",
    "\n",
    "### Why This Matters\n",
    "\n",
    "Weight decay should be a consistent regularization force, but Adam makes it inconsistent:\n",
    "\n",
    "```\n",
    "Parameter Update Comparison:\n",
    "\n",
    "Large gradients → small adaptive LR → weak weight decay effect\n",
    "Small gradients → large adaptive LR → strong weight decay effect\n",
    "\n",
    "This is backwards! We want consistent regularization.\n",
    "```\n",
    "\n",
    "### AdamW's Fix: Decoupled Weight Decay\n",
    "\n",
    "AdamW separates gradient-based updates from weight decay:\n",
    "\n",
    "```\n",
    "AdamW's approach (correct):\n",
    "1. m = β₁ * m + (1-β₁) * pure_gradient  ← NO weight decay here\n",
    "2. v = β₂ * v + (1-β₂) * pure_gradient²\n",
    "3. step = m / √v\n",
    "4. parameter = parameter - learning_rate * step        ← gradient update\n",
    "5. parameter = parameter * (1 - weight_decay_rate)    ← separate decay\n",
    "\n",
    "Result: Consistent regularization independent of gradient magnitudes!\n",
    "```\n",
    "\n",
    "### Visual Comparison\n",
    "\n",
    "```\n",
    "Adam weight decay:               AdamW weight decay:\n",
    "\n",
    "gradient ──┐                    gradient ──→ adaptive ──→ param\n",
    "           ├─→ adaptive ──→ param                  update\n",
    "weight ────┘   scaling\n",
    "decay\n",
    "                                weight ─────────→ param\n",
    "                                decay           shrinkage\n",
    "\n",
    "Coupled (inconsistent)          Decoupled (consistent)\n",
    "```\n",
    "\n",
    "**Key Insight:** AdamW treats optimization and regularization as separate, independent processes, leading to better training dynamics and generalization."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3aa8bf4",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": false,
     "grade_id": "adamw-optimizer",
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "#| export\n",
    "class AdamW(Optimizer):\n",
    "    \"\"\"\n",
    "    AdamW optimizer with decoupled weight decay.\n",
    "\n",
    "    AdamW fixes a bug in Adam's weight decay implementation by decoupling\n",
    "    weight decay from the gradient-based update. This leads to better\n",
    "    regularization and is the preferred version for most applications.\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, params: List[Tensor], lr: float = 0.001, betas: tuple = (0.9, 0.999), eps: float = 1e-8, weight_decay: float = 0.01):\n",
    "        \"\"\"\n",
    "        Initialize AdamW optimizer.\n",
    "\n",
    "        TODO: Set up AdamW with decoupled weight decay\n",
    "\n",
    "        APPROACH:\n",
    "        1. Call parent constructor\n",
    "        2. Store hyperparameters (note higher default weight_decay)\n",
    "        3. Initialize moment buffers like Adam\n",
    "\n",
    "        KEY DIFFERENCE from Adam:\n",
    "        - Weight decay is applied directly to parameters, not added to gradients\n",
    "        - This provides better regularization behavior\n",
    "\n",
    "        EXAMPLE:\n",
    "        >>> optimizer = AdamW(model.parameters(), lr=0.001, weight_decay=0.01)\n",
    "        \"\"\"\n",
    "        ### BEGIN SOLUTION\n",
    "        super().__init__(params)\n",
    "\n",
    "        self.lr = lr\n",
    "        self.beta1, self.beta2 = betas\n",
    "        self.eps = eps\n",
    "        self.weight_decay = weight_decay\n",
    "\n",
    "        # Initialize moment buffers (same as Adam)\n",
    "        self.m_buffers = [None for _ in self.params]\n",
    "        self.v_buffers = [None for _ in self.params]\n",
    "        ### END SOLUTION\n",
    "\n",
    "    def step(self):\n",
    "        \"\"\"\n",
    "        Perform AdamW update step with decoupled weight decay.\n",
    "\n",
    "        TODO: Implement AdamW parameter update\n",
    "\n",
    "        APPROACH:\n",
    "        1. For each parameter with gradients:\n",
    "           a. Update moments using gradients (NOT modified by weight decay)\n",
    "           b. Compute bias-corrected moments\n",
    "           c. Apply gradient-based update\n",
    "           d. Apply weight decay directly to parameters\n",
    "\n",
    "        KEY DIFFERENCE from Adam:\n",
    "        - Weight decay: θ_t = θ_t - lr * weight_decay * θ_t (applied after gradient update)\n",
    "        - NOT: grad = grad + weight_decay * param (Adam's incorrect approach)\n",
    "\n",
    "        FORMULAS:\n",
    "        - Same moment updates as Adam (using unmodified gradients)\n",
    "        - Gradient update: θ_t = θ_{t-1} - lr * m̂_t / (√v̂_t + ε)\n",
    "        - Weight decay: θ_t = θ_t * (1 - lr * weight_decay)\n",
    "\n",
    "        HINT: Apply weight decay after gradient update for proper decoupling\n",
    "        \"\"\"\n",
    "        ### BEGIN SOLUTION\n",
    "        # Increment step counter first\n",
    "        self.step_count += 1\n",
    "\n",
    "        for i, param in enumerate(self.params):\n",
    "            if param.grad is None:\n",
    "                continue\n",
    "\n",
    "            # Get gradient (NOT modified by weight decay) - param.grad is already a numpy array\n",
    "            grad = param.grad\n",
    "\n",
    "            # Initialize buffers if needed\n",
    "            if self.m_buffers[i] is None:\n",
    "                self.m_buffers[i] = np.zeros_like(param.data)\n",
    "                self.v_buffers[i] = np.zeros_like(param.data)\n",
    "\n",
    "            # Update moments using pure gradients\n",
    "            self.m_buffers[i] = self.beta1 * self.m_buffers[i] + (1 - self.beta1) * grad\n",
    "            self.v_buffers[i] = self.beta2 * self.v_buffers[i] + (1 - self.beta2) * (grad ** 2)\n",
    "\n",
    "            # Compute bias correction\n",
    "            bias_correction1 = 1 - self.beta1 ** self.step_count\n",
    "            bias_correction2 = 1 - self.beta2 ** self.step_count\n",
    "\n",
    "            # Compute bias-corrected moments\n",
    "            m_hat = self.m_buffers[i] / bias_correction1\n",
    "            v_hat = self.v_buffers[i] / bias_correction2\n",
    "\n",
    "            # Apply gradient-based update\n",
    "            param.data = param.data - self.lr * m_hat / (np.sqrt(v_hat) + self.eps)\n",
    "\n",
    "            # Apply decoupled weight decay\n",
    "            if self.weight_decay != 0:\n",
    "                param.data = param.data * (1 - self.lr * self.weight_decay)\n",
    "        ### END SOLUTION"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d2f82434",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### 🔬 Unit Test: AdamW Optimizer\n",
    "This test validates our AdamW implementation with decoupled weight decay.\n",
    "**What we're testing**: AdamW updates with proper weight decay decoupling\n",
    "**Why it matters**: State-of-the-art optimizer for transformer models\n",
    "**Expected**: Correct separation of gradient updates and weight decay"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b5ef1de5",
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "test-adamw",
     "locked": true,
     "points": 20
    }
   },
   "outputs": [],
   "source": [
    "def test_unit_adamw_optimizer():\n",
    "    \"\"\"🔬 Test AdamW optimizer implementation.\"\"\"\n",
    "    print(\"🔬 Unit Test: AdamW Optimizer...\")\n",
    "\n",
    "    # Test AdamW vs Adam difference in weight decay\n",
    "    # Create identical parameters for comparison\n",
    "    param_adam = Tensor([1.0, 2.0], requires_grad=True)\n",
    "    param_adamw = Tensor([1.0, 2.0], requires_grad=True)\n",
    "\n",
    "    param_adam.grad = Tensor([0.1, 0.2])\n",
    "    param_adamw.grad = Tensor([0.1, 0.2])\n",
    "\n",
    "    # Create optimizers with same settings\n",
    "    adam = Adam([param_adam], lr=0.01, weight_decay=0.01)\n",
    "    adamw = AdamW([param_adamw], lr=0.01, weight_decay=0.01)\n",
    "\n",
    "    # Take one step\n",
    "    adam.step()\n",
    "    adamw.step()\n",
    "\n",
    "    # Results should be different due to weight decay implementation\n",
    "    assert not np.allclose(param_adam.data, param_adamw.data, rtol=1e-6)\n",
    "\n",
    "    # Test AdamW basic functionality\n",
    "    param = Tensor([1.0, 2.0], requires_grad=True)\n",
    "    param.grad = Tensor([0.1, 0.2])\n",
    "\n",
    "    optimizer = AdamW([param], lr=0.01, weight_decay=0.01)\n",
    "    original_data = param.data.copy()\n",
    "\n",
    "    optimizer.step()\n",
    "\n",
    "    # Parameter should have changed\n",
    "    assert not np.array_equal(param.data, original_data)\n",
    "    assert optimizer.step_count == 1\n",
    "\n",
    "    # Test that moment buffers are created\n",
    "    assert optimizer.m_buffers[0] is not None\n",
    "    assert optimizer.v_buffers[0] is not None\n",
    "\n",
    "    # Test zero weight decay behaves like Adam\n",
    "    param1 = Tensor([1.0, 2.0], requires_grad=True)\n",
    "    param2 = Tensor([1.0, 2.0], requires_grad=True)\n",
    "\n",
    "    param1.grad = Tensor([0.1, 0.2])\n",
    "    param2.grad = Tensor([0.1, 0.2])\n",
    "\n",
    "    adam_no_wd = Adam([param1], lr=0.01, weight_decay=0.0)\n",
    "    adamw_no_wd = AdamW([param2], lr=0.01, weight_decay=0.0)\n",
    "\n",
    "    adam_no_wd.step()\n",
    "    adamw_no_wd.step()\n",
    "\n",
    "    # Should be very similar (within numerical precision)\n",
    "    assert np.allclose(param1.data, param2.data, rtol=1e-10)\n",
    "\n",
    "    print(\"✅ AdamW optimizer works correctly!\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    test_unit_adamw_optimizer()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bcdba1b2",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 2
   },
   "source": [
    "## 4. Integration: Bringing It Together\n",
    "\n",
    "Now let's see how our optimizers perform in realistic scenarios. We'll compare their behavior on the same optimization problem to understand their different characteristics.\n",
    "\n",
    "### Optimizer Behavior Comparison\n",
    "\n",
    "Each optimizer takes a different approach to the same problem:\n",
    "\n",
    "```\n",
    "Optimization Problem: Find minimum of f(x) = x²\n",
    "\n",
    "SGD approach:        Adam approach:        AdamW approach:\n",
    "  ↓                    ↓                     ↓\n",
    " x ──→ minimize       x ──→ minimize       x ──→ minimize\n",
    "  ↑                    ↑                     ↑\n",
    "fixed LR           adaptive LR          adaptive LR + decay\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c76b7c1b",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## 5. Systems Analysis: Optimizer Performance and Memory\n",
    "\n",
    "Different optimizers have very different resource requirements. Understanding these trade-offs is crucial for production ML systems.\n",
    "\n",
    "### Memory Usage Patterns\n",
    "\n",
    "```\n",
    "Optimizer Memory Requirements (per parameter):\n",
    "\n",
    "SGD:           Adam/AdamW:\n",
    "┌────────┐     ┌────────┐\n",
    "│ param  │     │ param  │\n",
    "├────────┤     ├────────┤\n",
    "│momentum│     │   m    │ ← first moment\n",
    "└────────┘     ├────────┤\n",
    "               │   v    │ ← second moment\n",
    "               └────────┘\n",
    "\n",
    "2× memory       3× memory\n",
    "```\n",
    "\n",
    "### Computational Complexity\n",
    "\n",
    "```\n",
    "Per-step Operations:\n",
    "\n",
    "SGD:                     Adam:\n",
    "• 1 multiplication       • 3 multiplications\n",
    "• 1 addition            • 4 additions\n",
    "• 1 subtraction         • 1 subtraction\n",
    "                        • 1 square root\n",
    "                        • 1 division\n",
    "\n",
    "O(n) simple ops         O(n) complex ops\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c150b80f",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": false,
     "grade_id": "optimizer-analysis",
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "def analyze_optimizer_memory_usage():\n",
    "    \"\"\"📊 Analyze memory usage of different optimizers.\"\"\"\n",
    "    print(\"📊 Analyzing Optimizer Memory Usage...\")\n",
    "\n",
    "    # Create test parameters of different sizes\n",
    "    param_sizes = [1000, 10000, 100000]  # 1K, 10K, 100K parameters\n",
    "\n",
    "    print(\"Optimizer Memory Analysis (per parameter tensor):\")\n",
    "    print(\"=\" * 60)\n",
    "    print(f\"{'Size':<10} {'SGD':<10} {'Adam':<10} {'AdamW':<10} {'Ratio':<10}\")\n",
    "    print(\"-\" * 60)\n",
    "\n",
    "    for size in param_sizes:\n",
    "        # Create parameter\n",
    "        param = Tensor(np.random.randn(size), requires_grad=True)\n",
    "        param.grad = Tensor(np.random.randn(size))\n",
    "\n",
    "        # SGD memory (parameter + momentum buffer)\n",
    "        sgd = SGD([param], momentum=0.9)\n",
    "        sgd.step()  # Initialize buffers\n",
    "        sgd_memory = size * 2  # param + momentum buffer\n",
    "\n",
    "        # Adam memory (parameter + 2 moment buffers)\n",
    "        param_adam = Tensor(np.random.randn(size), requires_grad=True)\n",
    "        param_adam.grad = Tensor(np.random.randn(size))\n",
    "        adam = Adam([param_adam])\n",
    "        adam.step()  # Initialize buffers\n",
    "        adam_memory = size * 3  # param + m_buffer + v_buffer\n",
    "\n",
    "        # AdamW memory (same as Adam)\n",
    "        adamw_memory = adam_memory\n",
    "\n",
    "        # Memory ratio (Adam/SGD)\n",
    "        ratio = adam_memory / sgd_memory\n",
    "\n",
    "        print(f\"{size:<10} {sgd_memory:<10} {adam_memory:<10} {adamw_memory:<10} {ratio:.1f}x\")\n",
    "\n",
    "    print(\"\\n💡 Key Insights:\")\n",
    "    print(\"- SGD: 2× parameter memory (momentum buffer)\")\n",
    "    print(\"- Adam/AdamW: 3× parameter memory (two moment buffers)\")\n",
    "    print(\"- Memory scales linearly with model size\")\n",
    "    print(\"- Trade-off: More memory for better convergence\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "535b5b00",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": false,
     "grade_id": "optimizer-convergence",
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "def analyze_optimizer_convergence_behavior():\n",
    "    \"\"\"📊 Analyze convergence behavior of different optimizers.\"\"\"\n",
    "    print(\"📊 Analyzing Optimizer Convergence Behavior...\")\n",
    "\n",
    "    # Simulate optimization of a quadratic function: f(x) = 0.5 * x^2\n",
    "    # Optimal solution: x* = 0, gradient = x\n",
    "\n",
    "    def quadratic_loss(x):\n",
    "        \"\"\"Simple quadratic function for optimization testing.\"\"\"\n",
    "        return 0.5 * (x ** 2).sum()\n",
    "\n",
    "    def compute_gradient(x):\n",
    "        \"\"\"Gradient of quadratic function: df/dx = x.\"\"\"\n",
    "        return x.copy()\n",
    "\n",
    "    # Starting point\n",
    "    x_start = np.array([5.0, -3.0, 2.0])  # Far from optimum [0, 0, 0]\n",
    "\n",
    "    # Test different optimizers\n",
    "    optimizers_to_test = [\n",
    "        (\"SGD\", SGD, {\"lr\": 0.1}),\n",
    "        (\"SGD+Momentum\", SGD, {\"lr\": 0.1, \"momentum\": 0.9}),\n",
    "        (\"Adam\", Adam, {\"lr\": 0.1}),\n",
    "        (\"AdamW\", AdamW, {\"lr\": 0.1, \"weight_decay\": 0.01})\n",
    "    ]\n",
    "\n",
    "    print(\"Convergence Analysis (quadratic function f(x) = 0.5 * x²):\")\n",
    "    print(\"=\" * 70)\n",
    "    print(f\"{'Optimizer':<15} {'Step 0':<12} {'Step 5':<12} {'Step 10':<12} {'Final Loss':<12}\")\n",
    "    print(\"-\" * 70)\n",
    "\n",
    "    for name, optimizer_class, kwargs in optimizers_to_test:\n",
    "        # Reset parameter\n",
    "        param = Tensor(x_start.copy(), requires_grad=True)\n",
    "        optimizer = optimizer_class([param], **kwargs)\n",
    "\n",
    "        losses = []\n",
    "\n",
    "        # Run optimization for 10 steps\n",
    "        for step in range(11):\n",
    "            # Compute loss and gradient\n",
    "            loss = quadratic_loss(param.data)\n",
    "            param.grad = Tensor(compute_gradient(param.data))\n",
    "\n",
    "            losses.append(loss)\n",
    "\n",
    "            # Update parameters\n",
    "            if step < 10:  # Don't update after last evaluation\n",
    "                optimizer.step()\n",
    "                optimizer.zero_grad()\n",
    "\n",
    "        # Format results\n",
    "        step0 = f\"{losses[0]:.6f}\"\n",
    "        step5 = f\"{losses[5]:.6f}\"\n",
    "        step10 = f\"{losses[10]:.6f}\"\n",
    "        final = f\"{losses[10]:.6f}\"\n",
    "\n",
    "        print(f\"{name:<15} {step0:<12} {step5:<12} {step10:<12} {final:<12}\")\n",
    "\n",
    "    print(\"\\n💡 Key Insights:\")\n",
    "    print(\"- SGD: Steady progress but can be slow\")\n",
    "    print(\"- SGD+Momentum: Faster convergence, less oscillation\")\n",
    "    print(\"- Adam: Adaptive rates help with different parameter scales\")\n",
    "    print(\"- AdamW: Similar to Adam with regularization effects\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "29bc4e50",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "source": [
    "\"\"\"\n",
    "# 🧪 Module Integration Test\n",
    "\n",
    "Final validation that everything works together correctly.\n",
    "\"\"\"\n",
    "\n",
    "def import_previous_module(module_name: str, component_name: str):\n",
    "    import sys\n",
    "    import os\n",
    "    sys.path.append(os.path.join(os.path.dirname(__file__), '..', module_name))\n",
    "    module = __import__(f\"{module_name.split('_')[1]}_dev\")\n",
    "    return getattr(module, component_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b7a7d1cf",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": true,
     "grade_id": "module-integration",
     "locked": true,
     "points": 25
    }
   },
   "outputs": [],
   "source": [
    "def test_module():\n",
    "    \"\"\"\n",
    "    Comprehensive test of entire module functionality.\n",
    "\n",
    "    This final test runs before module summary to ensure:\n",
    "    - All unit tests pass\n",
    "    - Functions work together correctly\n",
    "    - Module is ready for integration with TinyTorch\n",
    "    \"\"\"\n",
    "    print(\"🧪 RUNNING MODULE INTEGRATION TEST\")\n",
    "    print(\"=\" * 50)\n",
    "\n",
    "    # Run all unit tests\n",
    "    print(\"Running unit tests...\")\n",
    "    test_unit_optimizer_base()\n",
    "    test_unit_sgd_optimizer()\n",
    "    test_unit_adam_optimizer()\n",
    "    test_unit_adamw_optimizer()\n",
    "\n",
    "    print(\"\\nRunning integration scenarios...\")\n",
    "\n",
    "    # Test realistic neural network optimization scenario\n",
    "    print(\"🔬 Integration Test: Multi-layer Network Optimization...\")\n",
    "\n",
    "    # Import components from previous modules using standardized helper\n",
    "    Tensor = import_previous_module('01_tensor', 'Tensor')\n",
    "    Linear = import_previous_module('03_layers', 'Linear')\n",
    "    ReLU = import_previous_module('02_activations', 'ReLU')\n",
    "    MSELoss = import_previous_module('04_losses', 'MSELoss')\n",
    "\n",
    "    # Create parameters for a 2-layer network\n",
    "    # Layer 1: 3 inputs -> 4 hidden\n",
    "    W1 = Tensor(np.random.randn(3, 4) * 0.1, requires_grad=True)\n",
    "    b1 = Tensor(np.zeros(4), requires_grad=True)\n",
    "\n",
    "    # Layer 2: 4 hidden -> 2 outputs\n",
    "    W2 = Tensor(np.random.randn(4, 2) * 0.1, requires_grad=True)\n",
    "    b2 = Tensor(np.zeros(2), requires_grad=True)\n",
    "\n",
    "    params = [W1, b1, W2, b2]\n",
    "\n",
    "    # Add realistic gradients\n",
    "    W1.grad = Tensor(np.random.randn(3, 4) * 0.01)\n",
    "    b1.grad = Tensor(np.random.randn(4) * 0.01)\n",
    "    W2.grad = Tensor(np.random.randn(4, 2) * 0.01)\n",
    "    b2.grad = Tensor(np.random.randn(2) * 0.01)\n",
    "\n",
    "    # Test all optimizers on same network\n",
    "    optimizers = [\n",
    "        SGD(params, lr=0.01, momentum=0.9),\n",
    "        Adam([p for p in params], lr=0.001),  # Fresh param list for Adam\n",
    "        AdamW([p for p in params], lr=0.001, weight_decay=0.01)  # Fresh param list for AdamW\n",
    "    ]\n",
    "\n",
    "    # Save original parameter values\n",
    "    original_params = [p.data.copy() for p in params]\n",
    "\n",
    "    # Test SGD\n",
    "    optimizers[0].step()\n",
    "    sgd_params = [p.data.copy() for p in params]\n",
    "\n",
    "    # Restore parameters and test Adam\n",
    "    for i, p in enumerate(params):\n",
    "        p.data = original_params[i].copy()\n",
    "        # Re-add gradients since they may have been modified\n",
    "        if i == 0:\n",
    "            p.grad = Tensor(np.random.randn(3, 4) * 0.01)\n",
    "        elif i == 1:\n",
    "            p.grad = Tensor(np.random.randn(4) * 0.01)\n",
    "        elif i == 2:\n",
    "            p.grad = Tensor(np.random.randn(4, 2) * 0.01)\n",
    "        else:\n",
    "            p.grad = Tensor(np.random.randn(2) * 0.01)\n",
    "\n",
    "    # Update parameter references for Adam\n",
    "    optimizers[1].params = params\n",
    "    optimizers[1].step()\n",
    "    adam_params = [p.data.copy() for p in params]\n",
    "\n",
    "    # Restore parameters and test AdamW\n",
    "    for i, p in enumerate(params):\n",
    "        p.data = original_params[i].copy()\n",
    "        # Re-add gradients\n",
    "        if i == 0:\n",
    "            p.grad = Tensor(np.random.randn(3, 4) * 0.01)\n",
    "        elif i == 1:\n",
    "            p.grad = Tensor(np.random.randn(4) * 0.01)\n",
    "        elif i == 2:\n",
    "            p.grad = Tensor(np.random.randn(4, 2) * 0.01)\n",
    "        else:\n",
    "            p.grad = Tensor(np.random.randn(2) * 0.01)\n",
    "\n",
    "    # Update parameter references for AdamW\n",
    "    optimizers[2].params = params\n",
    "    optimizers[2].step()\n",
    "    adamw_params = [p.data.copy() for p in params]\n",
    "\n",
    "    # Verify parameters changed differently for each optimizer\n",
    "    for i in range(len(params)):\n",
    "        # Parameters should be different from original\n",
    "        assert not np.array_equal(sgd_params[i], original_params[i])\n",
    "        assert not np.array_equal(adam_params[i], original_params[i])\n",
    "        assert not np.array_equal(adamw_params[i], original_params[i])\n",
    "\n",
    "        # Different optimizers should produce different results\n",
    "        assert not np.allclose(sgd_params[i], adam_params[i], rtol=1e-6)\n",
    "\n",
    "    print(\"✅ Multi-layer network optimization works!\")\n",
    "\n",
    "    # Test optimizer state management\n",
    "    print(\"🔬 Integration Test: Optimizer State Management...\")\n",
    "\n",
    "    param = Tensor([1.0, 2.0], requires_grad=True)\n",
    "    param.grad = Tensor([0.1, 0.2])\n",
    "\n",
    "    optimizer = Adam([param], lr=0.001)\n",
    "\n",
    "    # First step should initialize buffers\n",
    "    optimizer.step()\n",
    "    assert optimizer.m_buffers[0] is not None\n",
    "    assert optimizer.v_buffers[0] is not None\n",
    "    assert optimizer.step_count == 1\n",
    "\n",
    "    # Zero grad should clear gradients but preserve optimizer state\n",
    "    optimizer.zero_grad()\n",
    "    assert param.grad is None\n",
    "    assert optimizer.m_buffers[0] is not None  # State preserved\n",
    "    assert optimizer.step_count == 1  # Step count preserved\n",
    "\n",
    "    print(\"✅ Optimizer state management works!\")\n",
    "\n",
    "    print(\"\\n\" + \"=\" * 50)\n",
    "    print(\"🎉 ALL TESTS PASSED! Module ready for export.\")\n",
    "    print(\"Run: tito module complete 06_optimizers\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5311ee9b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Run comprehensive module test\n",
    "if __name__ == \"__main__\":\n",
    "    test_module()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cff0d2d5",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "## 🎯 MODULE SUMMARY: Optimizers\n",
    "\n",
    "Congratulations! You've built sophisticated optimization algorithms that power modern neural network training!\n",
    "\n",
    "### Key Accomplishments\n",
    "- Built SGD optimizer with momentum for stable gradient descent and oscillation reduction\n",
    "- Implemented Adam optimizer with adaptive learning rates and bias correction for different parameter scales\n",
    "- Created AdamW optimizer with decoupled weight decay for proper regularization\n",
    "- Analyzed memory trade-offs: SGD (2×), Adam/AdamW (3× parameter memory)\n",
    "- All tests pass ✅ (validated by `test_module()`)\n",
    "\n",
    "### Ready for Next Steps\n",
    "Your optimizer implementations enable sophisticated neural network training! With gradients from Module 05 and optimizers from Module 06, you're ready to build complete training loops.\n",
    "\n",
    "Export with: `tito module complete 06_optimizers`\n",
    "\n",
    "**Next**: Module 07 will add training loops, learning rate scheduling, and checkpointing for complete end-to-end neural network training!"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
