Pytorch batch size question for GANs

Hi, I am new to PyTorch. I was going through the DCGAN code in pytorch.


class Generator(nn.Module):
    def __init__(self, ngpu):
        super(Generator,self).__init__()
        self.ngpu = ngpu
        self.main = nn.Sequential(
            # input is Z, going into a convolution
            nn.ConvTranspose2d(nz, ngf * 8,4,1,0, bias=False),#(ic,oc,kernel,stride,padding)
            nn.BatchNorm2d(ngf * 8),
            nn.ReLU(True),
            # state size. (ngf*8) x 4 x 4
            nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),
            nn.BatchNorm2d(ngf * 4),
            nn.ReLU(True),
            # state size. (ngf*4 = 256) x 8 x 8
            nn.ConvTranspose2d( ngf * 4, ngf * 2, 4, 2, 1, bias=False),
            nn.BatchNorm2d(ngf * 2),
            nn.ReLU(True),
            # state size. (ngf*2 = 128) x 16 x 16
            nn.ConvTranspose2d( ngf * 2, ngf, 4, 2, 1, bias=False),
            nn.BatchNorm2d(ngf),
            nn.ReLU(True),
            # state size. (ngf = 64) x 32 x 32
            nn.ConvTranspose2d( ngf, nc, 4, 2, 1, bias=False),
            nn.Tanh()
             #state size. (nc) x 64 x 64
                )
    def forward(self, input):
        return self.main(input)
    
netG = Generator(ngpu).to(device)
netG.apply(weights_init)
print(netG)

fixed_noise = torch.randn(64,nz,1,1, device=device)
netG(fixed_noise.detach())

What I wanted to ask is how does the generator knows how many batches of images to generate? The code only specifies the numbers of input and output channels for the layers, there is no batch size specified in the generator class. is it because the input to the generator must be a tensor of [Batch_size, Channels, height, width] ? I am a bit confused. Thanks in advance

the model works on arbitrary batch size. in this specific training, 64 is the batch size.

1 Like

I see, so the model extracts the batch size information from the input(tensor) you assigned to the generator in the background?

Yes. That is correct.

1 Like