{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7a01df11",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "# Layers - Building Blocks of Neural Networks\n",
    "\n",
    "Welcome to the Layers module! This is where we build the fundamental components that stack together to form neural networks. Every neural network you've ever heard of - from simple perceptrons to massive transformers like GPT - is built by stacking these basic building blocks.\n",
    "\n",
    "## Learning Goals\n",
    "- **Deep Mathematical Understanding**: Grasp how matrix multiplication powers all neural networks\n",
    "- **Implementation Mastery**: Build matrix multiplication and Dense layers from scratch\n",
    "- **Visual Intuition**: See how data flows and transforms through layers\n",
    "- **Production Connection**: Understand how this connects to PyTorch, TensorFlow, and industry ML\n",
    "- **Architecture Foundation**: Learn to compose layers into complex networks\n",
    "- **Parameter Strategies**: Master weight initialization and shape management\n",
    "\n",
    "## Build → Use → Understand\n",
    "1. **Build**: Matrix multiplication and Dense layers with complete understanding\n",
    "2. **Use**: Create and test layers with real data and visual examples\n",
    "3. **Understand**: How linear transformations enable universal function approximation\n",
    "\n",
    "## Why This Module Is Critical\n",
    "Layers are the **universal building blocks** of machine learning:\n",
    "- **Computer Vision**: CNNs stack convolutional layers\n",
    "- **Natural Language**: Transformers stack attention layers\n",
    "- **Reinforcement Learning**: Policy networks stack dense layers\n",
    "- **Generative AI**: All generative models use layer composition\n",
    "\n",
    "Mastering layers means understanding the foundation of all modern AI."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ecda552d",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "layers-imports",
     "locked": false,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "#| default_exp core.layers\n",
    "\n",
    "#| export\n",
    "import numpy as np\n",
    "import os\n",
    "import sys\n",
    "\n",
    "# Import our dependencies - try from package first, then local modules\n",
    "try:\n",
    "    from tinytorch.core.tensor import Tensor\n",
    "    from tinytorch.core.activations import ReLU, Sigmoid, Tanh, Softmax\n",
    "except ImportError:\n",
    "    # For development, import from local modules\n",
    "    sys.path.append(os.path.join(os.path.dirname(__file__), '..', '01_tensor'))\n",
    "    sys.path.append(os.path.join(os.path.dirname(__file__), '..', '02_activations'))\n",
    "    try:\n",
    "        from tensor_dev import Tensor\n",
    "        from activations_dev import ReLU, Sigmoid, Tanh, Softmax\n",
    "    except ImportError:\n",
    "        # If the local modules are not available, use relative imports\n",
    "        from ..tensor.tensor_dev import Tensor\n",
    "        from ..activations.activations_dev import ReLU, Sigmoid, Tanh, Softmax"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb83ad7e",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "layers-welcome",
     "locked": false,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "print(\"🔥 TinyTorch Layers Module\")\n",
    "print(f\"NumPy version: {np.__version__}\")\n",
    "print(f\"Python version: {sys.version_info.major}.{sys.version_info.minor}\")\n",
    "print(\"Ready to build neural network layers!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6d697ebd",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "## 📦 Where This Code Lives in the Final Package\n",
    "\n",
    "**Learning Side:** You work in `modules/source/03_layers/layers_dev.py`  \n",
    "**Building Side:** Code exports to `tinytorch.core.layers`\n",
    "\n",
    "```python\n",
    "# Final package structure:\n",
    "from tinytorch.core.layers import Dense, Conv2D  # All layer types together!\n",
    "from tinytorch.core.tensor import Tensor  # The foundation\n",
    "from tinytorch.core.activations import ReLU, Sigmoid  # Nonlinearity\n",
    "```\n",
    "\n",
    "**Why this matters:**\n",
    "- **Learning:** Focused modules for deep understanding\n",
    "- **Production:** Proper organization like PyTorch's `torch.nn.Linear`\n",
    "- **Consistency:** All layer types live together in `core.layers`\n",
    "- **Integration:** Works seamlessly with tensors and activations"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1a72f74",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "## The Deep Mathematics of Neural Network Layers\n",
    "\n",
    "### What Are Neural Network Layers?\n",
    "Layers are **learnable function approximators** - each layer is a mathematical transformation that:\n",
    "1. **Takes input data**: Raw features, pixels, words, or intermediate representations\n",
    "2. **Applies learned transformation**: Linear combinations followed by nonlinear activations\n",
    "3. **Produces useful representations**: Features that are better for the final task\n",
    "\n",
    "### The Universal Layer Pattern\n",
    "Every layer in every neural network follows this fundamental pattern:\n",
    "```python\n",
    "def universal_layer(x):\n",
    "    # 1. Linear transformation (learnable)\n",
    "    linear_output = x @ weights + bias\n",
    "    \n",
    "    # 2. Nonlinear activation (fixed function)\n",
    "    output = activation(linear_output)\n",
    "    \n",
    "    return output\n",
    "```\n",
    "\n",
    "### Why This Simple Pattern Works for Everything\n",
    "\n",
    "#### The Mathematical Miracle\n",
    "- **Linear part**: Learns weighted combinations of input features\n",
    "- **Nonlinear part**: Enables complex decision boundaries\n",
    "- **Stacking**: Creates arbitrarily complex function approximation\n",
    "- **Universal approximation**: Proven to approximate any continuous function\n",
    "\n",
    "#### Visual Understanding\n",
    "```\n",
    "Input Features    →  Linear Transform  →  Nonlinear Activation  →  Output Features\n",
    "[x1, x2, x3]         [w11 w12 w13]         ReLU/Sigmoid/Tanh       [y1, y2]\n",
    "                      [w21 w22 w23]\n",
    "                      [bias1, bias2]\n",
    "```\n",
    "\n",
    "### Mathematical Foundation: Function Composition\n",
    "A neural network is mathematical function composition:\n",
    "```\n",
    "f(x) = layer_n(layer_{n-1}(...layer_2(layer_1(x))))\n",
    "\n",
    "Where each layer_i(x) = activation(x @ W_i + b_i)\n",
    "```\n",
    "\n",
    "**Key insight**: Each layer learns to transform its input into a representation that makes the next layer's job easier.\n",
    "\n",
    "### Real-World Applications\n",
    "\n",
    "#### Computer Vision\n",
    "- **Layer 1**: Detects edges and textures\n",
    "- **Layer 2**: Combines edges into shapes\n",
    "- **Layer 3**: Combines shapes into objects\n",
    "- **Final Layer**: Maps objects to class labels\n",
    "\n",
    "#### Natural Language Processing\n",
    "- **Embedding Layer**: Maps words to vector representations\n",
    "- **Hidden Layers**: Learn syntactic and semantic patterns\n",
    "- **Output Layer**: Maps representations to predictions\n",
    "\n",
    "#### Scientific Computing\n",
    "- **Physics**: Learn differential equation solutions\n",
    "- **Chemistry**: Predict molecular properties\n",
    "- **Biology**: Model protein folding\n",
    "\n",
    "### What We'll Build Step by Step\n",
    "\n",
    "1. **Matrix Multiplication Engine**: The mathematical core powering all layers\n",
    "2. **Dense Layer Implementation**: The fundamental building block\n",
    "3. **Weight Initialization Strategies**: How to start learning effectively\n",
    "4. **Layer Composition Patterns**: Building complex architectures\n",
    "5. **Integration with Activations**: Creating complete neural network components\n",
    "6. **Production-Ready Implementation**: Code that scales to real applications\n",
    "\n",
    "### Why Understanding Layers Deeply Matters\n",
    "\n",
    "#### For ML Engineers\n",
    "- **Debugging**: Understand why networks fail to train\n",
    "- **Architecture Design**: Know when to use which layer types\n",
    "- **Performance Optimization**: Optimize for specific hardware\n",
    "\n",
    "#### For AI Researchers\n",
    "- **Novel Architectures**: Invent new layer types\n",
    "- **Theoretical Understanding**: Prove properties of neural networks\n",
    "- **Algorithmic Innovation**: Develop new training methods\n",
    "\n",
    "#### For Industry Applications\n",
    "- **Model Deployment**: Optimize for production environments\n",
    "- **Transfer Learning**: Adapt pre-trained layers to new tasks\n",
    "- **Custom Solutions**: Build domain-specific architectures"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f6209ffe",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "## 🔧 DEVELOPMENT"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f1ede17e",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## Step 1: Matrix Multiplication - The Mathematical Engine of All AI\n",
    "\n",
    "### The Foundation of Modern AI\n",
    "Matrix multiplication is the **single most important operation** in all of machine learning. Every neural network, from simple classifiers to GPT and ChatGPT, is fundamentally powered by this operation:\n",
    "\n",
    "```\n",
    "C = A @ B  # This simple operation powers all of AI\n",
    "```\n",
    "\n",
    "### Deep Mathematical Understanding\n",
    "\n",
    "#### The Core Operation\n",
    "For matrices A (m×n) and B (n×p), the result C (m×p) is:\n",
    "```\n",
    "C[i,j] = Σ(k=0 to n-1) A[i,k] * B[k,j]\n",
    "```\n",
    "\n",
    "**Physical interpretation**: Each output element is a **weighted sum** of input features.\n",
    "\n",
    "#### Visual Step-by-Step Breakdown\n",
    "```\n",
    "Matrix A (2×2)    Matrix B (2×2)    Result C (2×2)\n",
    "┌─────────┐      ┌─────────┐      ┌─────────┐\n",
    "│  1   2  │  @   │  5   6  │  =   │ 19  22  │\n",
    "│  3   4  │      │  7   8  │      │ 43  50  │\n",
    "└─────────┘      └─────────┘      └─────────┘\n",
    "\n",
    "Step-by-step computation:\n",
    "C[0,0] = A[0,0]*B[0,0] + A[0,1]*B[1,0] = 1*5 + 2*7 = 5 + 14 = 19\n",
    "C[0,1] = A[0,0]*B[0,1] + A[0,1]*B[1,1] = 1*6 + 2*8 = 6 + 16 = 22\n",
    "C[1,0] = A[1,0]*B[0,0] + A[1,1]*B[1,0] = 3*5 + 4*7 = 15 + 28 = 43\n",
    "C[1,1] = A[1,0]*B[0,1] + A[1,1]*B[1,1] = 3*6 + 4*8 = 18 + 32 = 50\n",
    "```\n",
    "\n",
    "#### Neural Network Interpretation\n",
    "```\n",
    "Input Data        Weight Matrix     Output Features\n",
    "(batch × in)   @   (in × out)   =   (batch × out)\n",
    "┌─────────────┐   ┌─────────────┐   ┌─────────────┐\n",
    "│ sample 1    │   │ feature     │   │transformed  │\n",
    "│ sample 2    │ @ │ weights     │ = │features     │\n",
    "│    ...      │   │    ...      │   │    ...      │\n",
    "│ sample n    │   │             │   │             │\n",
    "└─────────────┘   └─────────────┘   └─────────────┘\n",
    "```\n",
    "\n",
    "### Why Matrix Multiplication Powers All AI\n",
    "\n",
    "#### 1. Feature Combination\n",
    "Each output is a **learned combination** of all input features:\n",
    "```\n",
    "output[i] = w1*input[0] + w2*input[1] + ... + wn*input[n-1]\n",
    "```\n",
    "The weights determine **which features matter** and **how they combine**.\n",
    "\n",
    "#### 2. Parallel Processing\n",
    "- **CPU vectorization**: Process multiple elements simultaneously\n",
    "- **GPU acceleration**: Thousands of cores compute matrix operations\n",
    "- **TPU optimization**: Specialized hardware for matrix computations\n",
    "\n",
    "#### 3. Mathematical Elegance\n",
    "- **Differentiable**: Gradients flow cleanly through matrix operations\n",
    "- **Composable**: Matrix operations stack naturally\n",
    "- **Expressive**: Can represent any linear transformation\n",
    "\n",
    "### Real-World Applications Powered by Matrix Multiplication\n",
    "\n",
    "#### Large Language Models (GPT, ChatGPT)\n",
    "```\n",
    "Attention(Q,K,V) = softmax(QK^T/√d)V  # Three matrix multiplications!\n",
    "```\n",
    "- **Q @ K^T**: Compute attention scores between all word pairs\n",
    "- **Attention @ V**: Weight and combine value vectors\n",
    "- **Linear layers**: Transform representations at each layer\n",
    "\n",
    "#### Computer Vision (ResNet, Vision Transformers)\n",
    "```\n",
    "Convolution ≈ Matrix Multiplication  # Convolution can be expressed as matrix ops\n",
    "```\n",
    "- **Feature maps**: Each filter creates a feature map via matrix operations\n",
    "- **Classification**: Final features → class logits via matrix multiplication\n",
    "- **Object detection**: Bounding box regression via matrix operations\n",
    "\n",
    "#### Recommendation Systems\n",
    "```\n",
    "User-Item Matrix @ Item-Feature Matrix = User-Feature Preferences\n",
    "```\n",
    "- **Collaborative filtering**: User similarity via matrix operations\n",
    "- **Content-based**: Feature matching via matrix computations\n",
    "- **Deep models**: Neural collaborative filtering via matrix layers\n",
    "\n",
    "### Performance Considerations\n",
    "\n",
    "#### Why We Use NumPy (and why GPUs exist)\n",
    "```\n",
    "# Naive Python loops: ~10 seconds for large matrices\n",
    "for i in range(m):\n",
    "    for j in range(p):\n",
    "        for k in range(n):\n",
    "            C[i,j] += A[i,k] * B[k,j]\n",
    "\n",
    "# NumPy (optimized C): ~0.01 seconds for same matrices\n",
    "C = A @ B\n",
    "\n",
    "# GPU (CUDA): ~0.001 seconds for same matrices\n",
    "C = torch.matmul(A_gpu, B_gpu)\n",
    "```\n",
    "\n",
    "#### Memory and Computation Complexity\n",
    "- **Memory**: O(mn + np + mp) to store three matrices\n",
    "- **Computation**: O(mnp) multiply-add operations\n",
    "- **For large models**: Billions of parameters × billions of operations\n",
    "\n",
    "### Debugging Matrix Multiplication\n",
    "\n",
    "#### Common Shape Errors\n",
    "```\n",
    "A.shape = (batch_size, input_features)     # e.g., (32, 784)\n",
    "B.shape = (input_features, output_features) # e.g., (784, 10)\n",
    "C.shape = (batch_size, output_features)     # result: (32, 10)\n",
    "\n",
    "# COMMON ERROR:\n",
    "A.shape = (32, 784)\n",
    "B.shape = (10, 784)  # Wrong! Should be (784, 10)\n",
    "# Error: Cannot multiply (32, 784) @ (10, 784)\n",
    "```\n",
    "\n",
    "#### Visual Debugging Technique\n",
    "```\n",
    "Always check: A's last dimension == B's first dimension\n",
    "              (m, n) @ (n, p) = (m, p) ✓\n",
    "              (m, n) @ (k, p) = ERROR if n ≠ k\n",
    "```\n",
    "\n",
    "### Connection to Production ML Systems\n",
    "\n",
    "#### PyTorch Implementation\n",
    "```python\n",
    "# Your implementation (educational)\n",
    "result = matmul(A, B)\n",
    "\n",
    "# PyTorch (production)\n",
    "result = torch.matmul(A, B)  # Optimized, GPU-accelerated\n",
    "result = A @ B               # Same operation\n",
    "```\n",
    "\n",
    "#### TensorFlow Implementation\n",
    "```python\n",
    "# Your implementation (educational)\n",
    "result = matmul(A, B)\n",
    "\n",
    "# TensorFlow (production)\n",
    "result = tf.matmul(A, B)     # Optimized, distributed computing\n",
    "result = A @ B               # Same operation\n",
    "```\n",
    "\n",
    "### Why Implement It Ourselves?\n",
    "1. **Deep Understanding**: See exactly what happens in each operation\n",
    "2. **Debugging Skills**: Understand why shape errors occur\n",
    "3. **Performance Intuition**: Appreciate why GPUs are essential\n",
    "4. **Algorithm Design**: Know how to optimize for specific use cases\n",
    "5. **Research Foundation**: Basis for developing new layer types"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "747fde13",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": false,
     "grade_id": "matmul-naive",
     "locked": false,
     "schema_version": 3,
     "solution": true,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "#| export\n",
    "def matmul(A: np.ndarray, B: np.ndarray) -> np.ndarray:\n",
    "    \"\"\"\n",
    "    Matrix multiplication using explicit for-loops for deep understanding.\n",
    "    \n",
    "    This implementation reveals the mathematical essence of neural networks!\n",
    "    Every time a neural network processes data, it's doing exactly this operation.\n",
    "        \n",
    "    TODO: Implement matrix multiplication using three nested for-loops.\n",
    "    \n",
    "    APPROACH:\n",
    "    1. Extract and validate matrix dimensions\n",
    "    2. Initialize result matrix with zeros\n",
    "    3. Implement the triple-nested loop structure\n",
    "    4. Accumulate dot products for each output element\n",
    "    \n",
    "    MATHEMATICAL FOUNDATION:\n",
    "    For C = A @ B, each element C[i,j] is the dot product of:\n",
    "    - Row i from matrix A: [A[i,0], A[i,1], ..., A[i,n-1]]\n",
    "    - Column j from matrix B: [B[0,j], B[1,j], ..., B[n-1,j]]\n",
    "    \n",
    "    VISUAL STEP-BY-STEP:\n",
    "    ```\n",
    "    A = [[1, 2],     B = [[5, 6],     C = [[?, ?],\n",
    "         [3, 4]]          [7, 8]]          [?, ?]]\n",
    "    \n",
    "    Computing C[0,0] (row 0 of A, column 0 of B):\n",
    "    A[0,:] = [1, 2]  ←→  B[:,0] = [5, 7]\n",
    "    C[0,0] = 1*5 + 2*7 = 5 + 14 = 19\n",
    "    \n",
    "    Computing C[0,1] (row 0 of A, column 1 of B):\n",
    "    A[0,:] = [1, 2]  ←→  B[:,1] = [6, 8]\n",
    "    C[0,1] = 1*6 + 2*8 = 6 + 16 = 22\n",
    "    \n",
    "    Computing C[1,0] (row 1 of A, column 0 of B):\n",
    "    A[1,:] = [3, 4]  ←→  B[:,0] = [5, 7]\n",
    "    C[1,0] = 3*5 + 4*7 = 15 + 28 = 43\n",
    "    \n",
    "    Computing C[1,1] (row 1 of A, column 1 of B):\n",
    "    A[1,:] = [3, 4]  ←→  B[:,1] = [6, 8]\n",
    "    C[1,1] = 3*6 + 4*8 = 18 + 32 = 50\n",
    "    \n",
    "    Final result: C = [[19, 22], [43, 50]]\n",
    "    ```\n",
    "    \n",
    "    IMPLEMENTATION ALGORITHM:\n",
    "    ```python\n",
    "    # 1. Get dimensions and validate\n",
    "    m, n = A.shape          # A is m×n\n",
    "    n2, p = B.shape         # B is n×p (n2 must equal n)\n",
    "    assert n == n2          # Inner dimensions must match\n",
    "    \n",
    "    # 2. Initialize result matrix\n",
    "    C = zeros(m, p)         # Result is m×p\n",
    "    \n",
    "    # 3. Triple nested loops\n",
    "    for i in range(m):      # For each row of A\n",
    "        for j in range(p):  # For each column of B\n",
    "            for k in range(n):  # For each element in dot product\n",
    "                C[i,j] += A[i,k] * B[k,j]  # Accumulate\n",
    "    ```\n",
    "    \n",
    "    NEURAL NETWORK CONNECTION:\n",
    "    In a neural network layer:\n",
    "    - A = input batch (batch_size × input_features)\n",
    "    - B = weight matrix (input_features × output_features)\n",
    "    - C = output batch (batch_size × output_features)\n",
    "    \n",
    "    Each C[i,j] represents how much output feature j is activated for input sample i.\n",
    "    \n",
    "    DEBUGGING HINTS:\n",
    "    - Check shapes: A.shape = (m,n), B.shape = (n,p) → C.shape = (m,p)\n",
    "    - Common error: Swapping B's dimensions (should be input_features × output_features)\n",
    "    - Accumulation: Start with C[i,j] = 0, then add all A[i,k] * B[k,j]\n",
    "    - Index bounds: i ∈ [0,m), j ∈ [0,p), k ∈ [0,n)\n",
    "    \n",
    "    PERFORMANCE NOTE:\n",
    "    This implementation is O(mnp) time complexity and helps you understand:\n",
    "    - Why GPUs are essential for deep learning (parallelizable operations)\n",
    "    - Why NumPy/BLAS libraries are much faster (optimized C/Fortran)\n",
    "    - How memory access patterns affect performance\n",
    "    \n",
    "    LEARNING CONNECTIONS:\n",
    "    - Foundation of ALL neural network computations\n",
    "    - Understanding enables debugging shape mismatches\n",
    "    - Basis for implementing custom layer types\n",
    "    - Essential for optimizing model performance\n",
    "    - Connects to linear algebra theory\n",
    "    \"\"\"\n",
    "    ### BEGIN SOLUTION\n",
    "    # Get matrix dimensions\n",
    "    m, n = A.shape\n",
    "    n2, p = B.shape\n",
    "    \n",
    "    # Check compatibility\n",
    "    if n != n2:\n",
    "        raise ValueError(f\"Incompatible matrix dimensions: A is {m}x{n}, B is {n2}x{p}\")\n",
    "    \n",
    "    # Initialize result matrix\n",
    "    C = np.zeros((m, p))\n",
    "    \n",
    "    # Triple nested loop for matrix multiplication\n",
    "    for i in range(m):\n",
    "        for j in range(p):\n",
    "            for k in range(n):\n",
    "                C[i, j] += A[i, k] * B[k, j]\n",
    "    \n",
    "    return C\n",
    "    ### END SOLUTION"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7adfdec3",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### 🧪 Test Your Matrix Multiplication\n",
    "\n",
    "Once you implement the `matmul` function above, run this cell to test it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cce7880b",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": true,
     "grade_id": "test-matmul-immediate",
     "locked": true,
     "points": 10,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "def test_unit_matrix_multiplication():\n",
    "    \"\"\"Test matrix multiplication implementation\"\"\"\n",
    "    print(\"🔬 Unit Test: Matrix Multiplication...\")\n",
    "\n",
    "# Test simple 2x2 case\n",
    "    A = np.array([[1, 2], [3, 4]], dtype=np.float32)\n",
    "    B = np.array([[5, 6], [7, 8]], dtype=np.float32)\n",
    "    \n",
    "    result = matmul(A, B)\n",
    "    expected = np.array([[19, 22], [43, 50]], dtype=np.float32)\n",
    "    \n",
    "    assert np.allclose(result, expected), f\"Matrix multiplication failed: expected {expected}, got {result}\"\n",
    "    \n",
    "    # Compare with NumPy\n",
    "    numpy_result = A @ B\n",
    "    assert np.allclose(result, numpy_result), f\"Doesn't match NumPy: got {result}, expected {numpy_result}\"\n",
    "\n",
    "# Test different shapes\n",
    "    A2 = np.array([[1, 2, 3]], dtype=np.float32)  # 1x3\n",
    "    B2 = np.array([[4], [5], [6]], dtype=np.float32)  # 3x1\n",
    "    result2 = matmul(A2, B2)\n",
    "    expected2 = np.array([[32]], dtype=np.float32)  # 1*4 + 2*5 + 3*6 = 32\n",
    "    \n",
    "    assert np.allclose(result2, expected2), f\"1x3 @ 3x1 failed: expected {expected2}, got {result2}\"\n",
    "    \n",
    "    # Test 3x3 case\n",
    "    A3 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32)\n",
    "    B3 = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=np.float32)  # Identity\n",
    "    result3 = matmul(A3, B3)\n",
    "    \n",
    "    assert np.allclose(result3, A3), \"Multiplication by identity should preserve matrix\"\n",
    "    \n",
    "    # Test incompatible shapes\n",
    "    A4 = np.array([[1, 2]], dtype=np.float32)  # 1x2\n",
    "    B4 = np.array([[3], [4], [5]], dtype=np.float32)  # 3x1\n",
    "    \n",
    "    try:\n",
    "        matmul(A4, B4)\n",
    "        assert False, \"Should raise error for incompatible shapes\"\n",
    "    except ValueError as e:\n",
    "        assert \"Incompatible matrix dimensions\" in str(e)\n",
    "    \n",
    "    print(\"✅ Matrix multiplication tests passed!\")\n",
    "    print(f\"✅ 2x2 multiplication working correctly\")\n",
    "    print(f\"✅ Matches NumPy's implementation\")\n",
    "    print(f\"✅ Handles different shapes correctly\")\n",
    "    print(f\"✅ Proper error handling for incompatible shapes\")\n",
    "\n",
    "# Test function defined (called in main block)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ca716326",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "### 🎯 CHECKPOINT: Matrix Multiplication Mastery\n",
    "\n",
    "You've just implemented the mathematical engine that powers ALL neural networks! \n",
    "\n",
    "#### What You've Accomplished\n",
    "✅ **Deep Understanding**: You now understand exactly what happens inside every neural network layer  \n",
    "✅ **Implementation Skills**: You can build matrix operations from mathematical first principles  \n",
    "✅ **Debugging Abilities**: You understand why shape mismatches occur and how to fix them  \n",
    "✅ **Performance Intuition**: You appreciate why GPUs and optimized libraries are essential  \n",
    "\n",
    "#### Mathematical Concepts Mastered\n",
    "- **Dot Products**: The fundamental operation combining features with weights\n",
    "- **Shape Compatibility**: Understanding when matrices can be multiplied\n",
    "- **Computational Complexity**: O(mnp) operations for (m×n) @ (n×p) matrices\n",
    "- **Memory Layout**: How data flows through matrix operations\n",
    "\n",
    "#### Real-World Connection\n",
    "Your implementation does exactly what happens inside:\n",
    "- **PyTorch**: `torch.matmul(A, B)` uses the same mathematical principles\n",
    "- **TensorFlow**: `tf.matmul(A, B)` performs identical operations\n",
    "- **NumPy**: `A @ B` follows the same algorithm (just optimized in C)\n",
    "\n",
    "#### Ready for Next Step\n",
    "With matrix multiplication mastered, you're ready to build Dense layers - the fundamental building blocks that stack together to create all neural networks!\n",
    "\n",
    "**Key insight**: Every time you see `layer(x)` in any neural network, you now know it's doing matrix multiplication under the hood."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee28a59f",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## Step 2: Dense Layer - The Foundation of All Neural Networks\n",
    "\n",
    "### What is a Dense Layer?\n",
    "A **Dense layer** (also called Linear or Fully Connected layer) is the fundamental building block that appears in EVERY neural network architecture ever created:\n",
    "\n",
    "```python\n",
    "output = input @ weights + bias\n",
    "```\n",
    "\n",
    "This simple equation powers:\n",
    "- **GPT and language models**: Transform text representations\n",
    "- **ResNet and vision models**: Classify image features\n",
    "- **Recommendation systems**: Map user preferences\n",
    "- **Scientific AI**: Model physical phenomena\n",
    "\n",
    "### The Mathematical Miracle of Dense Layers\n",
    "\n",
    "#### Universal Function Approximation\n",
    "Dense layers have a **mathematically proven superpower**: Stack enough of them with nonlinear activations, and they can approximate **any continuous function**!\n",
    "\n",
    "```python\n",
    "# This can learn ANY pattern:\n",
    "f(x) = dense_n(activation(dense_{n-1}(...activation(dense_1(x)))))\n",
    "```\n",
    "\n",
    "#### Why This Works\n",
    "```\n",
    "Linear Transformation + Nonlinear Activation = Universal Expressiveness\n",
    "```\n",
    "\n",
    "1. **Linear part (y = xW + b)**: Learns feature combinations\n",
    "2. **Nonlinear activation**: Enables complex decision boundaries\n",
    "3. **Stacking**: Creates arbitrarily complex functions\n",
    "\n",
    "### Deep Mathematical Understanding\n",
    "\n",
    "#### The Linear Transformation Matrix\n",
    "```\n",
    "Input Features    Weight Matrix      Output Features\n",
    "┌─────────────┐  ┌─────────────────┐  ┌─────────────┐\n",
    "│ pixel_1     │  │ w₁₁  w₁₂  w₁₃ │  │ feature_1   │\n",
    "│ pixel_2     │  │ w₂₁  w₂₂  w₂₃ │  │ feature_2   │\n",
    "│ pixel_3     │  │ w₃₁  w₃₂  w₃₃ │  │ feature_3   │\n",
    "│    ...      │  │  ⋮    ⋮    ⋮  │  │    ...      │\n",
    "│ pixel_784   │  │ w₇₈₄₁ ... w₇₈₄₃│  │             │\n",
    "└─────────────┘  └─────────────────┘  └─────────────┘\n",
    "(784 features)    (784 × 3 weights)    (3 features)\n",
    "```\n",
    "\n",
    "**Key insight**: Each output feature is a **learned combination** of ALL input features.\n",
    "\n",
    "#### Weight Interpretation\n",
    "Each weight w[i,j] represents:\n",
    "- **How much input feature i contributes to output feature j**\n",
    "- **Positive weights**: Input increases output\n",
    "- **Negative weights**: Input decreases output\n",
    "- **Large weights**: Strong influence\n",
    "- **Small weights**: Weak influence\n",
    "\n",
    "#### Bias Terms\n",
    "```\n",
    "Without bias: y = xW     (line through origin)\n",
    "With bias:    y = xW + b (line can be shifted)\n",
    "```\n",
    "\n",
    "Bias allows the layer to **shift its output**, enabling:\n",
    "- **Better fit**: Not forced through origin\n",
    "- **Increased expressiveness**: More flexible transformations\n",
    "- **Faster training**: Better starting point\n",
    "\n",
    "### Real-World Architecture Patterns\n",
    "\n",
    "#### Computer Vision\n",
    "```python\n",
    "# Image classification pipeline\n",
    "image → flatten → dense(784→512) → relu → dense(512→10) → softmax\n",
    "#                 ↑ Feature extraction    ↑ Classification\n",
    "```\n",
    "\n",
    "#### Natural Language Processing\n",
    "```python\n",
    "# Text classification pipeline\n",
    "text → embed → dense(300→128) → tanh → dense(128→2) → sigmoid\n",
    "#              ↑ Representation learning  ↑ Binary classification\n",
    "```\n",
    "\n",
    "#### Generative Models\n",
    "```python\n",
    "# VAE decoder\n",
    "noise → dense(100→256) → relu → dense(256→784) → sigmoid → image\n",
    "#       ↑ Expand latent code    ↑ Generate pixels\n",
    "```\n",
    "\n",
    "### Weight Initialization: The Science of Starting Right\n",
    "\n",
    "#### Why Initialization Matters\n",
    "```\n",
    "Poor initialization → Vanishing/exploding gradients → Training failure\n",
    "Good initialization → Stable gradients → Successful training\n",
    "```\n",
    "\n",
    "#### Xavier/Glorot Initialization\n",
    "```python\n",
    "scale = sqrt(2 / (input_size + output_size))\n",
    "weights ~ Normal(0, scale²)\n",
    "```\n",
    "\n",
    "**Mathematical motivation**: Preserves activation variance across layers.\n",
    "\n",
    "#### Alternative Strategies\n",
    "```python\n",
    "# He initialization (better for ReLU)\n",
    "scale = sqrt(2 / input_size)\n",
    "\n",
    "# LeCun initialization (for SELU)\n",
    "scale = sqrt(1 / input_size)\n",
    "\n",
    "# Uniform Xavier\n",
    "limit = sqrt(6 / (input_size + output_size))\n",
    "weights ~ Uniform(-limit, limit)\n",
    "```\n",
    "\n",
    "### Production System Comparison\n",
    "\n",
    "#### PyTorch Dense Layer\n",
    "```python\n",
    "# Your implementation\n",
    "layer = Dense(input_size=784, output_size=10)\n",
    "\n",
    "# PyTorch equivalent\n",
    "layer = torch.nn.Linear(in_features=784, out_features=10)\n",
    "\n",
    "# Identical mathematical operation!\n",
    "output = layer(input)  # y = xW^T + b (note: PyTorch transposes W)\n",
    "```\n",
    "\n",
    "#### TensorFlow Dense Layer\n",
    "```python\n",
    "# Your implementation\n",
    "layer = Dense(input_size=784, output_size=10)\n",
    "\n",
    "# TensorFlow equivalent\n",
    "layer = tf.keras.layers.Dense(units=10, input_shape=(784,))\n",
    "\n",
    "# Same mathematical operation!\n",
    "output = layer(input)  # y = xW + b\n",
    "```\n",
    "\n",
    "### Memory and Computational Complexity\n",
    "\n",
    "#### Parameter Count\n",
    "```\n",
    "Parameters = input_size × output_size + output_size (if bias)\n",
    "Example: Dense(784, 512) has 784 × 512 + 512 = 401,920 parameters\n",
    "```\n",
    "\n",
    "#### Computational Complexity\n",
    "```\n",
    "FLOPs per sample = 2 × input_size × output_size\n",
    "Example: Dense(784, 512) requires 2 × 784 × 512 = 802,816 operations\n",
    "```\n",
    "\n",
    "#### Memory Usage\n",
    "```\n",
    "Memory = (batch_size × input_size × 4) +     # Input (float32)\n",
    "         (input_size × output_size × 4) +   # Weights\n",
    "         (output_size × 4) +               # Bias\n",
    "         (batch_size × output_size × 4)    # Output\n",
    "```\n",
    "\n",
    "### Design Philosophy\n",
    "\n",
    "#### When to Use Dense Layers\n",
    "- **Always**: As final classification/regression layers\n",
    "- **Often**: For combining features from other layer types\n",
    "- **Sometimes**: As hidden layers in simple architectures\n",
    "- **Rarely**: For processing raw high-dimensional data (use CNN/RNN instead)\n",
    "\n",
    "#### Architecture Decisions\n",
    "```python\n",
    "# Width vs Depth trade-off\n",
    "Wide: Dense(1000, 2000)     # More parameters, might overfit\n",
    "Deep: Dense(1000, 500) → Dense(500, 250) → Dense(250, 125)  # More layers\n",
    "\n",
    "# Rule of thumb: Start simple, add complexity as needed\n",
    "```\n",
    "\n",
    "### Connection to Advanced Architectures\n",
    "\n",
    "#### Attention Mechanisms\n",
    "```python\n",
    "# Multi-head attention uses THREE dense layers\n",
    "Q = dense_q(x)  # Query projection\n",
    "K = dense_k(x)  # Key projection\n",
    "V = dense_v(x)  # Value projection\n",
    "attention = softmax(QK^T/√d) @ V\n",
    "```\n",
    "\n",
    "#### Residual Connections\n",
    "```python\n",
    "# ResNet block with dense layers\n",
    "def residual_dense_block(x):\n",
    "    residual = x\n",
    "    x = dense1(x)\n",
    "    x = activation(x)\n",
    "    x = dense2(x)\n",
    "    return x + residual  # Skip connection\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2c4a9d60",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": false,
     "grade_id": "dense-layer",
     "locked": false,
     "schema_version": 3,
     "solution": true,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "#| export\n",
    "class Dense:\n",
    "    \"\"\"\n",
    "    Dense (Linear/Fully Connected) Layer\n",
    "    \n",
    "    Applies a linear transformation: y = xW + b\n",
    "    \n",
    "    This is the fundamental building block of neural networks.\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self, input_size: int, output_size: int, use_bias: bool = True):\n",
    "        \"\"\"\n",
    "        Initialize Dense layer with random weights and optional bias.\n",
    "        \n",
    "        This initialization is CRITICAL for successful neural network training!\n",
    "        Poor initialization can cause vanishing/exploding gradients and training failure.\n",
    "        \n",
    "        TODO: Implement Dense layer initialization with proper weight scaling.\n",
    "        \n",
    "        APPROACH:\n",
    "        1. Store layer configuration parameters\n",
    "        2. Initialize weights using Xavier/Glorot strategy\n",
    "        3. Initialize bias terms (typically zeros)\n",
    "        4. Convert arrays to Tensor objects for compatibility\n",
    "        \n",
    "        WEIGHT INITIALIZATION DEEP DIVE:\n",
    "        \n",
    "        Why Random Initialization?\n",
    "        - Breaks symmetry: All neurons start different\n",
    "        - Enables learning: Gradients won't be identical\n",
    "        - Avoids dead neurons: Some neurons activate from start\n",
    "        \n",
    "        Xavier/Glorot Initialization Strategy:\n",
    "        ```\n",
    "        scale = sqrt(2 / (input_size + output_size))\n",
    "        weights ~ Normal(0, scale²)\n",
    "        ```\n",
    "        \n",
    "        Mathematical Justification:\n",
    "        - Maintains activation variance across layers\n",
    "        - Prevents vanishing/exploding gradients\n",
    "        - Empirically proven to improve training\n",
    "        \n",
    "        VISUAL INITIALIZATION PATTERN:\n",
    "        ```\n",
    "        Input Layer (3 neurons)    Dense Layer (2 neurons)\n",
    "        ┌─────┐                   ┌─────┐\n",
    "        │ x₁  │ ──w₁₁──→         │ y₁  │\n",
    "        │     │    \\\\              │     │\n",
    "        │ x₂  │ ──w₂₁─w₂₂──→     │ y₂  │\n",
    "        │     │    /              │     │\n",
    "        │ x₃  │ ──w₃₁──→         │     │\n",
    "        └─────┘   +b₁   +b₂      └─────┘\n",
    "        \n",
    "        Weight Matrix W (3×2):     Bias Vector b (2×1):\n",
    "        ┌──────────────┐          ┌────┐\n",
    "        │ w₁₁   w₁₂   │          │ b₁ │\n",
    "        │ w₂₁   w₂₂   │          │ b₂ │\n",
    "        │ w₃₁   w₃₂   │          └────┘\n",
    "        └──────────────┘\n",
    "        ```\n",
    "        \n",
    "        EXAMPLE INITIALIZATION:\n",
    "        ```python\n",
    "        layer = Dense(input_size=784, output_size=10)  # MNIST classifier\n",
    "        # Weight shape: (784, 10) - each output connects to all inputs\n",
    "        # Bias shape: (10,) - one bias per output neuron\n",
    "        # Scale: sqrt(2/(784+10)) ≈ 0.05 - prevents gradients from exploding\n",
    "        ```\n",
    "        \n",
    "        IMPLEMENTATION STEPS:\n",
    "        ```python\n",
    "        # 1. Store configuration\n",
    "        self.input_size = input_size      # Number of input features\n",
    "        self.output_size = output_size    # Number of output neurons\n",
    "        self.use_bias = use_bias          # Whether to include bias terms\n",
    "        \n",
    "        # 2. Calculate Xavier scale\n",
    "        scale = np.sqrt(2.0 / (input_size + output_size))\n",
    "        \n",
    "        # 3. Initialize weights (shape matters!)\n",
    "        weight_data = np.random.randn(input_size, output_size) * scale\n",
    "        \n",
    "        # 4. Initialize bias (usually zeros)\n",
    "        if use_bias:\n",
    "            bias_data = np.zeros(output_size)\n",
    "        \n",
    "        # 5. Convert to Tensors\n",
    "        self.weights = Tensor(weight_data)\n",
    "        self.bias = Tensor(bias_data) if use_bias else None\n",
    "        ```\n",
    "        \n",
    "        ALTERNATIVE INITIALIZATION STRATEGIES:\n",
    "        \n",
    "        He Initialization (better for ReLU):\n",
    "        ```python\n",
    "        scale = np.sqrt(2.0 / input_size)  # Only input size\n",
    "        ```\n",
    "        \n",
    "        Uniform Xavier:\n",
    "        ```python\n",
    "        limit = np.sqrt(6.0 / (input_size + output_size))\n",
    "        weights = np.random.uniform(-limit, limit, (input_size, output_size))\n",
    "        ```\n",
    "        \n",
    "        COMMON INITIALIZATION MISTAKES:\n",
    "        1. **All zeros**: No learning (dead neurons)\n",
    "        2. **Too large**: Exploding gradients\n",
    "        3. **Too small**: Vanishing gradients\n",
    "        4. **Wrong shape**: Broadcasting errors\n",
    "        5. **Same values**: Symmetry problem\n",
    "        \n",
    "        PRODUCTION SYSTEM COMPARISON:\n",
    "        ```python\n",
    "        # Your implementation\n",
    "        layer = Dense(input_size, output_size)\n",
    "        \n",
    "        # PyTorch equivalent\n",
    "        layer = torch.nn.Linear(input_size, output_size)\n",
    "        # Uses Kaiming uniform initialization by default\n",
    "        \n",
    "        # TensorFlow equivalent\n",
    "        layer = tf.keras.layers.Dense(output_size, input_shape=(input_size,))\n",
    "        # Uses Glorot uniform initialization by default\n",
    "        ```\n",
    "        \n",
    "        DEBUGGING HINTS:\n",
    "        - Print weight statistics: mean ≈ 0, std ≈ scale\n",
    "        - Check shapes: weights (input_size, output_size), bias (output_size,)\n",
    "        - Verify Tensor conversion: isinstance(self.weights, Tensor)\n",
    "        - Test forward pass: no shape errors\n",
    "        \n",
    "        LEARNING CONNECTIONS:\n",
    "        - Foundation for all layer types (Conv2D, LSTM, Attention)\n",
    "        - Understanding gradients and backpropagation\n",
    "        - Basis for transfer learning (loading pre-trained weights)\n",
    "        - Essential for model architecture design\n",
    "        \"\"\"\n",
    "        ### BEGIN SOLUTION\n",
    "        # Store layer parameters\n",
    "        self.input_size = input_size\n",
    "        self.output_size = output_size\n",
    "        self.use_bias = use_bias\n",
    "        \n",
    "        # Xavier/Glorot initialization\n",
    "        scale = np.sqrt(2.0 / (input_size + output_size))\n",
    "        \n",
    "        # Initialize weights with random values\n",
    "        weight_data = np.random.randn(input_size, output_size) * scale\n",
    "        self.weights = Tensor(weight_data)\n",
    "        \n",
    "        # Initialize bias\n",
    "        if use_bias:\n",
    "            bias_data = np.zeros(output_size)\n",
    "            self.bias = Tensor(bias_data)\n",
    "        else:\n",
    "            self.bias = None\n",
    "        ### END SOLUTION\n",
    "    \n",
    "    def forward(self, x):\n",
    "        \"\"\"\n",
    "        Forward pass through the Dense layer: the heart of neural computation.\n",
    "        \n",
    "        This function implements y = xW + b, the fundamental equation that powers\n",
    "        all neural networks from simple perceptrons to massive transformers!\n",
    "        \n",
    "        TODO: Implement the forward pass with proper shape handling.\n",
    "        \n",
    "        APPROACH:\n",
    "        1. Apply matrix multiplication for feature combination\n",
    "        2. Add bias terms for output shifting\n",
    "        3. Return properly shaped Tensor result\n",
    "        4. Handle batch processing automatically\n",
    "        \n",
    "        MATHEMATICAL FOUNDATION:\n",
    "        \n",
    "        The Linear Transformation:\n",
    "        ```\n",
    "        y = xW + b\n",
    "        \n",
    "        Where:\n",
    "        x: Input features    (batch_size × input_features)\n",
    "        W: Weight matrix     (input_features × output_features)\n",
    "        b: Bias vector       (output_features,)\n",
    "        y: Output features   (batch_size × output_features)\n",
    "        ```\n",
    "        \n",
    "        VISUAL DATA FLOW:\n",
    "        ```\n",
    "        Input Batch          Weight Matrix        Bias Vector       Output Batch\n",
    "        ┌─────────────┐     ┌─────────────┐     ┌─────────┐      ┌─────────────┐\n",
    "        │ [x₁₁ x₁₂]  │     │ [w₁₁ w₁₂]  │     │ [b₁ b₂] │      │ [y₁₁ y₁₂]  │\n",
    "        │ [x₂₁ x₂₂]  │  @  │ [w₂₁ w₂₂]  │  +  │         │  =   │ [y₂₁ y₂₂]  │\n",
    "        │ [x₃₁ x₃₂]  │     └─────────────┘     └─────────┘      │ [y₃₁ y₃₂]  │\n",
    "        └─────────────┘                                          └─────────────┘\n",
    "        (3×2)              (2×2)              (2,)              (3×2)\n",
    "        ```\n",
    "        \n",
    "        STEP-BY-STEP COMPUTATION:\n",
    "        \n",
    "        For each output element y[i,j]:\n",
    "        ```\n",
    "        y[i,j] = Σₖ x[i,k] * W[k,j] + b[j]\n",
    "        \n",
    "        Example:\n",
    "        x = [[1, 2]]        # 1 sample, 2 features\n",
    "        W = [[0.5, 0.3],    # 2 input → 2 output\n",
    "             [0.7, 0.4]]\n",
    "        b = [0.1, 0.2]      # bias for each output\n",
    "        \n",
    "        y[0,0] = x[0,0]*W[0,0] + x[0,1]*W[1,0] + b[0]\n",
    "               = 1*0.5 + 2*0.7 + 0.1 = 0.5 + 1.4 + 0.1 = 2.0\n",
    "        \n",
    "        y[0,1] = x[0,0]*W[0,1] + x[0,1]*W[1,1] + b[1]\n",
    "               = 1*0.3 + 2*0.4 + 0.2 = 0.3 + 0.8 + 0.2 = 1.3\n",
    "        \n",
    "        Result: y = [[2.0, 1.3]]\n",
    "        ```\n",
    "        \n",
    "        BATCH PROCESSING MAGIC:\n",
    "        The same operation works for ANY batch size:\n",
    "        ```\n",
    "        Single sample:  (1, features) @ (features, outputs) = (1, outputs)\n",
    "        Mini-batch:     (32, features) @ (features, outputs) = (32, outputs)\n",
    "        Large batch:    (1000, features) @ (features, outputs) = (1000, outputs)\n",
    "        ```\n",
    "        \n",
    "        IMPLEMENTATION DETAILS:\n",
    "        ```python\n",
    "        # 1. Matrix multiplication (the core operation)\n",
    "        linear_output = matmul(x.data, self.weights.data)\n",
    "        \n",
    "        # 2. Bias addition (broadcasting handles shape automatically)\n",
    "        if self.use_bias and self.bias is not None:\n",
    "            linear_output = linear_output + self.bias.data\n",
    "            # Broadcasting: (batch_size, output_features) + (output_features,)\n",
    "            #            → (batch_size, output_features)\n",
    "        \n",
    "        # 3. Return as proper Tensor type\n",
    "        return type(x)(linear_output)  # Preserves Tensor class\n",
    "        ```\n",
    "        \n",
    "        BROADCASTING EXPLANATION:\n",
    "        NumPy automatically broadcasts the bias:\n",
    "        ```\n",
    "        linear_output.shape = (batch_size, output_features)  # e.g., (32, 10)\n",
    "        bias.shape         = (output_features,)             # e.g., (10,)\n",
    "        \n",
    "        # Broadcasting adds bias to each sample:\n",
    "        result[i,j] = linear_output[i,j] + bias[j]  # for all i\n",
    "        ```\n",
    "        \n",
    "        REAL-WORLD APPLICATIONS:\n",
    "        \n",
    "        Image Classification:\n",
    "        ```\n",
    "        # Flatten image: (28, 28) → (784,)\n",
    "        # Dense layer: (784,) → (10,) class scores\n",
    "        x = flattened_image  # Shape: (batch, 784)\n",
    "        scores = dense_layer(x)  # Shape: (batch, 10)\n",
    "        ```\n",
    "        \n",
    "        Language Model:\n",
    "        ```\n",
    "        # Word embedding: word_id → dense vector\n",
    "        # Dense layer: hidden → vocabulary scores\n",
    "        x = hidden_state  # Shape: (batch, hidden_size)\n",
    "        logits = output_layer(x)  # Shape: (batch, vocab_size)\n",
    "        ```\n",
    "        \n",
    "        COMMON SHAPE ERRORS AND SOLUTIONS:\n",
    "        ```\n",
    "        Error: \"Cannot multiply (32, 784) and (10, 784)\"\n",
    "        Solution: Weight shape should be (784, 10), not (10, 784)\n",
    "        \n",
    "        Error: \"Cannot add (32, 10) and (784,)\"\n",
    "        Solution: Bias shape should be (10,), not (784,)\n",
    "        \n",
    "        Error: \"Expected 2D input, got 1D\"\n",
    "        Solution: Reshape input from (features,) to (1, features)\n",
    "        ```\n",
    "        \n",
    "        DEBUGGING CHECKLIST:\n",
    "        - Input shape: (batch_size, input_features)\n",
    "        - Weight shape: (input_features, output_features)\n",
    "        - Bias shape: (output_features,) or None\n",
    "        - Output shape: (batch_size, output_features)\n",
    "        \n",
    "        PERFORMANCE NOTES:\n",
    "        - Matrix multiplication is O(batch × input × output)\n",
    "        - Most computation time spent here in large models\n",
    "        - GPU acceleration crucial for large layers\n",
    "        - Memory usage: store input, weights, bias, output\n",
    "        \n",
    "        LEARNING CONNECTIONS:\n",
    "        - Foundation of backpropagation (gradients flow through this operation)\n",
    "        - Basis for all advanced layer types (attention, convolution)\n",
    "        - Understanding enables custom layer development\n",
    "        - Critical for model optimization and deployment\n",
    "        \"\"\"\n",
    "        ### BEGIN SOLUTION\n",
    "        # Perform matrix multiplication\n",
    "        linear_output = matmul(x.data, self.weights.data)\n",
    "        \n",
    "        # Add bias if present\n",
    "        if self.use_bias and self.bias is not None:\n",
    "            linear_output = linear_output + self.bias.data\n",
    "        \n",
    "        return type(x)(linear_output)\n",
    "        ### END SOLUTION\n",
    "    \n",
    "    def __call__(self, x):\n",
    "        \"\"\"Make the layer callable: layer(x) instead of layer.forward(x)\"\"\"\n",
    "        return self.forward(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a2541988",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### 🧪 Test Your Dense Layer\n",
    "\n",
    "Once you implement the Dense layer above, run this cell to test it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "277f1d8c",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": true,
     "grade_id": "test-dense-layer",
     "locked": true,
     "points": 15,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "def test_unit_dense_layer():\n",
    "    \"\"\"Test Dense layer implementation\"\"\"\n",
    "    print(\"🔬 Unit Test: Dense Layer...\")\n",
    "    \n",
    "    # Test layer creation\n",
    "    layer = Dense(input_size=3, output_size=2)\n",
    "    \n",
    "    # Check weight and bias shapes\n",
    "    assert layer.weights.shape == (3, 2), f\"Weight shape should be (3, 2), got {layer.weights.shape}\"\n",
    "    assert layer.bias is not None, \"Bias should not be None when use_bias=True\"\n",
    "    assert layer.bias.shape == (2,), f\"Bias shape should be (2,), got {layer.bias.shape}\"\n",
    "    \n",
    "    # Test forward pass\n",
    "    input_data = Tensor([[1, 2, 3]])  # Shape: (1, 3)\n",
    "    output = layer(input_data)\n",
    "    \n",
    "    # Check output shape\n",
    "    assert output.shape == (1, 2), f\"Output shape should be (1, 2), got {output.shape}\"\n",
    "    \n",
    "    # Test batch processing\n",
    "    batch_input = Tensor([[1, 2, 3], [4, 5, 6]])  # Shape: (2, 3)\n",
    "    batch_output = layer(batch_input)\n",
    "    \n",
    "    assert batch_output.shape == (2, 2), f\"Batch output shape should be (2, 2), got {batch_output.shape}\"\n",
    "\n",
    "# Test without bias\n",
    "    no_bias_layer = Dense(input_size=3, output_size=2, use_bias=False)\n",
    "    assert no_bias_layer.bias is None, \"Layer without bias should have None bias\"\n",
    "    \n",
    "    no_bias_output = no_bias_layer(input_data)\n",
    "    assert no_bias_output.shape == (1, 2), \"No-bias layer should still produce correct shape\"\n",
    "    \n",
    "    # Test that different inputs produce different outputs\n",
    "    input1 = Tensor([[1, 0, 0]])\n",
    "    input2 = Tensor([[0, 1, 0]])\n",
    "    \n",
    "    output1 = layer(input1)\n",
    "    output2 = layer(input2)\n",
    "    \n",
    "    # Should not be equal (with high probability due to random initialization)\n",
    "    assert not np.allclose(output1.data, output2.data), \"Different inputs should produce different outputs\"\n",
    "    \n",
    "    # Test linearity property: layer(a*x) = a*layer(x)\n",
    "    scale = 2.0\n",
    "    scaled_input = Tensor([[2, 4, 6]])  # 2 * [1, 2, 3]\n",
    "    scaled_output = layer(scaled_input)\n",
    "    \n",
    "    # Due to bias, this won't be exactly 2*output, but the linear part should scale\n",
    "    print(\"✅ Dense layer tests passed!\")\n",
    "    print(f\"✅ Correct weight and bias initialization\")\n",
    "    print(f\"✅ Forward pass produces correct shapes\")\n",
    "    print(f\"✅ Batch processing works correctly\")\n",
    "    print(f\"✅ Bias and no-bias variants work\")\n",
    "    print(f\"✅ Naive matrix multiplication option works\")\n",
    "\n",
    "# Test function defined (called in main block)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f793e702",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "### 🎯 CHECKPOINT: Dense Layer Implementation Complete\n",
    "\n",
    "Congratulations! You've just implemented the fundamental building block of all neural networks!\n",
    "\n",
    "#### What You've Accomplished\n",
    "✅ **Dense Layer Mastery**: You can now build the core component of every neural network  \n",
    "✅ **Weight Initialization**: You understand how to start training with proper parameter scaling  \n",
    "✅ **Shape Management**: You handle batch processing and broadcasting automatically  \n",
    "✅ **Production-Ready Code**: Your implementation matches PyTorch and TensorFlow standards  \n",
    "\n",
    "#### Mathematical Concepts Mastered\n",
    "- **Linear Transformations**: y = xW + b is now deeply understood\n",
    "- **Parameter Initialization**: Xavier/Glorot scaling for stable gradients\n",
    "- **Broadcasting**: Automatic shape handling for bias addition\n",
    "- **Batch Processing**: Same operation works for any batch size\n",
    "\n",
    "#### Real-World Impact\n",
    "Your Dense layer implementation enables:\n",
    "- **Image Classification**: Transform pixel features to class predictions\n",
    "- **Language Models**: Map word embeddings to vocabulary scores\n",
    "- **Recommendation Systems**: Learn user-item preference mappings\n",
    "- **Scientific Computing**: Model complex physical phenomena\n",
    "\n",
    "#### Connection to Advanced AI\n",
    "Every advanced architecture uses your Dense layer:\n",
    "- **Transformers (GPT)**: Attention layers are built from Dense layers\n",
    "- **ResNets**: Skip connections combine with Dense layers\n",
    "- **GANs**: Both generator and discriminator use Dense layers\n",
    "- **VAEs**: Encoder and decoder networks built from Dense layers\n",
    "\n",
    "#### Ready for Integration\n",
    "With Dense layers mastered, you're ready to see how they combine with activation functions to create complete neural network components that can learn any pattern!\n",
    "\n",
    "**Key insight**: You now understand the mathematical foundation of all modern AI systems."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8c0d4c3",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## Step 3: Layer Integration with Activations - Building Complete Neural Networks\n",
    "\n",
    "### The Magic of Layer + Activation Composition\n",
    "Now we combine Dense layers with activation functions to create complete neural network components that can learn ANY pattern! This is where the true power of neural networks emerges.\n",
    "\n",
    "### The Universal Neural Network Building Block\n",
    "```python\n",
    "# This pattern appears in EVERY neural network:\n",
    "def neural_component(x):\n",
    "    # 1. Linear transformation (learnable)\n",
    "    linear_output = dense_layer(x)\n",
    "    \n",
    "    # 2. Nonlinear activation (fixed function)\n",
    "    final_output = activation_function(linear_output)\n",
    "    \n",
    "    return final_output\n",
    "```\n",
    "\n",
    "### Why This Simple Pattern Enables Universal Learning\n",
    "\n",
    "#### Mathematical Foundation\n",
    "```\n",
    "f(x) = activation(xW + b)\n",
    "```\n",
    "\n",
    "This combination provides:\n",
    "- **Linear part**: Learns optimal feature combinations\n",
    "- **Nonlinear part**: Enables complex decision boundaries\n",
    "- **Composability**: Stacks to approximate any function\n",
    "\n",
    "#### Visual Understanding of Layer + Activation\n",
    "```\n",
    "Input → Dense Layer → Activation → Output\n",
    "┌─────┐   ┌─────────┐   ┌──────────┐   ┌─────┐\n",
    "│ [1] │   │ [1 2]   │   │   ReLU   │   │ [2] │\n",
    "│ [2] │ → │ [3 4] @ │ → │ max(0,x) │ → │ [0] │\n",
    "│ [3] │   │ [5 6]   │   │          │   │ [8] │\n",
    "└─────┘   └─────────┘   └──────────┘   └─────┘\n",
    "         Linear Output    Nonlinear     Final\n",
    "         [2, -1, 8]      Activation     [2, 0, 8]\n",
    "```\n",
    "\n",
    "### Real-World Layer Patterns\n",
    "\n",
    "#### Hidden Layers (Feature Learning)\n",
    "```python\n",
    "# Most common pattern in neural networks\n",
    "hidden = relu(dense(x))  # Dense + ReLU\n",
    "\n",
    "# Why ReLU?\n",
    "# - Sparse activation (many zeros)\n",
    "# - No vanishing gradient problem\n",
    "# - Computationally efficient\n",
    "# - Biologically inspired\n",
    "```\n",
    "\n",
    "#### Classification Output Layers\n",
    "```python\n",
    "# Multi-class classification\n",
    "logits = dense(hidden)        # Raw scores\n",
    "probabilities = softmax(logits)  # Convert to probabilities\n",
    "\n",
    "# Binary classification  \n",
    "score = dense(hidden)         # Single score\n",
    "probability = sigmoid(score)   # Convert to probability [0,1]\n",
    "```\n",
    "\n",
    "#### Gated Mechanisms (Advanced Architectures)\n",
    "```python\n",
    "# LSTM/GRU gates\n",
    "forget_gate = sigmoid(dense_forget(x))  # Values in [0,1]\n",
    "input_gate = sigmoid(dense_input(x))    # Controls information flow\n",
    "output_gate = sigmoid(dense_output(x))  # Controls output\n",
    "\n",
    "# Attention mechanisms\n",
    "attention_scores = softmax(dense_attention(x))  # Probability distribution\n",
    "```\n",
    "\n",
    "### Deep Network Architecture Patterns\n",
    "\n",
    "#### Multi-Layer Perceptron (MLP)\n",
    "```python\n",
    "# Classic deep network architecture\n",
    "def mlp(x):\n",
    "    h1 = relu(dense1(x))      # Hidden layer 1\n",
    "    h2 = relu(dense2(h1))     # Hidden layer 2  \n",
    "    h3 = relu(dense3(h2))     # Hidden layer 3\n",
    "    output = softmax(dense4(h3))  # Output layer\n",
    "    return output\n",
    "\n",
    "# Each layer learns increasingly complex features:\n",
    "# Layer 1: Basic feature combinations\n",
    "# Layer 2: Feature interactions\n",
    "# Layer 3: Complex patterns\n",
    "# Output: Task-specific predictions\n",
    "```\n",
    "\n",
    "#### Residual Network Block\n",
    "```python\n",
    "# ResNet-style skip connections\n",
    "def residual_block(x):\n",
    "    residual = x\n",
    "    h1 = relu(dense1(x))\n",
    "    h2 = dense2(h1)  # No activation before skip connection\n",
    "    output = relu(h2 + residual)  # Add skip connection\n",
    "    return output\n",
    "\n",
    "# Why this works:\n",
    "# - Enables very deep networks\n",
    "# - Solves vanishing gradient problem\n",
    "# - Allows learning identity mappings\n",
    "```\n",
    "\n",
    "#### Attention Mechanism\n",
    "```python\n",
    "# Transformer-style attention\n",
    "def attention_layer(x):\n",
    "    queries = dense_q(x)      # Project to query space\n",
    "    keys = dense_k(x)         # Project to key space\n",
    "    values = dense_v(x)       # Project to value space\n",
    "    \n",
    "    # Compute attention scores\n",
    "    scores = queries @ keys.T / sqrt(d_model)\n",
    "    attention_weights = softmax(scores)\n",
    "    \n",
    "    # Apply attention to values\n",
    "    output = attention_weights @ values\n",
    "    return output\n",
    "```\n",
    "\n",
    "### Layer Combination Strategies\n",
    "\n",
    "#### Width vs Depth Trade-offs\n",
    "```python\n",
    "# Wide network (fewer layers, more neurons)\n",
    "def wide_network(x):\n",
    "    h1 = relu(dense(x, 1000))    # Large hidden layer\n",
    "    output = softmax(dense(h1, 10))\n",
    "    return output\n",
    "\n",
    "# Deep network (more layers, fewer neurons)\n",
    "def deep_network(x):\n",
    "    h1 = relu(dense(x, 100))\n",
    "    h2 = relu(dense(h1, 100))\n",
    "    h3 = relu(dense(h2, 100))\n",
    "    h4 = relu(dense(h3, 100))\n",
    "    output = softmax(dense(h4, 10))\n",
    "    return output\n",
    "\n",
    "# General trend: Deeper networks often perform better\n",
    "```\n",
    "\n",
    "#### Activation Function Selection Guide\n",
    "```python\n",
    "# Hidden layers\n",
    "hidden = relu(dense(x))       # Default choice, works well\n",
    "hidden = leaky_relu(dense(x)) # Prevents dead neurons\n",
    "hidden = gelu(dense(x))       # Used in transformers\n",
    "hidden = swish(dense(x))      # Smooth, self-gated\n",
    "\n",
    "# Output layers\n",
    "classification = softmax(dense(x))  # Multi-class probabilities\n",
    "binary = sigmoid(dense(x))          # Binary probability\n",
    "regression = dense(x)               # No activation for regression\n",
    "structured = tanh(dense(x))         # Bounded outputs [-1, 1]\n",
    "```\n",
    "\n",
    "### Training Considerations\n",
    "\n",
    "#### Gradient Flow Through Layer+Activation\n",
    "```python\n",
    "# Good gradient flow\n",
    "x → dense1 → relu → dense2 → relu → output\n",
    "    ↑ Well-conditioned gradients flow back\n",
    "\n",
    "# Poor gradient flow\n",
    "x → dense1 → sigmoid → dense2 → sigmoid → output\n",
    "    ↑ Gradients may vanish in deep networks\n",
    "```\n",
    "\n",
    "#### Initialization Strategies for Layer+Activation\n",
    "```python\n",
    "# Xavier/Glorot (for sigmoid, tanh)\n",
    "scale = sqrt(2 / (input_size + output_size))\n",
    "\n",
    "# He initialization (for ReLU)\n",
    "scale = sqrt(2 / input_size)\n",
    "\n",
    "# Activation function determines optimal initialization!\n",
    "```\n",
    "\n",
    "### Production Architecture Examples\n",
    "\n",
    "#### Image Classification (ResNet-style)\n",
    "```python\n",
    "def image_classifier(x):\n",
    "    # Feature extraction\n",
    "    h1 = relu(dense(flatten(x), 512))\n",
    "    h2 = relu(dense(h1, 256))\n",
    "    h3 = relu(dense(h2, 128))\n",
    "    \n",
    "    # Classification head\n",
    "    logits = dense(h3, num_classes)\n",
    "    probabilities = softmax(logits)\n",
    "    return probabilities\n",
    "```\n",
    "\n",
    "#### Language Model (Transformer-style)\n",
    "```python\n",
    "def language_model(x):\n",
    "    # Embedding and position encoding\n",
    "    embedded = embedding(x) + position_encoding(x)\n",
    "    \n",
    "    # Transformer layers\n",
    "    for _ in range(num_layers):\n",
    "        # Self-attention\n",
    "        attended = attention_layer(embedded)\n",
    "        embedded = layer_norm(embedded + attended)\n",
    "        \n",
    "        # Feed-forward\n",
    "        ff_output = relu(dense(embedded, ff_size))\n",
    "        ff_output = dense(ff_output, embed_size)\n",
    "        embedded = layer_norm(embedded + ff_output)\n",
    "    \n",
    "    # Output projection\n",
    "    logits = dense(embedded, vocab_size)\n",
    "    return softmax(logits)\n",
    "```\n",
    "\n",
    "#### Generative Model (VAE-style)\n",
    "```python\n",
    "def variational_autoencoder(x):\n",
    "    # Encoder\n",
    "    h1 = relu(dense(x, 256))\n",
    "    h2 = relu(dense(h1, 128))\n",
    "    mu = dense(h2, latent_size)      # Mean\n",
    "    log_var = dense(h2, latent_size) # Log variance\n",
    "    \n",
    "    # Reparameterization trick\n",
    "    eps = random_normal(latent_size)\n",
    "    z = mu + exp(0.5 * log_var) * eps\n",
    "    \n",
    "    # Decoder\n",
    "    h3 = relu(dense(z, 128))\n",
    "    h4 = relu(dense(h3, 256))\n",
    "    reconstruction = sigmoid(dense(h4, input_size))\n",
    "    \n",
    "    return reconstruction, mu, log_var\n",
    "```\n",
    "\n",
    "### Integration Testing Strategy\n",
    "Let's test that Dense layers work seamlessly with all activation functions to create complete neural network components!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e66d0037",
   "metadata": {
    "lines_to_next_cell": 1,
    "nbgrader": {
     "grade": true,
     "grade_id": "test-layer-activation-comprehensive",
     "locked": true,
     "points": 15,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "def test_unit_layer_activation():\n",
    "    \"\"\"Test Dense layer comprehensive testing with activation functions\"\"\"\n",
    "    print(\"🔬 Unit Test: Layer-Activation Comprehensive Test...\")\n",
    "    \n",
    "    # Create layer and activation functions\n",
    "    layer = Dense(input_size=4, output_size=3)\n",
    "    relu = ReLU()\n",
    "    sigmoid = Sigmoid()\n",
    "    tanh = Tanh()\n",
    "    softmax = Softmax()\n",
    "    \n",
    "    # Test input\n",
    "    input_data = Tensor([[1, -2, 3, -4], [2, 1, -1, 3]])  # Shape: (2, 4)\n",
    "    \n",
    "    # Test Dense + ReLU (common hidden layer pattern)\n",
    "    linear_output = layer(input_data)\n",
    "    relu_output = relu(linear_output)\n",
    "    \n",
    "    assert relu_output.shape == (2, 3), \"ReLU output should preserve shape\"\n",
    "    assert np.all(relu_output.data >= 0), \"ReLU output should be non-negative\"\n",
    "    \n",
    "    # Test Dense + Softmax (classification output pattern)\n",
    "    softmax_output = softmax(linear_output)\n",
    "    \n",
    "    assert softmax_output.shape == (2, 3), \"Softmax output should preserve shape\"\n",
    "    \n",
    "    # Each row should sum to 1 (probability distribution)\n",
    "    for i in range(2):\n",
    "        row_sum = np.sum(softmax_output.data[i])\n",
    "        assert abs(row_sum - 1.0) < 1e-6, f\"Row {i} should sum to 1, got {row_sum}\"\n",
    "    \n",
    "    # Test Dense + Sigmoid (binary classification pattern)\n",
    "    sigmoid_output = sigmoid(linear_output)\n",
    "    \n",
    "    assert sigmoid_output.shape == (2, 3), \"Sigmoid output should preserve shape\"\n",
    "    assert np.all(sigmoid_output.data > 0), \"Sigmoid output should be positive\"\n",
    "    assert np.all(sigmoid_output.data < 1), \"Sigmoid output should be less than 1\"\n",
    "    \n",
    "    # Test Dense + Tanh (hidden layer with centered outputs)\n",
    "    tanh_output = tanh(linear_output)\n",
    "    \n",
    "    assert tanh_output.shape == (2, 3), \"Tanh output should preserve shape\"\n",
    "    assert np.all(tanh_output.data > -1), \"Tanh output should be > -1\"\n",
    "    assert np.all(tanh_output.data < 1), \"Tanh output should be < 1\"\n",
    "    \n",
    "    # Test chained layers (simple 2-layer network)\n",
    "    layer1 = Dense(input_size=4, output_size=5)\n",
    "    layer2 = Dense(input_size=5, output_size=3)\n",
    "    \n",
    "    # Forward pass through 2-layer network\n",
    "    hidden = relu(layer1(input_data))\n",
    "    output = softmax(layer2(hidden))\n",
    "    \n",
    "    assert output.shape == (2, 3), \"2-layer network should produce correct output shape\"\n",
    "    \n",
    "    # Each output should be a valid probability distribution\n",
    "    for i in range(2):\n",
    "        row_sum = np.sum(output.data[i])\n",
    "        assert abs(row_sum - 1.0) < 1e-6, f\"Network output row {i} should sum to 1\"\n",
    "    \n",
    "    # Test that layers are learning-ready (have parameters)\n",
    "    assert hasattr(layer1, 'weights'), \"Layer should have weights\"\n",
    "    assert hasattr(layer1, 'bias'), \"Layer should have bias\"\n",
    "    assert isinstance(layer1.weights, Tensor), \"Weights should be Tensor\"\n",
    "    assert isinstance(layer1.bias, Tensor), \"Bias should be Tensor\"\n",
    "    \n",
    "    print(\"✅ Layer-activation comprehensive tests passed!\")\n",
    "    print(f\"✅ Dense + ReLU working correctly\")\n",
    "    print(f\"✅ Dense + Softmax producing valid probabilities\")\n",
    "    print(f\"✅ Dense + Sigmoid bounded correctly\")\n",
    "    print(f\"✅ Dense + Tanh centered correctly\")\n",
    "    print(f\"✅ Multi-layer networks working\")\n",
    "    print(f\"✅ All components ready for training!\")\n",
    "\n",
    "# Test function defined (called in main block)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a081ff0b",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "### 🎯 CHECKPOINT: Complete Neural Network Components Mastered\n",
    "\n",
    "Outstanding! You've now mastered the complete pipeline from basic matrix operations to full neural network components!\n",
    "\n",
    "#### What You've Accomplished\n",
    "✅ **Complete Neural Network Components**: Dense layers + activations working together  \n",
    "✅ **Real-World Architecture Patterns**: Understanding how components combine in production systems  \n",
    "✅ **Integration Mastery**: Seamless compatibility between layers, activations, and tensors  \n",
    "✅ **Production-Ready Implementation**: Code that scales to actual deep learning applications  \n",
    "\n",
    "#### Mathematical Concepts Mastered\n",
    "- **Universal Function Approximation**: Layer + activation composition enables learning any pattern\n",
    "- **Gradient Flow**: Understanding how gradients propagate through layer-activation chains\n",
    "- **Architecture Design**: Knowledge of when to use which layer-activation combinations\n",
    "- **Batch Processing**: Automatic handling of variable batch sizes\n",
    "\n",
    "#### Real-World Applications You Can Now Build\n",
    "Your implementations now enable:\n",
    "- **Image Classification**: Multi-layer networks for computer vision\n",
    "- **Language Models**: Transformer-style architectures for NLP\n",
    "- **Generative Models**: VAEs, GANs, and other generative architectures\n",
    "- **Recommendation Systems**: Deep collaborative filtering networks\n",
    "\n",
    "#### Advanced Architecture Patterns Understood\n",
    "- **Residual Networks**: Skip connections for very deep networks\n",
    "- **Attention Mechanisms**: Query-key-value patterns for transformers\n",
    "- **Gated Architectures**: LSTM/GRU-style information flow control\n",
    "- **Multi-layer Perceptrons**: Classic feedforward architectures\n",
    "\n",
    "**Key insight**: You can now understand and implement ANY neural network architecture!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96b8cd2f",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## 🔬 Integration Test: Layers with Tensors\n",
    "\n",
    "This is our first cumulative integration test.\n",
    "It ensures that the 'Layer' abstraction works correctly with the 'Tensor' class from the previous module."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6985727c",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "def test_module_layer_tensor_integration():\n",
    "    \"\"\"\n",
    "    Tests that a Tensor can be passed through a Layer subclass\n",
    "    and that the output is of the correct type and shape.\n",
    "    \"\"\"\n",
    "    print(\"🔬 Running Integration Test: Layer with Tensor...\")\n",
    "\n",
    "    # 1. Define a simple Layer that doubles the input\n",
    "    class DoubleLayer(Dense): # Inherit from Dense to get __call__\n",
    "        def forward(self, x: Tensor) -> Tensor:\n",
    "            return x * 2\n",
    "\n",
    "    # 2. Create an instance of the layer\n",
    "    double_layer = DoubleLayer(input_size=1, output_size=1) # Dummy sizes\n",
    "\n",
    "    # 3. Create a Tensor from the previous module\n",
    "    input_tensor = Tensor([1, 2, 3])\n",
    "\n",
    "    # 4. Perform the forward pass\n",
    "    output_tensor = double_layer(input_tensor)\n",
    "\n",
    "    # 5. Assert correctness\n",
    "    assert isinstance(output_tensor, Tensor), \"Output should be a Tensor\"\n",
    "    assert np.array_equal(output_tensor.data, np.array([2, 4, 6])), \"Output data is incorrect\"\n",
    "    print(\"✅ Integration Test Passed: Layer correctly processed Tensor.\")\n",
    "\n",
    "# Test function defined (called in main block)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dae64cf0",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "## 🏗️ ML Systems: Architecture Analysis & Memory Scaling\n",
    "\n",
    "Now that you have working neural network layers, let's develop **architecture analysis skills**. This section teaches you to understand how layer composition affects memory usage, parameter counts, and computational complexity.\n",
    "\n",
    "### **Learning Outcome**: *\"I understand how layers combine to create memory pressure and can analyze model architectures\"*\n",
    "\n",
    "---\n",
    "\n",
    "## Layer Architecture Profiler (Medium Guided Implementation)\n",
    "\n",
    "As an ML systems engineer, you need to understand how different layer configurations affect system resources. Let's build tools to analyze layer architectures and scaling patterns."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "679e2474",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "import time\n",
    "import psutil\n",
    "import os\n",
    "\n",
    "class LayerArchitectureProfiler:\n",
    "    \"\"\"\n",
    "    Architecture analysis toolkit for neural network layers.\n",
    "    \n",
    "    Helps ML engineers understand memory scaling, parameter counts,\n",
    "    and computational complexity of different layer configurations.\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self):\n",
    "        self.process = psutil.Process(os.getpid())\n",
    "        self.analysis_cache = {}\n",
    "        \n",
    "    def analyze_layer_parameters(self, input_size, hidden_size, output_size):\n",
    "        \"\"\"\n",
    "        Analyze parameter count and memory usage for a layer configuration.\n",
    "        \n",
    "        TODO: Implement parameter count analysis.\n",
    "        \n",
    "        STEP-BY-STEP IMPLEMENTATION:\n",
    "        1. Calculate weight matrix parameters: input_size * hidden_size\n",
    "        2. Calculate bias parameters: hidden_size  \n",
    "        3. Calculate total parameters: weights + bias\n",
    "        4. Calculate memory usage: parameters * 4 bytes (float32)\n",
    "        5. Return analysis dictionary with all metrics\n",
    "        \n",
    "        EXAMPLE:\n",
    "        profiler = LayerArchitectureProfiler()\n",
    "        analysis = profiler.analyze_layer_parameters(784, 128, 10)\n",
    "        print(f\"Parameters: {analysis['total_parameters']:,}\")\n",
    "        print(f\"Memory: {analysis['memory_mb']:.2f} MB\")\n",
    "        \n",
    "        HINTS:\n",
    "        - Weight matrix shape: (input_size, hidden_size)\n",
    "        - Bias vector shape: (hidden_size,)\n",
    "        - Float32 = 4 bytes per parameter\n",
    "        - Convert bytes to MB: bytes / (1024 * 1024)\n",
    "        \"\"\"\n",
    "        ### BEGIN SOLUTION\n",
    "        # Calculate parameters\n",
    "        weight_params = input_size * hidden_size\n",
    "        bias_params = hidden_size\n",
    "        total_params = weight_params + bias_params\n",
    "        \n",
    "        # Calculate memory (assuming float32 = 4 bytes)\n",
    "        memory_bytes = total_params * 4\n",
    "        memory_mb = memory_bytes / (1024 * 1024)\n",
    "        \n",
    "        return {\n",
    "            'input_size': input_size,\n",
    "            'hidden_size': hidden_size,\n",
    "            'output_size': output_size,\n",
    "            'weight_parameters': weight_params,\n",
    "            'bias_parameters': bias_params,\n",
    "            'total_parameters': total_params,\n",
    "            'memory_bytes': memory_bytes,\n",
    "            'memory_mb': memory_mb\n",
    "        }\n",
    "        ### END SOLUTION\n",
    "    \n",
    "    def analyze_network_scaling(self, input_size, hidden_sizes, output_size):\n",
    "        \"\"\"\n",
    "        Analyze how network depth affects parameter count and memory.\n",
    "        \n",
    "        TODO: Implement network scaling analysis.\n",
    "        \n",
    "        STEP-BY-STEP IMPLEMENTATION:\n",
    "        1. Initialize total parameters counter\n",
    "        2. For each layer in the network:\n",
    "           a. Calculate layer parameters using analyze_layer_parameters\n",
    "           b. Add to total count\n",
    "           c. Update input_size for next layer\n",
    "        3. Calculate total memory usage\n",
    "        4. Return comprehensive analysis\n",
    "        \n",
    "        EXAMPLE:\n",
    "        profiler = LayerArchitectureProfiler()\n",
    "        analysis = profiler.analyze_network_scaling(784, [512, 256, 128], 10)\n",
    "        print(f\"Total parameters: {analysis['total_parameters']:,}\")\n",
    "        print(f\"Layers: {len(analysis['layer_details'])}\")\n",
    "        \n",
    "        HINTS:\n",
    "        - Loop through hidden_sizes for each layer\n",
    "        - Track input_size changes: input → hidden[0] → hidden[1] → ... → output\n",
    "        - Sum all layer parameters\n",
    "        - Store per-layer details for analysis\n",
    "        \"\"\"\n",
    "        ### BEGIN SOLUTION\n",
    "        total_parameters = 0\n",
    "        layer_details = []\n",
    "        current_input = input_size\n",
    "        \n",
    "        # Analyze each hidden layer\n",
    "        for i, hidden_size in enumerate(hidden_sizes):\n",
    "            layer_analysis = self.analyze_layer_parameters(current_input, hidden_size, 0)\n",
    "            layer_analysis['layer_name'] = f'Hidden_{i+1}'\n",
    "            layer_details.append(layer_analysis)\n",
    "            total_parameters += layer_analysis['total_parameters']\n",
    "            current_input = hidden_size\n",
    "        \n",
    "        # Analyze output layer\n",
    "        output_analysis = self.analyze_layer_parameters(current_input, output_size, 0)\n",
    "        output_analysis['layer_name'] = 'Output'\n",
    "        layer_details.append(output_analysis)\n",
    "        total_parameters += output_analysis['total_parameters']\n",
    "        \n",
    "        # Calculate total memory\n",
    "        total_memory_mb = total_parameters * 4 / (1024 * 1024)\n",
    "        \n",
    "        return {\n",
    "            'network_architecture': f\"{input_size} → {' → '.join(map(str, hidden_sizes))} → {output_size}\",\n",
    "            'total_parameters': total_parameters,\n",
    "            'total_memory_mb': total_memory_mb,\n",
    "            'num_layers': len(hidden_sizes) + 1,\n",
    "            'layer_details': layer_details\n",
    "        }\n",
    "        ### END SOLUTION\n",
    "    \n",
    "    def compare_architectures(self, input_size, architecture_configs, output_size=10):\n",
    "        \"\"\"\n",
    "        Compare different network architectures for parameter efficiency.\n",
    "        \n",
    "        This function is PROVIDED to demonstrate architecture analysis.\n",
    "        Students use it to understand architecture trade-offs.\n",
    "        \"\"\"\n",
    "        print(f\"🏗️ ARCHITECTURE COMPARISON\")\n",
    "        print(f\"=\" * 50)\n",
    "        print(f\"Input size: {input_size}, Output size: {output_size}\")\n",
    "        \n",
    "        results = {}\n",
    "        \n",
    "        for arch_name, hidden_sizes in architecture_configs.items():\n",
    "            analysis = self.analyze_network_scaling(input_size, hidden_sizes, output_size)\n",
    "            results[arch_name] = analysis\n",
    "            \n",
    "            print(f\"\\n📊 {arch_name}:\")\n",
    "            print(f\"   Architecture: {analysis['network_architecture']}\")\n",
    "            print(f\"   Parameters: {analysis['total_parameters']:,}\")\n",
    "            print(f\"   Memory: {analysis['total_memory_mb']:.2f} MB\")\n",
    "            print(f\"   Layers: {analysis['num_layers']}\")\n",
    "        \n",
    "        # Find most/least parameter efficient\n",
    "        sorted_by_params = sorted(results.items(), key=lambda x: x[1]['total_parameters'])\n",
    "        most_efficient = sorted_by_params[0]\n",
    "        least_efficient = sorted_by_params[-1]\n",
    "        \n",
    "        print(f\"\\n🎯 EFFICIENCY ANALYSIS:\")\n",
    "        print(f\"   Most efficient: {most_efficient[0]} ({most_efficient[1]['total_parameters']:,} params)\")\n",
    "        print(f\"   Least efficient: {least_efficient[0]} ({least_efficient[1]['total_parameters']:,} params)\")\n",
    "        \n",
    "        efficiency_ratio = least_efficient[1]['total_parameters'] / most_efficient[1]['total_parameters']\n",
    "        print(f\"   Parameter difference: {efficiency_ratio:.1f}x\")\n",
    "        \n",
    "        return results\n",
    "    \n",
    "    def analyze_depth_vs_width_tradeoffs(self, input_size=784, output_size=10):\n",
    "        \"\"\"\n",
    "        Analyze the classic deep vs wide network trade-off.\n",
    "        \n",
    "        This function is PROVIDED to show systems thinking.\n",
    "        Students run it to understand architecture decisions.\n",
    "        \"\"\"\n",
    "        print(f\"🔍 DEPTH vs WIDTH ANALYSIS\")\n",
    "        print(f\"=\" * 40)\n",
    "        \n",
    "        # Test different depth vs width configurations\n",
    "        configurations = {\n",
    "            'Shallow Wide': [1024],                    # 1 huge layer\n",
    "            'Medium Wide': [512, 512],                 # 2 medium layers  \n",
    "            'Medium Deep': [256, 256, 256],           # 3 smaller layers\n",
    "            'Deep Narrow': [128, 128, 128, 128],      # 4 narrow layers\n",
    "            'Very Deep': [64, 64, 64, 64, 64, 64]     # 6 very narrow layers\n",
    "        }\n",
    "        \n",
    "        results = {}\n",
    "        for config_name, hidden_sizes in configurations.items():\n",
    "            analysis = self.analyze_network_scaling(input_size, hidden_sizes, output_size)\n",
    "            results[config_name] = analysis\n",
    "            \n",
    "            # Calculate depth and width metrics\n",
    "            depth = len(hidden_sizes)\n",
    "            avg_width = sum(hidden_sizes) / len(hidden_sizes)\n",
    "            max_width = max(hidden_sizes)\n",
    "            \n",
    "            print(f\"\\n{config_name}:\")\n",
    "            print(f\"   Depth: {depth} layers\")\n",
    "            print(f\"   Avg width: {avg_width:.0f} neurons\")\n",
    "            print(f\"   Max width: {max_width} neurons\")\n",
    "            print(f\"   Parameters: {analysis['total_parameters']:,}\")\n",
    "            print(f\"   Memory: {analysis['total_memory_mb']:.2f} MB\")\n",
    "        \n",
    "        print(f\"\\n💡 ARCHITECTURE INSIGHTS:\")\n",
    "        print(f\"   - Deeper networks: Better representation learning, harder to train\")\n",
    "        print(f\"   - Wider networks: More capacity per layer, more parameters\")\n",
    "        print(f\"   - Modern trend: Very deep (100+ layers) with skip connections\")\n",
    "        print(f\"   - Memory scales with total parameters regardless of arrangement\")\n",
    "        \n",
    "        return results\n",
    "\n",
    "def analyze_famous_architectures():\n",
    "    \"\"\"\n",
    "    Analyze parameter counts of famous neural network architectures.\n",
    "    \n",
    "    This function is PROVIDED to connect student work to real systems.\n",
    "    Shows how layer analysis applies to production models.\n",
    "    \"\"\"\n",
    "    profiler = LayerArchitectureProfiler()\n",
    "    \n",
    "    print(f\"🌟 FAMOUS ARCHITECTURE ANALYSIS\")\n",
    "    print(f\"=\" * 50)\n",
    "    \n",
    "    # Simplified versions of famous architectures\n",
    "    famous_models = {\n",
    "        'LeNet-5 (1998)': {\n",
    "            'description': 'First successful CNN',\n",
    "            'approx_params': 60_000,\n",
    "            'era': 'Early deep learning'\n",
    "        },\n",
    "        'AlexNet (2012)': {\n",
    "            'description': 'ImageNet breakthrough',\n",
    "            'approx_params': 60_000_000,\n",
    "            'era': 'Deep learning revolution'\n",
    "        },\n",
    "        'VGG-16 (2014)': {\n",
    "            'description': 'Very deep networks',\n",
    "            'approx_params': 138_000_000,\n",
    "            'era': 'Going deeper'\n",
    "        },\n",
    "        'ResNet-50 (2015)': {\n",
    "            'description': 'Skip connections enable very deep nets',\n",
    "            'approx_params': 25_600_000,\n",
    "            'era': 'Architecture innovation'\n",
    "        },\n",
    "        'GPT-3 (2020)': {\n",
    "            'description': 'Large language model',\n",
    "            'approx_params': 175_000_000_000,\n",
    "            'era': 'Scale revolution'\n",
    "        },\n",
    "        'GPT-4 (2023)': {\n",
    "            'description': 'Estimated multimodal model',\n",
    "            'approx_params': 1_800_000_000_000,\n",
    "            'era': 'Massive scale'\n",
    "        }\n",
    "    }\n",
    "    \n",
    "    print(f\"Model Evolution Over Time:\")\n",
    "    for model_name, info in famous_models.items():\n",
    "        params = info['approx_params']\n",
    "        memory_gb = params * 4 / (1024**3)  # Rough memory estimate\n",
    "        \n",
    "        print(f\"\\n{model_name}:\")\n",
    "        print(f\"   Parameters: {params:,}\")\n",
    "        print(f\"   Est. Memory: {memory_gb:.1f} GB\")\n",
    "        print(f\"   Description: {info['description']}\")\n",
    "        print(f\"   Era: {info['era']}\")\n",
    "    \n",
    "    # Show scaling progression\n",
    "    print(f\"\\n📈 SCALING PROGRESSION:\")\n",
    "    params_1998 = famous_models['LeNet-5 (1998)']['approx_params']\n",
    "    params_2023 = famous_models['GPT-4 (2023)']['approx_params']\n",
    "    scaling_factor = params_2023 / params_1998\n",
    "    \n",
    "    print(f\"   1998 → 2023: {scaling_factor:,.0f}x parameter increase\")\n",
    "    print(f\"   That's about {scaling_factor/1000000:.1f} million times larger!\")\n",
    "    print(f\"   Memory requirements grew from KB to TB\")\n",
    "    \n",
    "    print(f\"\\n🎯 SYSTEMS IMPLICATIONS:\")\n",
    "    print(f\"   - Parameter count directly affects memory requirements\")\n",
    "    print(f\"   - Larger models need distributed training across multiple GPUs\")\n",
    "    print(f\"   - Model serving requires careful memory management\")\n",
    "    print(f\"   - Architecture efficiency becomes crucial at scale\")\n",
    "    \n",
    "    return famous_models"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b84334e6",
   "metadata": {},
   "source": [
    "\"\"\"\n",
    "## 🎯 Learning Activity 1: Layer Architecture Analysis (Medium Guided Implementation)\n",
    "\n",
    "**Goal**: Learn to analyze neural network architectures and understand how layer configurations affect system resources.\n",
    "\n",
    "Complete the missing implementations in the `LayerArchitectureProfiler` class above, then use your profiler to understand architecture trade-offs.\n",
    "\"\"\"\n",
    "\n",
    "Architecture profiler (initialized at module level)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a3c55d6",
   "metadata": {},
   "source": [
    "\"\"\"\n",
    "## 🎯 Learning Activity 2: Architecture Comparison & Analysis (Review & Understand)\n",
    "\n",
    "**Goal**: Compare different network architectures and understand the depth vs width trade-offs that affect production ML systems.\n",
    "\"\"\"\n",
    "\n",
    "Architecture analysis functions (called in main block)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    # Run all layer tests\n",
    "    test_unit_matrix_multiplication()\n",
    "    test_unit_dense_layer()\n",
    "    test_unit_layer_activation()\n",
    "    test_module_layer_tensor_integration()\n",
    "    \n",
    "    # Initialize the layer architecture profiler\n",
    "    profiler = LayerArchitectureProfiler()\n",
    "\n",
    "    print(\"🏗️ LAYER ARCHITECTURE ANALYSIS\")\n",
    "    print(\"=\" * 50)\n",
    "\n",
    "    # Test 1: Single layer analysis\n",
    "    print(\"📊 Single Layer Analysis:\")\n",
    "    layer_configs = [\n",
    "        (784, 128),    # MNIST → small hidden\n",
    "        (784, 512),    # MNIST → medium hidden  \n",
    "        (784, 2048),   # MNIST → large hidden\n",
    "        (3072, 1024),  # CIFAR-10 → hidden\n",
    "    ]\n",
    "\n",
    "    for input_size, hidden_size in layer_configs:\n",
    "        analysis = profiler.analyze_layer_parameters(input_size, hidden_size, 10)\n",
    "        print(f\"   {input_size} → {hidden_size}: {analysis['total_parameters']:,} params, {analysis['memory_mb']:.2f} MB\")\n",
    "\n",
    "    # Test 2: Network scaling analysis\n",
    "    print(f\"\\n🔍 Network Scaling Analysis:\")\n",
    "    network_configs = [\n",
    "        ([128], \"Small network\"),\n",
    "        ([256, 128], \"Medium network\"),\n",
    "        ([512, 256, 128], \"Large network\"),\n",
    "        ([1024, 512, 256, 128], \"Very large network\")\n",
    "    ]\n",
    "\n",
    "    for hidden_sizes, description in network_configs:\n",
    "        analysis = profiler.analyze_network_scaling(784, hidden_sizes, 10)\n",
    "        print(f\"   {description}: {analysis['total_parameters']:,} params, {analysis['total_memory_mb']:.2f} MB\")\n",
    "\n",
    "    print(f\"\\n💡 SCALING INSIGHTS:\")\n",
    "    print(f\"   - Adding layers multiplies parameter count\")\n",
    "    print(f\"   - First layer often dominates parameter count (large input)\")\n",
    "    print(f\"   - Memory scales linearly with parameter count\")\n",
    "    print(f\"   - Architecture choice = resource planning decision\")\n",
    "    \n",
    "    # Compare different architecture strategies\n",
    "    input_size = 784  # MNIST flattened image\n",
    "    output_size = 10  # 10 digit classes\n",
    "\n",
    "    architecture_configs = {\n",
    "        'Baseline': [128],\n",
    "        'Wide Shallow': [512], \n",
    "        'Narrow Deep': [64, 64, 64],\n",
    "        'Pyramid': [256, 128, 64],\n",
    "        'Inverted Pyramid': [64, 128, 256],\n",
    "        'Bottleneck': [512, 32, 512]\n",
    "    }\n",
    "\n",
    "    # Students use their implemented analysis tools\n",
    "    comparison_results = profiler.compare_architectures(input_size, architecture_configs, output_size)\n",
    "\n",
    "    # Analyze depth vs width trade-offs\n",
    "    depth_width_results = profiler.analyze_depth_vs_width_tradeoffs(input_size, output_size)\n",
    "\n",
    "    # Connect to famous architectures\n",
    "    famous_analysis = analyze_famous_architectures()\n",
    "\n",
    "    print(f\"\\n🎯 KEY LEARNINGS FOR ML SYSTEMS ENGINEERS:\")\n",
    "    print(f\"=\" * 55)\n",
    "\n",
    "    print(f\"\\n1. 📊 PARAMETER SCALING:\")\n",
    "    print(f\"   First layer dominates: input_size × hidden_size\")\n",
    "    print(f\"   Layer composition multiplies parameter count\")\n",
    "    print(f\"   Memory = parameters × 4 bytes (float32)\")\n",
    "\n",
    "    print(f\"\\n2. 🏗️ ARCHITECTURE STRATEGIES:\")\n",
    "    print(f\"   Wide networks: More capacity, more parameters\")\n",
    "    print(f\"   Deep networks: Better representations, harder training\")\n",
    "    print(f\"   Bottlenecks: Compress then expand information\")\n",
    "\n",
    "    print(f\"\\n3. 🚀 PRODUCTION IMPLICATIONS:\")\n",
    "    print(f\"   Parameter count = memory requirements\")\n",
    "    print(f\"   Model serving: Load entire model into memory\")\n",
    "    print(f\"   Training: Need 2-3x model size for gradients/optimizer\")\n",
    "\n",
    "    print(f\"\\n4. 💰 COST IMPLICATIONS:\")\n",
    "    print(f\"   More parameters = larger cloud instances needed\")\n",
    "    print(f\"   GPU memory limits determine maximum model size\")\n",
    "    print(f\"   Distributed training costs scale with model size\")\n",
    "\n",
    "    print(f\"\\n💡 SYSTEMS ENGINEERING INSIGHT:\")\n",
    "    print(f\"Every layer you add is a resource planning decision:\")\n",
    "    print(f\"- More layers = more memory = higher cloud costs\")\n",
    "    print(f\"- Architecture efficiency matters at production scale\")\n",
    "    print(f\"- Understanding parameter scaling helps optimize deployments\")\n",
    "    \n",
    "    print(\"All tests passed!\")\n",
    "    print(\"Layers module complete!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "89dd1e17",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "## 🤔 ML Systems Thinking: Interactive Questions\n",
    "\n",
    "Now that you've built the fundamental building blocks of neural networks, let's connect this foundational work to broader ML systems challenges. These questions help you think critically about how layer abstractions scale to production ML environments.\n",
    "\n",
    "Take time to reflect thoughtfully on each question - your insights will help you understand how the layer concepts you've implemented connect to real-world ML systems engineering."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "db8da2f6",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "### Question 1: Parameter Management and Memory Optimization\n",
    "\n",
    "**Context**: Your Dense layer implementation stores weights and biases as Tensor objects with specific initialization strategies. In production ML systems with billions of parameters, efficient parameter management becomes critical for memory usage, training speed, and model deployment.\n",
    "\n",
    "**Reflection Question**: Design a parameter management system for large-scale neural networks that optimizes memory usage and supports efficient distributed training. How would you handle parameter initialization strategies for networks with hundreds of layers, implement parameter sharing across layers, and manage memory-efficient storage for billion-parameter models? Consider scenarios where memory constraints force trade-offs between model capacity and computational efficiency.\n",
    "\n",
    "Think about: parameter quantization, memory pooling, distributed parameter storage, and initialization strategies that maintain numerical stability across very deep networks.\n",
    "\n",
    "*Target length: 150-300 words*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "415f8ae8",
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "question-1-parameter-management",
     "locked": false,
     "points": 10,
     "schema_version": 3,
     "solution": true,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "YOUR REFLECTION ON PARAMETER MANAGEMENT AND MEMORY OPTIMIZATION:\n",
    "\n",
    "TODO: Replace this text with your thoughtful response about parameter management system design.\n",
    "\n",
    "Consider addressing:\n",
    "- How would you optimize parameter storage and memory usage for billion-parameter models?\n",
    "- What strategies would you use for parameter initialization in very deep networks?\n",
    "- How would you implement parameter sharing and distributed storage efficiently?\n",
    "- What role would quantization play in your parameter management system?\n",
    "- How would you balance memory constraints with model capacity requirements?\n",
    "\n",
    "Write a technical analysis connecting your layer implementations to real parameter management challenges.\n",
    "\n",
    "GRADING RUBRIC (Instructor Use):\n",
    "- Demonstrates understanding of large-scale parameter management challenges (3 points)\n",
    "- Addresses memory optimization and distributed storage strategies (3 points)\n",
    "- Shows practical knowledge of initialization and quantization techniques (2 points)\n",
    "- Demonstrates systems thinking about memory vs capacity trade-offs (2 points)\n",
    "- Clear technical reasoning and practical considerations (bonus points for innovative approaches)\n",
    "\"\"\"\n",
    "\n",
    "### BEGIN SOLUTION\n",
    "# Student response area - instructor will replace this section during grading setup\n",
    "# This is a manually graded question requiring technical analysis of parameter management\n",
    "# Students should demonstrate understanding of memory optimization and distributed parameter storage\n",
    "### END SOLUTION"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "efe4eb50",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "### Question 2: Abstraction Design and Framework Integration\n",
    "\n",
    "**Context**: Your layer implementation provides a clean abstraction that separates computation from parameter storage. Production ML frameworks must balance abstraction simplicity with performance optimization, automatic differentiation support, and hardware acceleration capabilities.\n",
    "\n",
    "**Reflection Question**: Architect a layer abstraction system that enables both research flexibility and production optimization. How would you design layer interfaces that support automatic differentiation, enable fusion with other operations for performance, and maintain compatibility across different execution backends (CPU, GPU, TPU)? Consider the challenge of providing high-level abstractions while allowing low-level optimization for specific hardware platforms.\n",
    "\n",
    "Think about: API design principles, automatic differentiation integration, operation fusion opportunities, and backend abstraction strategies.\n",
    "\n",
    "*Target length: 150-300 words*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dc7eb8a6",
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "question-2-abstraction-design",
     "locked": false,
     "points": 10,
     "schema_version": 3,
     "solution": true,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "YOUR REFLECTION ON ABSTRACTION DESIGN AND FRAMEWORK INTEGRATION:\n",
    "\n",
    "TODO: Replace this text with your thoughtful response about layer abstraction system design.\n",
    "\n",
    "Consider addressing:\n",
    "- How would you design layer abstractions that balance simplicity with optimization potential?\n",
    "- What strategies would you use to integrate layers with automatic differentiation systems?\n",
    "- How would you enable operation fusion while maintaining clean abstractions?\n",
    "- What role would backend abstraction play in supporting multiple hardware platforms?\n",
    "- How would you maintain API compatibility while enabling hardware-specific optimizations?\n",
    "\n",
    "Write an architectural analysis connecting your layer abstractions to real framework design challenges.\n",
    "\n",
    "GRADING RUBRIC (Instructor Use):\n",
    "- Shows understanding of abstraction design principles for ML systems (3 points)\n",
    "- Designs practical approaches to automatic differentiation integration (3 points)\n",
    "- Addresses performance optimization and hardware abstraction (2 points)\n",
    "- Demonstrates systems thinking about framework architecture (2 points)\n",
    "- Clear architectural reasoning with framework insights (bonus points for comprehensive understanding)\n",
    "\"\"\"\n",
    "\n",
    "### BEGIN SOLUTION\n",
    "# Student response area - instructor will replace this section during grading setup\n",
    "# This is a manually graded question requiring understanding of framework abstraction design\n",
    "# Students should demonstrate knowledge of balancing simplicity with optimization potential\n",
    "### END SOLUTION"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "115e1816",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "### Question 3: Initialization Strategies and Training Stability\n",
    "\n",
    "**Context**: Your Dense layer uses Xavier/Glorot initialization to maintain proper signal propagation through networks. In production training of very deep networks (hundreds of layers), initialization strategies become critical for training stability, convergence speed, and final model performance.\n",
    "\n",
    "**Reflection Question**: Design an advanced initialization system for training ultra-deep neural networks that ensures stable gradient flow and optimal convergence. How would you adapt initialization strategies for different layer types, handle initialization in networks with skip connections and attention mechanisms, and implement dynamic initialization that adapts during training? Consider scenarios where poor initialization causes training failures in expensive large-scale experiments.\n",
    "\n",
    "Think about: layer-specific initialization, residual connection handling, attention mechanism initialization, and adaptive initialization techniques.\n",
    "\n",
    "*Target length: 150-300 words*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0ad7be5a",
   "metadata": {
    "nbgrader": {
     "grade": true,
     "grade_id": "question-3-initialization-strategies",
     "locked": false,
     "points": 10,
     "schema_version": 3,
     "solution": true,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "YOUR REFLECTION ON INITIALIZATION STRATEGIES AND TRAINING STABILITY:\n",
    "\n",
    "TODO: Replace this text with your thoughtful response about advanced initialization system design.\n",
    "\n",
    "Consider addressing:\n",
    "- How would you design initialization strategies for different types of layers and architectures?\n",
    "- What approaches would you use to ensure stable gradient flow in ultra-deep networks?\n",
    "- How would you handle initialization for complex architectures with skip connections and attention?\n",
    "- What role would adaptive initialization play in improving training stability?\n",
    "- How would you prevent initialization-related training failures in large-scale experiments?\n",
    "\n",
    "Write a design analysis connecting your initialization implementations to real training stability challenges.\n",
    "\n",
    "GRADING RUBRIC (Instructor Use):\n",
    "- Understands initialization impact on training stability and gradient flow (3 points)\n",
    "- Designs practical approaches to layer-specific and adaptive initialization (3 points)\n",
    "- Addresses complex architecture initialization challenges (2 points)\n",
    "- Shows systems thinking about training optimization and stability (2 points)\n",
    "- Clear design reasoning with initialization optimization insights (bonus points for deep understanding)\n",
    "\"\"\"\n",
    "\n",
    "### BEGIN SOLUTION\n",
    "# Student response area - instructor will replace this section during grading setup\n",
    "# This is a manually graded question requiring understanding of initialization strategies and training stability\n",
    "# Students should demonstrate knowledge of gradient flow and initialization optimization challenges\n",
    "### END SOLUTION"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36ce8f89",
   "metadata": {},
   "source": [
    "\"\"\"\n",
    "# 🎯 MODULE SUMMARY: Neural Network Layers - Foundation of All AI\n",
    "\n",
    "🎉 **CONGRATULATIONS!** You've just mastered the mathematical and computational foundation of ALL modern artificial intelligence!\n",
    "\n",
    "## What You've Accomplished: A Complete AI Foundation\n",
    "\n",
    "### ✅ Mathematical Mastery\n",
    "- **Matrix Multiplication Engine**: The core operation powering every neural network\n",
    "- **Dense Layer Implementation**: The universal building block of all AI systems\n",
    "- **Universal Function Approximation**: Understanding how layer+activation enables learning ANY pattern\n",
    "- **Weight Initialization Science**: Xavier/Glorot strategies for stable training\n",
    "\n",
    "### ✅ Implementation Excellence\n",
    "- **Production-Grade Code**: Your implementations match PyTorch and TensorFlow standards\n",
    "- **Shape Management Mastery**: Automatic batch processing and broadcasting\n",
    "- **Error Handling**: Robust validation and meaningful error messages\n",
    "- **Integration Ready**: Seamless compatibility with Tensor and Activation modules\n",
    "\n",
    "### ✅ Real-World Architecture Understanding\n",
    "- **Multi-Layer Perceptrons**: Classic feedforward architectures\n",
    "- **Residual Networks**: Skip connections for ultra-deep networks\n",
    "- **Attention Mechanisms**: The foundation of transformers and GPT models\n",
    "- **Generative Architectures**: VAEs, GANs, and modern generative AI\n",
    "\n",
    "## Deep Mathematical Concepts Mastered\n",
    "\n",
    "### Linear Algebra Foundations\n",
    "```\n",
    "Matrix Multiplication: C = A @ B\n",
    "Dense Layer: y = xW + b\n",
    "Universal Approximation: f(x) = activation_n(...activation_1(x @ W_1 + b_1)...)\n",
    "```\n",
    "\n",
    "### Parameter Learning Theory\n",
    "- **Initialization Strategies**: Why random weights break symmetry\n",
    "- **Gradient Flow**: How learning signals propagate through networks  \n",
    "- **Batch Processing**: Vectorized operations for computational efficiency\n",
    "- **Broadcasting**: Automatic shape handling for different tensor dimensions\n",
    "\n",
    "### Architecture Design Principles\n",
    "- **Width vs Depth**: Trade-offs in network architecture\n",
    "- **Activation Selection**: Choosing the right nonlinearity for each layer\n",
    "- **Skip Connections**: Enabling ultra-deep networks with residual learning\n",
    "- **Attention Patterns**: Query-key-value mechanisms for sequence modeling\n",
    "\n",
    "## Real-World Impact: What You Can Now Build\n",
    "\n",
    "### 🖼️ Computer Vision\n",
    "```python\n",
    "Image classification with your Dense layers\n",
    "image → flatten → dense(784→512) → relu → dense(512→256) → relu → dense(256→10) → softmax\n",
    "```\n",
    "- **Object Recognition**: Classify images into thousands of categories\n",
    "- **Medical Imaging**: Detect diseases from X-rays and MRI scans\n",
    "- **Autonomous Vehicles**: Recognize traffic signs and pedestrians\n",
    "\n",
    "### 🗣️ Natural Language Processing\n",
    "```python\n",
    "Language model with your Dense layers\n",
    "text → embed → dense(300→128) → tanh → dense(128→vocab) → softmax\n",
    "```\n",
    "- **Language Models**: Build GPT-style text generation systems\n",
    "- **Machine Translation**: Translate between any pair of languages  \n",
    "- **Sentiment Analysis**: Understand emotional content in text\n",
    "\n",
    "### 🎯 Recommendation Systems\n",
    "```python\n",
    "Collaborative filtering with your Dense layers\n",
    "user_features → dense(1000→256) → relu → dense(256→items) → sigmoid\n",
    "```\n",
    "- **Netflix Recommendations**: Predict what movies users will enjoy\n",
    "- **E-commerce**: Suggest products based on browsing history\n",
    "- **Social Media**: Recommend friends and content\n",
    "\n",
    "### 🧪 Scientific AI\n",
    "```python\n",
    "Physics simulation with your Dense layers\n",
    "parameters → dense(10→64) → relu → dense(64→64) → relu → dense(64→1) → output\n",
    "```\n",
    "- **Drug Discovery**: Predict molecular properties for new medicines\n",
    "- **Climate Modeling**: Simulate complex atmospheric phenomena\n",
    "- **Materials Science**: Design new materials with desired properties\n",
    "\n",
    "## Connection to Advanced AI Systems\n",
    "\n",
    "### 🤖 Large Language Models (GPT, ChatGPT)\n",
    "```python\n",
    "Every transformer layer uses YOUR Dense implementation\n",
    "attention_output → dense(hidden→hidden) → relu → dense(hidden→hidden)\n",
    "```\n",
    "Your Dense layers power the feed-forward networks in every transformer!\n",
    "\n",
    "### 🎨 Generative AI (DALL-E, Stable Diffusion)  \n",
    "```python\n",
    "Generative models built on YOUR foundation\n",
    "noise → dense(100→256) → relu → dense(256→784) → sigmoid → image\n",
    "```\n",
    "Your layers enable the neural networks that create art and images!\n",
    "\n",
    "### 🎮 Reinforcement Learning (AlphaGo, game AI)\n",
    "```python\n",
    "Policy networks use YOUR Dense layers\n",
    "game_state → dense(board→256) → relu → dense(256→actions) → softmax\n",
    "```\n",
    "Your implementation enables AI that masters complex games!\n",
    "\n",
    "## Professional Skills Developed\n",
    "\n",
    "### 🏗️ Software Engineering\n",
    "- **Clean Code**: Well-documented, readable implementations\n",
    "- **Testing**: Comprehensive validation of functionality\n",
    "- **API Design**: Consistent, intuitive interfaces\n",
    "- **Error Handling**: Graceful failure modes with helpful messages\n",
    "\n",
    "### 🧮 Mathematical Computing\n",
    "- **Numerical Stability**: Proper initialization and scaling\n",
    "- **Performance Optimization**: Understanding computational complexity\n",
    "- **Memory Management**: Efficient tensor operations\n",
    "- **Debugging**: Systematic approaches to shape and gradient issues\n",
    "\n",
    "### 🔬 Machine Learning Engineering\n",
    "- **Architecture Design**: Knowing when to use which layer types\n",
    "- **Hyperparameter Selection**: Understanding initialization and activation choices\n",
    "- **Gradient Flow**: Designing networks for stable training\n",
    "- **Production Deployment**: Building scalable, maintainable systems\n",
    "\n",
    "## Industry-Standard Implementation Quality\n",
    "\n",
    "### Production System Equivalence\n",
    "```python\n",
    "Your implementation\n",
    "layer = Dense(input_size=784, output_size=10)\n",
    "output = layer(input)\n",
    "\n",
    "PyTorch equivalent\n",
    "layer = torch.nn.Linear(784, 10)\n",
    "output = layer(input)\n",
    "\n",
    "TensorFlow equivalent  \n",
    "layer = tf.keras.layers.Dense(10)\n",
    "output = layer(input)\n",
    "\n",
    "IDENTICAL MATHEMATICAL OPERATIONS!\n",
    "```\n",
    "\n",
    "### Performance Considerations\n",
    "- **Computational Complexity**: O(batch_size × input_size × output_size)\n",
    "- **Memory Usage**: Optimal tensor storage and reuse\n",
    "- **GPU Acceleration**: Foundation for hardware optimization\n",
    "- **Distributed Computing**: Basis for multi-device training\n",
    "\n",
    "## Advanced Topics You're Now Ready For\n",
    "\n",
    "### 🧠 Specialized Architectures\n",
    "- **Convolutional Networks**: For image and spatial data processing\n",
    "- **Recurrent Networks**: For sequential data and time series\n",
    "- **Graph Neural Networks**: For structured data and relationships\n",
    "- **Transformer Architectures**: For attention-based modeling\n",
    "\n",
    "### 🎯 Advanced Training Techniques\n",
    "- **Batch Normalization**: Stabilizing training in deep networks\n",
    "- **Dropout Regularization**: Preventing overfitting\n",
    "- **Learning Rate Scheduling**: Optimizing convergence\n",
    "- **Transfer Learning**: Adapting pre-trained models\n",
    "\n",
    "### 🚀 Cutting-Edge Research\n",
    "- **Neural Architecture Search**: Automatically designing networks\n",
    "- **Meta-Learning**: Learning to learn new tasks quickly\n",
    "- **Federated Learning**: Training across distributed devices\n",
    "- **Quantum Neural Networks**: Quantum computing + neural networks\n",
    "\n",
    "## Your Neural Network Toolkit\n",
    "\n",
    "You now have the complete foundation to understand and implement:\n",
    "\n",
    "```python\n",
    "ANY neural network architecture can be built with your components!\n",
    "\n",
    "def your_neural_network(x):\n",
    "    # Foundation layers (YOUR implementation)\n",
    "    h1 = relu(dense1(x))\n",
    "    h2 = relu(dense2(h1))\n",
    "    \n",
    "    # Advanced patterns (built on YOUR foundation)\n",
    "    attention = attention_layer(h2)\n",
    "    residual = h2 + attention\n",
    "    \n",
    "    # Output (YOUR implementation)\n",
    "    output = softmax(dense_output(residual))\n",
    "    return output\n",
    "```\n",
    "\n",
    "## Next Steps: Continue Your AI Journey\n",
    "\n",
    "### 🔧 Module 5: Convolutional Layers\n",
    "Build specialized layers for image processing and computer vision\n",
    "\n",
    "### 📊 Module 6: Optimization\n",
    "Implement gradient descent and advanced optimization algorithms  \n",
    "\n",
    "### 🔄 Module 7: Training Loops\n",
    "Create complete training and validation pipelines\n",
    "\n",
    "### 🌐 Module 8: Advanced Architectures\n",
    "Build transformers, ResNets, and state-of-the-art models\n",
    "\n",
    "## The Bigger Picture: Your Impact on AI\n",
    "\n",
    "**You now understand the mathematical foundation of:**\n",
    "- Every neural network ever created\n",
    "- All modern AI systems (GPT, DALL-E, AlphaGo, etc.)\n",
    "- The core operations that power trillion-dollar AI companies\n",
    "- The building blocks enabling the current AI revolution\n",
    "\n",
    "**Your layer implementations:**\n",
    "- Are mathematically equivalent to production systems\n",
    "- Form the foundation of all advanced architectures  \n",
    "- Enable you to contribute to cutting-edge AI research\n",
    "- Provide the knowledge to build the next generation of AI systems\n",
    "\n",
    "## 🌟 **You Are Now a Neural Network Architect!**\n",
    "\n",
    "With your deep understanding of layers, you can:\n",
    "- **Understand** any neural network architecture\n",
    "- **Implement** custom layer types for new applications\n",
    "- **Debug** training issues in complex models\n",
    "- **Optimize** networks for production deployment\n",
    "- **Research** novel architectures for unsolved problems\n",
    "\n",
    "**Welcome to the community of AI builders! Your journey to mastering neural networks is well underway.**\n",
    "\n",
    "---\n",
    "\n",
    "*\"Every expert was once a beginner. Every pro was once an amateur. Every icon was once an unknown.\" - Robin Sharma*\n",
    "\n",
    "**You've built the foundation. Now go build the future of AI!** 🚀\n",
    "\"\"\"\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    # Run all layer tests\n",
    "    test_unit_matrix_multiplication()\n",
    "    test_unit_dense_layer()\n",
    "    test_unit_layer_activation()\n",
    "    test_module_layer_tensor_integration()\n",
    "    \n",
    "    # Initialize the layer architecture profiler\n",
    "    profiler = LayerArchitectureProfiler()\n",
    "\n",
    "    print(\"🏗️ LAYER ARCHITECTURE ANALYSIS\")\n",
    "    print(\"=\" * 50)\n",
    "\n",
    "    # Test 1: Single layer analysis\n",
    "    print(\"📊 Single Layer Analysis:\")\n",
    "    layer_configs = [\n",
    "        (784, 128),    # MNIST → small hidden\n",
    "        (784, 512),    # MNIST → medium hidden  \n",
    "        (784, 2048),   # MNIST → large hidden\n",
    "        (3072, 1024),  # CIFAR-10 → hidden\n",
    "    ]\n",
    "\n",
    "    for input_size, hidden_size in layer_configs:\n",
    "        analysis = profiler.analyze_layer_parameters(input_size, hidden_size, 10)\n",
    "        print(f\"   {input_size} → {hidden_size}: {analysis['total_parameters']:,} params, {analysis['memory_mb']:.2f} MB\")\n",
    "\n",
    "    # Test 2: Network scaling analysis\n",
    "    print(f\"\\n🔍 Network Scaling Analysis:\")\n",
    "    network_configs = [\n",
    "        ([128], \"Small network\"),\n",
    "        ([256, 128], \"Medium network\"),\n",
    "        ([512, 256, 128], \"Large network\"),\n",
    "        ([1024, 512, 256, 128], \"Very large network\")\n",
    "    ]\n",
    "\n",
    "    for hidden_sizes, description in network_configs:\n",
    "        analysis = profiler.analyze_network_scaling(784, hidden_sizes, 10)\n",
    "        print(f\"   {description}: {analysis['total_parameters']:,} params, {analysis['total_memory_mb']:.2f} MB\")\n",
    "\n",
    "    print(f\"\\n💡 SCALING INSIGHTS:\")\n",
    "    print(f\"   - Adding layers multiplies parameter count\")\n",
    "    print(f\"   - First layer often dominates parameter count (large input)\")\n",
    "    print(f\"   - Memory scales linearly with parameter count\")\n",
    "    print(f\"   - Architecture choice = resource planning decision\")\n",
    "    \n",
    "    # Compare different architecture strategies\n",
    "    input_size = 784  # MNIST flattened image\n",
    "    output_size = 10  # 10 digit classes\n",
    "\n",
    "    architecture_configs = {\n",
    "        'Baseline': [128],\n",
    "        'Wide Shallow': [512], \n",
    "        'Narrow Deep': [64, 64, 64],\n",
    "        'Pyramid': [256, 128, 64],\n",
    "        'Inverted Pyramid': [64, 128, 256],\n",
    "        'Bottleneck': [512, 32, 512]\n",
    "    }\n",
    "\n",
    "    # Students use their implemented analysis tools\n",
    "    comparison_results = profiler.compare_architectures(input_size, architecture_configs, output_size)\n",
    "\n",
    "    # Analyze depth vs width trade-offs\n",
    "    depth_width_results = profiler.analyze_depth_vs_width_tradeoffs(input_size, output_size)\n",
    "\n",
    "    # Connect to famous architectures\n",
    "    famous_analysis = analyze_famous_architectures()\n",
    "\n",
    "    print(f\"\\n🎯 KEY LEARNINGS FOR ML SYSTEMS ENGINEERS:\")\n",
    "    print(f\"=\" * 55)\n",
    "\n",
    "    print(f\"\\n1. 📊 PARAMETER SCALING:\")\n",
    "    print(f\"   First layer dominates: input_size × hidden_size\")\n",
    "    print(f\"   Layer composition multiplies parameter count\")\n",
    "    print(f\"   Memory = parameters × 4 bytes (float32)\")\n",
    "\n",
    "    print(f\"\\n2. 🏗️ ARCHITECTURE STRATEGIES:\")\n",
    "    print(f\"   Wide networks: More capacity, more parameters\")\n",
    "    print(f\"   Deep networks: Better representations, harder training\")\n",
    "    print(f\"   Bottlenecks: Compress then expand information\")\n",
    "\n",
    "    print(f\"\\n3. 🚀 PRODUCTION IMPLICATIONS:\")\n",
    "    print(f\"   Parameter count = memory requirements\")\n",
    "    print(f\"   Model serving: Load entire model into memory\")\n",
    "    print(f\"   Training: Need 2-3x model size for gradients/optimizer\")\n",
    "\n",
    "    print(f\"\\n4. 💰 COST IMPLICATIONS:\")\n",
    "    print(f\"   More parameters = larger cloud instances needed\")\n",
    "    print(f\"   GPU memory limits determine maximum model size\")\n",
    "    print(f\"   Distributed training costs scale with model size\")\n",
    "\n",
    "    print(f\"\\n💡 SYSTEMS ENGINEERING INSIGHT:\")\n",
    "    print(f\"Every layer you add is a resource planning decision:\")\n",
    "    print(f\"- More layers = more memory = higher cloud costs\")\n",
    "    print(f\"- Architecture efficiency matters at production scale\")\n",
    "    print(f\"- Understanding parameter scaling helps optimize deployments\")\n",
    "    \n",
    "    print(\"All tests passed!\")\n",
    "    print(\"Layers module complete!\")"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "main_language": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
