Files
2026-06-01 23:32:14 +02:00

899 lines
37 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "bbb863a1",
"metadata": {},
"source": [
"# Aufgabe 2 - Designing Efficient CNNs for FashionMNIST\n",
"\n",
"In this exercise we want to design and implement our own efficient CNN in pytorch with the\n",
"techniques introduced in the lecture. Because we cannot calculate the latency on the hardware\n",
"yet, we use the amount of FLOPs as a proxy metric for now. Keep in mind that FLOPs only\n",
"correlate losely with latency.\n",
"\n",
"## 2.1 - Baseline Model\n",
"\n",
"Before designing an efficient architecture we want to implement a baseline model to compare\n",
"to. For that design a CNN that achieves at least a Test Accuracy ≥ 91% on FashionMNIST.\n",
"What is the architecture? How did you train it?"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "cc5ec561",
"metadata": {},
"outputs": [],
"source": [
"# Imports\n",
"import torch\n",
"import torch.nn as nn\n",
"from torchvision import datasets\n",
"from torchvision import transforms\n",
"from torch.utils.data import DataLoader\n",
"from torch.utils.flop_counter import FlopCounterMode"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "fe685559",
"metadata": {},
"outputs": [],
"source": [
"# Daten Laden\n",
"transform = transforms.ToTensor()\n",
"\n",
"train_dataset = datasets.FashionMNIST(\n",
" root=\"./data\",\n",
" train=True,\n",
" download=True,\n",
" transform=transform\n",
")\n",
"\n",
"test_dataset = datasets.FashionMNIST(\n",
" root=\"./data\",\n",
" train=False,\n",
" download=True,\n",
" transform=transform\n",
")\n",
"\n",
"train_loader = DataLoader(\n",
" train_dataset,\n",
" batch_size=128,\n",
" shuffle=True\n",
")\n",
"\n",
"test_loader = DataLoader(\n",
" test_dataset,\n",
" batch_size=128\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "b9eba0b3",
"metadata": {},
"outputs": [],
"source": [
"# Modell definieren\n",
"class BaselineCNN(nn.Module):\n",
" def __init__(self):\n",
" super().__init__()\n",
"\n",
" self.features = nn.Sequential(\n",
" nn.Conv2d(1, 32, kernel_size=3, padding=1),\n",
" nn.BatchNorm2d(32),\n",
" nn.ReLU(),\n",
"\n",
" nn.MaxPool2d(2),\n",
"\n",
" nn.Conv2d(32, 64, kernel_size=3, padding=1),\n",
" nn.BatchNorm2d(64),\n",
" nn.ReLU(),\n",
"\n",
" nn.MaxPool2d(2)\n",
" )\n",
"\n",
" self.classifier = nn.Sequential(\n",
" nn.Flatten(),\n",
" nn.Linear(64 * 7 * 7, 128),\n",
" nn.ReLU(),\n",
" nn.Dropout(0.3),\n",
" nn.Linear(128, 10)\n",
" )\n",
"\n",
" def forward(self, x):\n",
" x = self.features(x)\n",
" return self.classifier(x)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "727e78f0",
"metadata": {},
"outputs": [],
"source": [
"device = torch.device(\n",
" \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "e601cfc3",
"metadata": {},
"outputs": [],
"source": [
"# Evaluation\n",
"def evaluate(model, loader):\n",
"\n",
" model.eval()\n",
"\n",
" correct = 0\n",
" total = 0\n",
"\n",
" with torch.no_grad():\n",
"\n",
" for images, labels in loader:\n",
"\n",
" images = images.to(device)\n",
" labels = labels.to(device)\n",
"\n",
" outputs = model(images)\n",
"\n",
" pred = outputs.argmax(dim=1)\n",
"\n",
" total += labels.size(0)\n",
" correct += (pred == labels).sum().item()\n",
"\n",
" return 100 * correct / total"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "4bb7adb2",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch [1/10] Loss: 0.4392 Test Acc: 88.35%\n",
"Epoch [2/10] Loss: 0.2589 Test Acc: 90.31%\n",
"Epoch [3/10] Loss: 0.2085 Test Acc: 89.40%\n",
"Epoch [4/10] Loss: 0.1787 Test Acc: 91.56%\n",
"Epoch [5/10] Loss: 0.1536 Test Acc: 91.81%\n",
"Epoch [6/10] Loss: 0.1299 Test Acc: 91.80%\n",
"Epoch [7/10] Loss: 0.1102 Test Acc: 91.71%\n",
"Epoch [8/10] Loss: 0.0903 Test Acc: 92.02%\n",
"Epoch [9/10] Loss: 0.0756 Test Acc: 91.33%\n",
"Epoch [10/10] Loss: 0.0659 Test Acc: 91.67%\n"
]
}
],
"source": [
"# Training\n",
"model = BaselineCNN().to(device)\n",
"criterion = nn.CrossEntropyLoss()\n",
"\n",
"optimizer = torch.optim.Adam(\n",
" model.parameters(),\n",
" lr=1e-3\n",
")\n",
"\n",
"epochs = 10\n",
"batch_size = 128\n",
"\n",
"for epoch in range(epochs):\n",
"\n",
" running_loss = 0.0\n",
"\n",
" for images, labels in train_loader:\n",
"\n",
" images = images.to(device)\n",
" labels = labels.to(device)\n",
"\n",
" # Gradienten zurücksetzen\n",
" optimizer.zero_grad()\n",
"\n",
" # Forward Pass\n",
" outputs = model(images)\n",
"\n",
" # Loss berechnen\n",
" loss = criterion(outputs, labels)\n",
"\n",
" # Backpropagation\n",
" loss.backward()\n",
"\n",
" # Gewichte aktualisieren\n",
" optimizer.step()\n",
"\n",
" running_loss += loss.item()\n",
"\n",
" avg_loss = running_loss / len(train_loader)\n",
"\n",
" test_acc = evaluate(model, test_loader)\n",
"\n",
" print(\n",
" f\"Epoch [{epoch+1}/{epochs}] \"\n",
" f\"Loss: {avg_loss:.4f} \"\n",
" f\"Test Acc: {test_acc:.2f}%\"\n",
" )"
]
},
{
"cell_type": "markdown",
"id": "62327de9",
"metadata": {},
"source": [
"## 2.2 - Resource Analysis\n",
"\n",
"Analyse your baseline model according to its resources used. What are the:\n",
"\n",
"- Total parameters\n",
"- FLOPs per forward pass for one sample\n",
"\n",
"For the number of parameters you may use the function implemented in the previous exercise.\n",
"For the FLOPs (Floating Point Operations) a function has to be implemented. For this, you\n",
"may use the torch.utils.flop_counter package or the formulas given in the lecture."
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "402594a0",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Parameters: 421,834\n"
]
}
],
"source": [
"# Parameter zählen\n",
"def count_parameters(model):\n",
" return sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
"\n",
"print(f\"Parameters: {count_parameters(model):,}\")"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "97089d7d",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Module FLOP % Total\n",
"---------------------- --------- ---------\n",
"BaselineCNN 8482.304K 100.00%\n",
"- aten.convolution 7676.928K 90.51%\n",
"- aten.addmm 805.376K 9.49%\n",
"BaselineCNN.classifier 805.376K 9.49%\n",
"- aten.addmm 805.376K 9.49%\n",
"BaselineCNN.features 7676.928K 90.51%\n",
"- aten.convolution 7676.928K 90.51%\n",
"8482304\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/tmp/ipykernel_2188/1016987829.py:4: UserWarning: mods argument is not needed anymore, you can stop passing it\n",
" with FlopCounterMode(model) as flop_counter:\n",
"[W601 22:38:03.412580740 NNPACK.cpp:56] Could not initialize NNPACK! Reason: Unsupported hardware.\n",
"[W601 22:38:03.459700629 NNPACK.cpp:56] Could not initialize NNPACK! Reason: Unsupported hardware.\n"
]
}
],
"source": [
"# FLOPs berechnen\n",
"dummy_input = torch.randn(1, 1, 28, 28)\n",
"\n",
"with FlopCounterMode(model) as flop_counter:\n",
" model(dummy_input)\n",
"\n",
"print(flop_counter.get_total_flops())"
]
},
{
"cell_type": "markdown",
"id": "7090e67b",
"metadata": {},
"source": [
"## 2.3 - Model Optimization\n",
"\n",
"Design a more efficient CNN with the techniques introduced in the lecture. Your model should\n",
"fulfill at least the following constraints:\n",
"\n",
"- Test accuracy ≥ 90%\n",
"- FLOPs < 500,000\n",
"- Parameters < 80,000\n",
"\n",
"Describe the final model architecture, FLOP and parameter count and accuracy. Which techniques had which impact? What worked better or worse."
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "8558e428",
"metadata": {},
"outputs": [],
"source": [
"# Depthwise Separable Convolution\n",
"# Global Average Pooling\n",
"\n",
"class EfficientCNN_v1(nn.Module):\n",
" def __init__(self):\n",
" super().__init__()\n",
"\n",
" self.features = nn.Sequential(\n",
"\n",
" nn.Conv2d(1, 8, kernel_size=3, padding=1),\n",
" nn.BatchNorm2d(8),\n",
" nn.ReLU(),\n",
"\n",
" # Depthwise Separable Block\n",
" nn.Conv2d(\n",
" 8, 8,\n",
" kernel_size=3,\n",
" padding=1,\n",
" groups=8\n",
" ),\n",
" nn.Conv2d(\n",
" 8, 16,\n",
" kernel_size=1\n",
" ),\n",
" nn.ReLU(),\n",
"\n",
" nn.MaxPool2d(2),\n",
"\n",
" # Depthwise Separable Block\n",
" nn.Conv2d(\n",
" 16, 16,\n",
" kernel_size=3,\n",
" padding=1,\n",
" groups=16\n",
" ),\n",
" nn.Conv2d(\n",
" 16, 32,\n",
" kernel_size=1\n",
" ),\n",
" nn.ReLU(),\n",
"\n",
" nn.AdaptiveAvgPool2d(1)\n",
" )\n",
"\n",
" self.classifier = nn.Linear(32, 10)\n",
"\n",
" def forward(self, x):\n",
" x = self.features(x)\n",
"\n",
" x = x.view(x.size(0), -1)\n",
"\n",
" return self.classifier(x)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "00f44aa5",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch [1/20] Loss: 2.1468 Test Acc: 30.54%\n",
"Epoch [2/20] Loss: 1.5578 Test Acc: 55.40%\n",
"Epoch [3/20] Loss: 1.2292 Test Acc: 59.93%\n",
"Epoch [4/20] Loss: 1.0914 Test Acc: 63.49%\n",
"Epoch [5/20] Loss: 1.0124 Test Acc: 65.89%\n",
"Epoch [6/20] Loss: 0.9632 Test Acc: 66.95%\n",
"Epoch [7/20] Loss: 0.9346 Test Acc: 66.48%\n",
"Epoch [8/20] Loss: 0.9115 Test Acc: 68.69%\n",
"Epoch [9/20] Loss: 0.8977 Test Acc: 67.14%\n",
"Epoch [10/20] Loss: 0.8816 Test Acc: 69.54%\n",
"Epoch [11/20] Loss: 0.8703 Test Acc: 68.03%\n",
"Epoch [12/20] Loss: 0.8579 Test Acc: 69.75%\n",
"Epoch [13/20] Loss: 0.8456 Test Acc: 69.96%\n",
"Epoch [14/20] Loss: 0.8354 Test Acc: 70.74%\n",
"Epoch [15/20] Loss: 0.8254 Test Acc: 71.17%\n",
"Epoch [16/20] Loss: 0.8138 Test Acc: 70.77%\n",
"Epoch [17/20] Loss: 0.8047 Test Acc: 72.00%\n",
"Epoch [18/20] Loss: 0.7970 Test Acc: 71.91%\n",
"Epoch [19/20] Loss: 0.7871 Test Acc: 72.28%\n",
"Epoch [20/20] Loss: 0.7787 Test Acc: 72.62%\n"
]
}
],
"source": [
"efficient_model_v1 = EfficientCNN_v1().to(device)\n",
"\n",
"criterion = nn.CrossEntropyLoss()\n",
"\n",
"optimizer = torch.optim.Adam(\n",
" efficient_model_v1.parameters(),\n",
" lr=3e-4\n",
")\n",
"\n",
"epochs = 20\n",
"\n",
"for epoch in range(epochs):\n",
"\n",
" efficient_model_v1.train()\n",
"\n",
" running_loss = 0.0\n",
"\n",
" for images, labels in train_loader:\n",
"\n",
" images = images.to(device)\n",
" labels = labels.to(device)\n",
"\n",
" optimizer.zero_grad()\n",
"\n",
" outputs = efficient_model_v1(images)\n",
"\n",
" loss = criterion(outputs, labels)\n",
"\n",
" loss.backward()\n",
"\n",
" optimizer.step()\n",
"\n",
" running_loss += loss.item()\n",
"\n",
" avg_loss = running_loss / len(train_loader)\n",
"\n",
" test_acc = evaluate(\n",
" efficient_model_v1,\n",
" test_loader\n",
" )\n",
"\n",
" print(\n",
" f\"Epoch [{epoch+1}/{epochs}] \"\n",
" f\"Loss: {avg_loss:.4f} \"\n",
" f\"Test Acc: {test_acc:.2f}%\"\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "7d61ac2b",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Parameters: 1,354\n"
]
}
],
"source": [
"# Parameter zählen\n",
"print(f\"Parameters: {count_parameters(efficient_model_v1):,}\")"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "fabf6700",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Module FLOP % Total\n",
"-------------------------- -------- ---------\n",
"EfficientCNN_v1 684.288K 100.00%\n",
"- aten.convolution 683.648K 99.91%\n",
"- aten.addmm 0.640K 0.09%\n",
"EfficientCNN_v1.classifier 0.640K 0.09%\n",
"- aten.addmm 0.640K 0.09%\n",
"EfficientCNN_v1.features 683.648K 99.91%\n",
"- aten.convolution 683.648K 99.91%\n",
"684288\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/tmp/ipykernel_2188/292545192.py:2: UserWarning: mods argument is not needed anymore, you can stop passing it\n",
" with FlopCounterMode(efficient_model_v1) as flop_counter:\n",
"[W601 23:31:46.083943555 NNPACK.cpp:56] Could not initialize NNPACK! Reason: Unsupported hardware.\n",
"[W601 23:31:46.103110310 NNPACK.cpp:56] Could not initialize NNPACK! Reason: Unsupported hardware.\n",
"[W601 23:31:46.151250410 NNPACK.cpp:56] Could not initialize NNPACK! Reason: Unsupported hardware.\n"
]
}
],
"source": [
"# FLOPs berechnen\n",
"with FlopCounterMode(efficient_model_v1) as flop_counter:\n",
" efficient_model_v1(dummy_input)\n",
"\n",
"print(flop_counter.get_total_flops())"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "f4e8cf5e",
"metadata": {},
"outputs": [],
"source": [
"# Mehr Kanäle\n",
"# Mehr Depthwise Blöcke\n",
"\n",
"class EfficientCNN_v2(nn.Module):\n",
" def __init__(self):\n",
" super().__init__()\n",
"\n",
" self.features = nn.Sequential(\n",
"\n",
" # Stem\n",
" nn.Conv2d(1, 8, 3, padding=1),\n",
" nn.BatchNorm2d(8),\n",
" nn.ReLU(),\n",
"\n",
" # DS Block 1\n",
" nn.Conv2d(8, 8, 3, padding=1, groups=8),\n",
" nn.Conv2d(8, 16, 1),\n",
" nn.BatchNorm2d(16),\n",
" nn.ReLU(),\n",
"\n",
" nn.MaxPool2d(2),\n",
"\n",
" # DS Block 2\n",
" nn.Conv2d(16, 16, 3, padding=1, groups=16),\n",
" nn.Conv2d(16, 32, 1),\n",
" nn.BatchNorm2d(32),\n",
" nn.ReLU(),\n",
"\n",
" nn.MaxPool2d(2),\n",
"\n",
" # DS Block 3\n",
" nn.Conv2d(32, 32, 3, padding=1, groups=32),\n",
" nn.Conv2d(32, 48, 1),\n",
" nn.BatchNorm2d(48),\n",
" nn.ReLU(),\n",
"\n",
" nn.AdaptiveAvgPool2d(1)\n",
" )\n",
"\n",
" self.classifier = nn.Sequential(\n",
" nn.Linear(64, 128),\n",
" nn.ReLU(),\n",
" nn.Dropout(0.2),\n",
" nn.Linear(128, 10)\n",
" )\n",
"\n",
" def forward(self, x):\n",
" x = self.features(x)\n",
" x = torch.flatten(x, 1)\n",
" return self.classifier(x)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "4055292f",
"metadata": {},
"outputs": [
{
"ename": "RuntimeError",
"evalue": "mat1 and mat2 shapes cannot be multiplied (128x48 and 64x128)",
"output_type": "error",
"traceback": [
"\u001b[31m---------------------------------------------------------------------------\u001b[39m",
"\u001b[31mRuntimeError\u001b[39m Traceback (most recent call last)",
"\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[13]\u001b[39m\u001b[32m, line 25\u001b[39m\n\u001b[32m 21\u001b[39m labels = labels.to(device)\n\u001b[32m 22\u001b[39m \n\u001b[32m 23\u001b[39m optimizer.zero_grad()\n\u001b[32m 24\u001b[39m \n\u001b[32m---> \u001b[39m\u001b[32m25\u001b[39m outputs = efficient_model_v2(images)\n\u001b[32m 26\u001b[39m \n\u001b[32m 27\u001b[39m loss = criterion(outputs, labels)\n\u001b[32m 28\u001b[39m \n",
"\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/eml_legacy/lib/python3.11/site-packages/torch/nn/modules/module.py:1779\u001b[39m, in \u001b[36mModule._wrapped_call_impl\u001b[39m\u001b[34m(self, *args, **kwargs)\u001b[39m\n\u001b[32m 1777\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m._compiled_call_impl(*args, **kwargs) \u001b[38;5;66;03m# type: ignore[misc]\u001b[39;00m\n\u001b[32m 1778\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m-> \u001b[39m\u001b[32m1779\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[30;43mself\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43m_call_impl\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43margs\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43mkwargs\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n",
"\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/eml_legacy/lib/python3.11/site-packages/torch/nn/modules/module.py:1790\u001b[39m, in \u001b[36mModule._call_impl\u001b[39m\u001b[34m(self, *args, **kwargs)\u001b[39m\n\u001b[32m 1785\u001b[39m \u001b[38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in\u001b[39;00m\n\u001b[32m 1786\u001b[39m \u001b[38;5;66;03m# this function, and just call forward.\u001b[39;00m\n\u001b[32m 1787\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[38;5;28mself\u001b[39m._backward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m._backward_pre_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m._forward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m._forward_pre_hooks\n\u001b[32m 1788\u001b[39m \u001b[38;5;129;01mor\u001b[39;00m _global_backward_pre_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_backward_hooks\n\u001b[32m 1789\u001b[39m \u001b[38;5;129;01mor\u001b[39;00m _global_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_forward_pre_hooks):\n\u001b[32m-> \u001b[39m\u001b[32m1790\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[30;43mforward_call\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43margs\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43mkwargs\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 1792\u001b[39m result = \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[32m 1793\u001b[39m called_always_called_hooks = \u001b[38;5;28mset\u001b[39m()\n",
"\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[11]\u001b[39m\u001b[32m, line 50\u001b[39m, in \u001b[36mEfficientCNN_v2.forward\u001b[39m\u001b[34m(self, x)\u001b[39m\n\u001b[32m 47\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m forward(self, x):\n\u001b[32m 48\u001b[39m x = self.features(x)\n\u001b[32m 49\u001b[39m x = torch.flatten(x, \u001b[32m1\u001b[39m)\n\u001b[32m---> \u001b[39m\u001b[32m50\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m self.classifier(x)\n",
"\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/eml_legacy/lib/python3.11/site-packages/torch/nn/modules/module.py:1779\u001b[39m, in \u001b[36mModule._wrapped_call_impl\u001b[39m\u001b[34m(self, *args, **kwargs)\u001b[39m\n\u001b[32m 1777\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m._compiled_call_impl(*args, **kwargs) \u001b[38;5;66;03m# type: ignore[misc]\u001b[39;00m\n\u001b[32m 1778\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m-> \u001b[39m\u001b[32m1779\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[30;43mself\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43m_call_impl\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43margs\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43mkwargs\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n",
"\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/eml_legacy/lib/python3.11/site-packages/torch/nn/modules/module.py:1790\u001b[39m, in \u001b[36mModule._call_impl\u001b[39m\u001b[34m(self, *args, **kwargs)\u001b[39m\n\u001b[32m 1785\u001b[39m \u001b[38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in\u001b[39;00m\n\u001b[32m 1786\u001b[39m \u001b[38;5;66;03m# this function, and just call forward.\u001b[39;00m\n\u001b[32m 1787\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[38;5;28mself\u001b[39m._backward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m._backward_pre_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m._forward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m._forward_pre_hooks\n\u001b[32m 1788\u001b[39m \u001b[38;5;129;01mor\u001b[39;00m _global_backward_pre_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_backward_hooks\n\u001b[32m 1789\u001b[39m \u001b[38;5;129;01mor\u001b[39;00m _global_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_forward_pre_hooks):\n\u001b[32m-> \u001b[39m\u001b[32m1790\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[30;43mforward_call\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43margs\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43mkwargs\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 1792\u001b[39m result = \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[32m 1793\u001b[39m called_always_called_hooks = \u001b[38;5;28mset\u001b[39m()\n",
"\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/eml_legacy/lib/python3.11/site-packages/torch/nn/modules/container.py:253\u001b[39m, in \u001b[36mSequential.forward\u001b[39m\u001b[34m(self, input)\u001b[39m\n\u001b[32m 249\u001b[39m \u001b[38;5;250m\u001b[39m\u001b[33;03m\"\"\"\u001b[39;00m\n\u001b[32m 250\u001b[39m \u001b[33;03mRuns the forward pass.\u001b[39;00m\n\u001b[32m 251\u001b[39m \u001b[33;03m\"\"\"\u001b[39;00m\n\u001b[32m 252\u001b[39m \u001b[38;5;28;01mfor\u001b[39;00m module \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mself\u001b[39m:\n\u001b[32m--> \u001b[39m\u001b[32m253\u001b[39m \u001b[38;5;28minput\u001b[39m = \u001b[30;43mmodule\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43minput\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 254\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28minput\u001b[39m\n",
"\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/eml_legacy/lib/python3.11/site-packages/torch/nn/modules/module.py:1779\u001b[39m, in \u001b[36mModule._wrapped_call_impl\u001b[39m\u001b[34m(self, *args, **kwargs)\u001b[39m\n\u001b[32m 1777\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m._compiled_call_impl(*args, **kwargs) \u001b[38;5;66;03m# type: ignore[misc]\u001b[39;00m\n\u001b[32m 1778\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m-> \u001b[39m\u001b[32m1779\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[30;43mself\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43m_call_impl\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43margs\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43mkwargs\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n",
"\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/eml_legacy/lib/python3.11/site-packages/torch/nn/modules/module.py:1790\u001b[39m, in \u001b[36mModule._call_impl\u001b[39m\u001b[34m(self, *args, **kwargs)\u001b[39m\n\u001b[32m 1785\u001b[39m \u001b[38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in\u001b[39;00m\n\u001b[32m 1786\u001b[39m \u001b[38;5;66;03m# this function, and just call forward.\u001b[39;00m\n\u001b[32m 1787\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m (\u001b[38;5;28mself\u001b[39m._backward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m._backward_pre_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m._forward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m._forward_pre_hooks\n\u001b[32m 1788\u001b[39m \u001b[38;5;129;01mor\u001b[39;00m _global_backward_pre_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_backward_hooks\n\u001b[32m 1789\u001b[39m \u001b[38;5;129;01mor\u001b[39;00m _global_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m _global_forward_pre_hooks):\n\u001b[32m-> \u001b[39m\u001b[32m1790\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[30;43mforward_call\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43margs\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43m*\u001b[39;49m\u001b[30;43mkwargs\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n\u001b[32m 1792\u001b[39m result = \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[32m 1793\u001b[39m called_always_called_hooks = \u001b[38;5;28mset\u001b[39m()\n",
"\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/eml_legacy/lib/python3.11/site-packages/torch/nn/modules/linear.py:134\u001b[39m, in \u001b[36mLinear.forward\u001b[39m\u001b[34m(self, input)\u001b[39m\n\u001b[32m 130\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mforward\u001b[39m(\u001b[38;5;28mself\u001b[39m, \u001b[38;5;28minput\u001b[39m: Tensor) -> Tensor:\n\u001b[32m 131\u001b[39m \u001b[38;5;250m \u001b[39m\u001b[33;03m\"\"\"\u001b[39;00m\n\u001b[32m 132\u001b[39m \u001b[33;03m Runs the forward pass.\u001b[39;00m\n\u001b[32m 133\u001b[39m \u001b[33;03m \"\"\"\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m134\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[30;43mF\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43mlinear\u001b[39;49m\u001b[30;43m(\u001b[39;49m\u001b[30;43minput\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43mself\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43mweight\u001b[39;49m\u001b[30;43m,\u001b[39;49m\u001b[30;43m \u001b[39;49m\u001b[30;43mself\u001b[39;49m\u001b[30;43m.\u001b[39;49m\u001b[30;43mbias\u001b[39;49m\u001b[30;43m)\u001b[39;49m\n",
"\u001b[31mRuntimeError\u001b[39m: mat1 and mat2 shapes cannot be multiplied (128x48 and 64x128)"
]
}
],
"source": [
"efficient_model_v2 = EfficientCNN_v2().to(device)\n",
"\n",
"criterion = nn.CrossEntropyLoss()\n",
"\n",
"optimizer = torch.optim.Adam(\n",
" efficient_model_v2.parameters(),\n",
" lr=3e-4\n",
")\n",
"\n",
"epochs = 20\n",
"\n",
"for epoch in range(epochs):\n",
"\n",
" efficient_model_v2.train()\n",
"\n",
" running_loss = 0.0\n",
"\n",
" for images, labels in train_loader:\n",
"\n",
" images = images.to(device)\n",
" labels = labels.to(device)\n",
"\n",
" optimizer.zero_grad()\n",
"\n",
" outputs = efficient_model_v2(images)\n",
"\n",
" loss = criterion(outputs, labels)\n",
"\n",
" loss.backward()\n",
"\n",
" optimizer.step()\n",
"\n",
" running_loss += loss.item()\n",
"\n",
" avg_loss = running_loss / len(train_loader)\n",
"\n",
" test_acc = evaluate(\n",
" efficient_model_v2,\n",
" test_loader\n",
" )\n",
"\n",
" print(\n",
" f\"Epoch [{epoch+1}/{epochs}] \"\n",
" f\"Loss: {avg_loss:.4f} \"\n",
" f\"Test Acc: {test_acc:.2f}%\"\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2ecc7605",
"metadata": {},
"outputs": [],
"source": [
"# Effizientes Modell entwickeln\n",
"# Standard-Convs\n",
"# GAP statt FC-Layer\n",
"\n",
"class EfficientCNN(nn.Module):\n",
" def __init__(self):\n",
" super().__init__()\n",
"\n",
" self.features = nn.Sequential(\n",
"\n",
" # 28x28\n",
" nn.Conv2d(1, 16, 3, padding=1),\n",
" nn.BatchNorm2d(16),\n",
" nn.ReLU(),\n",
"\n",
" nn.MaxPool2d(2), # -> 14x14\n",
"\n",
" # Block 1\n",
" nn.Conv2d(16, 32, 3, padding=1),\n",
" nn.BatchNorm2d(32),\n",
" nn.ReLU(),\n",
"\n",
" nn.MaxPool2d(2), # -> 7x7\n",
"\n",
" # Block 2\n",
" nn.Conv2d(32, 64, 3, padding=1),\n",
" nn.BatchNorm2d(64),\n",
" nn.ReLU(),\n",
"\n",
" nn.AdaptiveAvgPool2d(1)\n",
" )\n",
"\n",
" self.classifier = nn.Linear(64, 10)\n",
"\n",
" def forward(self, x):\n",
" x = self.features(x)\n",
" x = torch.flatten(x, 1)\n",
" return self.classifier(x)"
]
},
{
"cell_type": "code",
"execution_count": 61,
"id": "faaa2555",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch [1/40] Loss: 1.2384 Test Acc: 72.66%\n",
"Epoch [2/40] Loss: 0.6665 Test Acc: 78.41%\n",
"Epoch [3/40] Loss: 0.5299 Test Acc: 77.87%\n",
"Epoch [4/40] Loss: 0.4638 Test Acc: 82.23%\n",
"Epoch [5/40] Loss: 0.4224 Test Acc: 84.48%\n",
"Epoch [6/40] Loss: 0.3962 Test Acc: 85.04%\n",
"Epoch [7/40] Loss: 0.3755 Test Acc: 82.14%\n",
"Epoch [8/40] Loss: 0.3600 Test Acc: 85.85%\n",
"Epoch [9/40] Loss: 0.3455 Test Acc: 84.76%\n",
"Epoch [10/40] Loss: 0.3358 Test Acc: 86.58%\n",
"Epoch [11/40] Loss: 0.3249 Test Acc: 84.11%\n",
"Epoch [12/40] Loss: 0.3177 Test Acc: 85.51%\n",
"Epoch [13/40] Loss: 0.3106 Test Acc: 85.17%\n",
"Epoch [14/40] Loss: 0.3048 Test Acc: 84.21%\n",
"Epoch [15/40] Loss: 0.2999 Test Acc: 87.30%\n",
"Epoch [16/40] Loss: 0.2941 Test Acc: 86.06%\n",
"Epoch [17/40] Loss: 0.2930 Test Acc: 87.05%\n",
"Epoch [18/40] Loss: 0.2859 Test Acc: 88.07%\n",
"Epoch [19/40] Loss: 0.2820 Test Acc: 85.83%\n",
"Epoch [20/40] Loss: 0.2817 Test Acc: 88.14%\n",
"Epoch [21/40] Loss: 0.2768 Test Acc: 86.42%\n",
"Epoch [22/40] Loss: 0.2722 Test Acc: 87.58%\n",
"Epoch [23/40] Loss: 0.2696 Test Acc: 87.98%\n",
"Epoch [24/40] Loss: 0.2675 Test Acc: 86.37%\n",
"Epoch [25/40] Loss: 0.2642 Test Acc: 88.48%\n",
"Epoch [26/40] Loss: 0.2605 Test Acc: 88.29%\n",
"Epoch [27/40] Loss: 0.2586 Test Acc: 88.21%\n",
"Epoch [28/40] Loss: 0.2556 Test Acc: 87.15%\n",
"Epoch [29/40] Loss: 0.2537 Test Acc: 86.96%\n",
"Epoch [30/40] Loss: 0.2506 Test Acc: 88.43%\n",
"Epoch [31/40] Loss: 0.2493 Test Acc: 87.89%\n",
"Epoch [32/40] Loss: 0.2462 Test Acc: 89.21%\n",
"Epoch [33/40] Loss: 0.2448 Test Acc: 87.62%\n",
"Epoch [34/40] Loss: 0.2411 Test Acc: 85.96%\n",
"Epoch [35/40] Loss: 0.2394 Test Acc: 89.00%\n",
"Epoch [36/40] Loss: 0.2391 Test Acc: 88.24%\n",
"Epoch [37/40] Loss: 0.2363 Test Acc: 87.82%\n",
"Epoch [38/40] Loss: 0.2348 Test Acc: 87.72%\n",
"Epoch [39/40] Loss: 0.2331 Test Acc: 89.24%\n",
"Epoch [40/40] Loss: 0.2290 Test Acc: 88.09%\n"
]
}
],
"source": [
"efficient_model = EfficientCNN().to(device)\n",
"\n",
"criterion = nn.CrossEntropyLoss()\n",
"\n",
"optimizer = torch.optim.Adam(\n",
" efficient_model.parameters(),\n",
" lr=3e-4,\n",
" weight_decay=1e-4\n",
")\n",
"\n",
"epochs = 40\n",
"\n",
"for epoch in range(epochs):\n",
"\n",
" efficient_model.train()\n",
"\n",
" running_loss = 0.0\n",
"\n",
" for images, labels in train_loader:\n",
"\n",
" images = images.to(device)\n",
" labels = labels.to(device)\n",
"\n",
" optimizer.zero_grad()\n",
"\n",
" outputs = efficient_model(images)\n",
"\n",
" loss = criterion(outputs, labels)\n",
"\n",
" loss.backward()\n",
"\n",
" optimizer.step()\n",
"\n",
" running_loss += loss.item()\n",
"\n",
" avg_loss = running_loss / len(train_loader)\n",
"\n",
" test_acc = evaluate(\n",
" efficient_model,\n",
" test_loader\n",
" )\n",
"\n",
" print(\n",
" f\"Epoch [{epoch+1}/{epochs}] \"\n",
" f\"Loss: {avg_loss:.4f} \"\n",
" f\"Test Acc: {test_acc:.2f}%\"\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": 62,
"id": "55289655",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Parameters: 24,170\n"
]
}
],
"source": [
"# Parameter zählen\n",
"print(f\"Parameters: {count_parameters(efficient_model):,}\")"
]
},
{
"cell_type": "code",
"execution_count": 63,
"id": "c2ca5ffc",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"C:\\Users\\denni\\AppData\\Local\\Temp\\ipykernel_15972\\4118664082.py:2: UserWarning: mods argument is not needed anymore, you can stop passing it\n",
" with FlopCounterMode(efficient_model) as flop_counter:\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Module FLOP % Total\n",
"----------------------- --------- ---------\n",
"EfficientCNN 3839.744K 100.00%\n",
"- aten.convolution 3838.464K 99.97%\n",
"- aten.addmm 1.280K 0.03%\n",
"EfficientCNN.classifier 1.280K 0.03%\n",
"- aten.addmm 1.280K 0.03%\n",
"EfficientCNN.features 3838.464K 99.97%\n",
"- aten.convolution 3838.464K 99.97%\n",
"3839744\n"
]
}
],
"source": [
"# FLOPs berechnen\n",
"with FlopCounterMode(efficient_model) as flop_counter:\n",
" efficient_model(dummy_input)\n",
"\n",
"print(flop_counter.get_total_flops())"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "eml_legacy",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.15"
}
},
"nbformat": 4,
"nbformat_minor": 5
}