gfpganv1_clean_arch.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. import math
  2. import random
  3. import torch
  4. from torch import nn
  5. from torch.nn import functional as F
  6. from .stylegan2_clean_arch import StyleGAN2GeneratorClean
  7. class StyleGAN2GeneratorCSFT(StyleGAN2GeneratorClean):
  8. """StyleGAN2 Generator with SFT modulation (Spatial Feature Transform).
  9. It is the clean version without custom compiled CUDA extensions used in StyleGAN2.
  10. Args:
  11. out_size (int): The spatial size of outputs.
  12. num_style_feat (int): Channel number of style features. Default: 512.
  13. num_mlp (int): Layer number of MLP style layers. Default: 8.
  14. channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2.
  15. narrow (float): The narrow ratio for channels. Default: 1.
  16. sft_half (bool): Whether to apply SFT on half of the input channels. Default: False.
  17. """
  18. def __init__(
  19. self,
  20. out_size,
  21. num_style_feat=512,
  22. num_mlp=8,
  23. channel_multiplier=2,
  24. narrow=1,
  25. sft_half=False,
  26. ):
  27. super(StyleGAN2GeneratorCSFT, self).__init__(
  28. out_size,
  29. num_style_feat=num_style_feat,
  30. num_mlp=num_mlp,
  31. channel_multiplier=channel_multiplier,
  32. narrow=narrow,
  33. )
  34. self.sft_half = sft_half
  35. def forward(
  36. self,
  37. styles,
  38. conditions,
  39. input_is_latent=False,
  40. noise=None,
  41. randomize_noise=True,
  42. truncation=1,
  43. truncation_latent=None,
  44. inject_index=None,
  45. return_latents=False,
  46. ):
  47. """Forward function for StyleGAN2GeneratorCSFT.
  48. Args:
  49. styles (list[Tensor]): Sample codes of styles.
  50. conditions (list[Tensor]): SFT conditions to generators.
  51. input_is_latent (bool): Whether input is latent style. Default: False.
  52. noise (Tensor | None): Input noise or None. Default: None.
  53. randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True.
  54. truncation (float): The truncation ratio. Default: 1.
  55. truncation_latent (Tensor | None): The truncation latent tensor. Default: None.
  56. inject_index (int | None): The injection index for mixing noise. Default: None.
  57. return_latents (bool): Whether to return style latents. Default: False.
  58. """
  59. # style codes -> latents with Style MLP layer
  60. if not input_is_latent:
  61. styles = [self.style_mlp(s) for s in styles]
  62. # noises
  63. if noise is None:
  64. if randomize_noise:
  65. noise = [None] * self.num_layers # for each style conv layer
  66. else: # use the stored noise
  67. noise = [
  68. getattr(self.noises, f"noise{i}") for i in range(self.num_layers)
  69. ]
  70. # style truncation
  71. if truncation < 1:
  72. style_truncation = []
  73. for style in styles:
  74. style_truncation.append(
  75. truncation_latent + truncation * (style - truncation_latent)
  76. )
  77. styles = style_truncation
  78. # get style latents with injection
  79. if len(styles) == 1:
  80. inject_index = self.num_latent
  81. if styles[0].ndim < 3:
  82. # repeat latent code for all the layers
  83. latent = styles[0].unsqueeze(1).repeat(1, inject_index, 1)
  84. else: # used for encoder with different latent code for each layer
  85. latent = styles[0]
  86. elif len(styles) == 2: # mixing noises
  87. if inject_index is None:
  88. inject_index = random.randint(1, self.num_latent - 1)
  89. latent1 = styles[0].unsqueeze(1).repeat(1, inject_index, 1)
  90. latent2 = (
  91. styles[1].unsqueeze(1).repeat(1, self.num_latent - inject_index, 1)
  92. )
  93. latent = torch.cat([latent1, latent2], 1)
  94. # main generation
  95. out = self.constant_input(latent.shape[0])
  96. out = self.style_conv1(out, latent[:, 0], noise=noise[0])
  97. skip = self.to_rgb1(out, latent[:, 1])
  98. i = 1
  99. for conv1, conv2, noise1, noise2, to_rgb in zip(
  100. self.style_convs[::2],
  101. self.style_convs[1::2],
  102. noise[1::2],
  103. noise[2::2],
  104. self.to_rgbs,
  105. ):
  106. out = conv1(out, latent[:, i], noise=noise1)
  107. # the conditions may have fewer levels
  108. if i < len(conditions):
  109. # SFT part to combine the conditions
  110. if self.sft_half: # only apply SFT to half of the channels
  111. out_same, out_sft = torch.split(out, int(out.size(1) // 2), dim=1)
  112. out_sft = out_sft * conditions[i - 1] + conditions[i]
  113. out = torch.cat([out_same, out_sft], dim=1)
  114. else: # apply SFT to all the channels
  115. out = out * conditions[i - 1] + conditions[i]
  116. out = conv2(out, latent[:, i + 1], noise=noise2)
  117. skip = to_rgb(out, latent[:, i + 2], skip) # feature back to the rgb space
  118. i += 2
  119. image = skip
  120. if return_latents:
  121. return image, latent
  122. else:
  123. return image, None
  124. class ResBlock(nn.Module):
  125. """Residual block with bilinear upsampling/downsampling.
  126. Args:
  127. in_channels (int): Channel number of the input.
  128. out_channels (int): Channel number of the output.
  129. mode (str): Upsampling/downsampling mode. Options: down | up. Default: down.
  130. """
  131. def __init__(self, in_channels, out_channels, mode="down"):
  132. super(ResBlock, self).__init__()
  133. self.conv1 = nn.Conv2d(in_channels, in_channels, 3, 1, 1)
  134. self.conv2 = nn.Conv2d(in_channels, out_channels, 3, 1, 1)
  135. self.skip = nn.Conv2d(in_channels, out_channels, 1, bias=False)
  136. if mode == "down":
  137. self.scale_factor = 0.5
  138. elif mode == "up":
  139. self.scale_factor = 2
  140. def forward(self, x):
  141. out = F.leaky_relu_(self.conv1(x), negative_slope=0.2)
  142. # upsample/downsample
  143. out = F.interpolate(
  144. out, scale_factor=self.scale_factor, mode="bilinear", align_corners=False
  145. )
  146. out = F.leaky_relu_(self.conv2(out), negative_slope=0.2)
  147. # skip
  148. x = F.interpolate(
  149. x, scale_factor=self.scale_factor, mode="bilinear", align_corners=False
  150. )
  151. skip = self.skip(x)
  152. out = out + skip
  153. return out
  154. class GFPGANv1Clean(nn.Module):
  155. """The GFPGAN architecture: Unet + StyleGAN2 decoder with SFT.
  156. It is the clean version without custom compiled CUDA extensions used in StyleGAN2.
  157. Ref: GFP-GAN: Towards Real-World Blind Face Restoration with Generative Facial Prior.
  158. Args:
  159. out_size (int): The spatial size of outputs.
  160. num_style_feat (int): Channel number of style features. Default: 512.
  161. channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2.
  162. decoder_load_path (str): The path to the pre-trained decoder model (usually, the StyleGAN2). Default: None.
  163. fix_decoder (bool): Whether to fix the decoder. Default: True.
  164. num_mlp (int): Layer number of MLP style layers. Default: 8.
  165. input_is_latent (bool): Whether input is latent style. Default: False.
  166. different_w (bool): Whether to use different latent w for different layers. Default: False.
  167. narrow (float): The narrow ratio for channels. Default: 1.
  168. sft_half (bool): Whether to apply SFT on half of the input channels. Default: False.
  169. """
  170. def __init__(
  171. self,
  172. out_size,
  173. num_style_feat=512,
  174. channel_multiplier=1,
  175. decoder_load_path=None,
  176. fix_decoder=True,
  177. # for stylegan decoder
  178. num_mlp=8,
  179. input_is_latent=False,
  180. different_w=False,
  181. narrow=1,
  182. sft_half=False,
  183. ):
  184. super(GFPGANv1Clean, self).__init__()
  185. self.input_is_latent = input_is_latent
  186. self.different_w = different_w
  187. self.num_style_feat = num_style_feat
  188. unet_narrow = narrow * 0.5 # by default, use a half of input channels
  189. channels = {
  190. "4": int(512 * unet_narrow),
  191. "8": int(512 * unet_narrow),
  192. "16": int(512 * unet_narrow),
  193. "32": int(512 * unet_narrow),
  194. "64": int(256 * channel_multiplier * unet_narrow),
  195. "128": int(128 * channel_multiplier * unet_narrow),
  196. "256": int(64 * channel_multiplier * unet_narrow),
  197. "512": int(32 * channel_multiplier * unet_narrow),
  198. "1024": int(16 * channel_multiplier * unet_narrow),
  199. }
  200. self.log_size = int(math.log(out_size, 2))
  201. first_out_size = 2 ** (int(math.log(out_size, 2)))
  202. self.conv_body_first = nn.Conv2d(3, channels[f"{first_out_size}"], 1)
  203. # downsample
  204. in_channels = channels[f"{first_out_size}"]
  205. self.conv_body_down = nn.ModuleList()
  206. for i in range(self.log_size, 2, -1):
  207. out_channels = channels[f"{2**(i - 1)}"]
  208. self.conv_body_down.append(ResBlock(in_channels, out_channels, mode="down"))
  209. in_channels = out_channels
  210. self.final_conv = nn.Conv2d(in_channels, channels["4"], 3, 1, 1)
  211. # upsample
  212. in_channels = channels["4"]
  213. self.conv_body_up = nn.ModuleList()
  214. for i in range(3, self.log_size + 1):
  215. out_channels = channels[f"{2**i}"]
  216. self.conv_body_up.append(ResBlock(in_channels, out_channels, mode="up"))
  217. in_channels = out_channels
  218. # to RGB
  219. self.toRGB = nn.ModuleList()
  220. for i in range(3, self.log_size + 1):
  221. self.toRGB.append(nn.Conv2d(channels[f"{2**i}"], 3, 1))
  222. if different_w:
  223. linear_out_channel = (int(math.log(out_size, 2)) * 2 - 2) * num_style_feat
  224. else:
  225. linear_out_channel = num_style_feat
  226. self.final_linear = nn.Linear(channels["4"] * 4 * 4, linear_out_channel)
  227. # the decoder: stylegan2 generator with SFT modulations
  228. self.stylegan_decoder = StyleGAN2GeneratorCSFT(
  229. out_size=out_size,
  230. num_style_feat=num_style_feat,
  231. num_mlp=num_mlp,
  232. channel_multiplier=channel_multiplier,
  233. narrow=narrow,
  234. sft_half=sft_half,
  235. )
  236. # load pre-trained stylegan2 model if necessary
  237. if decoder_load_path:
  238. self.stylegan_decoder.load_state_dict(
  239. torch.load(
  240. decoder_load_path, map_location=lambda storage, loc: storage
  241. )["params_ema"]
  242. )
  243. # fix decoder without updating params
  244. if fix_decoder:
  245. for _, param in self.stylegan_decoder.named_parameters():
  246. param.requires_grad = False
  247. # for SFT modulations (scale and shift)
  248. self.condition_scale = nn.ModuleList()
  249. self.condition_shift = nn.ModuleList()
  250. for i in range(3, self.log_size + 1):
  251. out_channels = channels[f"{2**i}"]
  252. if sft_half:
  253. sft_out_channels = out_channels
  254. else:
  255. sft_out_channels = out_channels * 2
  256. self.condition_scale.append(
  257. nn.Sequential(
  258. nn.Conv2d(out_channels, out_channels, 3, 1, 1),
  259. nn.LeakyReLU(0.2, True),
  260. nn.Conv2d(out_channels, sft_out_channels, 3, 1, 1),
  261. )
  262. )
  263. self.condition_shift.append(
  264. nn.Sequential(
  265. nn.Conv2d(out_channels, out_channels, 3, 1, 1),
  266. nn.LeakyReLU(0.2, True),
  267. nn.Conv2d(out_channels, sft_out_channels, 3, 1, 1),
  268. )
  269. )
  270. def forward(
  271. self, x, return_latents=False, return_rgb=True, randomize_noise=True, **kwargs
  272. ):
  273. """Forward function for GFPGANv1Clean.
  274. Args:
  275. x (Tensor): Input images.
  276. return_latents (bool): Whether to return style latents. Default: False.
  277. return_rgb (bool): Whether return intermediate rgb images. Default: True.
  278. randomize_noise (bool): Randomize noise, used when 'noise' is False. Default: True.
  279. """
  280. conditions = []
  281. unet_skips = []
  282. out_rgbs = []
  283. # encoder
  284. feat = F.leaky_relu_(self.conv_body_first(x), negative_slope=0.2)
  285. for i in range(self.log_size - 2):
  286. feat = self.conv_body_down[i](feat)
  287. unet_skips.insert(0, feat)
  288. feat = F.leaky_relu_(self.final_conv(feat), negative_slope=0.2)
  289. # style code
  290. style_code = self.final_linear(feat.view(feat.size(0), -1))
  291. if self.different_w:
  292. style_code = style_code.view(style_code.size(0), -1, self.num_style_feat)
  293. # decode
  294. for i in range(self.log_size - 2):
  295. # add unet skip
  296. feat = feat + unet_skips[i]
  297. # ResUpLayer
  298. feat = self.conv_body_up[i](feat)
  299. # generate scale and shift for SFT layers
  300. scale = self.condition_scale[i](feat)
  301. conditions.append(scale.clone())
  302. shift = self.condition_shift[i](feat)
  303. conditions.append(shift.clone())
  304. # generate rgb images
  305. if return_rgb:
  306. out_rgbs.append(self.toRGB[i](feat))
  307. # decoder
  308. image, _ = self.stylegan_decoder(
  309. [style_code],
  310. conditions,
  311. return_latents=return_latents,
  312. input_is_latent=self.input_is_latent,
  313. randomize_noise=randomize_noise,
  314. )
  315. return image, out_rgbs