{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "b1f32af6",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "# Module 04: Losses - Measuring How Wrong We Are\n",
    "\n",
    "Welcome to Module 04! Today you'll implement the mathematical functions that measure how wrong your model's predictions are - the essential feedback signal that enables all machine learning.\n",
    "\n",
    "## 🔗 Prerequisites & Progress\n",
    "**You've Built**: Tensors (data), Activations (intelligence), Layers (architecture)\n",
    "**You'll Build**: Loss functions that measure prediction quality\n",
    "**You'll Enable**: The feedback signal needed for training (Module 05: Autograd)\n",
    "\n",
    "**Connection Map**:\n",
    "```\n",
    "Layers → Losses → Autograd\n",
    "(predictions) (error measurement) (learning signals)\n",
    "```\n",
    "\n",
    "## Learning Objectives\n",
    "By the end of this module, you will:\n",
    "1. Implement MSELoss for regression problems\n",
    "2. Implement CrossEntropyLoss for classification problems\n",
    "3. Implement BinaryCrossEntropyLoss for binary classification\n",
    "4. Understand numerical stability in loss computation\n",
    "5. Test all loss functions with realistic examples\n",
    "\n",
    "Let's measure prediction quality!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e587fb8a",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "## 📦 Where This Code Lives in the Final Package\n",
    "\n",
    "**Learning Side:** You work in modules/04_losses/losses_dev.py\n",
    "**Building Side:** Code exports to tinytorch.core.losses\n",
    "\n",
    "```python\n",
    "# Final package structure:\n",
    "from tinytorch.core.losses import MSELoss, CrossEntropyLoss, BinaryCrossEntropyLoss, log_softmax  # This module\n",
    "```\n",
    "\n",
    "**Why this matters:**\n",
    "- **Learning:** Complete loss function system in one focused module\n",
    "- **Production:** Proper organization like PyTorch's torch.nn functional losses\n",
    "- **Consistency:** All loss computations and numerical stability in core.losses\n",
    "- **Integration:** Works seamlessly with layers for complete prediction-to-error workflow"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aae3876c",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "## 📋 Module Prerequisites & Setup\n",
    "\n",
    "This module builds on previous TinyTorch components. Here's what we need and why:\n",
    "\n",
    "**Required Components:**\n",
    "- **Tensor** (Module 01): Foundation for all loss computations\n",
    "- **Linear** (Module 03): For testing loss functions with realistic predictions  \n",
    "- **ReLU** (Module 02): For building test networks that generate realistic outputs\n",
    "\n",
    "**Integration Helper:**\n",
    "The `import_previous_module()` function below helps us cleanly import components from previous modules during development and testing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e96e3ea5",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "setup",
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "#| default_exp core.losses\n",
    "#| export\n",
    "\n",
    "import numpy as np\n",
    "from typing import Optional\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)\n",
    "\n",
    "# Import from tinytorch package\n",
    "from tinytorch.core.tensor import Tensor\n",
    "from tinytorch.core.layers import Linear\n",
    "from tinytorch.core.activations import ReLU"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d094d165",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "# Part 1: Introduction - What Are Loss Functions?\n",
    "\n",
    "Loss functions are the mathematical conscience of machine learning. They measure the distance between what your model predicts and what actually happened. Without loss functions, models have no way to improve - they're like athletes training without knowing their score.\n",
    "\n",
    "## The Three Essential Loss Functions\n",
    "\n",
    "Think of loss functions as different ways to measure \"wrongness\" - each optimized for different types of problems:\n",
    "\n",
    "**MSELoss (Mean Squared Error)**: \"How far off are my continuous predictions?\"\n",
    "- Used for: Regression (predicting house prices, temperature, stock values)\n",
    "- Calculation: Average of squared differences between predictions and targets\n",
    "- Properties: Heavily penalizes large errors, smooth gradients\n",
    "\n",
    "```\n",
    "Loss Landscape for MSE:\n",
    "     Loss\n",
    "      ^\n",
    "      |\n",
    "   4  |     *\n",
    "      |    / \\\n",
    "   2  |   /   \\\n",
    "      |  /     \\\n",
    "   0  |_/_______\\\\____> Prediction Error\n",
    "      0  -2  0  +2\n",
    "\n",
    "Quadratic growth: small errors → small penalty, large errors → huge penalty\n",
    "```\n",
    "\n",
    "**CrossEntropyLoss**: \"How confident am I in the wrong class?\"\n",
    "- Used for: Multi-class classification (image recognition, text classification)\n",
    "- Calculation: Negative log-likelihood of correct class probability\n",
    "- Properties: Encourages confident correct predictions, punishes confident wrong ones\n",
    "\n",
    "```\n",
    "Cross-Entropy Penalty Curve:\n",
    "     Loss\n",
    "      ^\n",
    "   10 |*\n",
    "      ||\n",
    "    5 | \\\n",
    "      |  \\\n",
    "    2 |   \\\n",
    "      |    \\\n",
    "    0 |_____\\\\____> Predicted Probability of Correct Class\n",
    "      0   0.5   1.0\n",
    "\n",
    "Logarithmic: wrong confident predictions get severe penalty\n",
    "```\n",
    "\n",
    "**BinaryCrossEntropyLoss**: \"How wrong am I about yes/no decisions?\"\n",
    "- Used for: Binary classification (spam detection, medical diagnosis)\n",
    "- Calculation: Cross-entropy specialized for two classes\n",
    "- Properties: Symmetric penalty for false positives and false negatives\n",
    "\n",
    "```\n",
    "Binary Decision Boundary:\n",
    "     Target=1 (Positive)    Target=0 (Negative)\n",
    "     ┌─────────────────┬─────────────────┐\n",
    "     │  Pred → 1.0     │  Pred → 1.0     │\n",
    "     │  Loss → 0       │  Loss → ∞       │\n",
    "     ├─────────────────┼─────────────────┤\n",
    "     │  Pred → 0.0     │  Pred → 0.0     │\n",
    "     │  Loss → ∞       │  Loss → 0       │\n",
    "     └─────────────────┴─────────────────┘\n",
    "```\n",
    "\n",
    "Each loss function creates a different \"error landscape\" that guides learning in different ways."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c395dbee",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "# Part 2: Mathematical Foundations\n",
    "\n",
    "## Mean Squared Error (MSE)\n",
    "The foundation of regression, MSE measures the average squared distance between predictions and targets:\n",
    "\n",
    "```\n",
    "MSE = (1/N) * Σ(prediction_i - target_i)²\n",
    "```\n",
    "\n",
    "**Why square the differences?**\n",
    "- Makes all errors positive (no cancellation between positive/negative errors)\n",
    "- Heavily penalizes large errors (error of 2 becomes 4, error of 10 becomes 100)\n",
    "- Creates smooth gradients for optimization\n",
    "\n",
    "## Cross-Entropy Loss\n",
    "For classification, we need to measure how wrong our probability distributions are:\n",
    "\n",
    "```\n",
    "CrossEntropy = -Σ target_i * log(prediction_i)\n",
    "```\n",
    "\n",
    "**The Log-Sum-Exp Trick**:\n",
    "Computing softmax directly can cause numerical overflow. The log-sum-exp trick provides stability:\n",
    "```\n",
    "log_softmax(x) = x - log(Σ exp(x_i))\n",
    "                = x - max(x) - log(Σ exp(x_i - max(x)))\n",
    "```\n",
    "\n",
    "This prevents exp(large_number) from exploding to infinity.\n",
    "\n",
    "## Binary Cross-Entropy\n",
    "A specialized case where we have only two classes:\n",
    "```\n",
    "BCE = -(target * log(prediction) + (1-target) * log(1-prediction))\n",
    "```\n",
    "\n",
    "The mathematics naturally handles both \"positive\" and \"negative\" cases in a single formula."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "898f3473",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "# Part 3: Implementation - Building Loss Functions\n",
    "\n",
    "Let's implement our loss functions with proper numerical stability and clear educational structure."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b621cc6",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## Log-Softmax - The Numerically Stable Foundation\n",
    "\n",
    "Before implementing loss functions, we need a reliable way to compute log-softmax. This function is the numerically stable backbone of classification losses.\n",
    "\n",
    "### Why Log-Softmax Matters\n",
    "\n",
    "Naive softmax can explode with large numbers:\n",
    "```\n",
    "Naive approach:\n",
    "  logits = [100, 200, 300]\n",
    "  exp(300) = 1.97 × 10^130  ← This breaks computers!\n",
    "\n",
    "Stable approach:\n",
    "  max_logit = 300\n",
    "  shifted = [-200, -100, 0]  ← Subtract max\n",
    "  exp(0) = 1.0  ← Manageable numbers\n",
    "```\n",
    "\n",
    "### The Log-Sum-Exp Trick Visualization\n",
    "\n",
    "```\n",
    "Original Computation:           Stable Computation:\n",
    "\n",
    "logits: [a, b, c]              logits: [a, b, c]\n",
    "   ↓                              ↓\n",
    "exp(logits)                    max_val = max(a,b,c)\n",
    "   ↓                              ↓\n",
    "sum(exp(logits))               shifted = [a-max, b-max, c-max]\n",
    "   ↓                              ↓\n",
    "log(sum)                       exp(shifted)  ← All ≤ 1.0\n",
    "   ↓                              ↓\n",
    "logits - log(sum)              sum(exp(shifted))\n",
    "                                  ↓\n",
    "                               log(sum) + max_val\n",
    "                                  ↓\n",
    "                               logits - (log(sum) + max_val)\n",
    "```\n",
    "\n",
    "Both give the same result, but the stable version never overflows!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2d449cd9",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": false,
     "grade_id": "log_softmax",
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "#| export\n",
    "def log_softmax(x: Tensor, dim: int = -1) -> Tensor:\n",
    "    \"\"\"\n",
    "    Compute log-softmax with numerical stability.\n",
    "\n",
    "    TODO: Implement numerically stable log-softmax using the log-sum-exp trick\n",
    "\n",
    "    APPROACH:\n",
    "    1. Find maximum along dimension (for stability)\n",
    "    2. Subtract max from input (prevents overflow)\n",
    "    3. Compute log(sum(exp(shifted_input)))\n",
    "    4. Return input - max - log_sum_exp\n",
    "\n",
    "    EXAMPLE:\n",
    "    >>> logits = Tensor([[1.0, 2.0, 3.0], [0.1, 0.2, 0.9]])\n",
    "    >>> result = log_softmax(logits, dim=-1)\n",
    "    >>> print(result.shape)\n",
    "    (2, 3)\n",
    "\n",
    "    HINT: Use np.max(x.data, axis=dim, keepdims=True) to preserve dimensions\n",
    "    \"\"\"\n",
    "    ### BEGIN SOLUTION\n",
    "    # Step 1: Find max along dimension for numerical stability\n",
    "    max_vals = np.max(x.data, axis=dim, keepdims=True)\n",
    "\n",
    "    # Step 2: Subtract max to prevent overflow\n",
    "    shifted = x.data - max_vals\n",
    "\n",
    "    # Step 3: Compute log(sum(exp(shifted)))\n",
    "    log_sum_exp = np.log(np.sum(np.exp(shifted), axis=dim, keepdims=True))\n",
    "\n",
    "    # Step 4: Return log_softmax = input - max - log_sum_exp\n",
    "    result = x.data - max_vals - log_sum_exp\n",
    "\n",
    "    return Tensor(result)\n",
    "    ### END SOLUTION"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "598bc3ea",
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "test_log_softmax",
     "locked": true,
     "points": 10
    }
   },
   "outputs": [],
   "source": [
    "def test_unit_log_softmax():\n",
    "    \"\"\"🔬 Test log_softmax numerical stability and correctness.\"\"\"\n",
    "    print(\"🔬 Unit Test: Log-Softmax...\")\n",
    "\n",
    "    # Test basic functionality\n",
    "    x = Tensor([[1.0, 2.0, 3.0], [0.1, 0.2, 0.9]])\n",
    "    result = log_softmax(x, dim=-1)\n",
    "\n",
    "    # Verify shape preservation\n",
    "    assert result.shape == x.shape, f\"Shape mismatch: expected {x.shape}, got {result.shape}\"\n",
    "\n",
    "    # Verify log-softmax properties: exp(log_softmax) should sum to 1\n",
    "    softmax_result = np.exp(result.data)\n",
    "    row_sums = np.sum(softmax_result, axis=-1)\n",
    "    assert np.allclose(row_sums, 1.0, atol=1e-6), f\"Softmax doesn't sum to 1: {row_sums}\"\n",
    "\n",
    "    # Test numerical stability with large values\n",
    "    large_x = Tensor([[100.0, 101.0, 102.0]])\n",
    "    large_result = log_softmax(large_x, dim=-1)\n",
    "    assert not np.any(np.isnan(large_result.data)), \"NaN values in result with large inputs\"\n",
    "    assert not np.any(np.isinf(large_result.data)), \"Inf values in result with large inputs\"\n",
    "\n",
    "    print(\"✅ log_softmax works correctly with numerical stability!\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    test_unit_log_softmax()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c87a381",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## MSELoss - Measuring Continuous Prediction Quality\n",
    "\n",
    "Mean Squared Error is the workhorse of regression problems. It measures how far your continuous predictions are from the true values.\n",
    "\n",
    "### When to Use MSE\n",
    "\n",
    "**Perfect for:**\n",
    "- House price prediction ($200k vs $195k)\n",
    "- Temperature forecasting (25°C vs 23°C)\n",
    "- Stock price prediction ($150 vs $148)\n",
    "- Any continuous value where \"distance\" matters\n",
    "\n",
    "### How MSE Shapes Learning\n",
    "\n",
    "```\n",
    "Prediction vs Target Visualization:\n",
    "\n",
    "Target = 100\n",
    "\n",
    "Prediction: 80   90   95   100  105  110  120\n",
    "Error:     -20  -10   -5    0   +5  +10  +20\n",
    "MSE:       400  100   25    0   25  100  400\n",
    "\n",
    "Loss Curve:\n",
    "     MSE\n",
    "      ^\n",
    "  400 |*           *\n",
    "      |\n",
    "  100 | *         *\n",
    "      |  \\\n",
    "   25 |   *     *\n",
    "      |    \\\\   /\n",
    "    0 |_____*_____> Prediction\n",
    "       80   100   120\n",
    "\n",
    "Quadratic penalty: Large errors are MUCH more costly than small errors\n",
    "```\n",
    "\n",
    "### Why Square the Errors?\n",
    "\n",
    "1. **Positive penalties**: (-10)² = 100, same as (+10)² = 100\n",
    "2. **Heavy punishment for large errors**: Error of 20 → penalty of 400\n",
    "3. **Smooth gradients**: Quadratic function has nice derivatives for optimization\n",
    "4. **Statistical foundation**: Maximum likelihood for Gaussian noise\n",
    "\n",
    "### MSE vs Other Regression Losses\n",
    "\n",
    "```\n",
    "Error Sensitivity Comparison:\n",
    "\n",
    " Error:   -10    -5     0     +5    +10\n",
    " MSE:     100    25     0     25    100  ← Quadratic growth\n",
    " MAE:      10     5     0      5     10  ← Linear growth\n",
    " Huber:    50    12.5   0    12.5    50  ← Hybrid approach\n",
    "\n",
    " MSE: More sensitive to outliers\n",
    " MAE: More robust to outliers\n",
    " Huber: Best of both worlds\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fbfd8db8",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": false,
     "grade_id": "mse_loss",
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "#| export\n",
    "class MSELoss:\n",
    "    \"\"\"Mean Squared Error loss for regression tasks.\"\"\"\n",
    "\n",
    "    def __init__(self):\n",
    "        \"\"\"Initialize MSE loss function.\"\"\"\n",
    "        pass\n",
    "\n",
    "    def forward(self, predictions: Tensor, targets: Tensor) -> Tensor:\n",
    "        \"\"\"\n",
    "        Compute mean squared error between predictions and targets.\n",
    "\n",
    "        TODO: Implement MSE loss calculation\n",
    "\n",
    "        APPROACH:\n",
    "        1. Compute difference: predictions - targets\n",
    "        2. Square the differences: diff²\n",
    "        3. Take mean across all elements\n",
    "\n",
    "        EXAMPLE:\n",
    "        >>> loss_fn = MSELoss()\n",
    "        >>> predictions = Tensor([1.0, 2.0, 3.0])\n",
    "        >>> targets = Tensor([1.5, 2.5, 2.8])\n",
    "        >>> loss = loss_fn(predictions, targets)\n",
    "        >>> print(f\"MSE Loss: {loss.data:.4f}\")\n",
    "        MSE Loss: 0.1467\n",
    "\n",
    "        HINTS:\n",
    "        - Use (predictions.data - targets.data) for element-wise difference\n",
    "        - Square with **2 or np.power(diff, 2)\n",
    "        - Use np.mean() to average over all elements\n",
    "        \"\"\"\n",
    "        ### BEGIN SOLUTION\n",
    "        # Step 1: Compute element-wise difference\n",
    "        diff = predictions.data - targets.data\n",
    "\n",
    "        # Step 2: Square the differences\n",
    "        squared_diff = diff ** 2\n",
    "\n",
    "        # Step 3: Take mean across all elements\n",
    "        mse = np.mean(squared_diff)\n",
    "\n",
    "        return Tensor(mse)\n",
    "        ### END SOLUTION\n",
    "\n",
    "    def __call__(self, predictions: Tensor, targets: Tensor) -> Tensor:\n",
    "        \"\"\"Allows the loss function to be called like a function.\"\"\"\n",
    "        return self.forward(predictions, targets)\n",
    "\n",
    "    def backward(self) -> Tensor:\n",
    "        \"\"\"\n",
    "        Compute gradients (implemented in Module 05: Autograd).\n",
    "\n",
    "        For now, this is a stub that students can ignore.\n",
    "        \"\"\"\n",
    "        pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "75d81b1d",
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "test_mse_loss",
     "locked": true,
     "points": 10
    }
   },
   "outputs": [],
   "source": [
    "def test_unit_mse_loss():\n",
    "    \"\"\"🔬 Test MSELoss implementation and properties.\"\"\"\n",
    "    print(\"🔬 Unit Test: MSE Loss...\")\n",
    "\n",
    "    loss_fn = MSELoss()\n",
    "\n",
    "    # Test perfect predictions (loss should be 0)\n",
    "    predictions = Tensor([1.0, 2.0, 3.0])\n",
    "    targets = Tensor([1.0, 2.0, 3.0])\n",
    "    perfect_loss = loss_fn.forward(predictions, targets)\n",
    "    assert np.allclose(perfect_loss.data, 0.0, atol=1e-7), f\"Perfect predictions should have 0 loss, got {perfect_loss.data}\"\n",
    "\n",
    "    # Test known case\n",
    "    predictions = Tensor([1.0, 2.0, 3.0])\n",
    "    targets = Tensor([1.5, 2.5, 2.8])\n",
    "    loss = loss_fn.forward(predictions, targets)\n",
    "\n",
    "    # Manual calculation: ((1-1.5)² + (2-2.5)² + (3-2.8)²) / 3 = (0.25 + 0.25 + 0.04) / 3 = 0.18\n",
    "    expected_loss = (0.25 + 0.25 + 0.04) / 3\n",
    "    assert np.allclose(loss.data, expected_loss, atol=1e-6), f\"Expected {expected_loss}, got {loss.data}\"\n",
    "\n",
    "    # Test that loss is always non-negative\n",
    "    random_pred = Tensor(np.random.randn(10))\n",
    "    random_target = Tensor(np.random.randn(10))\n",
    "    random_loss = loss_fn.forward(random_pred, random_target)\n",
    "    assert random_loss.data >= 0, f\"MSE loss should be non-negative, got {random_loss.data}\"\n",
    "\n",
    "    print(\"✅ MSELoss works correctly!\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    test_unit_mse_loss()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "51629e11",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## CrossEntropyLoss - Measuring Classification Confidence\n",
    "\n",
    "Cross-entropy loss is the gold standard for multi-class classification. It measures how wrong your probability predictions are and heavily penalizes confident mistakes.\n",
    "\n",
    "### When to Use Cross-Entropy\n",
    "\n",
    "**Perfect for:**\n",
    "- Image classification (cat, dog, bird)\n",
    "- Text classification (spam, ham, promotion)\n",
    "- Language modeling (next word prediction)\n",
    "- Any problem with mutually exclusive classes\n",
    "\n",
    "### Understanding Cross-Entropy Through Examples\n",
    "\n",
    "```\n",
    "Scenario: Image Classification (3 classes: cat, dog, bird)\n",
    "\n",
    "Case 1: Correct and Confident\n",
    "Model Output (logits): [5.0, 1.0, 0.1]  ← Very confident about \"cat\"\n",
    "After Softmax:        [0.95, 0.047, 0.003]\n",
    "True Label:           cat (class 0)\n",
    "Loss: -log(0.95) = 0.05  ← Very low loss ✅\n",
    "\n",
    "Case 2: Correct but Uncertain\n",
    "Model Output:         [1.1, 1.0, 0.9]  ← Uncertain between classes\n",
    "After Softmax:        [0.4, 0.33, 0.27]\n",
    "True Label:           cat (class 0)\n",
    "Loss: -log(0.4) = 0.92  ← Higher loss (uncertainty penalized)\n",
    "\n",
    "Case 3: Wrong and Confident\n",
    "Model Output:         [0.1, 5.0, 1.0]  ← Very confident about \"dog\"\n",
    "After Softmax:        [0.003, 0.95, 0.047]\n",
    "True Label:           cat (class 0)\n",
    "Loss: -log(0.003) = 5.8  ← Very high loss ❌\n",
    "```\n",
    "\n",
    "### Cross-Entropy's Learning Signal\n",
    "\n",
    "```\n",
    "What Cross-Entropy Teaches the Model:\n",
    "\n",
    "┌─────────────────┬─────────────────┬─────────────────┐\n",
    "│ Prediction      │ True Label      │ Learning Signal │\n",
    "├─────────────────┼─────────────────┼─────────────────┤\n",
    "│ Confident ✅    │ Correct ✅      │ \"Keep doing this\"│\n",
    "│ Uncertain ⚠️    │ Correct ✅      │ \"Be more confident\"│\n",
    "│ Confident ❌    │ Wrong ❌        │ \"STOP! Change everything\"│\n",
    "│ Uncertain ⚠️    │ Wrong ❌        │ \"Learn the right answer\"│\n",
    "└─────────────────┴─────────────────┴─────────────────┘\n",
    "\n",
    "Loss Landscape by Confidence:\n",
    "     Loss\n",
    "      ^\n",
    "    5 |*\n",
    "      ||\n",
    "    3 | *\n",
    "      |  \\\n",
    "    1 |   *\n",
    "      |    \\\\\n",
    "    0 |______**____> Predicted Probability (correct class)\n",
    "      0   0.5   1.0\n",
    "\n",
    "Message: \"Be confident when you're right!\"\n",
    "```\n",
    "\n",
    "### Why Cross-Entropy Works So Well\n",
    "\n",
    "1. **Probabilistic interpretation**: Measures quality of probability distributions\n",
    "2. **Strong gradients**: Large penalty for confident mistakes drives fast learning\n",
    "3. **Smooth optimization**: Log function provides nice gradients\n",
    "4. **Information theory**: Minimizes \"surprise\" about correct answers\n",
    "\n",
    "### Multi-Class vs Binary Classification\n",
    "\n",
    "```\n",
    "Multi-Class (3+ classes):          Binary (2 classes):\n",
    "\n",
    "Classes: [cat, dog, bird]         Classes: [spam, not_spam]\n",
    "Output:  [0.7, 0.2, 0.1]         Output:  0.8 (spam probability)\n",
    "Must sum to 1.0 ✅               Must be between 0 and 1 ✅\n",
    "Uses: CrossEntropyLoss            Uses: BinaryCrossEntropyLoss\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8ac37974",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": false,
     "grade_id": "cross_entropy_loss",
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "#| export\n",
    "class CrossEntropyLoss:\n",
    "    \"\"\"Cross-entropy loss for multi-class classification.\"\"\"\n",
    "\n",
    "    def __init__(self):\n",
    "        \"\"\"Initialize cross-entropy loss function.\"\"\"\n",
    "        pass\n",
    "\n",
    "    def forward(self, logits: Tensor, targets: Tensor) -> Tensor:\n",
    "        \"\"\"\n",
    "        Compute cross-entropy loss between logits and target class indices.\n",
    "\n",
    "        TODO: Implement cross-entropy loss with numerical stability\n",
    "\n",
    "        APPROACH:\n",
    "        1. Compute log-softmax of logits (numerically stable)\n",
    "        2. Select log-probabilities for correct classes\n",
    "        3. Return negative mean of selected log-probabilities\n",
    "\n",
    "        EXAMPLE:\n",
    "        >>> loss_fn = CrossEntropyLoss()\n",
    "        >>> logits = Tensor([[2.0, 1.0, 0.1], [0.5, 1.5, 0.8]])  # 2 samples, 3 classes\n",
    "        >>> targets = Tensor([0, 1])  # First sample is class 0, second is class 1\n",
    "        >>> loss = loss_fn(logits, targets)\n",
    "        >>> print(f\"Cross-Entropy Loss: {loss.data:.4f}\")\n",
    "\n",
    "        HINTS:\n",
    "        - Use log_softmax() for numerical stability\n",
    "        - targets.data.astype(int) ensures integer indices\n",
    "        - Use np.arange(batch_size) for row indexing: log_probs[np.arange(batch_size), targets]\n",
    "        - Return negative mean: -np.mean(selected_log_probs)\n",
    "        \"\"\"\n",
    "        ### BEGIN SOLUTION\n",
    "        # Step 1: Compute log-softmax for numerical stability\n",
    "        log_probs = log_softmax(logits, dim=-1)\n",
    "\n",
    "        # Step 2: Select log-probabilities for correct classes\n",
    "        batch_size = logits.shape[0]\n",
    "        target_indices = targets.data.astype(int)\n",
    "\n",
    "        # Select correct class log-probabilities using advanced indexing\n",
    "        selected_log_probs = log_probs.data[np.arange(batch_size), target_indices]\n",
    "\n",
    "        # Step 3: Return negative mean (cross-entropy is negative log-likelihood)\n",
    "        cross_entropy = -np.mean(selected_log_probs)\n",
    "\n",
    "        return Tensor(cross_entropy)\n",
    "        ### END SOLUTION\n",
    "\n",
    "    def __call__(self, logits: Tensor, targets: Tensor) -> Tensor:\n",
    "        \"\"\"Allows the loss function to be called like a function.\"\"\"\n",
    "        return self.forward(logits, targets)\n",
    "\n",
    "    def backward(self) -> Tensor:\n",
    "        \"\"\"\n",
    "        Compute gradients (implemented in Module 05: Autograd).\n",
    "\n",
    "        For now, this is a stub that students can ignore.\n",
    "        \"\"\"\n",
    "        pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4258d005",
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "test_cross_entropy_loss",
     "locked": true,
     "points": 10
    }
   },
   "outputs": [],
   "source": [
    "def test_unit_cross_entropy_loss():\n",
    "    \"\"\"🔬 Test CrossEntropyLoss implementation and properties.\"\"\"\n",
    "    print(\"🔬 Unit Test: Cross-Entropy Loss...\")\n",
    "\n",
    "    loss_fn = CrossEntropyLoss()\n",
    "\n",
    "    # Test perfect predictions (should have very low loss)\n",
    "    perfect_logits = Tensor([[10.0, -10.0, -10.0], [-10.0, 10.0, -10.0]])  # Very confident predictions\n",
    "    targets = Tensor([0, 1])  # Matches the confident predictions\n",
    "    perfect_loss = loss_fn.forward(perfect_logits, targets)\n",
    "    assert perfect_loss.data < 0.01, f\"Perfect predictions should have very low loss, got {perfect_loss.data}\"\n",
    "\n",
    "    # Test uniform predictions (should have loss ≈ log(num_classes))\n",
    "    uniform_logits = Tensor([[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])  # Equal probabilities\n",
    "    uniform_targets = Tensor([0, 1])\n",
    "    uniform_loss = loss_fn.forward(uniform_logits, uniform_targets)\n",
    "    expected_uniform_loss = np.log(3)  # log(3) ≈ 1.099 for 3 classes\n",
    "    assert np.allclose(uniform_loss.data, expected_uniform_loss, atol=0.1), f\"Uniform predictions should have loss ≈ log(3) = {expected_uniform_loss:.3f}, got {uniform_loss.data:.3f}\"\n",
    "\n",
    "    # Test that wrong confident predictions have high loss\n",
    "    wrong_logits = Tensor([[10.0, -10.0, -10.0], [-10.0, -10.0, 10.0]])  # Confident but wrong\n",
    "    wrong_targets = Tensor([1, 1])  # Opposite of confident predictions\n",
    "    wrong_loss = loss_fn.forward(wrong_logits, wrong_targets)\n",
    "    assert wrong_loss.data > 5.0, f\"Wrong confident predictions should have high loss, got {wrong_loss.data}\"\n",
    "\n",
    "    # Test numerical stability with large logits\n",
    "    large_logits = Tensor([[100.0, 50.0, 25.0]])\n",
    "    large_targets = Tensor([0])\n",
    "    large_loss = loss_fn.forward(large_logits, large_targets)\n",
    "    assert not np.isnan(large_loss.data), \"Loss should not be NaN with large logits\"\n",
    "    assert not np.isinf(large_loss.data), \"Loss should not be infinite with large logits\"\n",
    "\n",
    "    print(\"✅ CrossEntropyLoss works correctly!\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    test_unit_cross_entropy_loss()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e54d58b6",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## BinaryCrossEntropyLoss - Measuring Yes/No Decision Quality\n",
    "\n",
    "Binary Cross-Entropy is specialized for yes/no decisions. It's like regular cross-entropy but optimized for the special case of exactly two classes.\n",
    "\n",
    "### When to Use Binary Cross-Entropy\n",
    "\n",
    "**Perfect for:**\n",
    "- Spam detection (spam vs not spam)\n",
    "- Medical diagnosis (disease vs healthy)\n",
    "- Fraud detection (fraud vs legitimate)\n",
    "- Content moderation (toxic vs safe)\n",
    "- Any two-class decision problem\n",
    "\n",
    "### Understanding Binary Cross-Entropy\n",
    "\n",
    "```\n",
    "Binary Classification Decision Matrix:\n",
    "\n",
    "                 TRUE LABEL\n",
    "              Positive  Negative\n",
    "PREDICTED  P    TP       FP     ← Model says \"Yes\"\n",
    "           N    FN       TN     ← Model says \"No\"\n",
    "\n",
    "BCE Loss for each quadrant:\n",
    "- True Positive (TP): -log(prediction)     ← Reward confident correct \"Yes\"\n",
    "- False Positive (FP): -log(1-prediction) ← Punish confident wrong \"Yes\"\n",
    "- False Negative (FN): -log(prediction)   ← Punish confident wrong \"No\"\n",
    "- True Negative (TN): -log(1-prediction)  ← Reward confident correct \"No\"\n",
    "```\n",
    "\n",
    "### Binary Cross-Entropy Behavior Examples\n",
    "\n",
    "```\n",
    "Scenario: Spam Detection\n",
    "\n",
    "Case 1: Perfect Spam Detection\n",
    "Email: \"Buy now! 50% off! Limited time!\"\n",
    "Model Prediction: 0.99 (99% spam probability)\n",
    "True Label: 1 (actually spam)\n",
    "Loss: -log(0.99) = 0.01  ← Very low loss ✅\n",
    "\n",
    "Case 2: Uncertain About Spam\n",
    "Email: \"Meeting rescheduled to 2pm\"\n",
    "Model Prediction: 0.51 (slightly thinks spam)\n",
    "True Label: 0 (actually not spam)\n",
    "Loss: -log(1-0.51) = -log(0.49) = 0.71  ← Moderate loss\n",
    "\n",
    "Case 3: Confident Wrong Prediction\n",
    "Email: \"Hi mom, how are you?\"\n",
    "Model Prediction: 0.95 (very confident spam)\n",
    "True Label: 0 (actually not spam)\n",
    "Loss: -log(1-0.95) = -log(0.05) = 3.0  ← High loss ❌\n",
    "```\n",
    "\n",
    "### Binary vs Multi-Class Cross-Entropy\n",
    "\n",
    "```\n",
    "Binary Cross-Entropy:              Regular Cross-Entropy:\n",
    "\n",
    "Single probability output         Probability distribution output\n",
    "Predict: 0.8 (spam prob)         Predict: [0.1, 0.8, 0.1] (3 classes)\n",
    "Target: 1.0 (is spam)            Target: 1 (class index)\n",
    "\n",
    "Formula:                         Formula:\n",
    "-[y*log(p) + (1-y)*log(1-p)]    -log(p[target_class])\n",
    "\n",
    "Handles class imbalance well     Assumes balanced classes\n",
    "Optimized for 2-class case      General for N classes\n",
    "```\n",
    "\n",
    "### Why Binary Cross-Entropy is Special\n",
    "\n",
    "1. **Symmetric penalties**: False positives and false negatives treated equally\n",
    "2. **Probability calibration**: Output directly interpretable as probability\n",
    "3. **Efficient computation**: Simpler than full softmax for binary cases\n",
    "4. **Medical-grade**: Well-suited for safety-critical binary decisions\n",
    "\n",
    "### Loss Landscape Visualization\n",
    "\n",
    "```\n",
    "Binary Cross-Entropy Loss Surface:\n",
    "\n",
    "     Loss\n",
    "      ^\n",
    "   10 |*                    *     ← Wrong confident predictions\n",
    "      ||\n",
    "    5 | *                 *\n",
    "      |  \\\\               /\n",
    "    2 |   *             *          ← Uncertain predictions\n",
    "      |    \\\\           /\n",
    "    0 |_____*_______*_____> Prediction\n",
    "      0    0.2     0.8    1.0\n",
    "\n",
    "      Target = 1.0 (positive class)\n",
    "\n",
    "Message: \"Be confident about positive class, uncertain is okay,\n",
    "         but don't be confident about wrong class!\"\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8bad6550",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": false,
     "grade_id": "binary_cross_entropy_loss",
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "#| export\n",
    "class BinaryCrossEntropyLoss:\n",
    "    \"\"\"Binary cross-entropy loss for binary classification.\"\"\"\n",
    "\n",
    "    def __init__(self):\n",
    "        \"\"\"Initialize binary cross-entropy loss function.\"\"\"\n",
    "        pass\n",
    "\n",
    "    def forward(self, predictions: Tensor, targets: Tensor) -> Tensor:\n",
    "        \"\"\"\n",
    "        Compute binary cross-entropy loss.\n",
    "\n",
    "        TODO: Implement binary cross-entropy with numerical stability\n",
    "\n",
    "        APPROACH:\n",
    "        1. Clamp predictions to avoid log(0) and log(1)\n",
    "        2. Compute: -(targets * log(predictions) + (1-targets) * log(1-predictions))\n",
    "        3. Return mean across all samples\n",
    "\n",
    "        EXAMPLE:\n",
    "        >>> loss_fn = BinaryCrossEntropyLoss()\n",
    "        >>> predictions = Tensor([0.9, 0.1, 0.7, 0.3])  # Probabilities between 0 and 1\n",
    "        >>> targets = Tensor([1.0, 0.0, 1.0, 0.0])      # Binary labels\n",
    "        >>> loss = loss_fn(predictions, targets)\n",
    "        >>> print(f\"Binary Cross-Entropy Loss: {loss.data:.4f}\")\n",
    "\n",
    "        HINTS:\n",
    "        - Use np.clip(predictions.data, 1e-7, 1-1e-7) to prevent log(0)\n",
    "        - Binary cross-entropy: -(targets * log(preds) + (1-targets) * log(1-preds))\n",
    "        - Use np.mean() to average over all samples\n",
    "        \"\"\"\n",
    "        ### BEGIN SOLUTION\n",
    "        # Step 1: Clamp predictions to avoid numerical issues with log(0) and log(1)\n",
    "        eps = 1e-7\n",
    "        clamped_preds = np.clip(predictions.data, eps, 1 - eps)\n",
    "\n",
    "        # Step 2: Compute binary cross-entropy\n",
    "        # BCE = -(targets * log(preds) + (1-targets) * log(1-preds))\n",
    "        log_preds = np.log(clamped_preds)\n",
    "        log_one_minus_preds = np.log(1 - clamped_preds)\n",
    "\n",
    "        bce_per_sample = -(targets.data * log_preds + (1 - targets.data) * log_one_minus_preds)\n",
    "\n",
    "        # Step 3: Return mean across all samples\n",
    "        bce_loss = np.mean(bce_per_sample)\n",
    "\n",
    "        return Tensor(bce_loss)\n",
    "        ### END SOLUTION\n",
    "\n",
    "    def __call__(self, predictions: Tensor, targets: Tensor) -> Tensor:\n",
    "        \"\"\"Allows the loss function to be called like a function.\"\"\"\n",
    "        return self.forward(predictions, targets)\n",
    "\n",
    "    def backward(self) -> Tensor:\n",
    "        \"\"\"\n",
    "        Compute gradients (implemented in Module 05: Autograd).\n",
    "\n",
    "        For now, this is a stub that students can ignore.\n",
    "        \"\"\"\n",
    "        pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "466f02ef",
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "test_binary_cross_entropy_loss",
     "locked": true,
     "points": 10
    }
   },
   "outputs": [],
   "source": [
    "def test_unit_binary_cross_entropy_loss():\n",
    "    \"\"\"🔬 Test BinaryCrossEntropyLoss implementation and properties.\"\"\"\n",
    "    print(\"🔬 Unit Test: Binary Cross-Entropy Loss...\")\n",
    "\n",
    "    loss_fn = BinaryCrossEntropyLoss()\n",
    "\n",
    "    # Test perfect predictions\n",
    "    perfect_predictions = Tensor([0.9999, 0.0001, 0.9999, 0.0001])\n",
    "    targets = Tensor([1.0, 0.0, 1.0, 0.0])\n",
    "    perfect_loss = loss_fn.forward(perfect_predictions, targets)\n",
    "    assert perfect_loss.data < 0.01, f\"Perfect predictions should have very low loss, got {perfect_loss.data}\"\n",
    "\n",
    "    # Test worst predictions\n",
    "    worst_predictions = Tensor([0.0001, 0.9999, 0.0001, 0.9999])\n",
    "    worst_targets = Tensor([1.0, 0.0, 1.0, 0.0])\n",
    "    worst_loss = loss_fn.forward(worst_predictions, worst_targets)\n",
    "    assert worst_loss.data > 5.0, f\"Worst predictions should have high loss, got {worst_loss.data}\"\n",
    "\n",
    "    # Test uniform predictions (probability = 0.5)\n",
    "    uniform_predictions = Tensor([0.5, 0.5, 0.5, 0.5])\n",
    "    uniform_targets = Tensor([1.0, 0.0, 1.0, 0.0])\n",
    "    uniform_loss = loss_fn.forward(uniform_predictions, uniform_targets)\n",
    "    expected_uniform = -np.log(0.5)  # Should be about 0.693\n",
    "    assert np.allclose(uniform_loss.data, expected_uniform, atol=0.01), f\"Uniform predictions should have loss ≈ {expected_uniform:.3f}, got {uniform_loss.data:.3f}\"\n",
    "\n",
    "    # Test numerical stability at boundaries\n",
    "    boundary_predictions = Tensor([0.0, 1.0, 0.0, 1.0])\n",
    "    boundary_targets = Tensor([0.0, 1.0, 1.0, 0.0])\n",
    "    boundary_loss = loss_fn.forward(boundary_predictions, boundary_targets)\n",
    "    assert not np.isnan(boundary_loss.data), \"Loss should not be NaN at boundaries\"\n",
    "    assert not np.isinf(boundary_loss.data), \"Loss should not be infinite at boundaries\"\n",
    "\n",
    "    print(\"✅ BinaryCrossEntropyLoss works correctly!\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    test_unit_binary_cross_entropy_loss()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6bda8cd8",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "# Part 4: Integration - Bringing It Together\n",
    "\n",
    "Now let's test how our loss functions work together with real data scenarios and explore their behavior with different types of predictions.\n",
    "\n",
    "## Real-World Loss Function Usage Patterns\n",
    "\n",
    "Understanding when and why to use each loss function is crucial for ML engineering success:\n",
    "\n",
    "```\n",
    "Problem Type Decision Tree:\n",
    "\n",
    "What are you predicting?\n",
    "         │\n",
    "    ┌────┼────┐\n",
    "    │         │\n",
    "Continuous   Categorical\n",
    " Values       Classes\n",
    "    │         │\n",
    "    │    ┌───┼───┐\n",
    "    │    │       │\n",
    "    │   2 Classes  3+ Classes\n",
    "    │       │       │\n",
    " MSELoss   BCE Loss  CE Loss\n",
    "\n",
    "Examples:\n",
    "MSE: House prices, temperature, stock values\n",
    "BCE: Spam detection, fraud detection, medical diagnosis\n",
    "CE:  Image classification, language modeling, multiclass text classification\n",
    "```\n",
    "\n",
    "## Loss Function Behavior Comparison\n",
    "\n",
    "Each loss function creates different learning pressures on your model:\n",
    "\n",
    "```\n",
    "Error Sensitivity Comparison:\n",
    "\n",
    "Small Error (0.1):     Medium Error (0.5):     Large Error (2.0):\n",
    "\n",
    "MSE:     0.01         MSE:     0.25           MSE:     4.0\n",
    "BCE:     0.11         BCE:     0.69           BCE:     ∞ (clips to large)\n",
    "CE:      0.11         CE:      0.69           CE:      ∞ (clips to large)\n",
    "\n",
    "MSE: Quadratic growth, manageable with outliers\n",
    "BCE/CE: Logarithmic growth, explodes with confident wrong predictions\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6ce8804e",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "loss_comparison",
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "def compare_loss_behaviors():\n",
    "    \"\"\"\n",
    "    🔬 Compare how different loss functions behave with various prediction patterns.\n",
    "\n",
    "    This helps students understand when to use each loss function.\n",
    "    \"\"\"\n",
    "    print(\"🔬 Integration Test: Loss Function Behavior Comparison...\")\n",
    "\n",
    "    # Initialize loss functions\n",
    "    mse_loss = MSELoss()\n",
    "    ce_loss = CrossEntropyLoss()\n",
    "    bce_loss = BinaryCrossEntropyLoss()\n",
    "\n",
    "    print(\"\\n1. Regression Scenario (House Price Prediction)\")\n",
    "    print(\"   Predictions: [200k, 250k, 300k], Targets: [195k, 260k, 290k]\")\n",
    "    house_pred = Tensor([200.0, 250.0, 300.0])  # In thousands\n",
    "    house_target = Tensor([195.0, 260.0, 290.0])\n",
    "    mse = mse_loss.forward(house_pred, house_target)\n",
    "    print(f\"   MSE Loss: {mse.data:.2f} (thousand²)\")\n",
    "\n",
    "    print(\"\\n2. Multi-Class Classification (Image Recognition)\")\n",
    "    print(\"   Classes: [cat, dog, bird], Predicted: confident about cat, uncertain about dog\")\n",
    "    # Logits: [2.0, 0.5, 0.1] suggests model is most confident about class 0 (cat)\n",
    "    image_logits = Tensor([[2.0, 0.5, 0.1], [0.3, 1.8, 0.2]])  # Two samples\n",
    "    image_targets = Tensor([0, 1])  # First is cat (0), second is dog (1)\n",
    "    ce = ce_loss.forward(image_logits, image_targets)\n",
    "    print(f\"   Cross-Entropy Loss: {ce.data:.3f}\")\n",
    "\n",
    "    print(\"\\n3. Binary Classification (Spam Detection)\")\n",
    "    print(\"   Predictions: [0.9, 0.1, 0.7, 0.3] (spam probabilities)\")\n",
    "    spam_pred = Tensor([0.9, 0.1, 0.7, 0.3])\n",
    "    spam_target = Tensor([1.0, 0.0, 1.0, 0.0])  # 1=spam, 0=not spam\n",
    "    bce = bce_loss.forward(spam_pred, spam_target)\n",
    "    print(f\"   Binary Cross-Entropy Loss: {bce.data:.3f}\")\n",
    "\n",
    "    print(\"\\n💡 Key Insights:\")\n",
    "    print(\"   - MSE penalizes large errors heavily (good for continuous values)\")\n",
    "    print(\"   - Cross-Entropy encourages confident correct predictions\")\n",
    "    print(\"   - Binary Cross-Entropy balances false positives and negatives\")\n",
    "\n",
    "    return mse.data, ce.data, bce.data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b8eedcdc",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "loss_sensitivity",
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "def analyze_loss_sensitivity():\n",
    "    \"\"\"\n",
    "    📊 Analyze how sensitive each loss function is to prediction errors.\n",
    "\n",
    "    This demonstrates the different error landscapes created by each loss.\n",
    "    \"\"\"\n",
    "    print(\"\\n📊 Analysis: Loss Function Sensitivity to Errors...\")\n",
    "\n",
    "    # Create a range of prediction errors for analysis\n",
    "    true_value = 1.0\n",
    "    predictions = np.linspace(0.1, 1.9, 50)  # From 0.1 to 1.9\n",
    "\n",
    "    # Initialize loss functions\n",
    "    mse_loss = MSELoss()\n",
    "    bce_loss = BinaryCrossEntropyLoss()\n",
    "\n",
    "    mse_losses = []\n",
    "    bce_losses = []\n",
    "\n",
    "    for pred in predictions:\n",
    "        # MSE analysis\n",
    "        pred_tensor = Tensor([pred])\n",
    "        target_tensor = Tensor([true_value])\n",
    "        mse = mse_loss.forward(pred_tensor, target_tensor)\n",
    "        mse_losses.append(mse.data)\n",
    "\n",
    "        # BCE analysis (clamp prediction to valid probability range)\n",
    "        clamped_pred = max(0.01, min(0.99, pred))\n",
    "        bce_pred_tensor = Tensor([clamped_pred])\n",
    "        bce_target_tensor = Tensor([1.0])  # Target is \"positive class\"\n",
    "        bce = bce_loss.forward(bce_pred_tensor, bce_target_tensor)\n",
    "        bce_losses.append(bce.data)\n",
    "\n",
    "    # Find minimum losses\n",
    "    min_mse_idx = np.argmin(mse_losses)\n",
    "    min_bce_idx = np.argmin(bce_losses)\n",
    "\n",
    "    print(f\"MSE Loss:\")\n",
    "    print(f\"  Minimum at prediction = {predictions[min_mse_idx]:.2f}, loss = {mse_losses[min_mse_idx]:.4f}\")\n",
    "    print(f\"  At prediction = 0.5: loss = {mse_losses[24]:.4f}\")  # Middle of range\n",
    "    print(f\"  At prediction = 0.1: loss = {mse_losses[0]:.4f}\")\n",
    "\n",
    "    print(f\"\\nBinary Cross-Entropy Loss:\")\n",
    "    print(f\"  Minimum at prediction = {predictions[min_bce_idx]:.2f}, loss = {bce_losses[min_bce_idx]:.4f}\")\n",
    "    print(f\"  At prediction = 0.5: loss = {bce_losses[24]:.4f}\")\n",
    "    print(f\"  At prediction = 0.1: loss = {bce_losses[0]:.4f}\")\n",
    "\n",
    "    print(f\"\\n💡 Sensitivity Insights:\")\n",
    "    print(\"   - MSE grows quadratically with error distance\")\n",
    "    print(\"   - BCE grows logarithmically, heavily penalizing wrong confident predictions\")\n",
    "    print(\"   - Both encourage correct predictions but with different curvatures\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f3e45511",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "# Part 5: Systems Analysis - Understanding Loss Function Performance\n",
    "\n",
    "Loss functions seem simple, but they have important computational and numerical properties that affect training performance. Let's analyze the systems aspects.\n",
    "\n",
    "## Computational Complexity Analysis\n",
    "\n",
    "Different loss functions have different computational costs, especially at scale:\n",
    "\n",
    "```\n",
    "Computational Cost Comparison (Batch Size B, Classes C):\n",
    "\n",
    "MSELoss:\n",
    "┌───────────────┬───────────────┐\n",
    "│ Operation      │ Complexity     │\n",
    "├───────────────┼───────────────┤\n",
    "│ Subtraction    │ O(B)           │\n",
    "│ Squaring       │ O(B)           │\n",
    "│ Mean           │ O(B)           │\n",
    "│ Total          │ O(B)           │\n",
    "└───────────────┴───────────────┘\n",
    "\n",
    "CrossEntropyLoss:\n",
    "┌───────────────┬───────────────┐\n",
    "│ Operation      │ Complexity     │\n",
    "├───────────────┼───────────────┤\n",
    "│ Max (stability)│ O(B*C)         │\n",
    "│ Exponential    │ O(B*C)         │\n",
    "│ Sum            │ O(B*C)         │\n",
    "│ Log            │ O(B)           │\n",
    "│ Indexing       │ O(B)           │\n",
    "│ Total          │ O(B*C)         │\n",
    "└───────────────┴───────────────┘\n",
    "\n",
    "Cross-entropy is C times more expensive than MSE!\n",
    "For ImageNet (C=1000), CE is 1000x more expensive than MSE.\n",
    "```\n",
    "\n",
    "## Memory Layout and Access Patterns\n",
    "\n",
    "```\n",
    "Memory Usage Patterns:\n",
    "\n",
    "MSE Forward Pass:              CE Forward Pass:\n",
    "\n",
    "Input:  [B] predictions       Input:  [B, C] logits\n",
    "       │                             │\n",
    "       │ subtract                    │ subtract max\n",
    "       v                             v\n",
    "Temp:  [B] differences        Temp1: [B, C] shifted\n",
    "       │                             │\n",
    "       │ square                      │ exponential\n",
    "       v                             v\n",
    "Temp:  [B] squared            Temp2: [B, C] exp_vals\n",
    "       │                             │\n",
    "       │ mean                        │ sum along C\n",
    "       v                             v\n",
    "Output: [1] scalar            Temp3: [B] sums\n",
    "                                     │\n",
    "Memory: 3*B*sizeof(float)            │ log + index\n",
    "                                     v\n",
    "                              Output: [1] scalar\n",
    "\n",
    "                              Memory: (3*B*C + 2*B)*sizeof(float)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1fad470f",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "analyze_numerical_stability",
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "def analyze_numerical_stability():\n",
    "    \"\"\"\n",
    "    📊 Demonstrate why numerical stability matters in loss computation.\n",
    "\n",
    "    Shows the difference between naive and stable implementations.\n",
    "    \"\"\"\n",
    "    print(\"📊 Analysis: Numerical Stability in Loss Functions...\")\n",
    "\n",
    "    # Test with increasingly large logits\n",
    "    test_cases = [\n",
    "        (\"Small logits\", [1.0, 2.0, 3.0]),\n",
    "        (\"Medium logits\", [10.0, 20.0, 30.0]),\n",
    "        (\"Large logits\", [100.0, 200.0, 300.0]),\n",
    "        (\"Very large logits\", [500.0, 600.0, 700.0])\n",
    "    ]\n",
    "\n",
    "    print(\"\\nLog-Softmax Stability Test:\")\n",
    "    print(\"Case                 | Max Input | Log-Softmax Min | Numerically Stable?\")\n",
    "    print(\"-\" * 70)\n",
    "\n",
    "    for case_name, logits in test_cases:\n",
    "        x = Tensor([logits])\n",
    "\n",
    "        # Our stable implementation\n",
    "        stable_result = log_softmax(x, dim=-1)\n",
    "\n",
    "        max_input = np.max(logits)\n",
    "        min_output = np.min(stable_result.data)\n",
    "        is_stable = not (np.any(np.isnan(stable_result.data)) or np.any(np.isinf(stable_result.data)))\n",
    "\n",
    "        print(f\"{case_name:20} | {max_input:8.0f} | {min_output:15.3f} | {'✅ Yes' if is_stable else '❌ No'}\")\n",
    "\n",
    "    print(f\"\\n💡 Key Insight: Log-sum-exp trick prevents overflow\")\n",
    "    print(\"   Without it: exp(700) would cause overflow in standard softmax\")\n",
    "    print(\"   With it: We can handle arbitrarily large logits safely\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9b00d293",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "analyze_loss_memory",
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "def analyze_loss_memory():\n",
    "    \"\"\"\n",
    "    📊 Analyze memory usage patterns of different loss functions.\n",
    "\n",
    "    Understanding memory helps with batch size decisions.\n",
    "    \"\"\"\n",
    "    print(\"\\n📊 Analysis: Loss Function Memory Usage...\")\n",
    "\n",
    "    batch_sizes = [32, 128, 512, 1024]\n",
    "    num_classes = 1000  # Like ImageNet\n",
    "\n",
    "    print(\"\\nMemory Usage by Batch Size:\")\n",
    "    print(\"Batch Size | MSE (MB) | CrossEntropy (MB) | BCE (MB) | Notes\")\n",
    "    print(\"-\" * 75)\n",
    "\n",
    "    for batch_size in batch_sizes:\n",
    "        # Memory calculations (assuming float32 = 4 bytes)\n",
    "        bytes_per_float = 4\n",
    "\n",
    "        # MSE: predictions + targets (both same size as output)\n",
    "        mse_elements = batch_size * 1  # Regression usually has 1 output\n",
    "        mse_memory = mse_elements * bytes_per_float * 2 / 1e6  # Convert to MB\n",
    "\n",
    "        # CrossEntropy: logits + targets + softmax + log_softmax\n",
    "        ce_logits = batch_size * num_classes\n",
    "        ce_targets = batch_size * 1  # Target indices\n",
    "        ce_softmax = batch_size * num_classes  # Intermediate softmax\n",
    "        ce_total_elements = ce_logits + ce_targets + ce_softmax\n",
    "        ce_memory = ce_total_elements * bytes_per_float / 1e6\n",
    "\n",
    "        # BCE: predictions + targets (binary, so smaller)\n",
    "        bce_elements = batch_size * 1\n",
    "        bce_memory = bce_elements * bytes_per_float * 2 / 1e6\n",
    "\n",
    "        notes = \"Linear scaling\" if batch_size == 32 else f\"{batch_size//32}× first\"\n",
    "\n",
    "        print(f\"{batch_size:10} | {mse_memory:8.2f} | {ce_memory:13.2f} | {bce_memory:7.2f} | {notes}\")\n",
    "\n",
    "    print(f\"\\n💡 Memory Insights:\")\n",
    "    print(\"   - CrossEntropy dominates due to large vocabulary (num_classes)\")\n",
    "    print(\"   - Memory scales linearly with batch size\")\n",
    "    print(\"   - Intermediate activations (softmax) double CE memory\")\n",
    "    print(f\"   - For batch=1024, CE needs {ce_memory:.1f}MB just for loss computation\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d84d73d8",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "# Part 6: Production Context - How Loss Functions Scale\n",
    "\n",
    "Understanding how loss functions behave in production helps make informed engineering decisions about model architecture and training strategies.\n",
    "\n",
    "## Loss Function Scaling Challenges\n",
    "\n",
    "As models grow larger, loss function bottlenecks become critical:\n",
    "\n",
    "```\n",
    "Scaling Challenge Matrix:\n",
    "\n",
    "                    │ Small Model     │ Large Model      │ Production Scale\n",
    "                    │ (MNIST)         │ (ImageNet)       │ (GPT/BERT)\n",
    "────────────────────┼─────────────────┼──────────────────┼──────────────────\n",
    "Classes (C)         │ 10              │ 1,000            │ 50,000+\n",
    "Batch Size (B)      │ 64              │ 256              │ 2,048\n",
    "Memory (CE)         │ 2.5 KB          │ 1 MB             │ 400 MB\n",
    "Memory (MSE)        │ 0.25 KB         │ 1 KB             │ 8 KB\n",
    "Bottleneck          │ None            │ Softmax compute  │ Vocabulary memory\n",
    "\n",
    "Memory grows as B*C for cross-entropy!\n",
    "At scale, vocabulary (C) dominates everything.\n",
    "```\n",
    "\n",
    "## Engineering Optimizations in Production\n",
    "\n",
    "```\n",
    "Common Production Optimizations:\n",
    "\n",
    "1. Hierarchical Softmax:\n",
    "   ┌─────────────────┐\n",
    "   │ Full Softmax:      │\n",
    "   │ O(V) per sample    │  ┌─────────────────┐\n",
    "   │ 50k classes = 50k  │  │ Hierarchical:       │\n",
    "   │ operations         │  │ O(log V) per sample │\n",
    "   └─────────────────┘  │ 50k classes = 16   │\n",
    "                          │ operations         │\n",
    "                          └─────────────────┘\n",
    "\n",
    "2. Sampled Softmax:\n",
    "   Instead of computing over all 50k classes,\n",
    "   sample 1k negative classes + correct class.\n",
    "   50× speedup for training!\n",
    "\n",
    "3. Label Smoothing:\n",
    "   Instead of hard targets [0, 0, 1, 0],\n",
    "   use soft targets [0.1, 0.1, 0.7, 0.1].\n",
    "   Improves generalization.\n",
    "\n",
    "4. Mixed Precision:\n",
    "   Use FP16 for forward pass, FP32 for loss.\n",
    "   2× memory reduction, same accuracy.\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "828b26d1",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "analyze_production_patterns",
     "solution": true
    }
   },
   "outputs": [],
   "source": [
    "def analyze_production_patterns():\n",
    "    \"\"\"\n",
    "    🚀 Analyze loss function patterns in production ML systems.\n",
    "\n",
    "    Real insights from systems perspective.\n",
    "    \"\"\"\n",
    "    print(\"🚀 Production Analysis: Loss Function Engineering Patterns...\")\n",
    "\n",
    "    print(\"\\n1. Loss Function Choice by Problem Type:\")\n",
    "\n",
    "    scenarios = [\n",
    "        (\"Recommender Systems\", \"BCE/MSE\", \"User preference prediction\", \"Billions of interactions\"),\n",
    "        (\"Computer Vision\", \"CrossEntropy\", \"Image classification\", \"1000+ classes, large batches\"),\n",
    "        (\"NLP Translation\", \"CrossEntropy\", \"Next token prediction\", \"50k+ vocabulary\"),\n",
    "        (\"Medical Diagnosis\", \"BCE\", \"Disease probability\", \"Class imbalance critical\"),\n",
    "        (\"Financial Trading\", \"MSE/Huber\", \"Price prediction\", \"Outlier robustness needed\")\n",
    "    ]\n",
    "\n",
    "    print(\"System Type          | Loss Type    | Use Case              | Scale Challenge\")\n",
    "    print(\"-\" * 80)\n",
    "    for system, loss_type, use_case, challenge in scenarios:\n",
    "        print(f\"{system:20} | {loss_type:12} | {use_case:20} | {challenge}\")\n",
    "\n",
    "    print(\"\\n2. Engineering Trade-offs:\")\n",
    "\n",
    "    trade_offs = [\n",
    "        (\"CrossEntropy vs Label Smoothing\", \"Stability vs Confidence\", \"Label smoothing prevents overconfident predictions\"),\n",
    "        (\"MSE vs Huber Loss\", \"Sensitivity vs Robustness\", \"Huber is less sensitive to outliers\"),\n",
    "        (\"Full Softmax vs Sampled\", \"Accuracy vs Speed\", \"Hierarchical softmax for large vocabularies\"),\n",
    "        (\"Per-Sample vs Batch Loss\", \"Accuracy vs Memory\", \"Batch computation is more memory efficient\")\n",
    "    ]\n",
    "\n",
    "    print(\"\\nTrade-off                    | Spectrum              | Production Decision\")\n",
    "    print(\"-\" * 85)\n",
    "    for trade_off, spectrum, decision in trade_offs:\n",
    "        print(f\"{trade_off:28} | {spectrum:20} | {decision}\")\n",
    "\n",
    "    print(\"\\n💡 Production Insights:\")\n",
    "    print(\"   - Large vocabularies (50k+ tokens) dominate memory in CrossEntropy\")\n",
    "    print(\"   - Batch computation is 10-100× more efficient than per-sample\")\n",
    "    print(\"   - Numerical stability becomes critical at scale (FP16 training)\")\n",
    "    print(\"   - Loss computation is often <5% of total training time\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c2e05be0",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "## 🧪 Module Integration Test\n",
    "\n",
    "Final validation that everything works together correctly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94e3d5f7",
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "test_module",
     "locked": true,
     "points": 20
    }
   },
   "outputs": [],
   "source": [
    "def test_module():\n",
    "    \"\"\"\n",
    "    Comprehensive test of entire losses 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_log_softmax()\n",
    "    test_unit_mse_loss()\n",
    "    test_unit_cross_entropy_loss()\n",
    "    test_unit_binary_cross_entropy_loss()\n",
    "\n",
    "    print(\"\\nRunning integration scenarios...\")\n",
    "\n",
    "    # Test realistic end-to-end scenario with previous modules\n",
    "    print(\"🔬 Integration Test: Realistic training scenario...\")\n",
    "\n",
    "    # Simulate a complete prediction -> loss computation pipeline\n",
    "\n",
    "    # 1. MSE for regression (house price prediction)\n",
    "    house_predictions = Tensor([250.0, 180.0, 320.0, 400.0])  # Predicted prices in thousands\n",
    "    house_actual = Tensor([245.0, 190.0, 310.0, 420.0])       # Actual prices\n",
    "    mse_loss = MSELoss()\n",
    "    house_loss = mse_loss.forward(house_predictions, house_actual)\n",
    "    assert house_loss.data > 0, \"House price loss should be positive\"\n",
    "    assert house_loss.data < 1000, \"House price loss should be reasonable\"\n",
    "\n",
    "    # 2. CrossEntropy for classification (image recognition)\n",
    "    image_logits = Tensor([[2.1, 0.5, 0.3], [0.2, 2.8, 0.1], [0.4, 0.3, 2.2]])  # 3 images, 3 classes\n",
    "    image_labels = Tensor([0, 1, 2])  # Correct class for each image\n",
    "    ce_loss = CrossEntropyLoss()\n",
    "    image_loss = ce_loss.forward(image_logits, image_labels)\n",
    "    assert image_loss.data > 0, \"Image classification loss should be positive\"\n",
    "    assert image_loss.data < 5.0, \"Image classification loss should be reasonable\"\n",
    "\n",
    "    # 3. BCE for binary classification (spam detection)\n",
    "    spam_probabilities = Tensor([0.85, 0.12, 0.78, 0.23, 0.91])\n",
    "    spam_labels = Tensor([1.0, 0.0, 1.0, 0.0, 1.0])  # True spam labels\n",
    "    bce_loss = BinaryCrossEntropyLoss()\n",
    "    spam_loss = bce_loss.forward(spam_probabilities, spam_labels)\n",
    "    assert spam_loss.data > 0, \"Spam detection loss should be positive\"\n",
    "    assert spam_loss.data < 5.0, \"Spam detection loss should be reasonable\"\n",
    "\n",
    "    # 4. Test numerical stability with extreme values\n",
    "    extreme_logits = Tensor([[100.0, -100.0, 0.0]])\n",
    "    extreme_targets = Tensor([0])\n",
    "    extreme_loss = ce_loss.forward(extreme_logits, extreme_targets)\n",
    "    assert not np.isnan(extreme_loss.data), \"Loss should handle extreme values\"\n",
    "    assert not np.isinf(extreme_loss.data), \"Loss should not be infinite\"\n",
    "\n",
    "    print(\"✅ End-to-end loss computation works!\")\n",
    "    print(\"✅ All loss functions handle edge cases!\")\n",
    "    print(\"✅ Numerical stability verified!\")\n",
    "\n",
    "    print(\"\\n\" + \"=\" * 50)\n",
    "    print(\"🎉 ALL TESTS PASSED! Module ready for export.\")\n",
    "    print(\"Run: tito module complete 04\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dba6b8db",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Run comprehensive module test\n",
    "if __name__ == \"__main__\":\n",
    "    test_module()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4e80a940",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "## 🎯 MODULE SUMMARY: Losses\n",
    "\n",
    "Congratulations! You've built the measurement system that enables all machine learning!\n",
    "\n",
    "### Key Accomplishments\n",
    "- Built 3 essential loss functions: MSE, CrossEntropy, and BinaryCrossEntropy ✅\n",
    "- Implemented numerical stability with log-sum-exp trick ✅\n",
    "- Discovered memory scaling patterns with batch size and vocabulary ✅\n",
    "- Analyzed production trade-offs between different loss function choices ✅\n",
    "- All tests pass ✅ (validated by `test_module()`)\n",
    "\n",
    "### Ready for Next Steps\n",
    "Your loss functions provide the essential feedback signal for learning. These \"error measurements\" will become the starting point for backpropagation in Module 05!\n",
    "Export with: `tito module complete 04`\n",
    "\n",
    "**Next**: Module 05 will add automatic differentiation - the magic that computes how to improve predictions!"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
