{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d078c382",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "# Module 07: Training - Complete Learning Loops\n",
    "\n",
    "Welcome to Module 07! You're about to build the complete training infrastructure that brings neural networks to life through end-to-end learning.\n",
    "\n",
    "## 🔗 Prerequisites & Progress\n",
    "**You've Built**: Tensors, activations, layers, losses, gradients, and optimizers\n",
    "**You'll Build**: Complete training loops with checkpointing, scheduling, and gradient management\n",
    "**You'll Enable**: Full model training pipeline for the MLP milestone\n",
    "\n",
    "**Connection Map**:\n",
    "```\n",
    "Optimizers (Module 06) → Training (Module 07) → DataLoader (Module 08)\n",
    "(parameter updates)     (complete loops)      (efficient batching)\n",
    "```\n",
    "\n",
    "## Learning Objectives\n",
    "By the end of this module, you will:\n",
    "1. Implement a complete Trainer class with train/eval modes\n",
    "2. Build learning rate scheduling and gradient clipping\n",
    "3. Create checkpointing for model persistence\n",
    "4. Test training loops with immediate validation\n",
    "5. Understand gradient accumulation patterns\n",
    "\n",
    "Let's get started!\n",
    "\n",
    "## 📦 Where This Code Lives in the Final Package\n",
    "\n",
    "**Learning Side:** You work in `modules/07_training/training_dev.py`  \n",
    "**Building Side:** Code exports to `tinytorch.core.training`\n",
    "\n",
    "```python\n",
    "# How to use this module:\n",
    "from tinytorch.core.training import Trainer, CosineSchedule, clip_grad_norm\n",
    "```\n",
    "\n",
    "**Why this matters:**\n",
    "- **Learning:** Complete training system in one focused module for deep understanding\n",
    "- **Production:** Proper organization like PyTorch's training infrastructure with all training components together\n",
    "- **Consistency:** All training operations and scheduling functionality in core.training\n",
    "- **Integration:** Works seamlessly with optimizers and losses for complete learning pipelines"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "713e3bbb",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "imports",
     "locked": false,
     "solution": false
    }
   },
   "outputs": [],
   "source": [
    "#| default_exp core.training\n",
    "#| export\n",
    "\n",
    "import numpy as np\n",
    "import pickle\n",
    "import time\n",
    "from typing import Dict, List, Optional, Tuple, Any, Callable\n",
    "from pathlib import Path\n",
    "import sys\n",
    "import os\n",
    "\n",
    "# Import dependencies from other modules\n",
    "from tinytorch.core.tensor import Tensor\n",
    "from tinytorch.core.layers import Linear\n",
    "from tinytorch.core.losses import MSELoss, CrossEntropyLoss\n",
    "from tinytorch.core.optimizers import SGD, AdamW"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "afb387c8",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "## 🏗️ Part 1: Introduction - What is Training?\n",
    "\n",
    "Training is where the magic happens - it's the process that transforms a randomly initialized neural network into an intelligent system that can solve problems. Think of training as teaching: you show the model examples, it makes predictions, you measure how wrong it is, and then you adjust its parameters to do better next time.\n",
    "\n",
    "The training process follows a consistent pattern across all machine learning:\n",
    "\n",
    "1. **Forward Pass**: Input flows through the model to produce predictions\n",
    "2. **Loss Calculation**: Compare predictions to true answers\n",
    "3. **Backward Pass**: Compute gradients showing how to improve\n",
    "4. **Parameter Update**: Adjust model weights using an optimizer\n",
    "5. **Repeat**: Continue until the model learns the pattern\n",
    "\n",
    "But production training systems need much more than this basic loop. They need learning rate scheduling (starting fast, slowing down), gradient clipping (preventing exploding gradients), checkpointing (saving progress), and evaluation modes (testing without learning).\n",
    "\n",
    "**What we're building today:**\n",
    "- A complete `Trainer` class that orchestrates the entire learning process\n",
    "- Learning rate scheduling that adapts during training\n",
    "- Gradient clipping that prevents training instability\n",
    "- Checkpointing system for saving and resuming training\n",
    "- Train/eval modes for proper model behavior"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d729d7c",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "## 📐 Part 2: Foundations - Mathematical Background\n",
    "\n",
    "### Training Loop Mathematics\n",
    "\n",
    "The core training loop implements gradient descent with sophisticated improvements:\n",
    "\n",
    "**Basic Update Rule:**\n",
    "```\n",
    "θ(t+1) = θ(t) - η ∇L(θ(t))\n",
    "```\n",
    "Where θ are parameters, η is learning rate, and ∇L is the loss gradient.\n",
    "\n",
    "**Learning Rate Scheduling:**\n",
    "For cosine annealing over T epochs:\n",
    "```\n",
    "η(t) = η_min + (η_max - η_min) * (1 + cos(πt/T)) / 2\n",
    "```\n",
    "\n",
    "**Gradient Clipping:**\n",
    "When ||∇L|| > max_norm, rescale:\n",
    "```\n",
    "∇L ← ∇L * max_norm / ||∇L||\n",
    "```\n",
    "\n",
    "**Gradient Accumulation:**\n",
    "For effective batch size B_eff = accumulation_steps * B_actual:\n",
    "```\n",
    "∇L_accumulated = (1/accumulation_steps) * Σ ∇L_batch_i\n",
    "```\n",
    "\n",
    "### Train vs Eval Modes\n",
    "\n",
    "Many layers behave differently during training vs inference:\n",
    "- **Dropout**: Active during training, disabled during evaluation\n",
    "- **BatchNorm**: Updates statistics during training, uses fixed statistics during evaluation\n",
    "- **Gradient computation**: Enabled during training, disabled during evaluation for efficiency\n",
    "\n",
    "This mode switching is crucial for proper model behavior and performance."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d7cf949",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "## 🏗️ Part 3: Implementation - Building Training Infrastructure\n",
    "\n",
    "Now let's implement the complete training system. We'll build each component step by step: learning rate scheduling, gradient utilities, and finally the complete Trainer class.\n",
    "\n",
    "Each component will follow the pattern: **Explanation → Implementation → Test** so you understand what you're building before you build it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1adf013b",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### Learning Rate Scheduling - Adaptive Training Speed\n",
    "\n",
    "Learning rate scheduling is like adjusting your driving speed based on road conditions. You start fast on the highway (high learning rate for quick progress), then slow down in neighborhoods (low learning rate for fine-tuning).\n",
    "\n",
    "#### Why Cosine Scheduling Works\n",
    "\n",
    "Cosine annealing follows a smooth curve that provides:\n",
    "- **Aggressive learning initially** - Fast convergence when far from optimum\n",
    "- **Gradual slowdown** - Stable convergence as you approach the solution\n",
    "- **Smooth transitions** - No sudden learning rate drops that shock the model\n",
    "\n",
    "#### The Mathematics\n",
    "\n",
    "Cosine annealing uses the cosine function to smoothly transition from max_lr to min_lr:\n",
    "\n",
    "```\n",
    "Learning Rate Schedule:\n",
    "\n",
    "max_lr ┌─\\\n",
    "       │   \\\n",
    "       │     \\\n",
    "       │       \\\n",
    "       │         \\\n",
    "min_lr └───────────\\────────\n",
    "       0    25    50   75  100 epochs\n",
    "\n",
    "Formula: lr = min_lr + (max_lr - min_lr) * (1 + cos(π * epoch / total_epochs)) / 2\n",
    "```\n",
    "\n",
    "This creates a natural learning curve that adapts training speed to the optimization landscape."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "662af4ef",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": false,
     "grade_id": "scheduler",
     "locked": false,
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "#| export\n",
    "class CosineSchedule:\n",
    "    \"\"\"\n",
    "    Cosine annealing learning rate schedule.\n",
    "\n",
    "    Starts at max_lr, decreases following a cosine curve to min_lr over T epochs.\n",
    "    This provides aggressive learning initially, then fine-tuning at the end.\n",
    "\n",
    "    TODO: Implement cosine annealing schedule\n",
    "\n",
    "    APPROACH:\n",
    "    1. Store max_lr, min_lr, and total_epochs\n",
    "    2. In get_lr(), compute cosine factor: (1 + cos(π * epoch / total_epochs)) / 2\n",
    "    3. Interpolate: min_lr + (max_lr - min_lr) * cosine_factor\n",
    "\n",
    "    EXAMPLE:\n",
    "    >>> schedule = CosineSchedule(max_lr=0.1, min_lr=0.01, total_epochs=100)\n",
    "    >>> print(schedule.get_lr(0))    # Start: 0.1\n",
    "    >>> print(schedule.get_lr(50))   # Middle: ~0.055\n",
    "    >>> print(schedule.get_lr(100))  # End: 0.01\n",
    "\n",
    "    HINT: Use np.cos() and np.pi for the cosine calculation\n",
    "    \"\"\"\n",
    "    ### BEGIN SOLUTION\n",
    "    def __init__(self, max_lr: float = 0.1, min_lr: float = 0.01, total_epochs: int = 100):\n",
    "        self.max_lr = max_lr\n",
    "        self.min_lr = min_lr\n",
    "        self.total_epochs = total_epochs\n",
    "\n",
    "    def get_lr(self, epoch: int) -> float:\n",
    "        \"\"\"Get learning rate for current epoch.\"\"\"\n",
    "        if epoch >= self.total_epochs:\n",
    "            return self.min_lr\n",
    "\n",
    "        # Cosine annealing formula\n",
    "        cosine_factor = (1 + np.cos(np.pi * epoch / self.total_epochs)) / 2\n",
    "        return self.min_lr + (self.max_lr - self.min_lr) * cosine_factor\n",
    "    ### END SOLUTION"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ed62b32b",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### 🧪 Unit Test: CosineSchedule\n",
    "This test validates our learning rate scheduling implementation.\n",
    "**What we're testing**: Cosine annealing produces correct learning rates\n",
    "**Why it matters**: Proper scheduling often makes the difference between convergence and failure\n",
    "**Expected**: Smooth decrease from max_lr to min_lr following cosine curve"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "66ac37f2",
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "test_scheduler",
     "locked": true,
     "points": 10
    }
   },
   "outputs": [],
   "source": [
    "def test_unit_cosine_schedule():\n",
    "    \"\"\"🔬 Test CosineSchedule implementation.\"\"\"\n",
    "    print(\"🔬 Unit Test: CosineSchedule...\")\n",
    "\n",
    "    # Test basic schedule\n",
    "    schedule = CosineSchedule(max_lr=0.1, min_lr=0.01, total_epochs=100)\n",
    "\n",
    "    # Test start, middle, and end\n",
    "    lr_start = schedule.get_lr(0)\n",
    "    lr_middle = schedule.get_lr(50)\n",
    "    lr_end = schedule.get_lr(100)\n",
    "\n",
    "    print(f\"Learning rate at epoch 0: {lr_start:.4f}\")\n",
    "    print(f\"Learning rate at epoch 50: {lr_middle:.4f}\")\n",
    "    print(f\"Learning rate at epoch 100: {lr_end:.4f}\")\n",
    "\n",
    "    # Validate behavior\n",
    "    assert abs(lr_start - 0.1) < 1e-6, f\"Expected 0.1 at start, got {lr_start}\"\n",
    "    assert abs(lr_end - 0.01) < 1e-6, f\"Expected 0.01 at end, got {lr_end}\"\n",
    "    assert 0.01 < lr_middle < 0.1, f\"Middle LR should be between min and max, got {lr_middle}\"\n",
    "\n",
    "    # Test monotonic decrease in first half\n",
    "    lr_quarter = schedule.get_lr(25)\n",
    "    assert lr_quarter > lr_middle, \"LR should decrease monotonically in first half\"\n",
    "\n",
    "    print(\"✅ CosineSchedule works correctly!\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    test_unit_cosine_schedule()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "699b4fd0",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### Gradient Clipping - Preventing Training Explosions\n",
    "\n",
    "Gradient clipping is like having a speed governor on your car - it prevents dangerous situations where gradients become so large they destroy training progress.\n",
    "\n",
    "#### The Problem: Exploding Gradients\n",
    "\n",
    "During training, gradients can sometimes become extremely large, causing:\n",
    "- **Parameter updates that are too big** - Model jumps far from the optimal solution\n",
    "- **Numerical instability** - Values become NaN or infinite\n",
    "- **Training collapse** - Model performance suddenly degrades\n",
    "\n",
    "#### The Solution: Global Norm Clipping\n",
    "\n",
    "Instead of clipping each gradient individually, we compute the global norm across all parameters and scale uniformly:\n",
    "\n",
    "```\n",
    "Gradient Clipping Process:\n",
    "\n",
    "1. Compute Global Norm:\n",
    "   total_norm = √(sum of all gradient squares)\n",
    "\n",
    "2. Check if Clipping Needed:\n",
    "   if total_norm > max_norm:\n",
    "       clip_coefficient = max_norm / total_norm\n",
    "\n",
    "3. Scale All Gradients:\n",
    "   for each gradient:\n",
    "       gradient *= clip_coefficient\n",
    "\n",
    "Visualization:\n",
    "Original Gradients:  [100, 200, 50] → norm = 230\n",
    "With max_norm=1.0:   [0.43, 0.87, 0.22] → norm = 1.0\n",
    "```\n",
    "\n",
    "This preserves the relative magnitudes while preventing explosion."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c29122b4",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": false,
     "grade_id": "gradient_clipping",
     "locked": false,
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "def clip_grad_norm(parameters: List, max_norm: float = 1.0) -> float:\n",
    "    \"\"\"\n",
    "    Clip gradients by global norm to prevent exploding gradients.\n",
    "\n",
    "    This is crucial for training stability, especially with RNNs and deep networks.\n",
    "    Instead of clipping each gradient individually, we compute the global norm\n",
    "    across all parameters and scale uniformly if needed.\n",
    "\n",
    "    TODO: Implement gradient clipping by global norm\n",
    "\n",
    "    APPROACH:\n",
    "    1. Compute total norm: sqrt(sum of squared gradients across all parameters)\n",
    "    2. If total_norm > max_norm, compute clip_coef = max_norm / total_norm\n",
    "    3. Scale all gradients by clip_coef: grad *= clip_coef\n",
    "    4. Return the original norm for monitoring\n",
    "\n",
    "    EXAMPLE:\n",
    "    >>> params = [Tensor([1, 2, 3], requires_grad=True)]\n",
    "    >>> params[0].grad = Tensor([10, 20, 30])  # Large gradients\n",
    "    >>> original_norm = clip_grad_norm(params, max_norm=1.0)\n",
    "    >>> print(f\"Clipped norm: {np.linalg.norm(params[0].grad.data):.2f}\")  # Should be ≤ 1.0\n",
    "\n",
    "    HINTS:\n",
    "    - Use np.linalg.norm() to compute norms\n",
    "    - Only clip if total_norm > max_norm\n",
    "    - Modify gradients in-place for efficiency\n",
    "    \"\"\"\n",
    "    ### BEGIN SOLUTION\n",
    "    if not parameters:\n",
    "        return 0.0\n",
    "\n",
    "    # Collect all gradients and compute global norm\n",
    "    total_norm = 0.0\n",
    "    for param in parameters:\n",
    "        if hasattr(param, 'grad') and param.grad is not None:\n",
    "            # Handle both Tensor gradients and numpy array gradients\n",
    "            if isinstance(param.grad, np.ndarray):\n",
    "                grad_data = param.grad\n",
    "            elif hasattr(param.grad, 'data'):\n",
    "                grad_data = param.grad.data\n",
    "            else:\n",
    "                grad_data = np.array(param.grad)\n",
    "            total_norm += np.sum(grad_data ** 2)\n",
    "\n",
    "    total_norm = np.sqrt(total_norm)\n",
    "\n",
    "    # Clip if necessary\n",
    "    if total_norm > max_norm:\n",
    "        clip_coef = max_norm / total_norm\n",
    "        for param in parameters:\n",
    "            if hasattr(param, 'grad') and param.grad is not None:\n",
    "                # Handle both Tensor gradients and numpy array gradients\n",
    "                if isinstance(param.grad, np.ndarray):\n",
    "                    param.grad = param.grad * clip_coef\n",
    "                elif hasattr(param.grad, 'data'):\n",
    "                    param.grad.data = param.grad.data * clip_coef\n",
    "                else:\n",
    "                    param.grad = param.grad * clip_coef\n",
    "\n",
    "    return float(total_norm)\n",
    "    ### END SOLUTION"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ccdd0d37",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### 🧪 Unit Test: Gradient Clipping\n",
    "This test validates our gradient clipping implementation.\n",
    "**What we're testing**: Global norm clipping properly rescales large gradients\n",
    "**Why it matters**: Prevents exploding gradients that can destroy training\n",
    "**Expected**: Gradients scaled down when norm exceeds threshold"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd28d017",
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "test_clipping",
     "locked": true,
     "points": 10
    }
   },
   "outputs": [],
   "source": [
    "def test_unit_clip_grad_norm():\n",
    "    \"\"\"🔬 Test clip_grad_norm implementation.\"\"\"\n",
    "    print(\"🔬 Unit Test: Gradient Clipping...\")\n",
    "\n",
    "    # Use real Tensor from Module 01\n",
    "    import sys\n",
    "    # Tensor already imported at module level\n",
    "\n",
    "    # Test case 1: Large gradients that need clipping\n",
    "    param1 = Tensor([1.0, 2.0], requires_grad=True)\n",
    "    param1.grad = np.array([3.0, 4.0])  # norm = 5.0\n",
    "\n",
    "    param2 = Tensor([3.0, 4.0], requires_grad=True)\n",
    "    param2.grad = np.array([6.0, 8.0])  # norm = 10.0\n",
    "\n",
    "    params = [param1, param2]\n",
    "    # Total norm = sqrt(5² + 10²) = sqrt(125) ≈ 11.18\n",
    "\n",
    "    original_norm = clip_grad_norm(params, max_norm=1.0)\n",
    "\n",
    "    # Check original norm was large\n",
    "    assert original_norm > 1.0, f\"Original norm should be > 1.0, got {original_norm}\"\n",
    "\n",
    "    # Check gradients were clipped\n",
    "    new_norm = 0.0\n",
    "    for param in params:\n",
    "        if isinstance(param.grad, np.ndarray):\n",
    "            grad_data = param.grad\n",
    "        elif hasattr(param.grad, 'data'):\n",
    "            grad_data = param.grad.data\n",
    "        else:\n",
    "            grad_data = np.array(param.grad)\n",
    "        new_norm += np.sum(grad_data ** 2)\n",
    "    new_norm = np.sqrt(new_norm)\n",
    "\n",
    "    print(f\"Original norm: {original_norm:.2f}\")\n",
    "    print(f\"Clipped norm: {new_norm:.2f}\")\n",
    "\n",
    "    assert abs(new_norm - 1.0) < 1e-6, f\"Clipped norm should be 1.0, got {new_norm}\"\n",
    "\n",
    "    # Test case 2: Small gradients that don't need clipping\n",
    "    small_param = Tensor([1.0, 2.0], requires_grad=True)\n",
    "    small_param.grad = np.array([0.1, 0.2])\n",
    "    small_params = [small_param]\n",
    "    original_small = clip_grad_norm(small_params, max_norm=1.0)\n",
    "\n",
    "    assert original_small < 1.0, \"Small gradients shouldn't be clipped\"\n",
    "\n",
    "    print(\"✅ Gradient clipping works correctly!\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    test_unit_clip_grad_norm()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8519058a",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### Model Checkpointing - Saving Your Progress\n",
    "\n",
    "Checkpointing is like saving your progress in a video game - it lets you pause training, resume later, or share your trained model with others. Without checkpointing, you'd have to retrain from scratch every time!\n",
    "\n",
    "#### Why Checkpointing Matters\n",
    "\n",
    "Imagine training a large model for 10 hours, then your computer crashes. Without checkpoints, you lose everything. With checkpoints, you can:\n",
    "- **Resume training** after interruptions (power failure, crashes, etc.)\n",
    "- **Share models** with teammates or students\n",
    "- **Deploy models** to production systems\n",
    "- **Compare versions** to see which trained model works best\n",
    "- **Use pre-trained models** without waiting for training\n",
    "\n",
    "#### What Gets Saved\n",
    "\n",
    "A checkpoint is a dictionary containing everything needed to restore your model:\n",
    "```\n",
    "Checkpoint Dictionary:\n",
    "{\n",
    "    'model_params': [array1, array2, ...],  # All weight matrices\n",
    "    'config': {'layers': 2, 'dim': 32},     # Model architecture\n",
    "    'metadata': {'loss': 0.089, 'step': 5000}  # Training info\n",
    "}\n",
    "```\n",
    "\n",
    "Think of it as a complete snapshot of your model at a specific moment in time.\n",
    "\n",
    "#### Two Levels of Checkpointing\n",
    "\n",
    "1. **Low-level** (save_checkpoint/load_checkpoint): For custom training loops, just save what you need\n",
    "2. **High-level** (Trainer.save_checkpoint): Saves complete training state including optimizer and scheduler\n",
    "\n",
    "We'll implement both!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1b1d5b35",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": false,
     "grade_id": "save_checkpoint",
     "locked": false,
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "#| export\n",
    "def save_checkpoint(checkpoint_dict: Dict[str, Any], path: str):\n",
    "    \"\"\"\n",
    "    Save checkpoint dictionary to disk using pickle.\n",
    "    \n",
    "    This is a low-level utility for saving model state. Use this when you have\n",
    "    a custom training loop and want to save just what you need (model params,\n",
    "    config, metadata).\n",
    "    \n",
    "    For complete training state with optimizer and scheduler, use \n",
    "    Trainer.save_checkpoint() instead.\n",
    "    \n",
    "    TODO: Implement checkpoint saving with pickle\n",
    "    \n",
    "    APPROACH:\n",
    "    1. Create parent directory if it doesn't exist (Path(path).parent.mkdir)\n",
    "    2. Open file in binary write mode ('wb')\n",
    "    3. Use pickle.dump() to serialize the checkpoint dictionary\n",
    "    4. Print confirmation message\n",
    "    \n",
    "    EXAMPLE:\n",
    "    >>> model = SimpleModel()\n",
    "    >>> checkpoint = {\n",
    "    ...     'model_params': [p.data.copy() for p in model.parameters()],\n",
    "    ...     'config': {'embed_dim': 32, 'num_layers': 2},\n",
    "    ...     'metadata': {'final_loss': 0.089, 'training_steps': 5000}\n",
    "    ... }\n",
    "    >>> save_checkpoint(checkpoint, 'checkpoints/model.pkl')\n",
    "    ✓ Checkpoint saved: checkpoints/model.pkl\n",
    "    \n",
    "    HINTS:\n",
    "    - Use Path(path).parent.mkdir(parents=True, exist_ok=True)\n",
    "    - pickle.dump(obj, file) writes the object to file\n",
    "    - Always print a success message so users know it worked\n",
    "    \"\"\"\n",
    "    ### BEGIN SOLUTION\n",
    "    # Create parent directory if needed\n",
    "    Path(path).parent.mkdir(parents=True, exist_ok=True)\n",
    "    \n",
    "    # Save checkpoint using pickle\n",
    "    with open(path, 'wb') as f:\n",
    "        pickle.dump(checkpoint_dict, f)\n",
    "    \n",
    "    print(f\"✓ Checkpoint saved: {path}\")\n",
    "    ### END SOLUTION"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "48a4b962",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": false,
     "grade_id": "load_checkpoint",
     "locked": false,
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "#| export\n",
    "def load_checkpoint(path: str) -> Dict[str, Any]:\n",
    "    \"\"\"\n",
    "    Load checkpoint dictionary from disk using pickle.\n",
    "    \n",
    "    Companion function to save_checkpoint(). Restores the checkpoint dictionary\n",
    "    so you can rebuild your model, resume training, or inspect saved metadata.\n",
    "    \n",
    "    TODO: Implement checkpoint loading with pickle\n",
    "    \n",
    "    APPROACH:\n",
    "    1. Open file in binary read mode ('rb')\n",
    "    2. Use pickle.load() to deserialize the checkpoint\n",
    "    3. Print confirmation message\n",
    "    4. Return the loaded dictionary\n",
    "    \n",
    "    EXAMPLE:\n",
    "    >>> checkpoint = load_checkpoint('checkpoints/model.pkl')\n",
    "    ✓ Checkpoint loaded: checkpoints/model.pkl\n",
    "    >>> print(checkpoint['metadata']['final_loss'])\n",
    "    0.089\n",
    "    >>> model_params = checkpoint['model_params']\n",
    "    >>> # Now restore model: for param, data in zip(model.parameters(), model_params)...\n",
    "    \n",
    "    HINTS:\n",
    "    - pickle.load(file) reads and deserializes the object\n",
    "    - Return the loaded dictionary\n",
    "    - Print a success message for user feedback\n",
    "    \"\"\"\n",
    "    ### BEGIN SOLUTION\n",
    "    # Load checkpoint using pickle\n",
    "    with open(path, 'rb') as f:\n",
    "        checkpoint = pickle.load(f)\n",
    "    \n",
    "    print(f\"✓ Checkpoint loaded: {path}\")\n",
    "    return checkpoint\n",
    "    ### END SOLUTION"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f9b10115",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### 🧪 Unit Test: Checkpointing\n",
    "This test validates our checkpoint save/load implementation.\n",
    "**What we're testing**: Checkpoints can be saved and loaded correctly\n",
    "**Why it matters**: Broken checkpointing means lost training progress\n",
    "**Expected**: Saved data matches loaded data exactly"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e6066ed8",
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "test_checkpointing",
     "locked": true,
     "points": 10
    }
   },
   "outputs": [],
   "source": [
    "def test_unit_checkpointing():\n",
    "    \"\"\"🔬 Test save_checkpoint and load_checkpoint implementation.\"\"\"\n",
    "    print(\"🔬 Unit Test: Model Checkpointing...\")\n",
    "    \n",
    "    import tempfile\n",
    "    import os\n",
    "    \n",
    "    # Create a temporary checkpoint\n",
    "    test_checkpoint = {\n",
    "        'model_params': [np.array([1.0, 2.0, 3.0]), np.array([[4.0, 5.0], [6.0, 7.0]])],\n",
    "        'config': {'embed_dim': 32, 'num_layers': 2, 'num_heads': 8},\n",
    "        'metadata': {\n",
    "            'final_loss': 0.089,\n",
    "            'training_steps': 5000,\n",
    "            'timestamp': '2025-10-29',\n",
    "        }\n",
    "    }\n",
    "    \n",
    "    # Test save/load cycle\n",
    "    with tempfile.TemporaryDirectory() as tmpdir:\n",
    "        checkpoint_path = os.path.join(tmpdir, 'test_checkpoint.pkl')\n",
    "        \n",
    "        # Save checkpoint\n",
    "        save_checkpoint(test_checkpoint, checkpoint_path)\n",
    "        \n",
    "        # Verify file exists\n",
    "        assert os.path.exists(checkpoint_path), \"Checkpoint file should exist after saving\"\n",
    "        \n",
    "        # Load checkpoint\n",
    "        loaded_checkpoint = load_checkpoint(checkpoint_path)\n",
    "        \n",
    "        # Verify structure\n",
    "        assert 'model_params' in loaded_checkpoint, \"Checkpoint should have model_params\"\n",
    "        assert 'config' in loaded_checkpoint, \"Checkpoint should have config\"\n",
    "        assert 'metadata' in loaded_checkpoint, \"Checkpoint should have metadata\"\n",
    "        \n",
    "        # Verify data integrity\n",
    "        for orig_param, loaded_param in zip(test_checkpoint['model_params'], loaded_checkpoint['model_params']):\n",
    "            assert np.allclose(orig_param, loaded_param), \"Model parameters should match exactly\"\n",
    "        \n",
    "        assert loaded_checkpoint['config'] == test_checkpoint['config'], \"Config should match\"\n",
    "        assert loaded_checkpoint['metadata']['final_loss'] == 0.089, \"Metadata should be preserved\"\n",
    "        \n",
    "        print(f\"  Model params preserved: ✓\")\n",
    "        print(f\"  Config preserved: ✓\")\n",
    "        print(f\"  Metadata preserved: ✓\")\n",
    "    \n",
    "    # Test nested directory creation\n",
    "    with tempfile.TemporaryDirectory() as tmpdir:\n",
    "        nested_path = os.path.join(tmpdir, 'checkpoints', 'subdir', 'model.pkl')\n",
    "        save_checkpoint(test_checkpoint, nested_path)\n",
    "        assert os.path.exists(nested_path), \"Should create nested directories\"\n",
    "        print(f\"  Nested directory creation: ✓\")\n",
    "    \n",
    "    print(\"✅ Checkpointing works correctly!\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    test_unit_checkpointing()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c30df215",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### The Trainer Class - Orchestrating Complete Training\n",
    "\n",
    "The Trainer class is like a conductor orchestrating a symphony - it coordinates all the components (model, optimizer, loss function, scheduler) to create beautiful music (successful training).\n",
    "\n",
    "#### Training Loop Architecture\n",
    "\n",
    "The training loop follows a consistent pattern across all machine learning:\n",
    "\n",
    "```\n",
    "Training Loop Structure:\n",
    "\n",
    "for epoch in range(num_epochs):\n",
    "    ┌─────────────────── TRAINING PHASE ───────────────────┐\n",
    "    │                                                       │\n",
    "    │  for batch in dataloader:                            │\n",
    "    │      ┌─── Forward Pass ───┐                          │\n",
    "    │      │ 1. input → model   │                          │\n",
    "    │      │ 2. predictions     │                          │\n",
    "    │      └───────────────────┘                          │\n",
    "    │               ↓                                      │\n",
    "    │      ┌─── Loss Computation ───┐                     │\n",
    "    │      │ 3. loss = loss_fn()    │                     │\n",
    "    │      └───────────────────────┘                     │\n",
    "    │               ↓                                      │\n",
    "    │      ┌─── Backward Pass ───┐                       │\n",
    "    │      │ 4. loss.backward()  │                       │\n",
    "    │      │ 5. gradients        │                       │\n",
    "    │      └────────────────────┘                       │\n",
    "    │               ↓                                      │\n",
    "    │      ┌─── Parameter Update ───┐                    │\n",
    "    │      │ 6. optimizer.step()    │                    │\n",
    "    │      │ 7. zero gradients      │                    │\n",
    "    │      └───────────────────────┘                    │\n",
    "    └───────────────────────────────────────────────────┘\n",
    "             ↓\n",
    "    ┌─── Learning Rate Update ───┐\n",
    "    │ 8. scheduler.step()         │\n",
    "    └────────────────────────────┘\n",
    "```\n",
    "\n",
    "#### Key Features\n",
    "\n",
    "- **Train/Eval Modes**: Different behavior during training vs evaluation\n",
    "- **Gradient Accumulation**: Effective larger batch sizes with limited memory\n",
    "- **Checkpointing**: Save/resume training state for long experiments\n",
    "- **Progress Tracking**: Monitor loss, learning rate, and other metrics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "31a3a682",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": false,
     "grade_id": "trainer_class",
     "locked": false,
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "#| export\n",
    "class Trainer:\n",
    "    \"\"\"\n",
    "    Complete training orchestrator for neural networks.\n",
    "\n",
    "    Handles the full training lifecycle: forward pass, loss computation,\n",
    "    backward pass, optimization, scheduling, checkpointing, and evaluation.\n",
    "\n",
    "    This is the central class that brings together all the components\n",
    "    you've built in previous modules.\n",
    "\n",
    "    TODO: Implement complete Trainer class\n",
    "\n",
    "    APPROACH:\n",
    "    1. Store model, optimizer, loss function, and optional scheduler\n",
    "    2. train_epoch(): Loop through data, compute loss, update parameters\n",
    "    3. evaluate(): Similar loop but without gradient updates\n",
    "    4. save/load_checkpoint(): Persist training state for resumption\n",
    "\n",
    "    DESIGN PATTERNS:\n",
    "    - Context managers for train/eval modes\n",
    "    - Gradient accumulation for effective large batch sizes\n",
    "    - Progress tracking for monitoring\n",
    "    - Flexible scheduling integration\n",
    "    \"\"\"\n",
    "    ### BEGIN SOLUTION\n",
    "    def __init__(self, model, optimizer, loss_fn, scheduler=None, grad_clip_norm=None):\n",
    "        \"\"\"\n",
    "        Initialize trainer with model and training components.\n",
    "\n",
    "        Args:\n",
    "            model: Neural network to train\n",
    "            optimizer: Parameter update strategy (SGD, Adam, etc.)\n",
    "            loss_fn: Loss function (CrossEntropy, MSE, etc.)\n",
    "            scheduler: Optional learning rate scheduler\n",
    "            grad_clip_norm: Optional gradient clipping threshold\n",
    "        \"\"\"\n",
    "        self.model = model\n",
    "        self.optimizer = optimizer\n",
    "        self.loss_fn = loss_fn\n",
    "        self.scheduler = scheduler\n",
    "        self.grad_clip_norm = grad_clip_norm\n",
    "\n",
    "        # Training state\n",
    "        self.epoch = 0\n",
    "        self.step = 0\n",
    "        self.training_mode = True\n",
    "\n",
    "        # History tracking\n",
    "        self.history = {\n",
    "            'train_loss': [],\n",
    "            'eval_loss': [],\n",
    "            'learning_rates': []\n",
    "        }\n",
    "\n",
    "    def train_epoch(self, dataloader, accumulation_steps=1):\n",
    "        \"\"\"\n",
    "        Train for one epoch through the dataset.\n",
    "\n",
    "        Args:\n",
    "            dataloader: Iterable yielding (inputs, targets) batches\n",
    "            accumulation_steps: Number of batches to accumulate before update\n",
    "\n",
    "        Returns:\n",
    "            Average loss for the epoch\n",
    "        \"\"\"\n",
    "        self.model.training = True\n",
    "        self.training_mode = True\n",
    "\n",
    "        total_loss = 0.0\n",
    "        num_batches = 0\n",
    "        accumulated_loss = 0.0\n",
    "\n",
    "        for batch_idx, (inputs, targets) in enumerate(dataloader):\n",
    "            # Forward pass\n",
    "            outputs = self.model.forward(inputs)\n",
    "            loss = self.loss_fn.forward(outputs, targets)\n",
    "\n",
    "            # Scale loss for accumulation\n",
    "            scaled_loss = loss.data / accumulation_steps\n",
    "            accumulated_loss += scaled_loss\n",
    "\n",
    "            # Backward pass\n",
    "            if hasattr(loss, 'backward'):\n",
    "                loss.backward()\n",
    "\n",
    "            # Update parameters every accumulation_steps\n",
    "            if (batch_idx + 1) % accumulation_steps == 0:\n",
    "                # Gradient clipping\n",
    "                if self.grad_clip_norm is not None:\n",
    "                    params = []\n",
    "                    if hasattr(self.model, 'parameters'):\n",
    "                        params = self.model.parameters()\n",
    "                    clip_grad_norm(params, self.grad_clip_norm)\n",
    "\n",
    "                # Optimizer step\n",
    "                self.optimizer.step()\n",
    "                self.optimizer.zero_grad()\n",
    "\n",
    "                total_loss += accumulated_loss\n",
    "                accumulated_loss = 0.0\n",
    "                num_batches += 1\n",
    "                self.step += 1\n",
    "\n",
    "        # Handle remaining accumulated gradients\n",
    "        if accumulated_loss > 0:\n",
    "            if self.grad_clip_norm is not None:\n",
    "                params = []\n",
    "                if hasattr(self.model, 'parameters'):\n",
    "                    params = self.model.parameters()\n",
    "                clip_grad_norm(params, self.grad_clip_norm)\n",
    "\n",
    "            self.optimizer.step()\n",
    "            self.optimizer.zero_grad()\n",
    "            total_loss += accumulated_loss\n",
    "            num_batches += 1\n",
    "\n",
    "        avg_loss = total_loss / max(num_batches, 1)\n",
    "        self.history['train_loss'].append(avg_loss)\n",
    "\n",
    "        # Update scheduler\n",
    "        if self.scheduler is not None:\n",
    "            current_lr = self.scheduler.get_lr(self.epoch)\n",
    "            # Update optimizer learning rate\n",
    "            if hasattr(self.optimizer, 'lr'):\n",
    "                self.optimizer.lr = current_lr\n",
    "            self.history['learning_rates'].append(current_lr)\n",
    "\n",
    "        self.epoch += 1\n",
    "        return avg_loss\n",
    "\n",
    "    def evaluate(self, dataloader):\n",
    "        \"\"\"\n",
    "        Evaluate model on dataset without updating parameters.\n",
    "\n",
    "        Args:\n",
    "            dataloader: Iterable yielding (inputs, targets) batches\n",
    "\n",
    "        Returns:\n",
    "            Average loss and accuracy\n",
    "        \"\"\"\n",
    "        self.model.training = False\n",
    "        self.training_mode = False\n",
    "\n",
    "        total_loss = 0.0\n",
    "        correct = 0\n",
    "        total = 0\n",
    "\n",
    "        for inputs, targets in dataloader:\n",
    "            # Forward pass only\n",
    "            outputs = self.model.forward(inputs)\n",
    "            loss = self.loss_fn.forward(outputs, targets)\n",
    "\n",
    "            total_loss += loss.data\n",
    "\n",
    "            # Calculate accuracy (for classification)\n",
    "            if hasattr(outputs, 'data') and hasattr(targets, 'data'):\n",
    "                if len(outputs.data.shape) > 1:  # Multi-class\n",
    "                    predictions = np.argmax(outputs.data, axis=1)\n",
    "                    if len(targets.data.shape) == 1:  # Integer targets\n",
    "                        correct += np.sum(predictions == targets.data)\n",
    "                    else:  # One-hot targets\n",
    "                        correct += np.sum(predictions == np.argmax(targets.data, axis=1))\n",
    "                    total += len(predictions)\n",
    "\n",
    "        avg_loss = total_loss / len(dataloader) if len(dataloader) > 0 else 0.0\n",
    "        accuracy = correct / total if total > 0 else 0.0\n",
    "\n",
    "        self.history['eval_loss'].append(avg_loss)\n",
    "\n",
    "        return avg_loss, accuracy\n",
    "\n",
    "    def save_checkpoint(self, path: str):\n",
    "        \"\"\"\n",
    "        Save complete training state for resumption.\n",
    "        \n",
    "        This high-level method saves everything needed to resume training:\n",
    "        model parameters, optimizer state, scheduler state, and training history.\n",
    "        \n",
    "        Uses the low-level save_checkpoint() function internally.\n",
    "\n",
    "        Args:\n",
    "            path: File path to save checkpoint\n",
    "        \"\"\"\n",
    "        checkpoint = {\n",
    "            'epoch': self.epoch,\n",
    "            'step': self.step,\n",
    "            'model_state': self._get_model_state(),\n",
    "            'optimizer_state': self._get_optimizer_state(),\n",
    "            'scheduler_state': self._get_scheduler_state(),\n",
    "            'history': self.history,\n",
    "            'training_mode': self.training_mode\n",
    "        }\n",
    "\n",
    "        # Use the standalone save_checkpoint function\n",
    "        save_checkpoint(checkpoint, path)\n",
    "\n",
    "    def load_checkpoint(self, path: str):\n",
    "        \"\"\"\n",
    "        Load training state from checkpoint.\n",
    "        \n",
    "        This high-level method restores complete training state including\n",
    "        model parameters, optimizer state, scheduler state, and history.\n",
    "        \n",
    "        Uses the low-level load_checkpoint() function internally.\n",
    "\n",
    "        Args:\n",
    "            path: File path to load checkpoint from\n",
    "        \"\"\"\n",
    "        # Use the standalone load_checkpoint function\n",
    "        checkpoint = load_checkpoint(path)\n",
    "\n",
    "        self.epoch = checkpoint['epoch']\n",
    "        self.step = checkpoint['step']\n",
    "        self.history = checkpoint['history']\n",
    "        self.training_mode = checkpoint['training_mode']\n",
    "\n",
    "        # Restore states (simplified for educational purposes)\n",
    "        if 'model_state' in checkpoint:\n",
    "            self._set_model_state(checkpoint['model_state'])\n",
    "        if 'optimizer_state' in checkpoint:\n",
    "            self._set_optimizer_state(checkpoint['optimizer_state'])\n",
    "        if 'scheduler_state' in checkpoint:\n",
    "            self._set_scheduler_state(checkpoint['scheduler_state'])\n",
    "\n",
    "    def _get_model_state(self):\n",
    "        \"\"\"Extract model parameters for checkpointing.\"\"\"\n",
    "        if hasattr(self.model, 'parameters'):\n",
    "            return {i: param.data.copy() for i, param in enumerate(self.model.parameters())}\n",
    "        return {}\n",
    "\n",
    "    def _set_model_state(self, state):\n",
    "        \"\"\"Restore model parameters from checkpoint.\"\"\"\n",
    "        if hasattr(self.model, 'parameters'):\n",
    "            for i, param in enumerate(self.model.parameters()):\n",
    "                if i in state:\n",
    "                    param.data = state[i].copy()\n",
    "\n",
    "    def _get_optimizer_state(self):\n",
    "        \"\"\"Extract optimizer state for checkpointing.\"\"\"\n",
    "        state = {}\n",
    "        if hasattr(self.optimizer, 'lr'):\n",
    "            state['lr'] = self.optimizer.lr\n",
    "        if hasattr(self.optimizer, 'momentum_buffers'):\n",
    "            state['momentum_buffers'] = self.optimizer.momentum_buffers.copy()\n",
    "        return state\n",
    "\n",
    "    def _set_optimizer_state(self, state):\n",
    "        \"\"\"Restore optimizer state from checkpoint.\"\"\"\n",
    "        if 'lr' in state and hasattr(self.optimizer, 'lr'):\n",
    "            self.optimizer.lr = state['lr']\n",
    "        if 'momentum_buffers' in state and hasattr(self.optimizer, 'momentum_buffers'):\n",
    "            self.optimizer.momentum_buffers = state['momentum_buffers']\n",
    "\n",
    "    def _get_scheduler_state(self):\n",
    "        \"\"\"Extract scheduler state for checkpointing.\"\"\"\n",
    "        if self.scheduler is None:\n",
    "            return None\n",
    "        return {\n",
    "            'max_lr': getattr(self.scheduler, 'max_lr', None),\n",
    "            'min_lr': getattr(self.scheduler, 'min_lr', None),\n",
    "            'total_epochs': getattr(self.scheduler, 'total_epochs', None)\n",
    "        }\n",
    "\n",
    "    def _set_scheduler_state(self, state):\n",
    "        \"\"\"Restore scheduler state from checkpoint.\"\"\"\n",
    "        if state is None or self.scheduler is None:\n",
    "            return\n",
    "        for key, value in state.items():\n",
    "            if hasattr(self.scheduler, key):\n",
    "                setattr(self.scheduler, key, value)\n",
    "    ### END SOLUTION"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5bda48d0",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### 🧪 Unit Test: Trainer Class\n",
    "This test validates our complete training system.\n",
    "**What we're testing**: Trainer orchestrates training loop correctly\n",
    "**Why it matters**: This is the backbone that enables all neural network training\n",
    "**Expected**: Training reduces loss, evaluation works, checkpointing preserves state"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5ec503db",
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "test_trainer",
     "locked": true,
     "points": 15
    }
   },
   "outputs": [],
   "source": [
    "def test_unit_trainer():\n",
    "    \"\"\"🔬 Test Trainer implementation.\"\"\"\n",
    "    print(\"🔬 Unit Test: Trainer...\")\n",
    "\n",
    "    # Use REAL components from previous modules (already imported at module level)\n",
    "\n",
    "    # Create a simple model using REAL Linear layer\n",
    "    class SimpleModel:\n",
    "        def __init__(self):\n",
    "            self.layer = Linear(2, 1)  # Real Linear from Module 03\n",
    "            self.training = True\n",
    "\n",
    "        def forward(self, x):\n",
    "            return self.layer.forward(x)\n",
    "\n",
    "        def parameters(self):\n",
    "            return self.layer.parameters()\n",
    "\n",
    "    # Create trainer with REAL components\n",
    "    model = SimpleModel()\n",
    "    optimizer = SGD(model.parameters(), lr=0.01)  # Real SGD from Module 06\n",
    "    loss_fn = MSELoss()  # Real MSELoss from Module 04\n",
    "    scheduler = CosineSchedule(max_lr=0.1, min_lr=0.01, total_epochs=10)\n",
    "\n",
    "    trainer = Trainer(model, optimizer, loss_fn, scheduler, grad_clip_norm=1.0)\n",
    "\n",
    "    # Test training\n",
    "    print(\"Testing training epoch...\")\n",
    "    # Use real Tensors for data\n",
    "    dataloader = [\n",
    "        (Tensor([[1.0, 0.5]]), Tensor([[2.0]])),\n",
    "        (Tensor([[0.5, 1.0]]), Tensor([[1.5]]))\n",
    "    ]\n",
    "\n",
    "    loss = trainer.train_epoch(dataloader)\n",
    "    assert isinstance(loss, (float, np.floating)), f\"Expected float loss, got {type(loss)}\"\n",
    "    assert trainer.epoch == 1, f\"Expected epoch 1, got {trainer.epoch}\"\n",
    "\n",
    "    # Test evaluation\n",
    "    print(\"Testing evaluation...\")\n",
    "    eval_loss, accuracy = trainer.evaluate(dataloader)\n",
    "    assert isinstance(eval_loss, (float, np.floating)), f\"Expected float eval_loss, got {type(eval_loss)}\"\n",
    "    assert isinstance(accuracy, (float, np.floating)), f\"Expected float accuracy, got {type(accuracy)}\"\n",
    "\n",
    "    # Test checkpointing\n",
    "    print(\"Testing checkpointing...\")\n",
    "    checkpoint_path = \"/tmp/test_checkpoint.pkl\"\n",
    "    trainer.save_checkpoint(checkpoint_path)\n",
    "\n",
    "    # Modify trainer state\n",
    "    original_epoch = trainer.epoch\n",
    "    trainer.epoch = 999\n",
    "\n",
    "    # Load checkpoint\n",
    "    trainer.load_checkpoint(checkpoint_path)\n",
    "    assert trainer.epoch == original_epoch, f\"Checkpoint didn't restore epoch correctly\"\n",
    "\n",
    "    # Clean up\n",
    "    import os\n",
    "    if os.path.exists(checkpoint_path):\n",
    "        os.remove(checkpoint_path)\n",
    "\n",
    "    print(f\"✅ Trainer works correctly! Final loss: {loss:.4f}\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    test_unit_trainer()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "caaf7f6f",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 2
   },
   "source": [
    "## 🔧 Part 4: Integration - Bringing Training Together\n",
    "\n",
    "Now let's create a complete training example that demonstrates how all the components work together. This integration shows the full power of our training infrastructure."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e1d3c55e",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "source": [
    "\"\"\"\n",
    "# 🧪 Part 4: Module Integration Test\n",
    "\n",
    "Final validation that everything works together correctly.\n",
    "\"\"\"\n",
    "\n",
    "\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": "markdown",
   "id": "f6985f5f",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## 🧪 Part 5: Module Integration Test\n",
    "\n",
    "Final validation that everything works together correctly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "532392ab",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": true,
     "grade_id": "test_module",
     "locked": true,
     "points": 20
    }
   },
   "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_cosine_schedule()\n",
    "    test_unit_clip_grad_norm()\n",
    "    test_unit_trainer()\n",
    "\n",
    "    print(\"\\nRunning integration scenarios...\")\n",
    "\n",
    "    # Test complete training pipeline integration with REAL components\n",
    "    print(\"🔬 Integration Test: Complete Training Pipeline...\")\n",
    "\n",
    "    # Use REAL components from previous modules (already imported at module level)\n",
    "\n",
    "    # Create a simple model using REAL Linear layer\n",
    "    class SimpleModel:\n",
    "        def __init__(self):\n",
    "            self.layer = Linear(2, 1)  # Real Linear from Module 03\n",
    "            self.training = True\n",
    "\n",
    "        def forward(self, x):\n",
    "            return self.layer.forward(x)\n",
    "\n",
    "        def parameters(self):\n",
    "            return self.layer.parameters()\n",
    "\n",
    "    # Create integrated system with REAL components\n",
    "    model = SimpleModel()\n",
    "    optimizer = SGD(model.parameters(), lr=0.01)  # Real SGD from Module 06\n",
    "    loss_fn = MSELoss()  # Real MSELoss from Module 04\n",
    "    scheduler = CosineSchedule(max_lr=0.1, min_lr=0.001, total_epochs=3)\n",
    "\n",
    "    trainer = Trainer(\n",
    "        model=model,\n",
    "        optimizer=optimizer,\n",
    "        loss_fn=loss_fn,\n",
    "        scheduler=scheduler,\n",
    "        grad_clip_norm=0.5\n",
    "    )\n",
    "\n",
    "    # Test data using REAL Tensors\n",
    "    data = [\n",
    "        (Tensor([[1.0, 0.5]]), Tensor([[0.8]])),\n",
    "        (Tensor([[0.5, 1.0]]), Tensor([[0.2]]))\n",
    "    ]\n",
    "\n",
    "    # Test training\n",
    "    initial_loss = trainer.train_epoch(data)\n",
    "    assert isinstance(initial_loss, (float, np.floating)), \"Training should return float loss\"\n",
    "    assert trainer.epoch == 1, \"Epoch should increment\"\n",
    "\n",
    "    # Test evaluation\n",
    "    eval_loss, accuracy = trainer.evaluate(data)\n",
    "    assert isinstance(eval_loss, (float, np.floating)), \"Evaluation should return float loss\"\n",
    "    assert isinstance(accuracy, (float, np.floating)), \"Evaluation should return float accuracy\"\n",
    "\n",
    "    # Test scheduling\n",
    "    lr_epoch_0 = scheduler.get_lr(0)\n",
    "    lr_epoch_1 = scheduler.get_lr(1)\n",
    "    assert lr_epoch_0 > lr_epoch_1, \"Learning rate should decrease\"\n",
    "\n",
    "    # Test gradient clipping with large gradients using real Tensor\n",
    "    large_param = Tensor([1.0, 2.0], requires_grad=True)\n",
    "    large_param.grad = np.array([100.0, 200.0])\n",
    "    large_params = [large_param]\n",
    "\n",
    "    original_norm = clip_grad_norm(large_params, max_norm=1.0)\n",
    "    assert original_norm > 1.0, \"Original norm should be large\"\n",
    "\n",
    "    if isinstance(large_params[0].grad, np.ndarray):\n",
    "        grad_data = large_params[0].grad\n",
    "    elif hasattr(large_params[0].grad, 'data'):\n",
    "        grad_data = large_params[0].grad.data\n",
    "    else:\n",
    "        grad_data = np.array(large_params[0].grad)\n",
    "    new_norm = np.linalg.norm(grad_data)\n",
    "    assert abs(new_norm - 1.0) < 1e-6, \"Clipped norm should equal max_norm\"\n",
    "\n",
    "    # Test checkpointing\n",
    "    checkpoint_path = \"/tmp/integration_test_checkpoint.pkl\"\n",
    "    trainer.save_checkpoint(checkpoint_path)\n",
    "\n",
    "    original_epoch = trainer.epoch\n",
    "    trainer.epoch = 999\n",
    "    trainer.load_checkpoint(checkpoint_path)\n",
    "\n",
    "    assert trainer.epoch == original_epoch, \"Checkpoint should restore state\"\n",
    "\n",
    "    # Clean up\n",
    "    import os\n",
    "    if os.path.exists(checkpoint_path):\n",
    "        os.remove(checkpoint_path)\n",
    "\n",
    "    print(\"✅ End-to-end training pipeline works!\")\n",
    "\n",
    "    print(\"\\n\" + \"=\" * 50)\n",
    "    print(\"🎉 ALL TESTS PASSED! Module ready for export.\")\n",
    "    print(\"Run: tito module complete 07\")\n",
    "\n",
    "# test_module()  # Moved to main guard"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "054f03ae",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "main",
     "locked": false,
     "solution": false
    }
   },
   "outputs": [],
   "source": [
    "# Run comprehensive module test\n",
    "if __name__ == \"__main__\":\n",
    "    test_module()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bee424e5",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "## 🎯 MODULE SUMMARY: Training\n",
    "\n",
    "Congratulations! You've built a complete training infrastructure that can orchestrate the entire machine learning training process!\n",
    "\n",
    "### Key Accomplishments\n",
    "- Built Trainer class with complete training/evaluation loops\n",
    "- Implemented CosineSchedule for adaptive learning rate management\n",
    "- Created clip_grad_norm for training stability and gradient management\n",
    "- Added comprehensive checkpointing for training persistence\n",
    "- All tests pass ✅ (validated by `test_module()`)\n",
    "\n",
    "### Ready for Next Steps\n",
    "Your training implementation enables sophisticated model training with proper scheduling, stability controls, and state management.\n",
    "Export with: `tito module complete 07`\n",
    "\n",
    "**Next**: Module 08 will add DataLoader for efficient data pipeline management, completing the full training infrastructure needed for the MLP milestone!\n",
    "\n",
    "### Systems Insights Gained\n",
    "- Learning rate scheduling often provides better convergence than fixed rates\n",
    "- Gradient clipping preserves direction while preventing instability\n",
    "- Checkpointing enables fault-tolerant training for production systems\n",
    "\n",
    "**🎓 You now understand the complete training infrastructure that powers modern ML systems!**"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
