Creating a stack of convolutional layers using for loop in forward function of a pytoch class for Residual block
I'm defining a residual block in pytorch for ResNet in which you can input how many convolutional layers you want to have and not necessarily two. This is done through a parameter named nc (number of Convs). The first layer gets ni as the number of input nf number of filters. But from second layer on I put them in a for loop. Here's my code:

class ResBlock(nn.Module):
    def __init__(self, ni, nf,nc=2):
        super().__init__()
        self.conv1 = nn.Conv2d(ni,nf, kernel_size=3, stride=2, padding=0)
        self.conv2 = nn.Conv2d(nf,nf, kernel_size=3, stride=1, padding=0)
        self.conv1x1 = nn.Conv2d(ni, nf, kernel_size=1, stride=1, padding=0)
        self.nc = nc    
    def forward(self, x): 
        y = self.conv1(x)
        for i in range(self.nc-1):
            y = self.conv2(y)
            print(torch.mean(y))            
        return self.conv1x1(x) + y


But no matter what value I give to nc, it always returns 2 convs with kernel size 3. I'm not sure if for loop can really do this job in pytorch but it was working when I used functional API in Keras. Could anyone help me understand what's going on?

Yeah, printing a nn.Module object is often misleading. When you print, you get:

# for ni=3, nf=16
ResBlock(
  (conv1): Conv2d(3, 16, kernel_size=(3, 3), stride=(2, 2))
  (conv2): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1))
  (conv1x1): Conv2d(3, 16, kernel_size=(1, 1), stride=(1, 1))
)


because these are the only 3 Modules you registered in the __init__ of the ResBlock.

The actual forward can (and in your case will) be doing something completely different.
