from torch import nn
import torch.nn.functional as F

class LeNet5(nn.Module):
    """LeNet-5 without padding in the first layer.
       This is based on Caffe's implementation of Lenet-5 and is slightly different
       from the vanilla LeNet-5. Note that the first layer does NOT have padding
       and therefore intermediate shapes do not match the official LeNet-5.
       Based on https://github.com/mi-lad/snip/blob/master/train.py
       by Milad Alizadeh.
       """

    def __init__(self, class_num):
        super().__init__()
        self.conv1 = nn.Conv2d(1, 20, 5, padding=0, bias=True)
        self.conv2 = nn.Conv2d(20, 50, 5, bias=True)
        self.fc3 = nn.Linear(50 * 4 * 4, 500)
        self.fc4 = nn.Linear(500, class_num)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.max_pool2d(x, 2)
        x = F.relu(self.conv2(x))
        x = F.max_pool2d(x, 2)
        x = F.relu(self.fc3(x.view(-1, 50 * 4 * 4)))
        x = self.fc4(x)
        return x

class LeNet5_cifar(nn.Module):
    def __init__(self, out_size=10):
        super().__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, out_size)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * 5 * 5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x