{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ba78f72a",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| default_exp core.introduction"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb716e26",
   "metadata": {
    "cell_marker": "\"\"\"",
    "nbgrader": {
     "grade": false,
     "grade_id": "introduction-overview",
     "locked": false,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "source": [
    "# TinyTorch System Introduction & Architecture Overview\n",
    "\n",
    "Welcome to **TinyTorch** - a complete neural network framework built from scratch for deep learning education and understanding.\n",
    "\n",
    "This introduction module provides:\n",
    "- **Visual system architecture** - Complete framework overview\n",
    "- **Interactive dependency graphs** - How all 16 modules connect\n",
    "- **Learning roadmap** - Guided path through the system\n",
    "- **Component analysis** - What each module implements\n",
    "\n",
    "Let's explore the architecture of this comprehensive ML framework!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fc2baa1a",
   "metadata": {
    "nbgrader": {
     "grade": false,
     "grade_id": "introduction-imports",
     "locked": false,
     "schema_version": 3,
     "solution": false,
     "task": false
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.patches as patches\n",
    "from matplotlib.patches import FancyBboxPatch, Circle, ConnectionPatch\n",
    "from pathlib import Path\n",
    "import yaml\n",
    "import networkx as nx\n",
    "from typing import Dict, List, Tuple, Set\n",
    "import seaborn as sns\n",
    "from dataclasses import dataclass\n",
    "from collections import defaultdict, deque\n",
    "\n",
    "# Set plotting style for professional visualizations\n",
    "plt.style.use('seaborn-v0_8')\n",
    "sns.set_palette(\"husl\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c7ef396",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## Module Metadata Analysis System\n",
    "\n",
    "First, let's build tools to automatically analyze all TinyTorch modules and their relationships.\n",
    "This will power our interactive visualizations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1eea1377",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "@dataclass\n",
    "class ModuleInfo:\n",
    "    \"\"\"Complete information about a TinyTorch module\"\"\"\n",
    "    name: str\n",
    "    title: str\n",
    "    description: str\n",
    "    prerequisites: List[str]\n",
    "    enables: List[str]\n",
    "    components: List[str]\n",
    "    difficulty: str\n",
    "    time_estimate: str\n",
    "    exports_to: str\n",
    "    \n",
    "    def difficulty_level(self) -> int:\n",
    "        \"\"\"Convert difficulty stars to numeric level\"\"\"\n",
    "        return self.difficulty.count('⭐')\n",
    "    \n",
    "    def estimated_hours(self) -> float:\n",
    "        \"\"\"Extract numeric time estimate\"\"\"\n",
    "        time_str = self.time_estimate.lower()\n",
    "        if 'capstone' in time_str:\n",
    "            return 40.0  # Capstone project estimate\n",
    "        \n",
    "        # Extract first number from time estimate\n",
    "        import re\n",
    "        numbers = re.findall(r'\\d+', time_str)\n",
    "        if numbers:\n",
    "            return float(numbers[0])\n",
    "        return 4.0  # Default estimate\n",
    "\n",
    "#| export\n",
    "class TinyTorchAnalyzer:\n",
    "    \"\"\"Comprehensive analysis of TinyTorch module system\"\"\"\n",
    "    \n",
    "    def __init__(self, modules_path: str = \"/Users/VJ/GitHub/TinyTorch/modules/source\"):\n",
    "        self.modules_path = Path(modules_path)\n",
    "        self.modules: Dict[str, ModuleInfo] = {}\n",
    "        self.dependency_graph = nx.DiGraph()\n",
    "        self._load_all_modules()\n",
    "        self._build_dependency_graph()\n",
    "    \n",
    "    def _load_all_modules(self):\n",
    "        \"\"\"Load metadata from all module.yaml files\"\"\"\n",
    "        for module_dir in sorted(self.modules_path.iterdir()):\n",
    "            if module_dir.is_dir() and not module_dir.name.startswith('.'):\n",
    "                yaml_file = module_dir / 'module.yaml'\n",
    "                if yaml_file.exists():\n",
    "                    try:\n",
    "                        with open(yaml_file, 'r') as f:\n",
    "                            data = yaml.safe_load(f)\n",
    "                        \n",
    "                        # Handle different YAML formats in the modules\n",
    "                        if 'dependencies' in data:\n",
    "                            deps = data['dependencies']\n",
    "                            prerequisites = deps.get('prerequisites', [])\n",
    "                            enables = deps.get('enables', [])\n",
    "                        else:\n",
    "                            # Handle older format\n",
    "                            prerequisites = data.get('dependencies', [])\n",
    "                            enables = []\n",
    "                        \n",
    "                        module_info = ModuleInfo(\n",
    "                            name=data.get('name', module_dir.name),\n",
    "                            title=data.get('title', module_dir.name.title()),\n",
    "                            description=data.get('description', ''),\n",
    "                            prerequisites=prerequisites,\n",
    "                            enables=enables,\n",
    "                            components=data.get('components', []),\n",
    "                            difficulty=data.get('difficulty', '⭐'),\n",
    "                            time_estimate=data.get('time_estimate', '2-4 hours'),\n",
    "                            exports_to=data.get('exports_to', f'tinytorch.{module_dir.name}')\n",
    "                        )\n",
    "                        \n",
    "                        self.modules[module_info.name] = module_info\n",
    "                        \n",
    "                    except Exception as e:\n",
    "                        print(f\"Warning: Could not load {yaml_file}: {e}\")\n",
    "    \n",
    "    def _build_dependency_graph(self):\n",
    "        \"\"\"Build NetworkX graph of module dependencies\"\"\"\n",
    "        # Add all modules as nodes\n",
    "        for name, module in self.modules.items():\n",
    "            self.dependency_graph.add_node(name, **{\n",
    "                'title': module.title,\n",
    "                'description': module.description,\n",
    "                'difficulty': module.difficulty_level(),\n",
    "                'time': module.estimated_hours(),\n",
    "                'components': len(module.components)\n",
    "            })\n",
    "        \n",
    "        # Add dependency edges\n",
    "        for name, module in self.modules.items():\n",
    "            for prereq in module.prerequisites:\n",
    "                if prereq in self.modules:\n",
    "                    self.dependency_graph.add_edge(prereq, name)\n",
    "    \n",
    "    def get_learning_path(self) -> List[str]:\n",
    "        \"\"\"Generate optimal learning path through modules using topological sort\"\"\"\n",
    "        try:\n",
    "            return list(nx.topological_sort(self.dependency_graph))\n",
    "        except nx.NetworkXError:\n",
    "            # Fallback if cycles exist\n",
    "            return sorted(self.modules.keys())\n",
    "    \n",
    "    def get_module_levels(self) -> Dict[str, int]:\n",
    "        \"\"\"Assign modules to learning levels based on dependencies\"\"\"\n",
    "        levels = {}\n",
    "        path = self.get_learning_path()\n",
    "        \n",
    "        for module in path:\n",
    "            prereqs = self.modules[module].prerequisites\n",
    "            if not prereqs:\n",
    "                levels[module] = 0\n",
    "            else:\n",
    "                max_prereq_level = max((levels.get(p, 0) for p in prereqs if p in levels), default=0)\n",
    "                levels[module] = max_prereq_level + 1\n",
    "        \n",
    "        return levels\n",
    "\n",
    "# Initialize the analyzer\n",
    "analyzer = TinyTorchAnalyzer()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80f4ec79",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### Test the Module Analysis System\n",
    "\n",
    "Let's verify our module analyzer is working correctly by examining a few key modules."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5c811cdf",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "def test_module_analyzer():\n",
    "    \"\"\"Test that our module analyzer correctly loads and processes modules\"\"\"\n",
    "    \n",
    "    # Test basic loading\n",
    "    assert len(analyzer.modules) >= 10, \"Should load multiple modules\"\n",
    "    \n",
    "    # Test specific modules exist\n",
    "    key_modules = ['setup', 'tensor', 'activations', 'training']\n",
    "    for module_name in key_modules:\n",
    "        assert module_name in analyzer.modules, f\"Should load {module_name} module\"\n",
    "    \n",
    "    # Test dependency relationships\n",
    "    tensor_module = analyzer.modules['tensor']\n",
    "    assert 'setup' in tensor_module.prerequisites, \"Tensor should depend on setup\"\n",
    "    \n",
    "    # Test learning path generation\n",
    "    learning_path = analyzer.get_learning_path()\n",
    "    setup_pos = learning_path.index('setup') if 'setup' in learning_path else -1\n",
    "    tensor_pos = learning_path.index('tensor') if 'tensor' in learning_path else -1\n",
    "    \n",
    "    if setup_pos >= 0 and tensor_pos >= 0:\n",
    "        assert setup_pos < tensor_pos, \"Setup should come before tensor in learning path\"\n",
    "    \n",
    "    print(\"✅ Module analyzer tests passed!\")\n",
    "    \n",
    "    # Show some sample data\n",
    "    print(f\"\\n📋 Sample modules loaded:\")\n",
    "    for name in list(analyzer.modules.keys())[:5]:\n",
    "        module = analyzer.modules[name]\n",
    "        print(f\"  • {module.title} ({module.difficulty}) - {len(module.components)} components\")\n",
    "\n",
    "# test_module_analyzer() # Test moved to main block"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "638f30b5",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## Interactive Dependency Visualization\n",
    "\n",
    "Now let's create beautiful, interactive visualizations of the TinyTorch module dependency system."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "090c643a",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "#| export  \n",
    "def create_dependency_graph_visualization(figsize=(16, 12)):\n",
    "    \"\"\"Create an interactive dependency graph visualization\"\"\"\n",
    "    \n",
    "    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize)\n",
    "    \n",
    "    # Left plot: Hierarchical layout\n",
    "    ax1.set_title(\"TinyTorch Module Dependencies\\n(Hierarchical Layout)\", fontsize=16, fontweight='bold')\n",
    "    \n",
    "    # Calculate positions using spring layout with hierarchy\n",
    "    levels = analyzer.get_module_levels()\n",
    "    pos = {}\n",
    "    \n",
    "    # Group modules by level\n",
    "    level_groups = defaultdict(list)\n",
    "    for module, level in levels.items():\n",
    "        level_groups[level].append(module)\n",
    "    \n",
    "    # Position modules in levels\n",
    "    max_level = max(levels.values()) if levels else 0\n",
    "    for level, modules in level_groups.items():\n",
    "        y = max_level - level  # Higher levels at top\n",
    "        for i, module in enumerate(sorted(modules)):\n",
    "            x = (i - len(modules)/2) * 2.5\n",
    "            pos[module] = (x, y * 2)\n",
    "    \n",
    "    # Draw the graph\n",
    "    G = analyzer.dependency_graph\n",
    "    \n",
    "    # Node colors based on difficulty\n",
    "    node_colors = []\n",
    "    node_sizes = []\n",
    "    for node in G.nodes():\n",
    "        difficulty = analyzer.modules[node].difficulty_level()\n",
    "        node_colors.append(plt.cm.viridis(difficulty / 5.0))  # Normalize to 0-1\n",
    "        node_sizes.append(200 + difficulty * 100)\n",
    "    \n",
    "    # Draw nodes and edges\n",
    "    nx.draw_networkx_nodes(G, pos, node_color=node_colors, node_size=node_sizes, \n",
    "                          alpha=0.8, ax=ax1)\n",
    "    nx.draw_networkx_edges(G, pos, edge_color='gray', alpha=0.6, \n",
    "                          arrows=True, arrowsize=20, ax=ax1)\n",
    "    \n",
    "    # Add labels\n",
    "    labels = {node: analyzer.modules[node].name for node in G.nodes()}\n",
    "    nx.draw_networkx_labels(G, pos, labels, font_size=8, font_weight='bold', ax=ax1)\n",
    "    \n",
    "    ax1.set_aspect('equal')\n",
    "    ax1.axis('off')\n",
    "    \n",
    "    # Right plot: Circular layout\n",
    "    ax2.set_title(\"TinyTorch Module Dependencies\\n(Circular Layout)\", fontsize=16, fontweight='bold')\n",
    "    \n",
    "    # Circular layout\n",
    "    pos_circular = nx.circular_layout(G)\n",
    "    \n",
    "    nx.draw_networkx_nodes(G, pos_circular, node_color=node_colors, node_size=node_sizes,\n",
    "                          alpha=0.8, ax=ax2)\n",
    "    nx.draw_networkx_edges(G, pos_circular, edge_color='gray', alpha=0.4,\n",
    "                          arrows=True, arrowsize=15, ax=ax2)\n",
    "    nx.draw_networkx_labels(G, pos_circular, labels, font_size=7, font_weight='bold', ax=ax2)\n",
    "    \n",
    "    ax2.set_aspect('equal')\n",
    "    ax2.axis('off')\n",
    "    \n",
    "    # Add legend\n",
    "    difficulty_colors = [plt.cm.viridis(i/5.0) for i in range(1, 6)]\n",
    "    legend_elements = [plt.Line2D([0], [0], marker='o', color='w', \n",
    "                                 markerfacecolor=color, markersize=10, \n",
    "                                 label=f\"{'⭐' * (i+1)} Difficulty\")\n",
    "                      for i, color in enumerate(difficulty_colors)]\n",
    "    \n",
    "    fig.legend(handles=legend_elements, loc='upper center', bbox_to_anchor=(0.5, 0.02), ncol=5)\n",
    "    \n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "    \n",
    "    return fig\n",
    "\n",
    "# Create dependency visualization function (called in main block)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "069b520d",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### Test the Dependency Visualization\n",
    "\n",
    "Let's verify our dependency graph captures the correct relationships."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "877f9487",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "def test_dependency_relationships():\n",
    "    \"\"\"Test that dependency relationships are correctly captured\"\"\"\n",
    "    \n",
    "    G = analyzer.dependency_graph\n",
    "    \n",
    "    # Test that setup has no prerequisites (should be a source node)\n",
    "    setup_predecessors = list(G.predecessors('setup')) if 'setup' in G else []\n",
    "    print(f\"Setup prerequisites: {setup_predecessors}\")\n",
    "    \n",
    "    # Test that capstone depends on many modules (should have many predecessors)\n",
    "    if 'capstone' in G:\n",
    "        capstone_predecessors = list(G.predecessors('capstone'))\n",
    "        print(f\"Capstone depends on {len(capstone_predecessors)} modules: {capstone_predecessors[:5]}...\")\n",
    "        assert len(capstone_predecessors) >= 5, \"Capstone should depend on many modules\"\n",
    "    \n",
    "    # Test learning path makes sense\n",
    "    learning_path = analyzer.get_learning_path()\n",
    "    print(f\"\\n📚 Learning path ({len(learning_path)} modules):\")\n",
    "    for i, module in enumerate(learning_path[:8]):  # Show first 8\n",
    "        print(f\"  {i+1:2d}. {analyzer.modules[module].title}\")\n",
    "    \n",
    "    print(\"✅ Dependency relationship tests passed!\")\n",
    "\n",
    "# test_dependency_relationships() # Test moved to main block"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "777db080",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## System Architecture Overview\n",
    "\n",
    "Let's create a comprehensive system architecture diagram showing how all TinyTorch components work together."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e03d264e",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "#| export\n",
    "def create_system_architecture_diagram(figsize=(18, 12)):\n",
    "    \"\"\"Create a comprehensive TinyTorch system architecture diagram\"\"\"\n",
    "    \n",
    "    fig, ax = plt.subplots(figsize=figsize)\n",
    "    ax.set_xlim(0, 20)\n",
    "    ax.set_ylim(0, 12)\n",
    "    ax.set_aspect('equal')\n",
    "    \n",
    "    # Define architectural layers\n",
    "    layers = {\n",
    "        'Foundation': {'y': 1, 'color': '#FF6B6B', 'modules': ['setup', 'tensor']},\n",
    "        'Core Components': {'y': 3, 'color': '#4ECDC4', 'modules': ['activations', 'layers', 'dataloader']},\n",
    "        'Network Architecture': {'y': 5, 'color': '#45B7D1', 'modules': ['dense', 'spatial', 'attention']},\n",
    "        'Training System': {'y': 7, 'color': '#96CEB4', 'modules': ['autograd', 'optimizers', 'training']},\n",
    "        'Production & Optimization': {'y': 9, 'color': '#FFEAA7', 'modules': ['compression', 'kernels', 'benchmarking']},\n",
    "        'MLOps & Integration': {'y': 11, 'color': '#DDA0DD', 'modules': ['mlops', 'capstone']}\n",
    "    }\n",
    "    \n",
    "    # Draw layer backgrounds\n",
    "    for layer_name, layer_info in layers.items():\n",
    "        y = layer_info['y']\n",
    "        rect = FancyBboxPatch((1, y-0.4), 18, 1.2, \n",
    "                             boxstyle=\"round,pad=0.1\",\n",
    "                             facecolor=layer_info['color'], \n",
    "                             alpha=0.3, edgecolor='black', linewidth=1)\n",
    "        ax.add_patch(rect)\n",
    "        \n",
    "        # Layer label\n",
    "        ax.text(0.5, y, layer_name, fontsize=12, fontweight='bold', \n",
    "               rotation=90, va='center', ha='center')\n",
    "    \n",
    "    # Draw modules within layers\n",
    "    module_positions = {}\n",
    "    for layer_name, layer_info in layers.items():\n",
    "        y = layer_info['y']\n",
    "        modules = [m for m in layer_info['modules'] if m in analyzer.modules]\n",
    "        \n",
    "        for i, module_name in enumerate(modules):\n",
    "            module = analyzer.modules[module_name]\n",
    "            x = 2 + (i * 16 / max(len(modules), 1))\n",
    "            module_positions[module_name] = (x, y)\n",
    "            \n",
    "            # Module box\n",
    "            width = min(3.5, 14 / len(modules))\n",
    "            box = FancyBboxPatch((x-width/2, y-0.3), width, 0.6,\n",
    "                               boxstyle=\"round,pad=0.05\",\n",
    "                               facecolor='white', edgecolor='black',\n",
    "                               linewidth=2)\n",
    "            ax.add_patch(box)\n",
    "            \n",
    "            # Module title\n",
    "            ax.text(x, y+0.1, module.title, fontsize=9, fontweight='bold',\n",
    "                   ha='center', va='center')\n",
    "            \n",
    "            # Difficulty and components\n",
    "            ax.text(x, y-0.15, f\"{module.difficulty} • {len(module.components)} comp.\",\n",
    "                   fontsize=7, ha='center', va='center', style='italic')\n",
    "    \n",
    "    # Draw dependency arrows between layers\n",
    "    for module_name, module in analyzer.modules.items():\n",
    "        if module_name in module_positions:\n",
    "            x1, y1 = module_positions[module_name]\n",
    "            for prereq in module.prerequisites:\n",
    "                if prereq in module_positions:\n",
    "                    x2, y2 = module_positions[prereq]\n",
    "                    if abs(y1 - y2) > 1:  # Only draw arrows between different layers\n",
    "                        arrow = ConnectionPatch((x2, y2+0.3), (x1, y1-0.3), \"data\", \"data\",\n",
    "                                              arrowstyle=\"->\", shrinkA=0, shrinkB=0,\n",
    "                                              mutation_scale=15, alpha=0.6, color='gray')\n",
    "                        ax.add_patch(arrow)\n",
    "    \n",
    "    # Title and annotations\n",
    "    ax.text(10, 11.7, 'TinyTorch System Architecture', fontsize=20, fontweight='bold', ha='center')\n",
    "    ax.text(10, 0.3, 'Data flows upward through layers • Arrows show dependencies', \n",
    "           fontsize=10, ha='center', style='italic')\n",
    "    \n",
    "    ax.set_xticks([])\n",
    "    ax.set_yticks([])\n",
    "    ax.spines['top'].set_visible(False)\n",
    "    ax.spines['right'].set_visible(False)\n",
    "    ax.spines['bottom'].set_visible(False)\n",
    "    ax.spines['left'].set_visible(False)\n",
    "    \n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "    \n",
    "    return fig, module_positions\n",
    "\n",
    "# System architecture diagram function (called in main block)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b69140e",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### Test the System Architecture Visualization\n",
    "\n",
    "Let's verify our architecture diagram correctly represents the system structure."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94012b85",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "def test_system_architecture():\n",
    "    \"\"\"Test that the system architecture is correctly represented\"\"\"\n",
    "    \n",
    "    # Test that we have positions for all modules\n",
    "    expected_modules = set(analyzer.modules.keys())\n",
    "    positioned_modules = set(module_positions.keys())\n",
    "    \n",
    "    missing_modules = expected_modules - positioned_modules\n",
    "    if missing_modules:\n",
    "        print(f\"⚠️  Missing modules in architecture: {missing_modules}\")\n",
    "    \n",
    "    # Test layer organization makes sense\n",
    "    foundation_modules = ['setup', 'tensor']\n",
    "    core_modules = ['activations', 'layers', 'dataloader']\n",
    "    \n",
    "    foundation_y = [module_positions[m][1] for m in foundation_modules if m in module_positions]\n",
    "    core_y = [module_positions[m][1] for m in core_modules if m in module_positions]\n",
    "    \n",
    "    if foundation_y and core_y:\n",
    "        assert min(core_y) > max(foundation_y), \"Core modules should be above foundation\"\n",
    "    \n",
    "    print(f\"✅ Architecture diagram includes {len(module_positions)} modules\")\n",
    "    print(f\"📊 Modules organized across {len(set(pos[1] for pos in module_positions.values()))} layers\")\n",
    "\n",
    "# test_system_architecture() # Test moved to main block"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77ab4589",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## Learning Roadmap Visualization\n",
    "\n",
    "Create an interactive learning roadmap that shows the optimal path through TinyTorch modules."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fa889a69",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "#| export\n",
    "def create_learning_roadmap(figsize=(16, 10)):\n",
    "    \"\"\"Create an interactive learning roadmap visualization\"\"\"\n",
    "    \n",
    "    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=figsize, height_ratios=[3, 1])\n",
    "    \n",
    "    # Get learning path and levels\n",
    "    learning_path = analyzer.get_learning_path()\n",
    "    levels = analyzer.get_module_levels()\n",
    "    \n",
    "    # Top plot: Learning path flowchart\n",
    "    ax1.set_title('TinyTorch Learning Roadmap\\n(Optimal Learning Sequence)', \n",
    "                 fontsize=16, fontweight='bold')\n",
    "    \n",
    "    # Calculate positions for roadmap\n",
    "    path_positions = {}\n",
    "    cumulative_time = 0\n",
    "    y_positions = {}\n",
    "    \n",
    "    for i, module_name in enumerate(learning_path):\n",
    "        if module_name in analyzer.modules:\n",
    "            module = analyzer.modules[module_name]\n",
    "            level = levels.get(module_name, 0)\n",
    "            \n",
    "            # X position based on cumulative time\n",
    "            x = cumulative_time + module.estimated_hours() / 2\n",
    "            # Y position based on dependency level with some jitter\n",
    "            y = level + (i % 3 - 1) * 0.3\n",
    "            \n",
    "            path_positions[module_name] = (x, y)\n",
    "            y_positions[module_name] = y\n",
    "            cumulative_time += module.estimated_hours()\n",
    "    \n",
    "    # Draw the learning path\n",
    "    for i, module_name in enumerate(learning_path[:-1]):\n",
    "        if module_name in path_positions and learning_path[i+1] in path_positions:\n",
    "            x1, y1 = path_positions[module_name]\n",
    "            x2, y2 = path_positions[learning_path[i+1]]\n",
    "            \n",
    "            # Draw connecting line\n",
    "            ax1.plot([x1, x2], [y1, y2], 'gray', alpha=0.5, linewidth=1, zorder=1)\n",
    "    \n",
    "    # Draw modules\n",
    "    for module_name in learning_path:\n",
    "        if module_name in analyzer.modules and module_name in path_positions:\n",
    "            module = analyzer.modules[module_name]\n",
    "            x, y = path_positions[module_name]\n",
    "            \n",
    "            # Color based on difficulty\n",
    "            difficulty = module.difficulty_level()\n",
    "            color = plt.cm.viridis(difficulty / 5.0)\n",
    "            \n",
    "            # Draw module circle\n",
    "            circle = Circle((x, y), 0.4, facecolor=color, edgecolor='black',\n",
    "                          linewidth=2, alpha=0.8, zorder=3)\n",
    "            ax1.add_patch(circle)\n",
    "            \n",
    "            # Module number\n",
    "            ax1.text(x, y, str(learning_path.index(module_name) + 1), \n",
    "                    fontsize=10, fontweight='bold', ha='center', va='center',\n",
    "                    color='white', zorder=4)\n",
    "            \n",
    "            # Module name below\n",
    "            ax1.text(x, y-0.7, module.title, fontsize=8, ha='center', va='top',\n",
    "                    rotation=45, fontweight='bold')\n",
    "    \n",
    "    ax1.set_xlim(-2, cumulative_time + 2)\n",
    "    ax1.set_ylim(-1, max(y_positions.values()) + 1)\n",
    "    ax1.set_xlabel('Cumulative Learning Time (hours)', fontsize=12)\n",
    "    ax1.set_ylabel('Dependency Level', fontsize=12)\n",
    "    ax1.grid(True, alpha=0.3)\n",
    "    \n",
    "    # Bottom plot: Time and difficulty analysis\n",
    "    ax2.set_title('Module Difficulty and Time Distribution', fontsize=14, fontweight='bold')\n",
    "    \n",
    "    module_names = [analyzer.modules[name].title[:15] for name in learning_path \n",
    "                   if name in analyzer.modules]\n",
    "    difficulties = [analyzer.modules[name].difficulty_level() for name in learning_path \n",
    "                   if name in analyzer.modules]\n",
    "    times = [analyzer.modules[name].estimated_hours() for name in learning_path \n",
    "            if name in analyzer.modules]\n",
    "    \n",
    "    # Create stacked bar chart\n",
    "    x_pos = np.arange(len(module_names))\n",
    "    \n",
    "    # Time bars\n",
    "    bars1 = ax2.bar(x_pos, times, alpha=0.7, label='Time (hours)', color='lightblue')\n",
    "    \n",
    "    # Difficulty overlay\n",
    "    ax2_twin = ax2.twinx()\n",
    "    bars2 = ax2_twin.bar(x_pos, difficulties, alpha=0.5, label='Difficulty (⭐)', \n",
    "                        color='orange', width=0.6)\n",
    "    \n",
    "    ax2.set_xlabel('Modules (in learning order)', fontsize=12)\n",
    "    ax2.set_ylabel('Time (hours)', fontsize=12, color='blue')\n",
    "    ax2_twin.set_ylabel('Difficulty Level', fontsize=12, color='orange')\n",
    "    \n",
    "    ax2.set_xticks(x_pos)\n",
    "    ax2.set_xticklabels(module_names, rotation=45, ha='right')\n",
    "    \n",
    "    # Legends\n",
    "    ax2.legend(loc='upper left')\n",
    "    ax2_twin.legend(loc='upper right')\n",
    "    \n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "    \n",
    "    return fig, learning_path, cumulative_time\n",
    "\n",
    "# Learning roadmap function (called in main block)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c4a6fce",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### Test the Learning Roadmap\n",
    "\n",
    "Let's verify our learning roadmap is pedagogically sound and follows dependency constraints."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3612b019",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "def test_learning_roadmap():\n",
    "    \"\"\"Test that the learning roadmap respects dependencies and makes pedagogical sense\"\"\"\n",
    "    \n",
    "    # Test that all prerequisites come before dependents\n",
    "    path_indices = {module: i for i, module in enumerate(learning_path)}\n",
    "    \n",
    "    violations = []\n",
    "    for module_name in learning_path:\n",
    "        if module_name in analyzer.modules:\n",
    "            module = analyzer.modules[module_name]\n",
    "            module_index = path_indices[module_name]\n",
    "            \n",
    "            for prereq in module.prerequisites:\n",
    "                if prereq in path_indices:\n",
    "                    prereq_index = path_indices[prereq]\n",
    "                    if prereq_index >= module_index:\n",
    "                        violations.append(f\"{module_name} comes before its prerequisite {prereq}\")\n",
    "    \n",
    "    if violations:\n",
    "        print(\"⚠️  Dependency violations found:\")\n",
    "        for violation in violations:\n",
    "            print(f\"   {violation}\")\n",
    "    else:\n",
    "        print(\"✅ Learning roadmap respects all dependencies\")\n",
    "    \n",
    "    # Test reasonable progression\n",
    "    foundation_modules = ['setup', 'tensor']\n",
    "    advanced_modules = ['capstone', 'mlops', 'benchmarking']\n",
    "    \n",
    "    foundation_positions = [path_indices.get(m, -1) for m in foundation_modules]\n",
    "    advanced_positions = [path_indices.get(m, -1) for m in advanced_modules]\n",
    "    \n",
    "    foundation_positions = [p for p in foundation_positions if p >= 0]\n",
    "    advanced_positions = [p for p in advanced_positions if p >= 0]\n",
    "    \n",
    "    if foundation_positions and advanced_positions:\n",
    "        if max(foundation_positions) < min(advanced_positions):\n",
    "            print(\"✅ Foundation modules come before advanced modules\")\n",
    "        else:\n",
    "            print(\"⚠️  Some advanced modules come before foundation modules\")\n",
    "    \n",
    "    print(f\"📊 Total learning time: {total_time:.1f} hours ({total_time/8:.1f} work days)\")\n",
    "\n",
    "# test_learning_roadmap() # Test moved to main block"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9c879b00",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## Component Relationship Analysis\n",
    "\n",
    "Let's analyze the specific components within each module and how they relate to each other."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f29d6101",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "#| export\n",
    "def create_component_analysis(figsize=(14, 10)):\n",
    "    \"\"\"Create visualization of components within modules and their relationships\"\"\"\n",
    "    \n",
    "    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=figsize)\n",
    "    \n",
    "    # 1. Components per module\n",
    "    modules = [name for name in learning_path if name in analyzer.modules]\n",
    "    component_counts = [len(analyzer.modules[name].components) for name in modules]\n",
    "    module_titles = [analyzer.modules[name].title for name in modules]\n",
    "    \n",
    "    ax1.bar(range(len(modules)), component_counts, \n",
    "           color=plt.cm.viridis(np.linspace(0, 1, len(modules))))\n",
    "    ax1.set_title('Components per Module', fontweight='bold')\n",
    "    ax1.set_xlabel('Module')\n",
    "    ax1.set_ylabel('Number of Components')\n",
    "    ax1.set_xticks(range(len(modules)))\n",
    "    ax1.set_xticklabels([title[:10] for title in module_titles], rotation=45)\n",
    "    \n",
    "    # 2. Difficulty vs Components scatter\n",
    "    difficulties = [analyzer.modules[name].difficulty_level() for name in modules]\n",
    "    times = [analyzer.modules[name].estimated_hours() for name in modules]\n",
    "    \n",
    "    scatter = ax2.scatter(component_counts, difficulties, s=[t*20 for t in times], \n",
    "                         c=times, cmap='plasma', alpha=0.7)\n",
    "    ax2.set_title('Module Complexity Analysis', fontweight='bold')\n",
    "    ax2.set_xlabel('Number of Components')\n",
    "    ax2.set_ylabel('Difficulty Level')\n",
    "    ax2.grid(True, alpha=0.3)\n",
    "    \n",
    "    # Add colorbar for time\n",
    "    cbar = plt.colorbar(scatter, ax=ax2)\n",
    "    cbar.set_label('Time (hours)')\n",
    "    \n",
    "    # 3. Module categories pie chart\n",
    "    categories = {\n",
    "        'Foundation': ['setup', 'tensor', 'activations'],\n",
    "        'Architecture': ['layers', 'dense', 'spatial', 'attention'],\n",
    "        'Training': ['dataloader', 'autograd', 'optimizers', 'training'],\n",
    "        'Production': ['compression', 'kernels', 'benchmarking', 'mlops', 'capstone']\n",
    "    }\n",
    "    \n",
    "    category_counts = []\n",
    "    category_labels = []\n",
    "    category_colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4']\n",
    "    \n",
    "    for category, module_list in categories.items():\n",
    "        count = sum(1 for m in module_list if m in analyzer.modules)\n",
    "        if count > 0:\n",
    "            category_counts.append(count)\n",
    "            category_labels.append(f'{category}\\n({count} modules)')\n",
    "    \n",
    "    ax3.pie(category_counts, labels=category_labels, colors=category_colors[:len(category_counts)],\n",
    "           autopct='%1.0f%%', startangle=90)\n",
    "    ax3.set_title('Module Distribution by Category', fontweight='bold')\n",
    "    \n",
    "    # 4. Learning progression timeline\n",
    "    cumulative_components = np.cumsum([0] + component_counts)\n",
    "    cumulative_time = np.cumsum([0] + times)\n",
    "    \n",
    "    ax4.plot(cumulative_time[:-1], cumulative_components[:-1], 'o-', linewidth=2, markersize=6)\n",
    "    ax4.set_title('Learning Progression', fontweight='bold')\n",
    "    ax4.set_xlabel('Cumulative Time (hours)')\n",
    "    ax4.set_ylabel('Cumulative Components Learned')\n",
    "    ax4.grid(True, alpha=0.3)\n",
    "    \n",
    "    # Add milestone annotations\n",
    "    milestones = [0, len(modules)//4, len(modules)//2, 3*len(modules)//4, len(modules)-1]\n",
    "    for i in milestones:\n",
    "        if i < len(cumulative_time) - 1:\n",
    "            ax4.annotate(f'{cumulative_components[i]} comp.\\n{cumulative_time[i]:.0f}h',\n",
    "                        xy=(cumulative_time[i], cumulative_components[i]),\n",
    "                        xytext=(10, 10), textcoords='offset points',\n",
    "                        bbox=dict(boxstyle='round,pad=0.3', facecolor='yellow', alpha=0.7),\n",
    "                        fontsize=8)\n",
    "    \n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "    \n",
    "    return fig\n",
    "\n",
    "# Component analysis function (called in main block)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bcaf724a",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "### Test Component Analysis\n",
    "\n",
    "Let's verify our component analysis provides meaningful insights."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "341ed086",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "def test_component_analysis():\n",
    "    \"\"\"Test that component analysis reveals meaningful patterns\"\"\"\n",
    "    \n",
    "    # Test component distribution\n",
    "    total_components = sum(len(module.components) for module in analyzer.modules.values())\n",
    "    avg_components = total_components / len(analyzer.modules)\n",
    "    \n",
    "    print(f\"📊 Total components across all modules: {total_components}\")\n",
    "    print(f\"📊 Average components per module: {avg_components:.1f}\")\n",
    "    \n",
    "    # Find modules with most/least components\n",
    "    component_counts = [(name, len(module.components)) for name, module in analyzer.modules.items()]\n",
    "    component_counts.sort(key=lambda x: x[1], reverse=True)\n",
    "    \n",
    "    print(f\"\\n🏆 Modules with most components:\")\n",
    "    for name, count in component_counts[:3]:\n",
    "        print(f\"   {analyzer.modules[name].title}: {count} components\")\n",
    "    \n",
    "    print(f\"\\n🏆 Modules with least components:\")\n",
    "    for name, count in component_counts[-3:]:\n",
    "        print(f\"   {analyzer.modules[name].title}: {count} components\")\n",
    "    \n",
    "    # Test correlation between difficulty and components\n",
    "    difficulties = [module.difficulty_level() for module in analyzer.modules.values()]\n",
    "    components = [len(module.components) for module in analyzer.modules.values()]\n",
    "    \n",
    "    correlation = np.corrcoef(difficulties, components)[0, 1]\n",
    "    print(f\"\\n📈 Correlation between difficulty and components: {correlation:.2f}\")\n",
    "    \n",
    "    if correlation > 0.3:\n",
    "        print(\"✅ Higher difficulty modules tend to have more components\")\n",
    "    elif correlation < -0.3:\n",
    "        print(\"⚠️  Higher difficulty modules tend to have fewer components\")\n",
    "    else:\n",
    "        print(\"📊 No strong correlation between difficulty and component count\")\n",
    "\n",
    "# test_component_analysis() # Test moved to main block"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "be6a7a8c",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## Export Functions and Module Interface\n",
    "\n",
    "Create functions that can be imported and used by other parts of TinyTorch."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b37a5322",
   "metadata": {
    "lines_to_next_cell": 1
   },
   "outputs": [],
   "source": [
    "#| export\n",
    "def get_tinytorch_overview() -> Dict:\n",
    "    \"\"\"Get comprehensive overview of TinyTorch system for external use\"\"\"\n",
    "    return {\n",
    "        'total_modules': len(analyzer.modules),\n",
    "        'total_components': sum(len(module.components) for module in analyzer.modules.values()),\n",
    "        'learning_path': analyzer.get_learning_path(),\n",
    "        'total_time_hours': sum(module.estimated_hours() for module in analyzer.modules.values()),\n",
    "        'difficulty_levels': {name: module.difficulty_level() for name, module in analyzer.modules.items()},\n",
    "        'module_categories': {\n",
    "            'foundation': ['setup', 'tensor', 'activations'],\n",
    "            'architecture': ['layers', 'dense', 'spatial', 'attention'], \n",
    "            'training': ['dataloader', 'autograd', 'optimizers', 'training'],\n",
    "            'production': ['compression', 'kernels', 'benchmarking', 'mlops', 'capstone']\n",
    "        }\n",
    "    }\n",
    "\n",
    "#| export\n",
    "def visualize_tinytorch_system(save_plots: bool = False) -> Dict:\n",
    "    \"\"\"Generate all TinyTorch system visualizations\"\"\"\n",
    "    \n",
    "    visualizations = {}\n",
    "    \n",
    "    print(\"🎨 Generating TinyTorch system visualizations...\")\n",
    "    \n",
    "    # Generate dependency graph\n",
    "    print(\"   📊 Creating dependency graph...\")\n",
    "    dep_fig = create_dependency_graph_visualization()\n",
    "    visualizations['dependency_graph'] = dep_fig\n",
    "    \n",
    "    # Generate architecture diagram  \n",
    "    print(\"   🏗️  Creating architecture diagram...\")\n",
    "    arch_fig, positions = create_system_architecture_diagram()\n",
    "    visualizations['architecture'] = arch_fig\n",
    "    \n",
    "    # Generate learning roadmap\n",
    "    print(\"   📚 Creating learning roadmap...\")\n",
    "    roadmap_fig, path, time = create_learning_roadmap()\n",
    "    visualizations['roadmap'] = roadmap_fig\n",
    "    \n",
    "    # Generate component analysis\n",
    "    print(\"   🔍 Creating component analysis...\")\n",
    "    component_fig = create_component_analysis()\n",
    "    visualizations['components'] = component_fig\n",
    "    \n",
    "    if save_plots:\n",
    "        print(\"   💾 Saving plots to files...\")\n",
    "        for name, fig in visualizations.items():\n",
    "            fig.savefig(f'tinytorch_{name}.png', dpi=300, bbox_inches='tight')\n",
    "    \n",
    "    print(\"✅ All visualizations generated successfully!\")\n",
    "    \n",
    "    return visualizations\n",
    "\n",
    "#| export\n",
    "def get_module_info(module_name: str) -> Dict:\n",
    "    \"\"\"Get detailed information about a specific module\"\"\"\n",
    "    if module_name not in analyzer.modules:\n",
    "        return {'error': f'Module {module_name} not found'}\n",
    "    \n",
    "    module = analyzer.modules[module_name]\n",
    "    return {\n",
    "        'name': module.name,\n",
    "        'title': module.title,\n",
    "        'description': module.description,\n",
    "        'prerequisites': module.prerequisites,\n",
    "        'enables': module.enables,\n",
    "        'components': module.components,\n",
    "        'difficulty': module.difficulty,\n",
    "        'difficulty_level': module.difficulty_level(),\n",
    "        'time_estimate': module.time_estimate,\n",
    "        'estimated_hours': module.estimated_hours(),\n",
    "        'exports_to': module.exports_to\n",
    "    }\n",
    "\n",
    "#| export\n",
    "def get_learning_recommendations(current_module: str = None) -> Dict:\n",
    "    \"\"\"Get personalized learning recommendations\"\"\"\n",
    "    path = analyzer.get_learning_path()\n",
    "    \n",
    "    if current_module is None:\n",
    "        return {\n",
    "            'recommended_start': path[0] if path else None,\n",
    "            'full_path': path,\n",
    "            'total_time': sum(analyzer.modules[name].estimated_hours() \n",
    "                            for name in path if name in analyzer.modules)\n",
    "        }\n",
    "    \n",
    "    if current_module not in path:\n",
    "        return {'error': f'Module {current_module} not found in learning path'}\n",
    "    \n",
    "    current_index = path.index(current_module)\n",
    "    \n",
    "    return {\n",
    "        'current_module': current_module,\n",
    "        'progress': f\"{current_index + 1}/{len(path)}\",\n",
    "        'next_modules': path[current_index + 1:current_index + 4],  # Next 3 modules\n",
    "        'remaining_time': sum(analyzer.modules[name].estimated_hours() \n",
    "                            for name in path[current_index + 1:] \n",
    "                            if name in analyzer.modules),\n",
    "        'prerequisites_completed': path[:current_index],\n",
    "        'can_start': [name for name in path[current_index + 1:] \n",
    "                     if all(prereq in path[:current_index + 1] \n",
    "                           for prereq in analyzer.modules.get(name, ModuleInfo('','','',[],'',[],'','','')).prerequisites)]\n",
    "    }\n",
    "\n",
    "# Export functions (tested in main block)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "03d2a119",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "## ML Systems Thinking Questions\n",
    "\n",
    "Let's explore how TinyTorch's architecture connects to broader ML systems and production frameworks."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "baf329b8",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "### System Architecture & Design Patterns\n",
    "\n",
    "**Reflection Questions:**\n",
    "\n",
    "1. **Modular Design Philosophy**: How does TinyTorch's module dependency system compare to frameworks like PyTorch or TensorFlow? What are the advantages and trade-offs of explicit dependency management?\n",
    "\n",
    "2. **Component Composition**: Notice how higher-level modules (like `training`) depend on multiple lower-level modules (`tensor`, `autograd`, `optimizers`). How does this pattern reflect real ML system architecture?\n",
    "\n",
    "3. **Framework Evolution**: Looking at the learning roadmap, how might you extend TinyTorch to support distributed training or GPU acceleration? Where would new modules fit in the dependency graph?\n",
    "\n",
    "### Production ML Systems\n",
    "\n",
    "**Reflection Questions:**\n",
    "\n",
    "4. **Deployment Pipeline**: How do the later modules (`compression`, `benchmarking`, `mlops`) mirror real-world ML deployment concerns? What additional modules might production systems require?\n",
    "\n",
    "5. **System Integration**: If you were to deploy a TinyTorch model in production, which modules would be most critical for runtime efficiency? How might you minimize dependencies?\n",
    "\n",
    "6. **Monitoring & Observability**: How does the `mlops` module's position as a terminal node reflect its role in production systems? What additional monitoring capabilities might be needed?\n",
    "\n",
    "### Framework Design Decisions\n",
    "\n",
    "**Reflection Questions:**\n",
    "\n",
    "7. **Dependency Management**: Compare TinyTorch's explicit prerequisite system to frameworks like Keras or scikit-learn. How do design decisions about dependencies affect developer experience?\n",
    "\n",
    "8. **Component Granularity**: Some modules have many components (like `training`) while others have few (like `setup`). How do you balance component granularity in ML framework design?\n",
    "\n",
    "9. **Educational vs Production**: How might the educational goals of TinyTorch influence its architecture differently than a production framework? Where do you see pedagogical design choices?\n",
    "\n",
    "### Performance & Scalability\n",
    "\n",
    "**Reflection Questions:**\n",
    "\n",
    "10. **Computational Graph**: How does TinyTorch's module structure relate to computational graphs in frameworks like PyTorch or JAX? Where do you see opportunities for optimization?\n",
    "\n",
    "11. **Memory Management**: Looking at the component analysis, which modules are likely to be most memory-intensive? How might this influence deployment strategies?\n",
    "\n",
    "12. **Hardware Acceleration**: The `kernels` module focuses on hardware-aware optimization. How do production frameworks handle the trade-off between abstraction and performance?\n",
    "\n",
    "*These questions are designed to help you think beyond implementation details toward the broader patterns and principles that guide ML systems design in industry.*"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7bfaf3b7",
   "metadata": {
    "cell_marker": "\"\"\"",
    "lines_to_next_cell": 1
   },
   "source": [
    "## Comprehensive Testing\n",
    "\n",
    "Let's run comprehensive tests to ensure all our visualizations and analysis tools work correctly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "de1be3e8",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_comprehensive_tests():\n",
    "    \"\"\"Run comprehensive tests of the introduction module functionality\"\"\"\n",
    "    \n",
    "    print(\"🧪 Running comprehensive tests for TinyTorch Introduction Module...\")\n",
    "    print(\"=\" * 60)\n",
    "    \n",
    "    # Test 1: Module Loading\n",
    "    print(\"\\n1️⃣  Testing module loading...\")\n",
    "    assert len(analyzer.modules) >= 10, \"Should load multiple modules\"\n",
    "    assert 'setup' in analyzer.modules, \"Should load setup module\"\n",
    "    assert 'tensor' in analyzer.modules, \"Should load tensor module\"\n",
    "    print(\"✅ Module loading tests passed\")\n",
    "    \n",
    "    # Test 2: Dependency Graph\n",
    "    print(\"\\n2️⃣  Testing dependency graph...\")\n",
    "    G = analyzer.dependency_graph\n",
    "    assert G.number_of_nodes() >= 10, \"Should have multiple nodes\"\n",
    "    assert G.number_of_edges() >= 5, \"Should have dependency edges\"\n",
    "    print(\"✅ Dependency graph tests passed\")\n",
    "    \n",
    "    # Test 3: Learning Path\n",
    "    print(\"\\n3️⃣  Testing learning path...\")\n",
    "    path = analyzer.get_learning_path()\n",
    "    assert len(path) >= 10, \"Should have meaningful learning path\"\n",
    "    \n",
    "    # Verify no dependency violations\n",
    "    path_indices = {module: i for i, module in enumerate(path)}\n",
    "    violations = 0\n",
    "    for module_name in path:\n",
    "        if module_name in analyzer.modules:\n",
    "            module = analyzer.modules[module_name]\n",
    "            for prereq in module.prerequisites:\n",
    "                if prereq in path_indices:\n",
    "                    if path_indices[prereq] >= path_indices[module_name]:\n",
    "                        violations += 1\n",
    "    \n",
    "    assert violations == 0, f\"Learning path should have no dependency violations (found {violations})\"\n",
    "    print(\"✅ Learning path tests passed\")\n",
    "    \n",
    "    # Test 4: Component Analysis\n",
    "    print(\"\\n4️⃣  Testing component analysis...\")\n",
    "    total_components = sum(len(module.components) for module in analyzer.modules.values())\n",
    "    assert total_components >= 20, \"Should have meaningful number of components\"\n",
    "    print(\"✅ Component analysis tests passed\")\n",
    "    \n",
    "    # Test 5: Export Functions\n",
    "    print(\"\\n5️⃣  Testing export functions...\")\n",
    "    overview = get_tinytorch_overview()\n",
    "    assert 'total_modules' in overview, \"Overview should include module count\"\n",
    "    assert 'learning_path' in overview, \"Overview should include learning path\"\n",
    "    \n",
    "    module_info = get_module_info('setup')\n",
    "    assert 'title' in module_info, \"Module info should include title\"\n",
    "    \n",
    "    recommendations = get_learning_recommendations()\n",
    "    assert 'recommended_start' in recommendations, \"Should provide starting recommendation\"\n",
    "    print(\"✅ Export function tests passed\")\n",
    "    \n",
    "    # Test 6: Visualization Generation\n",
    "    print(\"\\n6️⃣  Testing visualization generation...\")\n",
    "    try:\n",
    "        # Test that we can generate all visualizations without errors\n",
    "        dep_fig = create_dependency_graph_visualization()\n",
    "        arch_fig, positions = create_system_architecture_diagram()\n",
    "        roadmap_fig, path, time = create_learning_roadmap()\n",
    "        component_fig = create_component_analysis()\n",
    "        \n",
    "        assert dep_fig is not None, \"Should generate dependency graph\"\n",
    "        assert arch_fig is not None, \"Should generate architecture diagram\"\n",
    "        assert roadmap_fig is not None, \"Should generate roadmap\"\n",
    "        assert component_fig is not None, \"Should generate component analysis\"\n",
    "        \n",
    "        # Close figures to save memory\n",
    "        plt.close(dep_fig)\n",
    "        plt.close(arch_fig)\n",
    "        plt.close(roadmap_fig)\n",
    "        plt.close(component_fig)\n",
    "        \n",
    "        print(\"✅ Visualization generation tests passed\")\n",
    "    except Exception as e:\n",
    "        print(f\"❌ Visualization test failed: {e}\")\n",
    "        raise\n",
    "    \n",
    "    print(\"\\n\" + \"=\" * 60)\n",
    "    print(\"🎉 ALL TESTS PASSED! TinyTorch Introduction Module is working correctly!\")\n",
    "    print(\"=\" * 60)\n",
    "    \n",
    "    # Summary statistics\n",
    "    print(f\"\\n📊 System Summary:\")\n",
    "    print(f\"   • {len(analyzer.modules)} modules loaded\")\n",
    "    print(f\"   • {analyzer.dependency_graph.number_of_edges()} dependencies mapped\")\n",
    "    print(f\"   • {len(analyzer.get_learning_path())} modules in learning path\")\n",
    "    print(f\"   • {sum(len(m.components) for m in analyzer.modules.values())} total components\")\n",
    "    print(f\"   • {sum(m.estimated_hours() for m in analyzer.modules.values()):.1f} total learning hours\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    # Run individual tests\n",
    "    test_module_analyzer()\n",
    "    test_dependency_relationships()\n",
    "    test_system_architecture()\n",
    "    test_learning_roadmap()\n",
    "    test_component_analysis()\n",
    "    \n",
    "    # Run comprehensive test suite\n",
    "    run_comprehensive_tests()\n",
    "    \n",
    "    # Create and display visualizations\n",
    "    dependency_fig = create_dependency_graph_visualization()\n",
    "    arch_fig, module_positions = create_system_architecture_diagram()\n",
    "    roadmap_fig, learning_path, total_time = create_learning_roadmap()\n",
    "    component_fig = create_component_analysis()\n",
    "    \n",
    "    print(f\"📚 Learning path contains {len(learning_path)} modules\")\n",
    "    print(f\"⏱️  Total estimated time: {total_time:.1f} hours\")\n",
    "    \n",
    "    # Test export functions\n",
    "    print(\"🧪 Testing export functions...\")\n",
    "    overview = get_tinytorch_overview()\n",
    "    print(f\"📊 System Overview: {overview['total_modules']} modules, {overview['total_components']} components\")\n",
    "    \n",
    "    setup_info = get_module_info('setup')\n",
    "    print(f\"📋 Setup Module: {setup_info['title']} - {setup_info['difficulty']}\")\n",
    "    \n",
    "    recommendations = get_learning_recommendations()\n",
    "    print(f\"📚 Learning Recommendations: Start with {recommendations['recommended_start']}\")\n",
    "    print(\"✅ Export functions working correctly!\")\n",
    "    \n",
    "    print(f\"📊 Loaded {len(analyzer.modules)} TinyTorch modules\")\n",
    "    print(f\"🔗 Built dependency graph with {analyzer.dependency_graph.number_of_edges()} connections\")\n",
    "    \n",
    "    print(\"All tests passed!\")\n",
    "    print(\"🎯 TinyTorch Introduction Module Complete!\")\n",
    "    print(\"📦 Exported functions ready for use by other modules\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9eb5b3b4",
   "metadata": {
    "cell_marker": "\"\"\""
   },
   "source": [
    "## Module Summary\n",
    "\n",
    "**Congratulations!** You've successfully explored the complete TinyTorch system architecture.\n",
    "\n",
    "### What You've Accomplished\n",
    "\n",
    "1. **📊 System Analysis**: Built tools to automatically analyze module dependencies and relationships\n",
    "2. **🎨 Interactive Visualizations**: Created comprehensive visual overviews of the entire framework\n",
    "3. **📚 Learning Roadmap**: Generated an optimal learning path through all 16 modules\n",
    "4. **🔍 Component Analysis**: Analyzed the components within each module and their complexity\n",
    "5. **🏗️  Architecture Overview**: Visualized how all TinyTorch components work together\n",
    "6. **🧪 Comprehensive Testing**: Validated that all analysis tools work correctly\n",
    "\n",
    "### Key Insights Discovered\n",
    "\n",
    "- **TinyTorch contains {len(analyzer.modules)} modules** with {sum(len(m.components) for m in analyzer.modules.values())} total components\n",
    "- **Learning path spans {sum(m.estimated_hours() for m in analyzer.modules.values()):.1f} hours** of estimated study time\n",
    "- **Dependency structure** ensures proper learning progression from foundations to production\n",
    "- **Modular design** enables flexible learning and component reuse\n",
    "\n",
    "### How This Connects to Industry ML Systems\n",
    "\n",
    "The architecture patterns you've explored in TinyTorch mirror those used in production ML frameworks:\n",
    "\n",
    "- **Modular Dependencies**: Similar to PyTorch's module system\n",
    "- **Component Composition**: Reflects how TensorFlow builds complex operations from primitives  \n",
    "- **Production Pipeline**: MLOps module mirrors real deployment concerns\n",
    "- **Performance Optimization**: Kernels and compression reflect production efficiency needs\n",
    "\n",
    "### Next Steps\n",
    "\n",
    "Now you're ready to dive into any TinyTorch module with a complete understanding of how it fits into the broader system. Use the learning roadmap to guide your journey through building a complete neural network framework from scratch!\n",
    "\n",
    "**Happy Learning! 🚀**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3d158287",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Export key functions for use by other modules\n",
    "__all__ = [\n",
    "    'TinyTorchAnalyzer',\n",
    "    'get_tinytorch_overview', \n",
    "    'visualize_tinytorch_system',\n",
    "    'get_module_info',\n",
    "    'get_learning_recommendations',\n",
    "    'create_dependency_graph_visualization',\n",
    "    'create_system_architecture_diagram', \n",
    "    'create_learning_roadmap',\n",
    "    'create_component_analysis'\n",
    "]"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "nbgrader,-all",
   "main_language": "python",
   "notebook_metadata_filter": "-all"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
