discriminator_arch.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from basicsr.utils.registry import ARCH_REGISTRY
  2. from torch import nn as nn
  3. from torch.nn import functional as F
  4. from torch.nn.utils import spectral_norm
  5. @ARCH_REGISTRY.register()
  6. class UNetDiscriminatorSN(nn.Module):
  7. """Defines a U-Net discriminator with spectral normalization (SN)"""
  8. def __init__(self, num_in_ch, num_feat=64, skip_connection=True):
  9. super(UNetDiscriminatorSN, self).__init__()
  10. self.skip_connection = skip_connection
  11. norm = spectral_norm
  12. self.conv0 = nn.Conv2d(num_in_ch, num_feat, kernel_size=3, stride=1, padding=1)
  13. self.conv1 = norm(nn.Conv2d(num_feat, num_feat * 2, 4, 2, 1, bias=False))
  14. self.conv2 = norm(nn.Conv2d(num_feat * 2, num_feat * 4, 4, 2, 1, bias=False))
  15. self.conv3 = norm(nn.Conv2d(num_feat * 4, num_feat * 8, 4, 2, 1, bias=False))
  16. # upsample
  17. self.conv4 = norm(nn.Conv2d(num_feat * 8, num_feat * 4, 3, 1, 1, bias=False))
  18. self.conv5 = norm(nn.Conv2d(num_feat * 4, num_feat * 2, 3, 1, 1, bias=False))
  19. self.conv6 = norm(nn.Conv2d(num_feat * 2, num_feat, 3, 1, 1, bias=False))
  20. # extra
  21. self.conv7 = norm(nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=False))
  22. self.conv8 = norm(nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=False))
  23. self.conv9 = nn.Conv2d(num_feat, 1, 3, 1, 1)
  24. def forward(self, x):
  25. x0 = F.leaky_relu(self.conv0(x), negative_slope=0.2, inplace=True)
  26. x1 = F.leaky_relu(self.conv1(x0), negative_slope=0.2, inplace=True)
  27. x2 = F.leaky_relu(self.conv2(x1), negative_slope=0.2, inplace=True)
  28. x3 = F.leaky_relu(self.conv3(x2), negative_slope=0.2, inplace=True)
  29. # upsample
  30. x3 = F.interpolate(x3, scale_factor=2, mode='bilinear', align_corners=False)
  31. x4 = F.leaky_relu(self.conv4(x3), negative_slope=0.2, inplace=True)
  32. if self.skip_connection:
  33. x4 = x4 + x2
  34. x4 = F.interpolate(x4, scale_factor=2, mode='bilinear', align_corners=False)
  35. x5 = F.leaky_relu(self.conv5(x4), negative_slope=0.2, inplace=True)
  36. if self.skip_connection:
  37. x5 = x5 + x1
  38. x5 = F.interpolate(x5, scale_factor=2, mode='bilinear', align_corners=False)
  39. x6 = F.leaky_relu(self.conv6(x5), negative_slope=0.2, inplace=True)
  40. if self.skip_connection:
  41. x6 = x6 + x0
  42. # extra
  43. out = F.leaky_relu(self.conv7(x6), negative_slope=0.2, inplace=True)
  44. out = F.leaky_relu(self.conv8(out), negative_slope=0.2, inplace=True)
  45. out = self.conv9(out)
  46. return out