model.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import functools
  2. import torch.nn as nn
  3. from taming.modules.util import ActNorm
  4. def weights_init(m):
  5. classname = m.__class__.__name__
  6. if classname.find('Conv') != -1:
  7. nn.init.normal_(m.weight.data, 0.0, 0.02)
  8. elif classname.find('BatchNorm') != -1:
  9. nn.init.normal_(m.weight.data, 1.0, 0.02)
  10. nn.init.constant_(m.bias.data, 0)
  11. class NLayerDiscriminator(nn.Module):
  12. """Defines a PatchGAN discriminator as in Pix2Pix
  13. --> see https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/networks.py
  14. """
  15. def __init__(self, input_nc=3, ndf=64, n_layers=3, use_actnorm=False):
  16. """Construct a PatchGAN discriminator
  17. Parameters:
  18. input_nc (int) -- the number of channels in input images
  19. ndf (int) -- the number of filters in the last conv layer
  20. n_layers (int) -- the number of conv layers in the discriminator
  21. norm_layer -- normalization layer
  22. """
  23. super(NLayerDiscriminator, self).__init__()
  24. if not use_actnorm:
  25. norm_layer = nn.BatchNorm2d
  26. else:
  27. norm_layer = ActNorm
  28. if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters
  29. use_bias = norm_layer.func != nn.BatchNorm2d
  30. else:
  31. use_bias = norm_layer != nn.BatchNorm2d
  32. kw = 4
  33. padw = 1
  34. sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]
  35. nf_mult = 1
  36. nf_mult_prev = 1
  37. for n in range(1, n_layers): # gradually increase the number of filters
  38. nf_mult_prev = nf_mult
  39. nf_mult = min(2 ** n, 8)
  40. sequence += [
  41. nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias),
  42. norm_layer(ndf * nf_mult),
  43. nn.LeakyReLU(0.2, True)
  44. ]
  45. nf_mult_prev = nf_mult
  46. nf_mult = min(2 ** n_layers, 8)
  47. sequence += [
  48. nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),
  49. norm_layer(ndf * nf_mult),
  50. nn.LeakyReLU(0.2, True)
  51. ]
  52. sequence += [
  53. nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # output 1 channel prediction map
  54. self.main = nn.Sequential(*sequence)
  55. def forward(self, input):
  56. """Standard forward."""
  57. return self.main(input)