model.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. # pytorch_diffusion + derived encoder decoder
  2. import math
  3. import torch
  4. import torch.nn as nn
  5. import numpy as np
  6. from einops import rearrange
  7. from ldm.util import instantiate_from_config
  8. from ldm.modules.attention import LinearAttention
  9. def get_timestep_embedding(timesteps, embedding_dim):
  10. """
  11. This matches the implementation in Denoising Diffusion Probabilistic Models:
  12. From Fairseq.
  13. Build sinusoidal embeddings.
  14. This matches the implementation in tensor2tensor, but differs slightly
  15. from the description in Section 3.5 of "Attention Is All You Need".
  16. """
  17. assert len(timesteps.shape) == 1
  18. half_dim = embedding_dim // 2
  19. emb = math.log(10000) / (half_dim - 1)
  20. emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb)
  21. emb = emb.to(device=timesteps.device)
  22. emb = timesteps.float()[:, None] * emb[None, :]
  23. emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
  24. if embedding_dim % 2 == 1: # zero pad
  25. emb = torch.nn.functional.pad(emb, (0,1,0,0))
  26. return emb
  27. def nonlinearity(x):
  28. # swish
  29. return x*torch.sigmoid(x)
  30. def Normalize(in_channels, num_groups=32):
  31. return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True)
  32. class Upsample(nn.Module):
  33. def __init__(self, in_channels, with_conv):
  34. super().__init__()
  35. self.with_conv = with_conv
  36. if self.with_conv:
  37. self.conv = torch.nn.Conv2d(in_channels,
  38. in_channels,
  39. kernel_size=3,
  40. stride=1,
  41. padding=1)
  42. def forward(self, x):
  43. x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
  44. if self.with_conv:
  45. x = self.conv(x)
  46. return x
  47. class Downsample(nn.Module):
  48. def __init__(self, in_channels, with_conv):
  49. super().__init__()
  50. self.with_conv = with_conv
  51. if self.with_conv:
  52. # no asymmetric padding in torch conv, must do it ourselves
  53. self.conv = torch.nn.Conv2d(in_channels,
  54. in_channels,
  55. kernel_size=3,
  56. stride=2,
  57. padding=0)
  58. def forward(self, x):
  59. if self.with_conv:
  60. pad = (0,1,0,1)
  61. x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
  62. x = self.conv(x)
  63. else:
  64. x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
  65. return x
  66. class ResnetBlock(nn.Module):
  67. def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
  68. dropout, temb_channels=512):
  69. super().__init__()
  70. self.in_channels = in_channels
  71. out_channels = in_channels if out_channels is None else out_channels
  72. self.out_channels = out_channels
  73. self.use_conv_shortcut = conv_shortcut
  74. self.norm1 = Normalize(in_channels)
  75. self.conv1 = torch.nn.Conv2d(in_channels,
  76. out_channels,
  77. kernel_size=3,
  78. stride=1,
  79. padding=1)
  80. if temb_channels > 0:
  81. self.temb_proj = torch.nn.Linear(temb_channels,
  82. out_channels)
  83. self.norm2 = Normalize(out_channels)
  84. self.dropout = torch.nn.Dropout(dropout)
  85. self.conv2 = torch.nn.Conv2d(out_channels,
  86. out_channels,
  87. kernel_size=3,
  88. stride=1,
  89. padding=1)
  90. if self.in_channels != self.out_channels:
  91. if self.use_conv_shortcut:
  92. self.conv_shortcut = torch.nn.Conv2d(in_channels,
  93. out_channels,
  94. kernel_size=3,
  95. stride=1,
  96. padding=1)
  97. else:
  98. self.nin_shortcut = torch.nn.Conv2d(in_channels,
  99. out_channels,
  100. kernel_size=1,
  101. stride=1,
  102. padding=0)
  103. def forward(self, x, temb):
  104. h = x
  105. h = self.norm1(h)
  106. h = nonlinearity(h)
  107. h = self.conv1(h)
  108. if temb is not None:
  109. h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None]
  110. h = self.norm2(h)
  111. h = nonlinearity(h)
  112. h = self.dropout(h)
  113. h = self.conv2(h)
  114. if self.in_channels != self.out_channels:
  115. if self.use_conv_shortcut:
  116. x = self.conv_shortcut(x)
  117. else:
  118. x = self.nin_shortcut(x)
  119. return x+h
  120. class LinAttnBlock(LinearAttention):
  121. """to match AttnBlock usage"""
  122. def __init__(self, in_channels):
  123. super().__init__(dim=in_channels, heads=1, dim_head=in_channels)
  124. class AttnBlock(nn.Module):
  125. def __init__(self, in_channels):
  126. super().__init__()
  127. self.in_channels = in_channels
  128. self.norm = Normalize(in_channels)
  129. self.q = torch.nn.Conv2d(in_channels,
  130. in_channels,
  131. kernel_size=1,
  132. stride=1,
  133. padding=0)
  134. self.k = torch.nn.Conv2d(in_channels,
  135. in_channels,
  136. kernel_size=1,
  137. stride=1,
  138. padding=0)
  139. self.v = torch.nn.Conv2d(in_channels,
  140. in_channels,
  141. kernel_size=1,
  142. stride=1,
  143. padding=0)
  144. self.proj_out = torch.nn.Conv2d(in_channels,
  145. in_channels,
  146. kernel_size=1,
  147. stride=1,
  148. padding=0)
  149. def forward(self, x):
  150. h_ = x
  151. h_ = self.norm(h_)
  152. q = self.q(h_)
  153. k = self.k(h_)
  154. v = self.v(h_)
  155. # compute attention
  156. b,c,h,w = q.shape
  157. q = q.reshape(b,c,h*w)
  158. q = q.permute(0,2,1) # b,hw,c
  159. k = k.reshape(b,c,h*w) # b,c,hw
  160. w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
  161. w_ = w_ * (int(c)**(-0.5))
  162. w_ = torch.nn.functional.softmax(w_, dim=2)
  163. # attend to values
  164. v = v.reshape(b,c,h*w)
  165. w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q)
  166. h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
  167. h_ = h_.reshape(b,c,h,w)
  168. h_ = self.proj_out(h_)
  169. return x+h_
  170. def make_attn(in_channels, attn_type="vanilla"):
  171. assert attn_type in ["vanilla", "linear", "none"], f'attn_type {attn_type} unknown'
  172. print(f"making attention of type '{attn_type}' with {in_channels} in_channels")
  173. if attn_type == "vanilla":
  174. return AttnBlock(in_channels)
  175. elif attn_type == "none":
  176. return nn.Identity(in_channels)
  177. else:
  178. return LinAttnBlock(in_channels)
  179. class Model(nn.Module):
  180. def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
  181. attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
  182. resolution, use_timestep=True, use_linear_attn=False, attn_type="vanilla"):
  183. super().__init__()
  184. if use_linear_attn: attn_type = "linear"
  185. self.ch = ch
  186. self.temb_ch = self.ch*4
  187. self.num_resolutions = len(ch_mult)
  188. self.num_res_blocks = num_res_blocks
  189. self.resolution = resolution
  190. self.in_channels = in_channels
  191. self.use_timestep = use_timestep
  192. if self.use_timestep:
  193. # timestep embedding
  194. self.temb = nn.Module()
  195. self.temb.dense = nn.ModuleList([
  196. torch.nn.Linear(self.ch,
  197. self.temb_ch),
  198. torch.nn.Linear(self.temb_ch,
  199. self.temb_ch),
  200. ])
  201. # downsampling
  202. self.conv_in = torch.nn.Conv2d(in_channels,
  203. self.ch,
  204. kernel_size=3,
  205. stride=1,
  206. padding=1)
  207. curr_res = resolution
  208. in_ch_mult = (1,)+tuple(ch_mult)
  209. self.down = nn.ModuleList()
  210. for i_level in range(self.num_resolutions):
  211. block = nn.ModuleList()
  212. attn = nn.ModuleList()
  213. block_in = ch*in_ch_mult[i_level]
  214. block_out = ch*ch_mult[i_level]
  215. for i_block in range(self.num_res_blocks):
  216. block.append(ResnetBlock(in_channels=block_in,
  217. out_channels=block_out,
  218. temb_channels=self.temb_ch,
  219. dropout=dropout))
  220. block_in = block_out
  221. if curr_res in attn_resolutions:
  222. attn.append(make_attn(block_in, attn_type=attn_type))
  223. down = nn.Module()
  224. down.block = block
  225. down.attn = attn
  226. if i_level != self.num_resolutions-1:
  227. down.downsample = Downsample(block_in, resamp_with_conv)
  228. curr_res = curr_res // 2
  229. self.down.append(down)
  230. # middle
  231. self.mid = nn.Module()
  232. self.mid.block_1 = ResnetBlock(in_channels=block_in,
  233. out_channels=block_in,
  234. temb_channels=self.temb_ch,
  235. dropout=dropout)
  236. self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
  237. self.mid.block_2 = ResnetBlock(in_channels=block_in,
  238. out_channels=block_in,
  239. temb_channels=self.temb_ch,
  240. dropout=dropout)
  241. # upsampling
  242. self.up = nn.ModuleList()
  243. for i_level in reversed(range(self.num_resolutions)):
  244. block = nn.ModuleList()
  245. attn = nn.ModuleList()
  246. block_out = ch*ch_mult[i_level]
  247. skip_in = ch*ch_mult[i_level]
  248. for i_block in range(self.num_res_blocks+1):
  249. if i_block == self.num_res_blocks:
  250. skip_in = ch*in_ch_mult[i_level]
  251. block.append(ResnetBlock(in_channels=block_in+skip_in,
  252. out_channels=block_out,
  253. temb_channels=self.temb_ch,
  254. dropout=dropout))
  255. block_in = block_out
  256. if curr_res in attn_resolutions:
  257. attn.append(make_attn(block_in, attn_type=attn_type))
  258. up = nn.Module()
  259. up.block = block
  260. up.attn = attn
  261. if i_level != 0:
  262. up.upsample = Upsample(block_in, resamp_with_conv)
  263. curr_res = curr_res * 2
  264. self.up.insert(0, up) # prepend to get consistent order
  265. # end
  266. self.norm_out = Normalize(block_in)
  267. self.conv_out = torch.nn.Conv2d(block_in,
  268. out_ch,
  269. kernel_size=3,
  270. stride=1,
  271. padding=1)
  272. def forward(self, x, t=None, context=None):
  273. #assert x.shape[2] == x.shape[3] == self.resolution
  274. if context is not None:
  275. # assume aligned context, cat along channel axis
  276. x = torch.cat((x, context), dim=1)
  277. if self.use_timestep:
  278. # timestep embedding
  279. assert t is not None
  280. temb = get_timestep_embedding(t, self.ch)
  281. temb = self.temb.dense[0](temb)
  282. temb = nonlinearity(temb)
  283. temb = self.temb.dense[1](temb)
  284. else:
  285. temb = None
  286. # downsampling
  287. hs = [self.conv_in(x)]
  288. for i_level in range(self.num_resolutions):
  289. for i_block in range(self.num_res_blocks):
  290. h = self.down[i_level].block[i_block](hs[-1], temb)
  291. if len(self.down[i_level].attn) > 0:
  292. h = self.down[i_level].attn[i_block](h)
  293. hs.append(h)
  294. if i_level != self.num_resolutions-1:
  295. hs.append(self.down[i_level].downsample(hs[-1]))
  296. # middle
  297. h = hs[-1]
  298. h = self.mid.block_1(h, temb)
  299. h = self.mid.attn_1(h)
  300. h = self.mid.block_2(h, temb)
  301. # upsampling
  302. for i_level in reversed(range(self.num_resolutions)):
  303. for i_block in range(self.num_res_blocks+1):
  304. h = self.up[i_level].block[i_block](
  305. torch.cat([h, hs.pop()], dim=1), temb)
  306. if len(self.up[i_level].attn) > 0:
  307. h = self.up[i_level].attn[i_block](h)
  308. if i_level != 0:
  309. h = self.up[i_level].upsample(h)
  310. # end
  311. h = self.norm_out(h)
  312. h = nonlinearity(h)
  313. h = self.conv_out(h)
  314. return h
  315. def get_last_layer(self):
  316. return self.conv_out.weight
  317. class Encoder(nn.Module):
  318. def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
  319. attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
  320. resolution, z_channels, double_z=True, use_linear_attn=False, attn_type="vanilla",
  321. **ignore_kwargs):
  322. super().__init__()
  323. if use_linear_attn: attn_type = "linear"
  324. self.ch = ch
  325. self.temb_ch = 0
  326. self.num_resolutions = len(ch_mult)
  327. self.num_res_blocks = num_res_blocks
  328. self.resolution = resolution
  329. self.in_channels = in_channels
  330. # downsampling
  331. self.conv_in = torch.nn.Conv2d(in_channels,
  332. self.ch,
  333. kernel_size=3,
  334. stride=1,
  335. padding=1)
  336. curr_res = resolution
  337. in_ch_mult = (1,)+tuple(ch_mult)
  338. self.in_ch_mult = in_ch_mult
  339. self.down = nn.ModuleList()
  340. for i_level in range(self.num_resolutions):
  341. block = nn.ModuleList()
  342. attn = nn.ModuleList()
  343. block_in = ch*in_ch_mult[i_level]
  344. block_out = ch*ch_mult[i_level]
  345. for i_block in range(self.num_res_blocks):
  346. block.append(ResnetBlock(in_channels=block_in,
  347. out_channels=block_out,
  348. temb_channels=self.temb_ch,
  349. dropout=dropout))
  350. block_in = block_out
  351. if curr_res in attn_resolutions:
  352. attn.append(make_attn(block_in, attn_type=attn_type))
  353. down = nn.Module()
  354. down.block = block
  355. down.attn = attn
  356. if i_level != self.num_resolutions-1:
  357. down.downsample = Downsample(block_in, resamp_with_conv)
  358. curr_res = curr_res // 2
  359. self.down.append(down)
  360. # middle
  361. self.mid = nn.Module()
  362. self.mid.block_1 = ResnetBlock(in_channels=block_in,
  363. out_channels=block_in,
  364. temb_channels=self.temb_ch,
  365. dropout=dropout)
  366. self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
  367. self.mid.block_2 = ResnetBlock(in_channels=block_in,
  368. out_channels=block_in,
  369. temb_channels=self.temb_ch,
  370. dropout=dropout)
  371. # end
  372. self.norm_out = Normalize(block_in)
  373. self.conv_out = torch.nn.Conv2d(block_in,
  374. 2*z_channels if double_z else z_channels,
  375. kernel_size=3,
  376. stride=1,
  377. padding=1)
  378. def forward(self, x):
  379. # timestep embedding
  380. temb = None
  381. # downsampling
  382. hs = [self.conv_in(x)]
  383. for i_level in range(self.num_resolutions):
  384. for i_block in range(self.num_res_blocks):
  385. h = self.down[i_level].block[i_block](hs[-1], temb)
  386. if len(self.down[i_level].attn) > 0:
  387. h = self.down[i_level].attn[i_block](h)
  388. hs.append(h)
  389. if i_level != self.num_resolutions-1:
  390. hs.append(self.down[i_level].downsample(hs[-1]))
  391. # middle
  392. h = hs[-1]
  393. h = self.mid.block_1(h, temb)
  394. h = self.mid.attn_1(h)
  395. h = self.mid.block_2(h, temb)
  396. # end
  397. h = self.norm_out(h)
  398. h = nonlinearity(h)
  399. h = self.conv_out(h)
  400. return h
  401. class Decoder(nn.Module):
  402. def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
  403. attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
  404. resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
  405. attn_type="vanilla", **ignorekwargs):
  406. super().__init__()
  407. if use_linear_attn: attn_type = "linear"
  408. self.ch = ch
  409. self.temb_ch = 0
  410. self.num_resolutions = len(ch_mult)
  411. self.num_res_blocks = num_res_blocks
  412. self.resolution = resolution
  413. self.in_channels = in_channels
  414. self.give_pre_end = give_pre_end
  415. self.tanh_out = tanh_out
  416. # compute in_ch_mult, block_in and curr_res at lowest res
  417. in_ch_mult = (1,)+tuple(ch_mult)
  418. block_in = ch*ch_mult[self.num_resolutions-1]
  419. curr_res = resolution // 2**(self.num_resolutions-1)
  420. self.z_shape = (1,z_channels,curr_res,curr_res)
  421. print("Working with z of shape {} = {} dimensions.".format(
  422. self.z_shape, np.prod(self.z_shape)))
  423. # z to block_in
  424. self.conv_in = torch.nn.Conv2d(z_channels,
  425. block_in,
  426. kernel_size=3,
  427. stride=1,
  428. padding=1)
  429. # middle
  430. self.mid = nn.Module()
  431. self.mid.block_1 = ResnetBlock(in_channels=block_in,
  432. out_channels=block_in,
  433. temb_channels=self.temb_ch,
  434. dropout=dropout)
  435. self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
  436. self.mid.block_2 = ResnetBlock(in_channels=block_in,
  437. out_channels=block_in,
  438. temb_channels=self.temb_ch,
  439. dropout=dropout)
  440. # upsampling
  441. self.up = nn.ModuleList()
  442. for i_level in reversed(range(self.num_resolutions)):
  443. block = nn.ModuleList()
  444. attn = nn.ModuleList()
  445. block_out = ch*ch_mult[i_level]
  446. for i_block in range(self.num_res_blocks+1):
  447. block.append(ResnetBlock(in_channels=block_in,
  448. out_channels=block_out,
  449. temb_channels=self.temb_ch,
  450. dropout=dropout))
  451. block_in = block_out
  452. if curr_res in attn_resolutions:
  453. attn.append(make_attn(block_in, attn_type=attn_type))
  454. up = nn.Module()
  455. up.block = block
  456. up.attn = attn
  457. if i_level != 0:
  458. up.upsample = Upsample(block_in, resamp_with_conv)
  459. curr_res = curr_res * 2
  460. self.up.insert(0, up) # prepend to get consistent order
  461. # end
  462. self.norm_out = Normalize(block_in)
  463. self.conv_out = torch.nn.Conv2d(block_in,
  464. out_ch,
  465. kernel_size=3,
  466. stride=1,
  467. padding=1)
  468. def forward(self, z):
  469. #assert z.shape[1:] == self.z_shape[1:]
  470. self.last_z_shape = z.shape
  471. # timestep embedding
  472. temb = None
  473. # z to block_in
  474. h = self.conv_in(z)
  475. # middle
  476. h = self.mid.block_1(h, temb)
  477. h = self.mid.attn_1(h)
  478. h = self.mid.block_2(h, temb)
  479. # upsampling
  480. for i_level in reversed(range(self.num_resolutions)):
  481. for i_block in range(self.num_res_blocks+1):
  482. h = self.up[i_level].block[i_block](h, temb)
  483. if len(self.up[i_level].attn) > 0:
  484. h = self.up[i_level].attn[i_block](h)
  485. if i_level != 0:
  486. h = self.up[i_level].upsample(h)
  487. # end
  488. if self.give_pre_end:
  489. return h
  490. h = self.norm_out(h)
  491. h = nonlinearity(h)
  492. h = self.conv_out(h)
  493. if self.tanh_out:
  494. h = torch.tanh(h)
  495. return h
  496. class SimpleDecoder(nn.Module):
  497. def __init__(self, in_channels, out_channels, *args, **kwargs):
  498. super().__init__()
  499. self.model = nn.ModuleList([nn.Conv2d(in_channels, in_channels, 1),
  500. ResnetBlock(in_channels=in_channels,
  501. out_channels=2 * in_channels,
  502. temb_channels=0, dropout=0.0),
  503. ResnetBlock(in_channels=2 * in_channels,
  504. out_channels=4 * in_channels,
  505. temb_channels=0, dropout=0.0),
  506. ResnetBlock(in_channels=4 * in_channels,
  507. out_channels=2 * in_channels,
  508. temb_channels=0, dropout=0.0),
  509. nn.Conv2d(2*in_channels, in_channels, 1),
  510. Upsample(in_channels, with_conv=True)])
  511. # end
  512. self.norm_out = Normalize(in_channels)
  513. self.conv_out = torch.nn.Conv2d(in_channels,
  514. out_channels,
  515. kernel_size=3,
  516. stride=1,
  517. padding=1)
  518. def forward(self, x):
  519. for i, layer in enumerate(self.model):
  520. if i in [1,2,3]:
  521. x = layer(x, None)
  522. else:
  523. x = layer(x)
  524. h = self.norm_out(x)
  525. h = nonlinearity(h)
  526. x = self.conv_out(h)
  527. return x
  528. class UpsampleDecoder(nn.Module):
  529. def __init__(self, in_channels, out_channels, ch, num_res_blocks, resolution,
  530. ch_mult=(2,2), dropout=0.0):
  531. super().__init__()
  532. # upsampling
  533. self.temb_ch = 0
  534. self.num_resolutions = len(ch_mult)
  535. self.num_res_blocks = num_res_blocks
  536. block_in = in_channels
  537. curr_res = resolution // 2 ** (self.num_resolutions - 1)
  538. self.res_blocks = nn.ModuleList()
  539. self.upsample_blocks = nn.ModuleList()
  540. for i_level in range(self.num_resolutions):
  541. res_block = []
  542. block_out = ch * ch_mult[i_level]
  543. for i_block in range(self.num_res_blocks + 1):
  544. res_block.append(ResnetBlock(in_channels=block_in,
  545. out_channels=block_out,
  546. temb_channels=self.temb_ch,
  547. dropout=dropout))
  548. block_in = block_out
  549. self.res_blocks.append(nn.ModuleList(res_block))
  550. if i_level != self.num_resolutions - 1:
  551. self.upsample_blocks.append(Upsample(block_in, True))
  552. curr_res = curr_res * 2
  553. # end
  554. self.norm_out = Normalize(block_in)
  555. self.conv_out = torch.nn.Conv2d(block_in,
  556. out_channels,
  557. kernel_size=3,
  558. stride=1,
  559. padding=1)
  560. def forward(self, x):
  561. # upsampling
  562. h = x
  563. for k, i_level in enumerate(range(self.num_resolutions)):
  564. for i_block in range(self.num_res_blocks + 1):
  565. h = self.res_blocks[i_level][i_block](h, None)
  566. if i_level != self.num_resolutions - 1:
  567. h = self.upsample_blocks[k](h)
  568. h = self.norm_out(h)
  569. h = nonlinearity(h)
  570. h = self.conv_out(h)
  571. return h
  572. class LatentRescaler(nn.Module):
  573. def __init__(self, factor, in_channels, mid_channels, out_channels, depth=2):
  574. super().__init__()
  575. # residual block, interpolate, residual block
  576. self.factor = factor
  577. self.conv_in = nn.Conv2d(in_channels,
  578. mid_channels,
  579. kernel_size=3,
  580. stride=1,
  581. padding=1)
  582. self.res_block1 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
  583. out_channels=mid_channels,
  584. temb_channels=0,
  585. dropout=0.0) for _ in range(depth)])
  586. self.attn = AttnBlock(mid_channels)
  587. self.res_block2 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
  588. out_channels=mid_channels,
  589. temb_channels=0,
  590. dropout=0.0) for _ in range(depth)])
  591. self.conv_out = nn.Conv2d(mid_channels,
  592. out_channels,
  593. kernel_size=1,
  594. )
  595. def forward(self, x):
  596. x = self.conv_in(x)
  597. for block in self.res_block1:
  598. x = block(x, None)
  599. x = torch.nn.functional.interpolate(x, size=(int(round(x.shape[2]*self.factor)), int(round(x.shape[3]*self.factor))))
  600. x = self.attn(x)
  601. for block in self.res_block2:
  602. x = block(x, None)
  603. x = self.conv_out(x)
  604. return x
  605. class MergedRescaleEncoder(nn.Module):
  606. def __init__(self, in_channels, ch, resolution, out_ch, num_res_blocks,
  607. attn_resolutions, dropout=0.0, resamp_with_conv=True,
  608. ch_mult=(1,2,4,8), rescale_factor=1.0, rescale_module_depth=1):
  609. super().__init__()
  610. intermediate_chn = ch * ch_mult[-1]
  611. self.encoder = Encoder(in_channels=in_channels, num_res_blocks=num_res_blocks, ch=ch, ch_mult=ch_mult,
  612. z_channels=intermediate_chn, double_z=False, resolution=resolution,
  613. attn_resolutions=attn_resolutions, dropout=dropout, resamp_with_conv=resamp_with_conv,
  614. out_ch=None)
  615. self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=intermediate_chn,
  616. mid_channels=intermediate_chn, out_channels=out_ch, depth=rescale_module_depth)
  617. def forward(self, x):
  618. x = self.encoder(x)
  619. x = self.rescaler(x)
  620. return x
  621. class MergedRescaleDecoder(nn.Module):
  622. def __init__(self, z_channels, out_ch, resolution, num_res_blocks, attn_resolutions, ch, ch_mult=(1,2,4,8),
  623. dropout=0.0, resamp_with_conv=True, rescale_factor=1.0, rescale_module_depth=1):
  624. super().__init__()
  625. tmp_chn = z_channels*ch_mult[-1]
  626. self.decoder = Decoder(out_ch=out_ch, z_channels=tmp_chn, attn_resolutions=attn_resolutions, dropout=dropout,
  627. resamp_with_conv=resamp_with_conv, in_channels=None, num_res_blocks=num_res_blocks,
  628. ch_mult=ch_mult, resolution=resolution, ch=ch)
  629. self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=z_channels, mid_channels=tmp_chn,
  630. out_channels=tmp_chn, depth=rescale_module_depth)
  631. def forward(self, x):
  632. x = self.rescaler(x)
  633. x = self.decoder(x)
  634. return x
  635. class Upsampler(nn.Module):
  636. def __init__(self, in_size, out_size, in_channels, out_channels, ch_mult=2):
  637. super().__init__()
  638. assert out_size >= in_size
  639. num_blocks = int(np.log2(out_size//in_size))+1
  640. factor_up = 1.+ (out_size % in_size)
  641. print(f"Building {self.__class__.__name__} with in_size: {in_size} --> out_size {out_size} and factor {factor_up}")
  642. self.rescaler = LatentRescaler(factor=factor_up, in_channels=in_channels, mid_channels=2*in_channels,
  643. out_channels=in_channels)
  644. self.decoder = Decoder(out_ch=out_channels, resolution=out_size, z_channels=in_channels, num_res_blocks=2,
  645. attn_resolutions=[], in_channels=None, ch=in_channels,
  646. ch_mult=[ch_mult for _ in range(num_blocks)])
  647. def forward(self, x):
  648. x = self.rescaler(x)
  649. x = self.decoder(x)
  650. return x
  651. class Resize(nn.Module):
  652. def __init__(self, in_channels=None, learned=False, mode="bilinear"):
  653. super().__init__()
  654. self.with_conv = learned
  655. self.mode = mode
  656. if self.with_conv:
  657. print(f"Note: {self.__class__.__name} uses learned downsampling and will ignore the fixed {mode} mode")
  658. raise NotImplementedError()
  659. assert in_channels is not None
  660. # no asymmetric padding in torch conv, must do it ourselves
  661. self.conv = torch.nn.Conv2d(in_channels,
  662. in_channels,
  663. kernel_size=4,
  664. stride=2,
  665. padding=1)
  666. def forward(self, x, scale_factor=1.0):
  667. if scale_factor==1.0:
  668. return x
  669. else:
  670. x = torch.nn.functional.interpolate(x, mode=self.mode, align_corners=False, scale_factor=scale_factor)
  671. return x
  672. class FirstStagePostProcessor(nn.Module):
  673. def __init__(self, ch_mult:list, in_channels,
  674. pretrained_model:nn.Module=None,
  675. reshape=False,
  676. n_channels=None,
  677. dropout=0.,
  678. pretrained_config=None):
  679. super().__init__()
  680. if pretrained_config is None:
  681. assert pretrained_model is not None, 'Either "pretrained_model" or "pretrained_config" must not be None'
  682. self.pretrained_model = pretrained_model
  683. else:
  684. assert pretrained_config is not None, 'Either "pretrained_model" or "pretrained_config" must not be None'
  685. self.instantiate_pretrained(pretrained_config)
  686. self.do_reshape = reshape
  687. if n_channels is None:
  688. n_channels = self.pretrained_model.encoder.ch
  689. self.proj_norm = Normalize(in_channels,num_groups=in_channels//2)
  690. self.proj = nn.Conv2d(in_channels,n_channels,kernel_size=3,
  691. stride=1,padding=1)
  692. blocks = []
  693. downs = []
  694. ch_in = n_channels
  695. for m in ch_mult:
  696. blocks.append(ResnetBlock(in_channels=ch_in,out_channels=m*n_channels,dropout=dropout))
  697. ch_in = m * n_channels
  698. downs.append(Downsample(ch_in, with_conv=False))
  699. self.model = nn.ModuleList(blocks)
  700. self.downsampler = nn.ModuleList(downs)
  701. def instantiate_pretrained(self, config):
  702. model = instantiate_from_config(config)
  703. self.pretrained_model = model.eval()
  704. # self.pretrained_model.train = False
  705. for param in self.pretrained_model.parameters():
  706. param.requires_grad = False
  707. @torch.no_grad()
  708. def encode_with_pretrained(self,x):
  709. c = self.pretrained_model.encode(x)
  710. if isinstance(c, DiagonalGaussianDistribution):
  711. c = c.mode()
  712. return c
  713. def forward(self,x):
  714. z_fs = self.encode_with_pretrained(x)
  715. z = self.proj_norm(z_fs)
  716. z = self.proj(z)
  717. z = nonlinearity(z)
  718. for submodel, downmodel in zip(self.model,self.downsampler):
  719. z = submodel(z,temb=None)
  720. z = downmodel(z)
  721. if self.do_reshape:
  722. z = rearrange(z,'b c h w -> b (h w) c')
  723. return z