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

37 KiB

Aufgabe 2 - Designing Efficient CNNs for FashionMNIST

In this exercise we want to design and implement our own efficient CNN in pytorch with the techniques introduced in the lecture. Because we cannot calculate the latency on the hardware yet, we use the amount of FLOPs as a proxy metric for now. Keep in mind that FLOPs only correlate losely with latency.

2.1 - Baseline Model

Before designing an efficient architecture we want to implement a baseline model to compare to. For that design a CNN that achieves at least a Test Accuracy ≥ 91% on FashionMNIST. What is the architecture? How did you train it?

In [1]:
# Imports
import torch
import torch.nn as nn
from torchvision import datasets
from torchvision import transforms
from torch.utils.data import DataLoader
from torch.utils.flop_counter import FlopCounterMode
In [2]:
# Daten Laden
transform = transforms.ToTensor()

train_dataset = datasets.FashionMNIST(
    root="./data",
    train=True,
    download=True,
    transform=transform
)

test_dataset = datasets.FashionMNIST(
    root="./data",
    train=False,
    download=True,
    transform=transform
)

train_loader = DataLoader(
    train_dataset,
    batch_size=128,
    shuffle=True
)

test_loader = DataLoader(
    test_dataset,
    batch_size=128
)
In [3]:
# Modell definieren
class BaselineCNN(nn.Module):
    def __init__(self):
        super().__init__()

        self.features = nn.Sequential(
            nn.Conv2d(1, 32, kernel_size=3, padding=1),
            nn.BatchNorm2d(32),
            nn.ReLU(),

            nn.MaxPool2d(2),

            nn.Conv2d(32, 64, kernel_size=3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(),

            nn.MaxPool2d(2)
        )

        self.classifier = nn.Sequential(
            nn.Flatten(),
            nn.Linear(64 * 7 * 7, 128),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(128, 10)
        )

    def forward(self, x):
        x = self.features(x)
        return self.classifier(x)
In [4]:
device = torch.device(
    "cuda" if torch.cuda.is_available() else "cpu"
)
In [5]:
# Evaluation
def evaluate(model, loader):

    model.eval()

    correct = 0
    total = 0

    with torch.no_grad():

        for images, labels in loader:

            images = images.to(device)
            labels = labels.to(device)

            outputs = model(images)

            pred = outputs.argmax(dim=1)

            total += labels.size(0)
            correct += (pred == labels).sum().item()

    return 100 * correct / total
In [6]:
# Training
model = BaselineCNN().to(device)
criterion = nn.CrossEntropyLoss()

optimizer = torch.optim.Adam(
    model.parameters(),
    lr=1e-3
)

epochs = 10
batch_size = 128

for epoch in range(epochs):

    running_loss = 0.0

    for images, labels in train_loader:

        images = images.to(device)
        labels = labels.to(device)

        # Gradienten zurücksetzen
        optimizer.zero_grad()

        # Forward Pass
        outputs = model(images)

        # Loss berechnen
        loss = criterion(outputs, labels)

        # Backpropagation
        loss.backward()

        # Gewichte aktualisieren
        optimizer.step()

        running_loss += loss.item()

    avg_loss = running_loss / len(train_loader)

    test_acc = evaluate(model, test_loader)

    print(
        f"Epoch [{epoch+1}/{epochs}] "
        f"Loss: {avg_loss:.4f} "
        f"Test Acc: {test_acc:.2f}%"
    )
Epoch [1/10] Loss: 0.4392 Test Acc: 88.35%
Epoch [2/10] Loss: 0.2589 Test Acc: 90.31%
Epoch [3/10] Loss: 0.2085 Test Acc: 89.40%
Epoch [4/10] Loss: 0.1787 Test Acc: 91.56%
Epoch [5/10] Loss: 0.1536 Test Acc: 91.81%
Epoch [6/10] Loss: 0.1299 Test Acc: 91.80%
Epoch [7/10] Loss: 0.1102 Test Acc: 91.71%
Epoch [8/10] Loss: 0.0903 Test Acc: 92.02%
Epoch [9/10] Loss: 0.0756 Test Acc: 91.33%
Epoch [10/10] Loss: 0.0659 Test Acc: 91.67%

2.2 - Resource Analysis

Analyse your baseline model according to its resources used. What are the:

  • Total parameters
  • FLOPs per forward pass for one sample

For the number of parameters you may use the function implemented in the previous exercise. For the FLOPs (Floating Point Operations) a function has to be implemented. For this, you may use the torch.utils.flop_counter package or the formulas given in the lecture.

In [7]:
# Parameter zählen
def count_parameters(model):
    return sum(p.numel() for p in model.parameters() if p.requires_grad)

print(f"Parameters: {count_parameters(model):,}")
Parameters: 421,834
In [8]:
# FLOPs berechnen
dummy_input = torch.randn(1, 1, 28, 28)

with FlopCounterMode(model) as flop_counter:
    model(dummy_input)

print(flop_counter.get_total_flops())
Module                       FLOP    % Total
----------------------  ---------  ---------
BaselineCNN             8482.304K    100.00%
- aten.convolution      7676.928K     90.51%
- aten.addmm             805.376K      9.49%
BaselineCNN.classifier   805.376K      9.49%
- aten.addmm             805.376K      9.49%
BaselineCNN.features    7676.928K     90.51%
- aten.convolution      7676.928K     90.51%
8482304
/tmp/ipykernel_2188/1016987829.py:4: UserWarning: mods argument is not needed anymore, you can stop passing it
  with FlopCounterMode(model) as flop_counter:
[W601 22:38:03.412580740 NNPACK.cpp:56] Could not initialize NNPACK! Reason: Unsupported hardware.
[W601 22:38:03.459700629 NNPACK.cpp:56] Could not initialize NNPACK! Reason: Unsupported hardware.

2.3 - Model Optimization

Design a more efficient CNN with the techniques introduced in the lecture. Your model should fulfill at least the following constraints:

  • Test accuracy ≥ 90%
  • FLOPs < 500,000
  • Parameters < 80,000

Describe the final model architecture, FLOP and parameter count and accuracy. Which techniques had which impact? What worked better or worse.

In [9]:
# Depthwise Separable Convolution
# Global Average Pooling

class EfficientCNN_v1(nn.Module):
    def __init__(self):
        super().__init__()

        self.features = nn.Sequential(

            nn.Conv2d(1, 8, kernel_size=3, padding=1),
            nn.BatchNorm2d(8),
            nn.ReLU(),

            # Depthwise Separable Block
            nn.Conv2d(
                8, 8,
                kernel_size=3,
                padding=1,
                groups=8
            ),
            nn.Conv2d(
                8, 16,
                kernel_size=1
            ),
            nn.ReLU(),

            nn.MaxPool2d(2),

            # Depthwise Separable Block
            nn.Conv2d(
                16, 16,
                kernel_size=3,
                padding=1,
                groups=16
            ),
            nn.Conv2d(
                16, 32,
                kernel_size=1
            ),
            nn.ReLU(),

            nn.AdaptiveAvgPool2d(1)
        )

        self.classifier = nn.Linear(32, 10)

    def forward(self, x):
        x = self.features(x)

        x = x.view(x.size(0), -1)

        return self.classifier(x)
In [10]:
efficient_model_v1 = EfficientCNN_v1().to(device)

criterion = nn.CrossEntropyLoss()

optimizer = torch.optim.Adam(
    efficient_model_v1.parameters(),
    lr=3e-4
)

epochs = 20

for epoch in range(epochs):

    efficient_model_v1.train()

    running_loss = 0.0

    for images, labels in train_loader:

        images = images.to(device)
        labels = labels.to(device)

        optimizer.zero_grad()

        outputs = efficient_model_v1(images)

        loss = criterion(outputs, labels)

        loss.backward()

        optimizer.step()

        running_loss += loss.item()

    avg_loss = running_loss / len(train_loader)

    test_acc = evaluate(
        efficient_model_v1,
        test_loader
    )

    print(
        f"Epoch [{epoch+1}/{epochs}] "
        f"Loss: {avg_loss:.4f} "
        f"Test Acc: {test_acc:.2f}%"
    )
Epoch [1/20] Loss: 2.1468 Test Acc: 30.54%
Epoch [2/20] Loss: 1.5578 Test Acc: 55.40%
Epoch [3/20] Loss: 1.2292 Test Acc: 59.93%
Epoch [4/20] Loss: 1.0914 Test Acc: 63.49%
Epoch [5/20] Loss: 1.0124 Test Acc: 65.89%
Epoch [6/20] Loss: 0.9632 Test Acc: 66.95%
Epoch [7/20] Loss: 0.9346 Test Acc: 66.48%
Epoch [8/20] Loss: 0.9115 Test Acc: 68.69%
Epoch [9/20] Loss: 0.8977 Test Acc: 67.14%
Epoch [10/20] Loss: 0.8816 Test Acc: 69.54%
Epoch [11/20] Loss: 0.8703 Test Acc: 68.03%
Epoch [12/20] Loss: 0.8579 Test Acc: 69.75%
Epoch [13/20] Loss: 0.8456 Test Acc: 69.96%
Epoch [14/20] Loss: 0.8354 Test Acc: 70.74%
Epoch [15/20] Loss: 0.8254 Test Acc: 71.17%
Epoch [16/20] Loss: 0.8138 Test Acc: 70.77%
Epoch [17/20] Loss: 0.8047 Test Acc: 72.00%
Epoch [18/20] Loss: 0.7970 Test Acc: 71.91%
Epoch [19/20] Loss: 0.7871 Test Acc: 72.28%
Epoch [20/20] Loss: 0.7787 Test Acc: 72.62%
In [14]:
# Parameter zählen
print(f"Parameters: {count_parameters(efficient_model_v1):,}")
Parameters: 1,354
In [15]:
# FLOPs berechnen
with FlopCounterMode(efficient_model_v1) as flop_counter:
    efficient_model_v1(dummy_input)

print(flop_counter.get_total_flops())
Module                          FLOP    % Total
--------------------------  --------  ---------
EfficientCNN_v1             684.288K    100.00%
- aten.convolution          683.648K     99.91%
- aten.addmm                  0.640K      0.09%
EfficientCNN_v1.classifier    0.640K      0.09%
- aten.addmm                  0.640K      0.09%
EfficientCNN_v1.features    683.648K     99.91%
- aten.convolution          683.648K     99.91%
684288
/tmp/ipykernel_2188/292545192.py:2: UserWarning: mods argument is not needed anymore, you can stop passing it
  with FlopCounterMode(efficient_model_v1) as flop_counter:
[W601 23:31:46.083943555 NNPACK.cpp:56] Could not initialize NNPACK! Reason: Unsupported hardware.
[W601 23:31:46.103110310 NNPACK.cpp:56] Could not initialize NNPACK! Reason: Unsupported hardware.
[W601 23:31:46.151250410 NNPACK.cpp:56] Could not initialize NNPACK! Reason: Unsupported hardware.
In [11]:
# Mehr Kanäle
# Mehr Depthwise Blöcke

class EfficientCNN_v2(nn.Module):
    def __init__(self):
        super().__init__()

        self.features = nn.Sequential(

            # Stem
            nn.Conv2d(1, 8, 3, padding=1),
            nn.BatchNorm2d(8),
            nn.ReLU(),

            # DS Block 1
            nn.Conv2d(8, 8, 3, padding=1, groups=8),
            nn.Conv2d(8, 16, 1),
            nn.BatchNorm2d(16),
            nn.ReLU(),

            nn.MaxPool2d(2),

            # DS Block 2
            nn.Conv2d(16, 16, 3, padding=1, groups=16),
            nn.Conv2d(16, 32, 1),
            nn.BatchNorm2d(32),
            nn.ReLU(),

            nn.MaxPool2d(2),

            # DS Block 3
            nn.Conv2d(32, 32, 3, padding=1, groups=32),
            nn.Conv2d(32, 48, 1),
            nn.BatchNorm2d(48),
            nn.ReLU(),

            nn.AdaptiveAvgPool2d(1)
        )

        self.classifier = nn.Sequential(
            nn.Linear(64, 128),
            nn.ReLU(),
            nn.Dropout(0.2),
            nn.Linear(128, 10)
        )

    def forward(self, x):
        x = self.features(x)
        x = torch.flatten(x, 1)
        return self.classifier(x)
In [13]:
efficient_model_v2 = EfficientCNN_v2().to(device)

criterion = nn.CrossEntropyLoss()

optimizer = torch.optim.Adam(
    efficient_model_v2.parameters(),
    lr=3e-4
)

epochs = 20

for epoch in range(epochs):

    efficient_model_v2.train()

    running_loss = 0.0

    for images, labels in train_loader:

        images = images.to(device)
        labels = labels.to(device)

        optimizer.zero_grad()

        outputs = efficient_model_v2(images)

        loss = criterion(outputs, labels)

        loss.backward()

        optimizer.step()

        running_loss += loss.item()

    avg_loss = running_loss / len(train_loader)

    test_acc = evaluate(
        efficient_model_v2,
        test_loader
    )

    print(
        f"Epoch [{epoch+1}/{epochs}] "
        f"Loss: {avg_loss:.4f} "
        f"Test Acc: {test_acc:.2f}%"
    )
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[13], line 25
     21         labels = labels.to(device)
     22 
     23         optimizer.zero_grad()
     24 
---> 25         outputs = efficient_model_v2(images)
     26 
     27         loss = criterion(outputs, labels)
     28 

File ~/miniconda3/envs/eml_legacy/lib/python3.11/site-packages/torch/nn/modules/module.py:1779, in Module._wrapped_call_impl(self, *args, **kwargs)
   1777     return self._compiled_call_impl(*args, **kwargs)  # type: ignore[misc]
   1778 else:
-> 1779     return self._call_impl(*args, **kwargs)

File ~/miniconda3/envs/eml_legacy/lib/python3.11/site-packages/torch/nn/modules/module.py:1790, in Module._call_impl(self, *args, **kwargs)
   1785 # If we don't have any hooks, we want to skip the rest of the logic in
   1786 # this function, and just call forward.
   1787 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
   1788         or _global_backward_pre_hooks or _global_backward_hooks
   1789         or _global_forward_hooks or _global_forward_pre_hooks):
-> 1790     return forward_call(*args, **kwargs)
   1792 result = None
   1793 called_always_called_hooks = set()

Cell In[11], line 50, in EfficientCNN_v2.forward(self, x)
     47     def forward(self, x):
     48         x = self.features(x)
     49         x = torch.flatten(x, 1)
---> 50         return self.classifier(x)

File ~/miniconda3/envs/eml_legacy/lib/python3.11/site-packages/torch/nn/modules/module.py:1779, in Module._wrapped_call_impl(self, *args, **kwargs)
   1777     return self._compiled_call_impl(*args, **kwargs)  # type: ignore[misc]
   1778 else:
-> 1779     return self._call_impl(*args, **kwargs)

File ~/miniconda3/envs/eml_legacy/lib/python3.11/site-packages/torch/nn/modules/module.py:1790, in Module._call_impl(self, *args, **kwargs)
   1785 # If we don't have any hooks, we want to skip the rest of the logic in
   1786 # this function, and just call forward.
   1787 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
   1788         or _global_backward_pre_hooks or _global_backward_hooks
   1789         or _global_forward_hooks or _global_forward_pre_hooks):
-> 1790     return forward_call(*args, **kwargs)
   1792 result = None
   1793 called_always_called_hooks = set()

File ~/miniconda3/envs/eml_legacy/lib/python3.11/site-packages/torch/nn/modules/container.py:253, in Sequential.forward(self, input)
    249 """
    250 Runs the forward pass.
    251 """
    252 for module in self:
--> 253     input = module(input)
    254 return input

File ~/miniconda3/envs/eml_legacy/lib/python3.11/site-packages/torch/nn/modules/module.py:1779, in Module._wrapped_call_impl(self, *args, **kwargs)
   1777     return self._compiled_call_impl(*args, **kwargs)  # type: ignore[misc]
   1778 else:
-> 1779     return self._call_impl(*args, **kwargs)

File ~/miniconda3/envs/eml_legacy/lib/python3.11/site-packages/torch/nn/modules/module.py:1790, in Module._call_impl(self, *args, **kwargs)
   1785 # If we don't have any hooks, we want to skip the rest of the logic in
   1786 # this function, and just call forward.
   1787 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
   1788         or _global_backward_pre_hooks or _global_backward_hooks
   1789         or _global_forward_hooks or _global_forward_pre_hooks):
-> 1790     return forward_call(*args, **kwargs)
   1792 result = None
   1793 called_always_called_hooks = set()

File ~/miniconda3/envs/eml_legacy/lib/python3.11/site-packages/torch/nn/modules/linear.py:134, in Linear.forward(self, input)
    130 def forward(self, input: Tensor) -> Tensor:
    131     """
    132     Runs the forward pass.
    133     """
--> 134     return F.linear(input, self.weight, self.bias)

RuntimeError: mat1 and mat2 shapes cannot be multiplied (128x48 and 64x128)
In [ ]:
# Effizientes Modell entwickeln
# Standard-Convs
# GAP statt FC-Layer

class EfficientCNN(nn.Module):
    def __init__(self):
        super().__init__()

        self.features = nn.Sequential(

            # 28x28
            nn.Conv2d(1, 16, 3, padding=1),
            nn.BatchNorm2d(16),
            nn.ReLU(),

            nn.MaxPool2d(2),      # -> 14x14

            # Block 1
            nn.Conv2d(16, 32, 3, padding=1),
            nn.BatchNorm2d(32),
            nn.ReLU(),

            nn.MaxPool2d(2),      # -> 7x7

            # Block 2
            nn.Conv2d(32, 64, 3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(),

            nn.AdaptiveAvgPool2d(1)
        )

        self.classifier = nn.Linear(64, 10)

    def forward(self, x):
        x = self.features(x)
        x = torch.flatten(x, 1)
        return self.classifier(x)
In [61]:
efficient_model = EfficientCNN().to(device)

criterion = nn.CrossEntropyLoss()

optimizer = torch.optim.Adam(
    efficient_model.parameters(),
    lr=3e-4,
    weight_decay=1e-4
)

epochs = 40

for epoch in range(epochs):

    efficient_model.train()

    running_loss = 0.0

    for images, labels in train_loader:

        images = images.to(device)
        labels = labels.to(device)

        optimizer.zero_grad()

        outputs = efficient_model(images)

        loss = criterion(outputs, labels)

        loss.backward()

        optimizer.step()

        running_loss += loss.item()

    avg_loss = running_loss / len(train_loader)

    test_acc = evaluate(
        efficient_model,
        test_loader
    )

    print(
        f"Epoch [{epoch+1}/{epochs}] "
        f"Loss: {avg_loss:.4f} "
        f"Test Acc: {test_acc:.2f}%"
    )
Epoch [1/40] Loss: 1.2384 Test Acc: 72.66%
Epoch [2/40] Loss: 0.6665 Test Acc: 78.41%
Epoch [3/40] Loss: 0.5299 Test Acc: 77.87%
Epoch [4/40] Loss: 0.4638 Test Acc: 82.23%
Epoch [5/40] Loss: 0.4224 Test Acc: 84.48%
Epoch [6/40] Loss: 0.3962 Test Acc: 85.04%
Epoch [7/40] Loss: 0.3755 Test Acc: 82.14%
Epoch [8/40] Loss: 0.3600 Test Acc: 85.85%
Epoch [9/40] Loss: 0.3455 Test Acc: 84.76%
Epoch [10/40] Loss: 0.3358 Test Acc: 86.58%
Epoch [11/40] Loss: 0.3249 Test Acc: 84.11%
Epoch [12/40] Loss: 0.3177 Test Acc: 85.51%
Epoch [13/40] Loss: 0.3106 Test Acc: 85.17%
Epoch [14/40] Loss: 0.3048 Test Acc: 84.21%
Epoch [15/40] Loss: 0.2999 Test Acc: 87.30%
Epoch [16/40] Loss: 0.2941 Test Acc: 86.06%
Epoch [17/40] Loss: 0.2930 Test Acc: 87.05%
Epoch [18/40] Loss: 0.2859 Test Acc: 88.07%
Epoch [19/40] Loss: 0.2820 Test Acc: 85.83%
Epoch [20/40] Loss: 0.2817 Test Acc: 88.14%
Epoch [21/40] Loss: 0.2768 Test Acc: 86.42%
Epoch [22/40] Loss: 0.2722 Test Acc: 87.58%
Epoch [23/40] Loss: 0.2696 Test Acc: 87.98%
Epoch [24/40] Loss: 0.2675 Test Acc: 86.37%
Epoch [25/40] Loss: 0.2642 Test Acc: 88.48%
Epoch [26/40] Loss: 0.2605 Test Acc: 88.29%
Epoch [27/40] Loss: 0.2586 Test Acc: 88.21%
Epoch [28/40] Loss: 0.2556 Test Acc: 87.15%
Epoch [29/40] Loss: 0.2537 Test Acc: 86.96%
Epoch [30/40] Loss: 0.2506 Test Acc: 88.43%
Epoch [31/40] Loss: 0.2493 Test Acc: 87.89%
Epoch [32/40] Loss: 0.2462 Test Acc: 89.21%
Epoch [33/40] Loss: 0.2448 Test Acc: 87.62%
Epoch [34/40] Loss: 0.2411 Test Acc: 85.96%
Epoch [35/40] Loss: 0.2394 Test Acc: 89.00%
Epoch [36/40] Loss: 0.2391 Test Acc: 88.24%
Epoch [37/40] Loss: 0.2363 Test Acc: 87.82%
Epoch [38/40] Loss: 0.2348 Test Acc: 87.72%
Epoch [39/40] Loss: 0.2331 Test Acc: 89.24%
Epoch [40/40] Loss: 0.2290 Test Acc: 88.09%
In [62]:
# Parameter zählen
print(f"Parameters: {count_parameters(efficient_model):,}")
Parameters: 24,170
In [63]:
# FLOPs berechnen
with FlopCounterMode(efficient_model) as flop_counter:
    efficient_model(dummy_input)

print(flop_counter.get_total_flops())
C:\Users\denni\AppData\Local\Temp\ipykernel_15972\4118664082.py:2: UserWarning: mods argument is not needed anymore, you can stop passing it
  with FlopCounterMode(efficient_model) as flop_counter:
Module                        FLOP    % Total
-----------------------  ---------  ---------
EfficientCNN             3839.744K    100.00%
- aten.convolution       3838.464K     99.97%
- aten.addmm                1.280K      0.03%
EfficientCNN.classifier     1.280K      0.03%
- aten.addmm                1.280K      0.03%
EfficientCNN.features    3838.464K     99.97%
- aten.convolution       3838.464K     99.97%
3839744