How to override the Conv2d forward method?

I’m learning how to implement AlexNet to train a set of medical images.
Here’s the model.

class AlexNet(nn.Module):

def __init__(self, num_classes=1000):
    super(AlexNet, self).__init__()
    self.features = nn.Sequential(
        nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
        nn.ReLU(inplace=True),
        nn.MaxPool2d(kernel_size=3, stride=2),
        nn.Conv2d(64, 192, kernel_size=5, padding=2),
        nn.ReLU(inplace=True),
        nn.MaxPool2d(kernel_size=3, stride=2),
        nn.Conv2d(192, 384, kernel_size=3, padding=1),
        nn.ReLU(inplace=True),
        nn.Conv2d(384, 256, kernel_size=3, padding=1),
        nn.ReLU(inplace=True),
        nn.Conv2d(256, 256, kernel_size=3, padding=1),
        nn.ReLU(inplace=True),
        nn.MaxPool2d(kernel_size=3, stride=2),
    )
    self.classifier = nn.Sequential(
        nn.Dropout(),
        nn.Linear(256 * 6 * 6, 4096),
        nn.ReLU(inplace=True),
        nn.Dropout(),
        nn.Linear(4096, 4096),
        nn.ReLU(inplace=True),
        nn.Linear(4096, num_classes),
    )

def forward(self, x):
    x = self.features(x)
    x = x.view(x.size(0), 256 * 6 * 6)
    x = self.classifier(x)
    return x

I encountered this error:

expected stride to be a single integer value or a list of 3 values to match the convolution dimensions, but got stride=[4, 4]

Someone suggested me that I can put a fixed stride size on the nn.Conv2d.forward function. I want to do it without rewriting the Conv2d function or modify the library.

I know this is probably a very simple Python problem, but I have no idea how to come up with the keyword for this problem. Thanks in advance.

It sounds like there is potentially a bug somewhere in the framework. Do you have a minimal reproducing example for this?

You can override the Conv2d.forward function pretty simply:

model = nn.Conv2d(...)
model.forward = <whatever you want>