mat.py 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946
  1. import os
  2. import random
  3. import cv2
  4. import numpy as np
  5. import torch
  6. import torch.nn as nn
  7. import torch.nn.functional as F
  8. import torch.utils.checkpoint as checkpoint
  9. from sorawm.iopaint.helper import (
  10. download_model,
  11. get_cache_path_by_url,
  12. load_model,
  13. norm_img,
  14. )
  15. from sorawm.iopaint.schema import InpaintRequest
  16. from .base import InpaintModel
  17. from .utils import (
  18. Conv2dLayer,
  19. FullyConnectedLayer,
  20. MinibatchStdLayer,
  21. activation_funcs,
  22. bias_act,
  23. conv2d_resample,
  24. normalize_2nd_moment,
  25. set_seed,
  26. setup_filter,
  27. to_2tuple,
  28. upsample2d,
  29. )
  30. class ModulatedConv2d(nn.Module):
  31. def __init__(
  32. self,
  33. in_channels, # Number of input channels.
  34. out_channels, # Number of output channels.
  35. kernel_size, # Width and height of the convolution kernel.
  36. style_dim, # dimension of the style code
  37. demodulate=True, # perfrom demodulation
  38. up=1, # Integer upsampling factor.
  39. down=1, # Integer downsampling factor.
  40. resample_filter=[
  41. 1,
  42. 3,
  43. 3,
  44. 1,
  45. ], # Low-pass filter to apply when resampling activations.
  46. conv_clamp=None, # Clamp the output to +-X, None = disable clamping.
  47. ):
  48. super().__init__()
  49. self.demodulate = demodulate
  50. self.weight = torch.nn.Parameter(
  51. torch.randn([1, out_channels, in_channels, kernel_size, kernel_size])
  52. )
  53. self.out_channels = out_channels
  54. self.kernel_size = kernel_size
  55. self.weight_gain = 1 / np.sqrt(in_channels * (kernel_size**2))
  56. self.padding = self.kernel_size // 2
  57. self.up = up
  58. self.down = down
  59. self.register_buffer("resample_filter", setup_filter(resample_filter))
  60. self.conv_clamp = conv_clamp
  61. self.affine = FullyConnectedLayer(style_dim, in_channels, bias_init=1)
  62. def forward(self, x, style):
  63. batch, in_channels, height, width = x.shape
  64. style = self.affine(style).view(batch, 1, in_channels, 1, 1)
  65. weight = self.weight * self.weight_gain * style
  66. if self.demodulate:
  67. decoefs = (weight.pow(2).sum(dim=[2, 3, 4]) + 1e-8).rsqrt()
  68. weight = weight * decoefs.view(batch, self.out_channels, 1, 1, 1)
  69. weight = weight.view(
  70. batch * self.out_channels, in_channels, self.kernel_size, self.kernel_size
  71. )
  72. x = x.view(1, batch * in_channels, height, width)
  73. x = conv2d_resample(
  74. x=x,
  75. w=weight,
  76. f=self.resample_filter,
  77. up=self.up,
  78. down=self.down,
  79. padding=self.padding,
  80. groups=batch,
  81. )
  82. out = x.view(batch, self.out_channels, *x.shape[2:])
  83. return out
  84. class StyleConv(torch.nn.Module):
  85. def __init__(
  86. self,
  87. in_channels, # Number of input channels.
  88. out_channels, # Number of output channels.
  89. style_dim, # Intermediate latent (W) dimensionality.
  90. resolution, # Resolution of this layer.
  91. kernel_size=3, # Convolution kernel size.
  92. up=1, # Integer upsampling factor.
  93. use_noise=False, # Enable noise input?
  94. activation="lrelu", # Activation function: 'relu', 'lrelu', etc.
  95. resample_filter=[
  96. 1,
  97. 3,
  98. 3,
  99. 1,
  100. ], # Low-pass filter to apply when resampling activations.
  101. conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping.
  102. demodulate=True, # perform demodulation
  103. ):
  104. super().__init__()
  105. self.conv = ModulatedConv2d(
  106. in_channels=in_channels,
  107. out_channels=out_channels,
  108. kernel_size=kernel_size,
  109. style_dim=style_dim,
  110. demodulate=demodulate,
  111. up=up,
  112. resample_filter=resample_filter,
  113. conv_clamp=conv_clamp,
  114. )
  115. self.use_noise = use_noise
  116. self.resolution = resolution
  117. if use_noise:
  118. self.register_buffer("noise_const", torch.randn([resolution, resolution]))
  119. self.noise_strength = torch.nn.Parameter(torch.zeros([]))
  120. self.bias = torch.nn.Parameter(torch.zeros([out_channels]))
  121. self.activation = activation
  122. self.act_gain = activation_funcs[activation].def_gain
  123. self.conv_clamp = conv_clamp
  124. def forward(self, x, style, noise_mode="random", gain=1):
  125. x = self.conv(x, style)
  126. assert noise_mode in ["random", "const", "none"]
  127. if self.use_noise:
  128. if noise_mode == "random":
  129. xh, xw = x.size()[-2:]
  130. noise = (
  131. torch.randn([x.shape[0], 1, xh, xw], device=x.device)
  132. * self.noise_strength
  133. )
  134. if noise_mode == "const":
  135. noise = self.noise_const * self.noise_strength
  136. x = x + noise
  137. act_gain = self.act_gain * gain
  138. act_clamp = self.conv_clamp * gain if self.conv_clamp is not None else None
  139. out = bias_act(
  140. x, self.bias, act=self.activation, gain=act_gain, clamp=act_clamp
  141. )
  142. return out
  143. class ToRGB(torch.nn.Module):
  144. def __init__(
  145. self,
  146. in_channels,
  147. out_channels,
  148. style_dim,
  149. kernel_size=1,
  150. resample_filter=[1, 3, 3, 1],
  151. conv_clamp=None,
  152. demodulate=False,
  153. ):
  154. super().__init__()
  155. self.conv = ModulatedConv2d(
  156. in_channels=in_channels,
  157. out_channels=out_channels,
  158. kernel_size=kernel_size,
  159. style_dim=style_dim,
  160. demodulate=demodulate,
  161. resample_filter=resample_filter,
  162. conv_clamp=conv_clamp,
  163. )
  164. self.bias = torch.nn.Parameter(torch.zeros([out_channels]))
  165. self.register_buffer("resample_filter", setup_filter(resample_filter))
  166. self.conv_clamp = conv_clamp
  167. def forward(self, x, style, skip=None):
  168. x = self.conv(x, style)
  169. out = bias_act(x, self.bias, clamp=self.conv_clamp)
  170. if skip is not None:
  171. if skip.shape != out.shape:
  172. skip = upsample2d(skip, self.resample_filter)
  173. out = out + skip
  174. return out
  175. def get_style_code(a, b):
  176. return torch.cat([a, b], dim=1)
  177. class DecBlockFirst(nn.Module):
  178. def __init__(
  179. self,
  180. in_channels,
  181. out_channels,
  182. activation,
  183. style_dim,
  184. use_noise,
  185. demodulate,
  186. img_channels,
  187. ):
  188. super().__init__()
  189. self.fc = FullyConnectedLayer(
  190. in_features=in_channels * 2,
  191. out_features=in_channels * 4**2,
  192. activation=activation,
  193. )
  194. self.conv = StyleConv(
  195. in_channels=in_channels,
  196. out_channels=out_channels,
  197. style_dim=style_dim,
  198. resolution=4,
  199. kernel_size=3,
  200. use_noise=use_noise,
  201. activation=activation,
  202. demodulate=demodulate,
  203. )
  204. self.toRGB = ToRGB(
  205. in_channels=out_channels,
  206. out_channels=img_channels,
  207. style_dim=style_dim,
  208. kernel_size=1,
  209. demodulate=False,
  210. )
  211. def forward(self, x, ws, gs, E_features, noise_mode="random"):
  212. x = self.fc(x).view(x.shape[0], -1, 4, 4)
  213. x = x + E_features[2]
  214. style = get_style_code(ws[:, 0], gs)
  215. x = self.conv(x, style, noise_mode=noise_mode)
  216. style = get_style_code(ws[:, 1], gs)
  217. img = self.toRGB(x, style, skip=None)
  218. return x, img
  219. class DecBlockFirstV2(nn.Module):
  220. def __init__(
  221. self,
  222. in_channels,
  223. out_channels,
  224. activation,
  225. style_dim,
  226. use_noise,
  227. demodulate,
  228. img_channels,
  229. ):
  230. super().__init__()
  231. self.conv0 = Conv2dLayer(
  232. in_channels=in_channels,
  233. out_channels=in_channels,
  234. kernel_size=3,
  235. activation=activation,
  236. )
  237. self.conv1 = StyleConv(
  238. in_channels=in_channels,
  239. out_channels=out_channels,
  240. style_dim=style_dim,
  241. resolution=4,
  242. kernel_size=3,
  243. use_noise=use_noise,
  244. activation=activation,
  245. demodulate=demodulate,
  246. )
  247. self.toRGB = ToRGB(
  248. in_channels=out_channels,
  249. out_channels=img_channels,
  250. style_dim=style_dim,
  251. kernel_size=1,
  252. demodulate=False,
  253. )
  254. def forward(self, x, ws, gs, E_features, noise_mode="random"):
  255. # x = self.fc(x).view(x.shape[0], -1, 4, 4)
  256. x = self.conv0(x)
  257. x = x + E_features[2]
  258. style = get_style_code(ws[:, 0], gs)
  259. x = self.conv1(x, style, noise_mode=noise_mode)
  260. style = get_style_code(ws[:, 1], gs)
  261. img = self.toRGB(x, style, skip=None)
  262. return x, img
  263. class DecBlock(nn.Module):
  264. def __init__(
  265. self,
  266. res,
  267. in_channels,
  268. out_channels,
  269. activation,
  270. style_dim,
  271. use_noise,
  272. demodulate,
  273. img_channels,
  274. ): # res = 2, ..., resolution_log2
  275. super().__init__()
  276. self.res = res
  277. self.conv0 = StyleConv(
  278. in_channels=in_channels,
  279. out_channels=out_channels,
  280. style_dim=style_dim,
  281. resolution=2**res,
  282. kernel_size=3,
  283. up=2,
  284. use_noise=use_noise,
  285. activation=activation,
  286. demodulate=demodulate,
  287. )
  288. self.conv1 = StyleConv(
  289. in_channels=out_channels,
  290. out_channels=out_channels,
  291. style_dim=style_dim,
  292. resolution=2**res,
  293. kernel_size=3,
  294. use_noise=use_noise,
  295. activation=activation,
  296. demodulate=demodulate,
  297. )
  298. self.toRGB = ToRGB(
  299. in_channels=out_channels,
  300. out_channels=img_channels,
  301. style_dim=style_dim,
  302. kernel_size=1,
  303. demodulate=False,
  304. )
  305. def forward(self, x, img, ws, gs, E_features, noise_mode="random"):
  306. style = get_style_code(ws[:, self.res * 2 - 5], gs)
  307. x = self.conv0(x, style, noise_mode=noise_mode)
  308. x = x + E_features[self.res]
  309. style = get_style_code(ws[:, self.res * 2 - 4], gs)
  310. x = self.conv1(x, style, noise_mode=noise_mode)
  311. style = get_style_code(ws[:, self.res * 2 - 3], gs)
  312. img = self.toRGB(x, style, skip=img)
  313. return x, img
  314. class MappingNet(torch.nn.Module):
  315. def __init__(
  316. self,
  317. z_dim, # Input latent (Z) dimensionality, 0 = no latent.
  318. c_dim, # Conditioning label (C) dimensionality, 0 = no label.
  319. w_dim, # Intermediate latent (W) dimensionality.
  320. num_ws, # Number of intermediate latents to output, None = do not broadcast.
  321. num_layers=8, # Number of mapping layers.
  322. embed_features=None, # Label embedding dimensionality, None = same as w_dim.
  323. layer_features=None, # Number of intermediate features in the mapping layers, None = same as w_dim.
  324. activation="lrelu", # Activation function: 'relu', 'lrelu', etc.
  325. lr_multiplier=0.01, # Learning rate multiplier for the mapping layers.
  326. w_avg_beta=0.995, # Decay for tracking the moving average of W during training, None = do not track.
  327. torch_dtype=torch.float32,
  328. ):
  329. super().__init__()
  330. self.z_dim = z_dim
  331. self.c_dim = c_dim
  332. self.w_dim = w_dim
  333. self.num_ws = num_ws
  334. self.num_layers = num_layers
  335. self.w_avg_beta = w_avg_beta
  336. self.torch_dtype = torch_dtype
  337. if embed_features is None:
  338. embed_features = w_dim
  339. if c_dim == 0:
  340. embed_features = 0
  341. if layer_features is None:
  342. layer_features = w_dim
  343. features_list = (
  344. [z_dim + embed_features] + [layer_features] * (num_layers - 1) + [w_dim]
  345. )
  346. if c_dim > 0:
  347. self.embed = FullyConnectedLayer(c_dim, embed_features)
  348. for idx in range(num_layers):
  349. in_features = features_list[idx]
  350. out_features = features_list[idx + 1]
  351. layer = FullyConnectedLayer(
  352. in_features,
  353. out_features,
  354. activation=activation,
  355. lr_multiplier=lr_multiplier,
  356. )
  357. setattr(self, f"fc{idx}", layer)
  358. if num_ws is not None and w_avg_beta is not None:
  359. self.register_buffer("w_avg", torch.zeros([w_dim]))
  360. def forward(
  361. self, z, c, truncation_psi=1, truncation_cutoff=None, skip_w_avg_update=False
  362. ):
  363. # Embed, normalize, and concat inputs.
  364. x = None
  365. if self.z_dim > 0:
  366. x = normalize_2nd_moment(z)
  367. if self.c_dim > 0:
  368. y = normalize_2nd_moment(self.embed(c))
  369. x = torch.cat([x, y], dim=1) if x is not None else y
  370. # Main layers.
  371. for idx in range(self.num_layers):
  372. layer = getattr(self, f"fc{idx}")
  373. x = layer(x)
  374. # Update moving average of W.
  375. if self.w_avg_beta is not None and self.training and not skip_w_avg_update:
  376. self.w_avg.copy_(x.detach().mean(dim=0).lerp(self.w_avg, self.w_avg_beta))
  377. # Broadcast.
  378. if self.num_ws is not None:
  379. x = x.unsqueeze(1).repeat([1, self.num_ws, 1])
  380. # Apply truncation.
  381. if truncation_psi != 1:
  382. assert self.w_avg_beta is not None
  383. if self.num_ws is None or truncation_cutoff is None:
  384. x = self.w_avg.lerp(x, truncation_psi)
  385. else:
  386. x[:, :truncation_cutoff] = self.w_avg.lerp(
  387. x[:, :truncation_cutoff], truncation_psi
  388. )
  389. return x
  390. class DisFromRGB(nn.Module):
  391. def __init__(
  392. self, in_channels, out_channels, activation
  393. ): # res = 2, ..., resolution_log2
  394. super().__init__()
  395. self.conv = Conv2dLayer(
  396. in_channels=in_channels,
  397. out_channels=out_channels,
  398. kernel_size=1,
  399. activation=activation,
  400. )
  401. def forward(self, x):
  402. return self.conv(x)
  403. class DisBlock(nn.Module):
  404. def __init__(
  405. self, in_channels, out_channels, activation
  406. ): # res = 2, ..., resolution_log2
  407. super().__init__()
  408. self.conv0 = Conv2dLayer(
  409. in_channels=in_channels,
  410. out_channels=in_channels,
  411. kernel_size=3,
  412. activation=activation,
  413. )
  414. self.conv1 = Conv2dLayer(
  415. in_channels=in_channels,
  416. out_channels=out_channels,
  417. kernel_size=3,
  418. down=2,
  419. activation=activation,
  420. )
  421. self.skip = Conv2dLayer(
  422. in_channels=in_channels,
  423. out_channels=out_channels,
  424. kernel_size=1,
  425. down=2,
  426. bias=False,
  427. )
  428. def forward(self, x):
  429. skip = self.skip(x, gain=np.sqrt(0.5))
  430. x = self.conv0(x)
  431. x = self.conv1(x, gain=np.sqrt(0.5))
  432. out = skip + x
  433. return out
  434. class Discriminator(torch.nn.Module):
  435. def __init__(
  436. self,
  437. c_dim, # Conditioning label (C) dimensionality.
  438. img_resolution, # Input resolution.
  439. img_channels, # Number of input color channels.
  440. channel_base=32768, # Overall multiplier for the number of channels.
  441. channel_max=512, # Maximum number of channels in any layer.
  442. channel_decay=1,
  443. cmap_dim=None, # Dimensionality of mapped conditioning label, None = default.
  444. activation="lrelu",
  445. mbstd_group_size=4, # Group size for the minibatch standard deviation layer, None = entire minibatch.
  446. mbstd_num_channels=1, # Number of features for the minibatch standard deviation layer, 0 = disable.
  447. ):
  448. super().__init__()
  449. self.c_dim = c_dim
  450. self.img_resolution = img_resolution
  451. self.img_channels = img_channels
  452. resolution_log2 = int(np.log2(img_resolution))
  453. assert img_resolution == 2**resolution_log2 and img_resolution >= 4
  454. self.resolution_log2 = resolution_log2
  455. def nf(stage):
  456. return np.clip(
  457. int(channel_base / 2 ** (stage * channel_decay)), 1, channel_max
  458. )
  459. if cmap_dim == None:
  460. cmap_dim = nf(2)
  461. if c_dim == 0:
  462. cmap_dim = 0
  463. self.cmap_dim = cmap_dim
  464. if c_dim > 0:
  465. self.mapping = MappingNet(
  466. z_dim=0, c_dim=c_dim, w_dim=cmap_dim, num_ws=None, w_avg_beta=None
  467. )
  468. Dis = [DisFromRGB(img_channels + 1, nf(resolution_log2), activation)]
  469. for res in range(resolution_log2, 2, -1):
  470. Dis.append(DisBlock(nf(res), nf(res - 1), activation))
  471. if mbstd_num_channels > 0:
  472. Dis.append(
  473. MinibatchStdLayer(
  474. group_size=mbstd_group_size, num_channels=mbstd_num_channels
  475. )
  476. )
  477. Dis.append(
  478. Conv2dLayer(
  479. nf(2) + mbstd_num_channels, nf(2), kernel_size=3, activation=activation
  480. )
  481. )
  482. self.Dis = nn.Sequential(*Dis)
  483. self.fc0 = FullyConnectedLayer(nf(2) * 4**2, nf(2), activation=activation)
  484. self.fc1 = FullyConnectedLayer(nf(2), 1 if cmap_dim == 0 else cmap_dim)
  485. def forward(self, images_in, masks_in, c):
  486. x = torch.cat([masks_in - 0.5, images_in], dim=1)
  487. x = self.Dis(x)
  488. x = self.fc1(self.fc0(x.flatten(start_dim=1)))
  489. if self.c_dim > 0:
  490. cmap = self.mapping(None, c)
  491. if self.cmap_dim > 0:
  492. x = (x * cmap).sum(dim=1, keepdim=True) * (1 / np.sqrt(self.cmap_dim))
  493. return x
  494. def nf(stage, channel_base=32768, channel_decay=1.0, channel_max=512):
  495. NF = {512: 64, 256: 128, 128: 256, 64: 512, 32: 512, 16: 512, 8: 512, 4: 512}
  496. return NF[2**stage]
  497. class Mlp(nn.Module):
  498. def __init__(
  499. self,
  500. in_features,
  501. hidden_features=None,
  502. out_features=None,
  503. act_layer=nn.GELU,
  504. drop=0.0,
  505. ):
  506. super().__init__()
  507. out_features = out_features or in_features
  508. hidden_features = hidden_features or in_features
  509. self.fc1 = FullyConnectedLayer(
  510. in_features=in_features, out_features=hidden_features, activation="lrelu"
  511. )
  512. self.fc2 = FullyConnectedLayer(
  513. in_features=hidden_features, out_features=out_features
  514. )
  515. def forward(self, x):
  516. x = self.fc1(x)
  517. x = self.fc2(x)
  518. return x
  519. def window_partition(x, window_size):
  520. """
  521. Args:
  522. x: (B, H, W, C)
  523. window_size (int): window size
  524. Returns:
  525. windows: (num_windows*B, window_size, window_size, C)
  526. """
  527. B, H, W, C = x.shape
  528. x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
  529. windows = (
  530. x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
  531. )
  532. return windows
  533. def window_reverse(windows, window_size: int, H: int, W: int):
  534. """
  535. Args:
  536. windows: (num_windows*B, window_size, window_size, C)
  537. window_size (int): Window size
  538. H (int): Height of image
  539. W (int): Width of image
  540. Returns:
  541. x: (B, H, W, C)
  542. """
  543. B = int(windows.shape[0] / (H * W / window_size / window_size))
  544. # B = windows.shape[0] / (H * W / window_size / window_size)
  545. x = windows.view(
  546. B, H // window_size, W // window_size, window_size, window_size, -1
  547. )
  548. x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
  549. return x
  550. class Conv2dLayerPartial(nn.Module):
  551. def __init__(
  552. self,
  553. in_channels, # Number of input channels.
  554. out_channels, # Number of output channels.
  555. kernel_size, # Width and height of the convolution kernel.
  556. bias=True, # Apply additive bias before the activation function?
  557. activation="linear", # Activation function: 'relu', 'lrelu', etc.
  558. up=1, # Integer upsampling factor.
  559. down=1, # Integer downsampling factor.
  560. resample_filter=[
  561. 1,
  562. 3,
  563. 3,
  564. 1,
  565. ], # Low-pass filter to apply when resampling activations.
  566. conv_clamp=None, # Clamp the output to +-X, None = disable clamping.
  567. trainable=True, # Update the weights of this layer during training?
  568. ):
  569. super().__init__()
  570. self.conv = Conv2dLayer(
  571. in_channels,
  572. out_channels,
  573. kernel_size,
  574. bias,
  575. activation,
  576. up,
  577. down,
  578. resample_filter,
  579. conv_clamp,
  580. trainable,
  581. )
  582. self.weight_maskUpdater = torch.ones(1, 1, kernel_size, kernel_size)
  583. self.slide_winsize = kernel_size**2
  584. self.stride = down
  585. self.padding = kernel_size // 2 if kernel_size % 2 == 1 else 0
  586. def forward(self, x, mask=None):
  587. if mask is not None:
  588. with torch.no_grad():
  589. if self.weight_maskUpdater.type() != x.type():
  590. self.weight_maskUpdater = self.weight_maskUpdater.to(x)
  591. update_mask = F.conv2d(
  592. mask,
  593. self.weight_maskUpdater,
  594. bias=None,
  595. stride=self.stride,
  596. padding=self.padding,
  597. )
  598. mask_ratio = self.slide_winsize / (update_mask.to(torch.float32) + 1e-8)
  599. update_mask = torch.clamp(update_mask, 0, 1) # 0 or 1
  600. mask_ratio = torch.mul(mask_ratio, update_mask).to(x.dtype)
  601. x = self.conv(x)
  602. x = torch.mul(x, mask_ratio)
  603. return x, update_mask
  604. else:
  605. x = self.conv(x)
  606. return x, None
  607. class WindowAttention(nn.Module):
  608. r"""Window based multi-head self attention (W-MSA) module with relative position bias.
  609. It supports both of shifted and non-shifted window.
  610. Args:
  611. dim (int): Number of input channels.
  612. window_size (tuple[int]): The height and width of the window.
  613. num_heads (int): Number of attention heads.
  614. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
  615. qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
  616. attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
  617. proj_drop (float, optional): Dropout ratio of output. Default: 0.0
  618. """
  619. def __init__(
  620. self,
  621. dim,
  622. window_size,
  623. num_heads,
  624. down_ratio=1,
  625. qkv_bias=True,
  626. qk_scale=None,
  627. attn_drop=0.0,
  628. proj_drop=0.0,
  629. ):
  630. super().__init__()
  631. self.dim = dim
  632. self.window_size = window_size # Wh, Ww
  633. self.num_heads = num_heads
  634. head_dim = dim // num_heads
  635. self.scale = qk_scale or head_dim**-0.5
  636. self.q = FullyConnectedLayer(in_features=dim, out_features=dim)
  637. self.k = FullyConnectedLayer(in_features=dim, out_features=dim)
  638. self.v = FullyConnectedLayer(in_features=dim, out_features=dim)
  639. self.proj = FullyConnectedLayer(in_features=dim, out_features=dim)
  640. self.softmax = nn.Softmax(dim=-1)
  641. def forward(self, x, mask_windows=None, mask=None):
  642. """
  643. Args:
  644. x: input features with shape of (num_windows*B, N, C)
  645. mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
  646. """
  647. B_, N, C = x.shape
  648. norm_x = F.normalize(x, p=2.0, dim=-1, eps=torch.finfo(x.dtype).eps)
  649. q = (
  650. self.q(norm_x)
  651. .reshape(B_, N, self.num_heads, C // self.num_heads)
  652. .permute(0, 2, 1, 3)
  653. )
  654. k = (
  655. self.k(norm_x)
  656. .view(B_, -1, self.num_heads, C // self.num_heads)
  657. .permute(0, 2, 3, 1)
  658. )
  659. v = (
  660. self.v(x)
  661. .view(B_, -1, self.num_heads, C // self.num_heads)
  662. .permute(0, 2, 1, 3)
  663. )
  664. attn = (q @ k) * self.scale
  665. if mask is not None:
  666. nW = mask.shape[0]
  667. attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(
  668. 1
  669. ).unsqueeze(0)
  670. attn = attn.view(-1, self.num_heads, N, N)
  671. if mask_windows is not None:
  672. attn_mask_windows = mask_windows.squeeze(-1).unsqueeze(1).unsqueeze(1)
  673. attn = attn + attn_mask_windows.masked_fill(
  674. attn_mask_windows == 0, float(-100.0)
  675. ).masked_fill(attn_mask_windows == 1, float(0.0))
  676. with torch.no_grad():
  677. mask_windows = torch.clamp(
  678. torch.sum(mask_windows, dim=1, keepdim=True), 0, 1
  679. ).repeat(1, N, 1)
  680. attn = self.softmax(attn)
  681. x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
  682. x = self.proj(x)
  683. return x, mask_windows
  684. class SwinTransformerBlock(nn.Module):
  685. r"""Swin Transformer Block.
  686. Args:
  687. dim (int): Number of input channels.
  688. input_resolution (tuple[int]): Input resulotion.
  689. num_heads (int): Number of attention heads.
  690. window_size (int): Window size.
  691. shift_size (int): Shift size for SW-MSA.
  692. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
  693. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
  694. qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
  695. drop (float, optional): Dropout rate. Default: 0.0
  696. attn_drop (float, optional): Attention dropout rate. Default: 0.0
  697. drop_path (float, optional): Stochastic depth rate. Default: 0.0
  698. act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
  699. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
  700. """
  701. def __init__(
  702. self,
  703. dim,
  704. input_resolution,
  705. num_heads,
  706. down_ratio=1,
  707. window_size=7,
  708. shift_size=0,
  709. mlp_ratio=4.0,
  710. qkv_bias=True,
  711. qk_scale=None,
  712. drop=0.0,
  713. attn_drop=0.0,
  714. drop_path=0.0,
  715. act_layer=nn.GELU,
  716. norm_layer=nn.LayerNorm,
  717. ):
  718. super().__init__()
  719. self.dim = dim
  720. self.input_resolution = input_resolution
  721. self.num_heads = num_heads
  722. self.window_size = window_size
  723. self.shift_size = shift_size
  724. self.mlp_ratio = mlp_ratio
  725. if min(self.input_resolution) <= self.window_size:
  726. # if window size is larger than input resolution, we don't partition windows
  727. self.shift_size = 0
  728. self.window_size = min(self.input_resolution)
  729. assert (
  730. 0 <= self.shift_size < self.window_size
  731. ), "shift_size must in 0-window_size"
  732. if self.shift_size > 0:
  733. down_ratio = 1
  734. self.attn = WindowAttention(
  735. dim,
  736. window_size=to_2tuple(self.window_size),
  737. num_heads=num_heads,
  738. down_ratio=down_ratio,
  739. qkv_bias=qkv_bias,
  740. qk_scale=qk_scale,
  741. attn_drop=attn_drop,
  742. proj_drop=drop,
  743. )
  744. self.fuse = FullyConnectedLayer(
  745. in_features=dim * 2, out_features=dim, activation="lrelu"
  746. )
  747. mlp_hidden_dim = int(dim * mlp_ratio)
  748. self.mlp = Mlp(
  749. in_features=dim,
  750. hidden_features=mlp_hidden_dim,
  751. act_layer=act_layer,
  752. drop=drop,
  753. )
  754. if self.shift_size > 0:
  755. attn_mask = self.calculate_mask(self.input_resolution)
  756. else:
  757. attn_mask = None
  758. self.register_buffer("attn_mask", attn_mask)
  759. def calculate_mask(self, x_size):
  760. # calculate attention mask for SW-MSA
  761. H, W = x_size
  762. img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1
  763. h_slices = (
  764. slice(0, -self.window_size),
  765. slice(-self.window_size, -self.shift_size),
  766. slice(-self.shift_size, None),
  767. )
  768. w_slices = (
  769. slice(0, -self.window_size),
  770. slice(-self.window_size, -self.shift_size),
  771. slice(-self.shift_size, None),
  772. )
  773. cnt = 0
  774. for h in h_slices:
  775. for w in w_slices:
  776. img_mask[:, h, w, :] = cnt
  777. cnt += 1
  778. mask_windows = window_partition(
  779. img_mask, self.window_size
  780. ) # nW, window_size, window_size, 1
  781. mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
  782. attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
  783. attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(
  784. attn_mask == 0, float(0.0)
  785. )
  786. return attn_mask
  787. def forward(self, x, x_size, mask=None):
  788. # H, W = self.input_resolution
  789. H, W = x_size
  790. B, L, C = x.shape
  791. # assert L == H * W, "input feature has wrong size"
  792. shortcut = x
  793. x = x.view(B, H, W, C)
  794. if mask is not None:
  795. mask = mask.view(B, H, W, 1)
  796. # cyclic shift
  797. if self.shift_size > 0:
  798. shifted_x = torch.roll(
  799. x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)
  800. )
  801. if mask is not None:
  802. shifted_mask = torch.roll(
  803. mask, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)
  804. )
  805. else:
  806. shifted_x = x
  807. if mask is not None:
  808. shifted_mask = mask
  809. # partition windows
  810. x_windows = window_partition(
  811. shifted_x, self.window_size
  812. ) # nW*B, window_size, window_size, C
  813. x_windows = x_windows.view(
  814. -1, self.window_size * self.window_size, C
  815. ) # nW*B, window_size*window_size, C
  816. if mask is not None:
  817. mask_windows = window_partition(shifted_mask, self.window_size)
  818. mask_windows = mask_windows.view(-1, self.window_size * self.window_size, 1)
  819. else:
  820. mask_windows = None
  821. # W-MSA/SW-MSA (to be compatible for testing on images whose shapes are the multiple of window size
  822. if self.input_resolution == x_size:
  823. attn_windows, mask_windows = self.attn(
  824. x_windows, mask_windows, mask=self.attn_mask
  825. ) # nW*B, window_size*window_size, C
  826. else:
  827. attn_windows, mask_windows = self.attn(
  828. x_windows,
  829. mask_windows,
  830. mask=self.calculate_mask(x_size).to(x.dtype).to(x.device),
  831. ) # nW*B, window_size*window_size, C
  832. # merge windows
  833. attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
  834. shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C
  835. if mask is not None:
  836. mask_windows = mask_windows.view(-1, self.window_size, self.window_size, 1)
  837. shifted_mask = window_reverse(mask_windows, self.window_size, H, W)
  838. # reverse cyclic shift
  839. if self.shift_size > 0:
  840. x = torch.roll(
  841. shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)
  842. )
  843. if mask is not None:
  844. mask = torch.roll(
  845. shifted_mask, shifts=(self.shift_size, self.shift_size), dims=(1, 2)
  846. )
  847. else:
  848. x = shifted_x
  849. if mask is not None:
  850. mask = shifted_mask
  851. x = x.view(B, H * W, C)
  852. if mask is not None:
  853. mask = mask.view(B, H * W, 1)
  854. # FFN
  855. x = self.fuse(torch.cat([shortcut, x], dim=-1))
  856. x = self.mlp(x)
  857. return x, mask
  858. class PatchMerging(nn.Module):
  859. def __init__(self, in_channels, out_channels, down=2):
  860. super().__init__()
  861. self.conv = Conv2dLayerPartial(
  862. in_channels=in_channels,
  863. out_channels=out_channels,
  864. kernel_size=3,
  865. activation="lrelu",
  866. down=down,
  867. )
  868. self.down = down
  869. def forward(self, x, x_size, mask=None):
  870. x = token2feature(x, x_size)
  871. if mask is not None:
  872. mask = token2feature(mask, x_size)
  873. x, mask = self.conv(x, mask)
  874. if self.down != 1:
  875. ratio = 1 / self.down
  876. x_size = (int(x_size[0] * ratio), int(x_size[1] * ratio))
  877. x = feature2token(x)
  878. if mask is not None:
  879. mask = feature2token(mask)
  880. return x, x_size, mask
  881. class PatchUpsampling(nn.Module):
  882. def __init__(self, in_channels, out_channels, up=2):
  883. super().__init__()
  884. self.conv = Conv2dLayerPartial(
  885. in_channels=in_channels,
  886. out_channels=out_channels,
  887. kernel_size=3,
  888. activation="lrelu",
  889. up=up,
  890. )
  891. self.up = up
  892. def forward(self, x, x_size, mask=None):
  893. x = token2feature(x, x_size)
  894. if mask is not None:
  895. mask = token2feature(mask, x_size)
  896. x, mask = self.conv(x, mask)
  897. if self.up != 1:
  898. x_size = (int(x_size[0] * self.up), int(x_size[1] * self.up))
  899. x = feature2token(x)
  900. if mask is not None:
  901. mask = feature2token(mask)
  902. return x, x_size, mask
  903. class BasicLayer(nn.Module):
  904. """A basic Swin Transformer layer for one stage.
  905. Args:
  906. dim (int): Number of input channels.
  907. input_resolution (tuple[int]): Input resolution.
  908. depth (int): Number of blocks.
  909. num_heads (int): Number of attention heads.
  910. window_size (int): Local window size.
  911. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
  912. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
  913. qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
  914. drop (float, optional): Dropout rate. Default: 0.0
  915. attn_drop (float, optional): Attention dropout rate. Default: 0.0
  916. drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
  917. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
  918. downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
  919. use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
  920. """
  921. def __init__(
  922. self,
  923. dim,
  924. input_resolution,
  925. depth,
  926. num_heads,
  927. window_size,
  928. down_ratio=1,
  929. mlp_ratio=2.0,
  930. qkv_bias=True,
  931. qk_scale=None,
  932. drop=0.0,
  933. attn_drop=0.0,
  934. drop_path=0.0,
  935. norm_layer=nn.LayerNorm,
  936. downsample=None,
  937. use_checkpoint=False,
  938. ):
  939. super().__init__()
  940. self.dim = dim
  941. self.input_resolution = input_resolution
  942. self.depth = depth
  943. self.use_checkpoint = use_checkpoint
  944. # patch merging layer
  945. if downsample is not None:
  946. # self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer)
  947. self.downsample = downsample
  948. else:
  949. self.downsample = None
  950. # build blocks
  951. self.blocks = nn.ModuleList(
  952. [
  953. SwinTransformerBlock(
  954. dim=dim,
  955. input_resolution=input_resolution,
  956. num_heads=num_heads,
  957. down_ratio=down_ratio,
  958. window_size=window_size,
  959. shift_size=0 if (i % 2 == 0) else window_size // 2,
  960. mlp_ratio=mlp_ratio,
  961. qkv_bias=qkv_bias,
  962. qk_scale=qk_scale,
  963. drop=drop,
  964. attn_drop=attn_drop,
  965. drop_path=drop_path[i]
  966. if isinstance(drop_path, list)
  967. else drop_path,
  968. norm_layer=norm_layer,
  969. )
  970. for i in range(depth)
  971. ]
  972. )
  973. self.conv = Conv2dLayerPartial(
  974. in_channels=dim, out_channels=dim, kernel_size=3, activation="lrelu"
  975. )
  976. def forward(self, x, x_size, mask=None):
  977. if self.downsample is not None:
  978. x, x_size, mask = self.downsample(x, x_size, mask)
  979. identity = x
  980. for blk in self.blocks:
  981. if self.use_checkpoint:
  982. x, mask = checkpoint.checkpoint(blk, x, x_size, mask)
  983. else:
  984. x, mask = blk(x, x_size, mask)
  985. if mask is not None:
  986. mask = token2feature(mask, x_size)
  987. x, mask = self.conv(token2feature(x, x_size), mask)
  988. x = feature2token(x) + identity
  989. if mask is not None:
  990. mask = feature2token(mask)
  991. return x, x_size, mask
  992. class ToToken(nn.Module):
  993. def __init__(self, in_channels=3, dim=128, kernel_size=5, stride=1):
  994. super().__init__()
  995. self.proj = Conv2dLayerPartial(
  996. in_channels=in_channels,
  997. out_channels=dim,
  998. kernel_size=kernel_size,
  999. activation="lrelu",
  1000. )
  1001. def forward(self, x, mask):
  1002. x, mask = self.proj(x, mask)
  1003. return x, mask
  1004. class EncFromRGB(nn.Module):
  1005. def __init__(
  1006. self, in_channels, out_channels, activation
  1007. ): # res = 2, ..., resolution_log2
  1008. super().__init__()
  1009. self.conv0 = Conv2dLayer(
  1010. in_channels=in_channels,
  1011. out_channels=out_channels,
  1012. kernel_size=1,
  1013. activation=activation,
  1014. )
  1015. self.conv1 = Conv2dLayer(
  1016. in_channels=out_channels,
  1017. out_channels=out_channels,
  1018. kernel_size=3,
  1019. activation=activation,
  1020. )
  1021. def forward(self, x):
  1022. x = self.conv0(x)
  1023. x = self.conv1(x)
  1024. return x
  1025. class ConvBlockDown(nn.Module):
  1026. def __init__(
  1027. self, in_channels, out_channels, activation
  1028. ): # res = 2, ..., resolution_log
  1029. super().__init__()
  1030. self.conv0 = Conv2dLayer(
  1031. in_channels=in_channels,
  1032. out_channels=out_channels,
  1033. kernel_size=3,
  1034. activation=activation,
  1035. down=2,
  1036. )
  1037. self.conv1 = Conv2dLayer(
  1038. in_channels=out_channels,
  1039. out_channels=out_channels,
  1040. kernel_size=3,
  1041. activation=activation,
  1042. )
  1043. def forward(self, x):
  1044. x = self.conv0(x)
  1045. x = self.conv1(x)
  1046. return x
  1047. def token2feature(x, x_size):
  1048. B, N, C = x.shape
  1049. h, w = x_size
  1050. x = x.permute(0, 2, 1).reshape(B, C, h, w)
  1051. return x
  1052. def feature2token(x):
  1053. B, C, H, W = x.shape
  1054. x = x.view(B, C, -1).transpose(1, 2)
  1055. return x
  1056. class Encoder(nn.Module):
  1057. def __init__(
  1058. self,
  1059. res_log2,
  1060. img_channels,
  1061. activation,
  1062. patch_size=5,
  1063. channels=16,
  1064. drop_path_rate=0.1,
  1065. ):
  1066. super().__init__()
  1067. self.resolution = []
  1068. for idx, i in enumerate(range(res_log2, 3, -1)): # from input size to 16x16
  1069. res = 2**i
  1070. self.resolution.append(res)
  1071. if i == res_log2:
  1072. block = EncFromRGB(img_channels * 2 + 1, nf(i), activation)
  1073. else:
  1074. block = ConvBlockDown(nf(i + 1), nf(i), activation)
  1075. setattr(self, "EncConv_Block_%dx%d" % (res, res), block)
  1076. def forward(self, x):
  1077. out = {}
  1078. for res in self.resolution:
  1079. res_log2 = int(np.log2(res))
  1080. x = getattr(self, "EncConv_Block_%dx%d" % (res, res))(x)
  1081. out[res_log2] = x
  1082. return out
  1083. class ToStyle(nn.Module):
  1084. def __init__(self, in_channels, out_channels, activation, drop_rate):
  1085. super().__init__()
  1086. self.conv = nn.Sequential(
  1087. Conv2dLayer(
  1088. in_channels=in_channels,
  1089. out_channels=in_channels,
  1090. kernel_size=3,
  1091. activation=activation,
  1092. down=2,
  1093. ),
  1094. Conv2dLayer(
  1095. in_channels=in_channels,
  1096. out_channels=in_channels,
  1097. kernel_size=3,
  1098. activation=activation,
  1099. down=2,
  1100. ),
  1101. Conv2dLayer(
  1102. in_channels=in_channels,
  1103. out_channels=in_channels,
  1104. kernel_size=3,
  1105. activation=activation,
  1106. down=2,
  1107. ),
  1108. )
  1109. self.pool = nn.AdaptiveAvgPool2d(1)
  1110. self.fc = FullyConnectedLayer(
  1111. in_features=in_channels, out_features=out_channels, activation=activation
  1112. )
  1113. # self.dropout = nn.Dropout(drop_rate)
  1114. def forward(self, x):
  1115. x = self.conv(x)
  1116. x = self.pool(x)
  1117. x = self.fc(x.flatten(start_dim=1))
  1118. # x = self.dropout(x)
  1119. return x
  1120. class DecBlockFirstV2(nn.Module):
  1121. def __init__(
  1122. self,
  1123. res,
  1124. in_channels,
  1125. out_channels,
  1126. activation,
  1127. style_dim,
  1128. use_noise,
  1129. demodulate,
  1130. img_channels,
  1131. ):
  1132. super().__init__()
  1133. self.res = res
  1134. self.conv0 = Conv2dLayer(
  1135. in_channels=in_channels,
  1136. out_channels=in_channels,
  1137. kernel_size=3,
  1138. activation=activation,
  1139. )
  1140. self.conv1 = StyleConv(
  1141. in_channels=in_channels,
  1142. out_channels=out_channels,
  1143. style_dim=style_dim,
  1144. resolution=2**res,
  1145. kernel_size=3,
  1146. use_noise=use_noise,
  1147. activation=activation,
  1148. demodulate=demodulate,
  1149. )
  1150. self.toRGB = ToRGB(
  1151. in_channels=out_channels,
  1152. out_channels=img_channels,
  1153. style_dim=style_dim,
  1154. kernel_size=1,
  1155. demodulate=False,
  1156. )
  1157. def forward(self, x, ws, gs, E_features, noise_mode="random"):
  1158. # x = self.fc(x).view(x.shape[0], -1, 4, 4)
  1159. x = self.conv0(x)
  1160. x = x + E_features[self.res]
  1161. style = get_style_code(ws[:, 0], gs)
  1162. x = self.conv1(x, style, noise_mode=noise_mode)
  1163. style = get_style_code(ws[:, 1], gs)
  1164. img = self.toRGB(x, style, skip=None)
  1165. return x, img
  1166. class DecBlock(nn.Module):
  1167. def __init__(
  1168. self,
  1169. res,
  1170. in_channels,
  1171. out_channels,
  1172. activation,
  1173. style_dim,
  1174. use_noise,
  1175. demodulate,
  1176. img_channels,
  1177. ): # res = 4, ..., resolution_log2
  1178. super().__init__()
  1179. self.res = res
  1180. self.conv0 = StyleConv(
  1181. in_channels=in_channels,
  1182. out_channels=out_channels,
  1183. style_dim=style_dim,
  1184. resolution=2**res,
  1185. kernel_size=3,
  1186. up=2,
  1187. use_noise=use_noise,
  1188. activation=activation,
  1189. demodulate=demodulate,
  1190. )
  1191. self.conv1 = StyleConv(
  1192. in_channels=out_channels,
  1193. out_channels=out_channels,
  1194. style_dim=style_dim,
  1195. resolution=2**res,
  1196. kernel_size=3,
  1197. use_noise=use_noise,
  1198. activation=activation,
  1199. demodulate=demodulate,
  1200. )
  1201. self.toRGB = ToRGB(
  1202. in_channels=out_channels,
  1203. out_channels=img_channels,
  1204. style_dim=style_dim,
  1205. kernel_size=1,
  1206. demodulate=False,
  1207. )
  1208. def forward(self, x, img, ws, gs, E_features, noise_mode="random"):
  1209. style = get_style_code(ws[:, self.res * 2 - 9], gs)
  1210. x = self.conv0(x, style, noise_mode=noise_mode)
  1211. x = x + E_features[self.res]
  1212. style = get_style_code(ws[:, self.res * 2 - 8], gs)
  1213. x = self.conv1(x, style, noise_mode=noise_mode)
  1214. style = get_style_code(ws[:, self.res * 2 - 7], gs)
  1215. img = self.toRGB(x, style, skip=img)
  1216. return x, img
  1217. class Decoder(nn.Module):
  1218. def __init__(
  1219. self, res_log2, activation, style_dim, use_noise, demodulate, img_channels
  1220. ):
  1221. super().__init__()
  1222. self.Dec_16x16 = DecBlockFirstV2(
  1223. 4, nf(4), nf(4), activation, style_dim, use_noise, demodulate, img_channels
  1224. )
  1225. for res in range(5, res_log2 + 1):
  1226. setattr(
  1227. self,
  1228. "Dec_%dx%d" % (2**res, 2**res),
  1229. DecBlock(
  1230. res,
  1231. nf(res - 1),
  1232. nf(res),
  1233. activation,
  1234. style_dim,
  1235. use_noise,
  1236. demodulate,
  1237. img_channels,
  1238. ),
  1239. )
  1240. self.res_log2 = res_log2
  1241. def forward(self, x, ws, gs, E_features, noise_mode="random"):
  1242. x, img = self.Dec_16x16(x, ws, gs, E_features, noise_mode=noise_mode)
  1243. for res in range(5, self.res_log2 + 1):
  1244. block = getattr(self, "Dec_%dx%d" % (2**res, 2**res))
  1245. x, img = block(x, img, ws, gs, E_features, noise_mode=noise_mode)
  1246. return img
  1247. class DecStyleBlock(nn.Module):
  1248. def __init__(
  1249. self,
  1250. res,
  1251. in_channels,
  1252. out_channels,
  1253. activation,
  1254. style_dim,
  1255. use_noise,
  1256. demodulate,
  1257. img_channels,
  1258. ):
  1259. super().__init__()
  1260. self.res = res
  1261. self.conv0 = StyleConv(
  1262. in_channels=in_channels,
  1263. out_channels=out_channels,
  1264. style_dim=style_dim,
  1265. resolution=2**res,
  1266. kernel_size=3,
  1267. up=2,
  1268. use_noise=use_noise,
  1269. activation=activation,
  1270. demodulate=demodulate,
  1271. )
  1272. self.conv1 = StyleConv(
  1273. in_channels=out_channels,
  1274. out_channels=out_channels,
  1275. style_dim=style_dim,
  1276. resolution=2**res,
  1277. kernel_size=3,
  1278. use_noise=use_noise,
  1279. activation=activation,
  1280. demodulate=demodulate,
  1281. )
  1282. self.toRGB = ToRGB(
  1283. in_channels=out_channels,
  1284. out_channels=img_channels,
  1285. style_dim=style_dim,
  1286. kernel_size=1,
  1287. demodulate=False,
  1288. )
  1289. def forward(self, x, img, style, skip, noise_mode="random"):
  1290. x = self.conv0(x, style, noise_mode=noise_mode)
  1291. x = x + skip
  1292. x = self.conv1(x, style, noise_mode=noise_mode)
  1293. img = self.toRGB(x, style, skip=img)
  1294. return x, img
  1295. class FirstStage(nn.Module):
  1296. def __init__(
  1297. self,
  1298. img_channels,
  1299. img_resolution=256,
  1300. dim=180,
  1301. w_dim=512,
  1302. use_noise=False,
  1303. demodulate=True,
  1304. activation="lrelu",
  1305. ):
  1306. super().__init__()
  1307. res = 64
  1308. self.conv_first = Conv2dLayerPartial(
  1309. in_channels=img_channels + 1,
  1310. out_channels=dim,
  1311. kernel_size=3,
  1312. activation=activation,
  1313. )
  1314. self.enc_conv = nn.ModuleList()
  1315. down_time = int(np.log2(img_resolution // res))
  1316. # 根据图片尺寸构建 swim transformer 的层数
  1317. for i in range(down_time): # from input size to 64
  1318. self.enc_conv.append(
  1319. Conv2dLayerPartial(
  1320. in_channels=dim,
  1321. out_channels=dim,
  1322. kernel_size=3,
  1323. down=2,
  1324. activation=activation,
  1325. )
  1326. )
  1327. # from 64 -> 16 -> 64
  1328. depths = [2, 3, 4, 3, 2]
  1329. ratios = [1, 1 / 2, 1 / 2, 2, 2]
  1330. num_heads = 6
  1331. window_sizes = [8, 16, 16, 16, 8]
  1332. drop_path_rate = 0.1
  1333. dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
  1334. self.tran = nn.ModuleList()
  1335. for i, depth in enumerate(depths):
  1336. res = int(res * ratios[i])
  1337. if ratios[i] < 1:
  1338. merge = PatchMerging(dim, dim, down=int(1 / ratios[i]))
  1339. elif ratios[i] > 1:
  1340. merge = PatchUpsampling(dim, dim, up=ratios[i])
  1341. else:
  1342. merge = None
  1343. self.tran.append(
  1344. BasicLayer(
  1345. dim=dim,
  1346. input_resolution=[res, res],
  1347. depth=depth,
  1348. num_heads=num_heads,
  1349. window_size=window_sizes[i],
  1350. drop_path=dpr[sum(depths[:i]) : sum(depths[: i + 1])],
  1351. downsample=merge,
  1352. )
  1353. )
  1354. # global style
  1355. down_conv = []
  1356. for i in range(int(np.log2(16))):
  1357. down_conv.append(
  1358. Conv2dLayer(
  1359. in_channels=dim,
  1360. out_channels=dim,
  1361. kernel_size=3,
  1362. down=2,
  1363. activation=activation,
  1364. )
  1365. )
  1366. down_conv.append(nn.AdaptiveAvgPool2d((1, 1)))
  1367. self.down_conv = nn.Sequential(*down_conv)
  1368. self.to_style = FullyConnectedLayer(
  1369. in_features=dim, out_features=dim * 2, activation=activation
  1370. )
  1371. self.ws_style = FullyConnectedLayer(
  1372. in_features=w_dim, out_features=dim, activation=activation
  1373. )
  1374. self.to_square = FullyConnectedLayer(
  1375. in_features=dim, out_features=16 * 16, activation=activation
  1376. )
  1377. style_dim = dim * 3
  1378. self.dec_conv = nn.ModuleList()
  1379. for i in range(down_time): # from 64 to input size
  1380. res = res * 2
  1381. self.dec_conv.append(
  1382. DecStyleBlock(
  1383. res,
  1384. dim,
  1385. dim,
  1386. activation,
  1387. style_dim,
  1388. use_noise,
  1389. demodulate,
  1390. img_channels,
  1391. )
  1392. )
  1393. def forward(self, images_in, masks_in, ws, noise_mode="random"):
  1394. x = torch.cat([masks_in - 0.5, images_in * masks_in], dim=1)
  1395. skips = []
  1396. x, mask = self.conv_first(x, masks_in) # input size
  1397. skips.append(x)
  1398. for i, block in enumerate(self.enc_conv): # input size to 64
  1399. x, mask = block(x, mask)
  1400. if i != len(self.enc_conv) - 1:
  1401. skips.append(x)
  1402. x_size = x.size()[-2:]
  1403. x = feature2token(x)
  1404. mask = feature2token(mask)
  1405. mid = len(self.tran) // 2
  1406. for i, block in enumerate(self.tran): # 64 to 16
  1407. if i < mid:
  1408. x, x_size, mask = block(x, x_size, mask)
  1409. skips.append(x)
  1410. elif i > mid:
  1411. x, x_size, mask = block(x, x_size, None)
  1412. x = x + skips[mid - i]
  1413. else:
  1414. x, x_size, mask = block(x, x_size, None)
  1415. mul_map = torch.ones_like(x) * 0.5
  1416. mul_map = F.dropout(mul_map, training=True)
  1417. ws = self.ws_style(ws[:, -1])
  1418. add_n = self.to_square(ws).unsqueeze(1)
  1419. add_n = (
  1420. F.interpolate(
  1421. add_n, size=x.size(1), mode="linear", align_corners=False
  1422. )
  1423. .squeeze(1)
  1424. .unsqueeze(-1)
  1425. )
  1426. x = x * mul_map + add_n * (1 - mul_map)
  1427. gs = self.to_style(
  1428. self.down_conv(token2feature(x, x_size)).flatten(start_dim=1)
  1429. )
  1430. style = torch.cat([gs, ws], dim=1)
  1431. x = token2feature(x, x_size).contiguous()
  1432. img = None
  1433. for i, block in enumerate(self.dec_conv):
  1434. x, img = block(
  1435. x, img, style, skips[len(self.dec_conv) - i - 1], noise_mode=noise_mode
  1436. )
  1437. # ensemble
  1438. img = img * (1 - masks_in) + images_in * masks_in
  1439. return img
  1440. class SynthesisNet(nn.Module):
  1441. def __init__(
  1442. self,
  1443. w_dim, # Intermediate latent (W) dimensionality.
  1444. img_resolution, # Output image resolution.
  1445. img_channels=3, # Number of color channels.
  1446. channel_base=32768, # Overall multiplier for the number of channels.
  1447. channel_decay=1.0,
  1448. channel_max=512, # Maximum number of channels in any layer.
  1449. activation="lrelu", # Activation function: 'relu', 'lrelu', etc.
  1450. drop_rate=0.5,
  1451. use_noise=False,
  1452. demodulate=True,
  1453. ):
  1454. super().__init__()
  1455. resolution_log2 = int(np.log2(img_resolution))
  1456. assert img_resolution == 2**resolution_log2 and img_resolution >= 4
  1457. self.num_layers = resolution_log2 * 2 - 3 * 2
  1458. self.img_resolution = img_resolution
  1459. self.resolution_log2 = resolution_log2
  1460. # first stage
  1461. self.first_stage = FirstStage(
  1462. img_channels,
  1463. img_resolution=img_resolution,
  1464. w_dim=w_dim,
  1465. use_noise=False,
  1466. demodulate=demodulate,
  1467. )
  1468. # second stage
  1469. self.enc = Encoder(
  1470. resolution_log2, img_channels, activation, patch_size=5, channels=16
  1471. )
  1472. self.to_square = FullyConnectedLayer(
  1473. in_features=w_dim, out_features=16 * 16, activation=activation
  1474. )
  1475. self.to_style = ToStyle(
  1476. in_channels=nf(4),
  1477. out_channels=nf(2) * 2,
  1478. activation=activation,
  1479. drop_rate=drop_rate,
  1480. )
  1481. style_dim = w_dim + nf(2) * 2
  1482. self.dec = Decoder(
  1483. resolution_log2, activation, style_dim, use_noise, demodulate, img_channels
  1484. )
  1485. def forward(self, images_in, masks_in, ws, noise_mode="random", return_stg1=False):
  1486. out_stg1 = self.first_stage(images_in, masks_in, ws, noise_mode=noise_mode)
  1487. # encoder
  1488. x = images_in * masks_in + out_stg1 * (1 - masks_in)
  1489. x = torch.cat([masks_in - 0.5, x, images_in * masks_in], dim=1)
  1490. E_features = self.enc(x)
  1491. fea_16 = E_features[4]
  1492. mul_map = torch.ones_like(fea_16) * 0.5
  1493. mul_map = F.dropout(mul_map, training=True)
  1494. add_n = self.to_square(ws[:, 0]).view(-1, 16, 16).unsqueeze(1)
  1495. add_n = F.interpolate(
  1496. add_n, size=fea_16.size()[-2:], mode="bilinear", align_corners=False
  1497. )
  1498. fea_16 = fea_16 * mul_map + add_n * (1 - mul_map)
  1499. E_features[4] = fea_16
  1500. # style
  1501. gs = self.to_style(fea_16)
  1502. # decoder
  1503. img = self.dec(fea_16, ws, gs, E_features, noise_mode=noise_mode)
  1504. # ensemble
  1505. img = img * (1 - masks_in) + images_in * masks_in
  1506. if not return_stg1:
  1507. return img
  1508. else:
  1509. return img, out_stg1
  1510. class Generator(nn.Module):
  1511. def __init__(
  1512. self,
  1513. z_dim, # Input latent (Z) dimensionality, 0 = no latent.
  1514. c_dim, # Conditioning label (C) dimensionality, 0 = no label.
  1515. w_dim, # Intermediate latent (W) dimensionality.
  1516. img_resolution, # resolution of generated image
  1517. img_channels, # Number of input color channels.
  1518. synthesis_kwargs={}, # Arguments for SynthesisNetwork.
  1519. mapping_kwargs={}, # Arguments for MappingNetwork.
  1520. ):
  1521. super().__init__()
  1522. self.z_dim = z_dim
  1523. self.c_dim = c_dim
  1524. self.w_dim = w_dim
  1525. self.img_resolution = img_resolution
  1526. self.img_channels = img_channels
  1527. self.synthesis = SynthesisNet(
  1528. w_dim=w_dim,
  1529. img_resolution=img_resolution,
  1530. img_channels=img_channels,
  1531. **synthesis_kwargs,
  1532. )
  1533. self.mapping = MappingNet(
  1534. z_dim=z_dim,
  1535. c_dim=c_dim,
  1536. w_dim=w_dim,
  1537. num_ws=self.synthesis.num_layers,
  1538. **mapping_kwargs,
  1539. )
  1540. def forward(
  1541. self,
  1542. images_in,
  1543. masks_in,
  1544. z,
  1545. c,
  1546. truncation_psi=1,
  1547. truncation_cutoff=None,
  1548. skip_w_avg_update=False,
  1549. noise_mode="none",
  1550. return_stg1=False,
  1551. ):
  1552. ws = self.mapping(
  1553. z,
  1554. c,
  1555. truncation_psi=truncation_psi,
  1556. truncation_cutoff=truncation_cutoff,
  1557. skip_w_avg_update=skip_w_avg_update,
  1558. )
  1559. img = self.synthesis(images_in, masks_in, ws, noise_mode=noise_mode)
  1560. return img
  1561. class Discriminator(torch.nn.Module):
  1562. def __init__(
  1563. self,
  1564. c_dim, # Conditioning label (C) dimensionality.
  1565. img_resolution, # Input resolution.
  1566. img_channels, # Number of input color channels.
  1567. channel_base=32768, # Overall multiplier for the number of channels.
  1568. channel_max=512, # Maximum number of channels in any layer.
  1569. channel_decay=1,
  1570. cmap_dim=None, # Dimensionality of mapped conditioning label, None = default.
  1571. activation="lrelu",
  1572. mbstd_group_size=4, # Group size for the minibatch standard deviation layer, None = entire minibatch.
  1573. mbstd_num_channels=1, # Number of features for the minibatch standard deviation layer, 0 = disable.
  1574. ):
  1575. super().__init__()
  1576. self.c_dim = c_dim
  1577. self.img_resolution = img_resolution
  1578. self.img_channels = img_channels
  1579. resolution_log2 = int(np.log2(img_resolution))
  1580. assert img_resolution == 2**resolution_log2 and img_resolution >= 4
  1581. self.resolution_log2 = resolution_log2
  1582. if cmap_dim == None:
  1583. cmap_dim = nf(2)
  1584. if c_dim == 0:
  1585. cmap_dim = 0
  1586. self.cmap_dim = cmap_dim
  1587. if c_dim > 0:
  1588. self.mapping = MappingNet(
  1589. z_dim=0, c_dim=c_dim, w_dim=cmap_dim, num_ws=None, w_avg_beta=None
  1590. )
  1591. Dis = [DisFromRGB(img_channels + 1, nf(resolution_log2), activation)]
  1592. for res in range(resolution_log2, 2, -1):
  1593. Dis.append(DisBlock(nf(res), nf(res - 1), activation))
  1594. if mbstd_num_channels > 0:
  1595. Dis.append(
  1596. MinibatchStdLayer(
  1597. group_size=mbstd_group_size, num_channels=mbstd_num_channels
  1598. )
  1599. )
  1600. Dis.append(
  1601. Conv2dLayer(
  1602. nf(2) + mbstd_num_channels, nf(2), kernel_size=3, activation=activation
  1603. )
  1604. )
  1605. self.Dis = nn.Sequential(*Dis)
  1606. self.fc0 = FullyConnectedLayer(nf(2) * 4**2, nf(2), activation=activation)
  1607. self.fc1 = FullyConnectedLayer(nf(2), 1 if cmap_dim == 0 else cmap_dim)
  1608. # for 64x64
  1609. Dis_stg1 = [DisFromRGB(img_channels + 1, nf(resolution_log2) // 2, activation)]
  1610. for res in range(resolution_log2, 2, -1):
  1611. Dis_stg1.append(DisBlock(nf(res) // 2, nf(res - 1) // 2, activation))
  1612. if mbstd_num_channels > 0:
  1613. Dis_stg1.append(
  1614. MinibatchStdLayer(
  1615. group_size=mbstd_group_size, num_channels=mbstd_num_channels
  1616. )
  1617. )
  1618. Dis_stg1.append(
  1619. Conv2dLayer(
  1620. nf(2) // 2 + mbstd_num_channels,
  1621. nf(2) // 2,
  1622. kernel_size=3,
  1623. activation=activation,
  1624. )
  1625. )
  1626. self.Dis_stg1 = nn.Sequential(*Dis_stg1)
  1627. self.fc0_stg1 = FullyConnectedLayer(
  1628. nf(2) // 2 * 4**2, nf(2) // 2, activation=activation
  1629. )
  1630. self.fc1_stg1 = FullyConnectedLayer(
  1631. nf(2) // 2, 1 if cmap_dim == 0 else cmap_dim
  1632. )
  1633. def forward(self, images_in, masks_in, images_stg1, c):
  1634. x = self.Dis(torch.cat([masks_in - 0.5, images_in], dim=1))
  1635. x = self.fc1(self.fc0(x.flatten(start_dim=1)))
  1636. x_stg1 = self.Dis_stg1(torch.cat([masks_in - 0.5, images_stg1], dim=1))
  1637. x_stg1 = self.fc1_stg1(self.fc0_stg1(x_stg1.flatten(start_dim=1)))
  1638. if self.c_dim > 0:
  1639. cmap = self.mapping(None, c)
  1640. if self.cmap_dim > 0:
  1641. x = (x * cmap).sum(dim=1, keepdim=True) * (1 / np.sqrt(self.cmap_dim))
  1642. x_stg1 = (x_stg1 * cmap).sum(dim=1, keepdim=True) * (
  1643. 1 / np.sqrt(self.cmap_dim)
  1644. )
  1645. return x, x_stg1
  1646. MAT_MODEL_URL = os.environ.get(
  1647. "MAT_MODEL_URL",
  1648. "https://github.com/Sanster/models/releases/download/add_mat/Places_512_FullData_G.pth",
  1649. )
  1650. MAT_MODEL_MD5 = os.environ.get("MAT_MODEL_MD5", "8ca927835fa3f5e21d65ffcb165377ed")
  1651. class MAT(InpaintModel):
  1652. name = "mat"
  1653. min_size = 512
  1654. pad_mod = 512
  1655. pad_to_square = True
  1656. is_erase_model = True
  1657. def init_model(self, device, **kwargs):
  1658. seed = 240 # pick up a random number
  1659. set_seed(seed)
  1660. fp16 = not kwargs.get("no_half", False)
  1661. use_gpu = "cuda" in str(device) and torch.cuda.is_available()
  1662. self.torch_dtype = torch.float16 if use_gpu and fp16 else torch.float32
  1663. G = Generator(
  1664. z_dim=512,
  1665. c_dim=0,
  1666. w_dim=512,
  1667. img_resolution=512,
  1668. img_channels=3,
  1669. mapping_kwargs={"torch_dtype": self.torch_dtype},
  1670. ).to(self.torch_dtype)
  1671. # fmt: off
  1672. self.model = load_model(G, MAT_MODEL_URL, device, MAT_MODEL_MD5)
  1673. self.z = torch.from_numpy(np.random.randn(1, G.z_dim)).to(self.torch_dtype).to(device)
  1674. self.label = torch.zeros([1, self.model.c_dim], device=device).to(self.torch_dtype)
  1675. # fmt: on
  1676. @staticmethod
  1677. def download():
  1678. download_model(MAT_MODEL_URL, MAT_MODEL_MD5)
  1679. @staticmethod
  1680. def is_downloaded() -> bool:
  1681. return os.path.exists(get_cache_path_by_url(MAT_MODEL_URL))
  1682. def forward(self, image, mask, config: InpaintRequest):
  1683. """Input images and output images have same size
  1684. images: [H, W, C] RGB
  1685. masks: [H, W] mask area == 255
  1686. return: BGR IMAGE
  1687. """
  1688. image = norm_img(image) # [0, 1]
  1689. image = image * 2 - 1 # [0, 1] -> [-1, 1]
  1690. mask = (mask > 127) * 255
  1691. mask = 255 - mask
  1692. mask = norm_img(mask)
  1693. image = (
  1694. torch.from_numpy(image).unsqueeze(0).to(self.torch_dtype).to(self.device)
  1695. )
  1696. mask = torch.from_numpy(mask).unsqueeze(0).to(self.torch_dtype).to(self.device)
  1697. output = self.model(
  1698. image, mask, self.z, self.label, truncation_psi=1, noise_mode="none"
  1699. )
  1700. output = (
  1701. (output.permute(0, 2, 3, 1) * 127.5 + 127.5)
  1702. .round()
  1703. .clamp(0, 255)
  1704. .to(torch.uint8)
  1705. )
  1706. output = output[0].cpu().numpy()
  1707. cur_res = cv2.cvtColor(output, cv2.COLOR_RGB2BGR)
  1708. return cur_res