openaimodel.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. from abc import abstractmethod
  2. from functools import partial
  3. import math
  4. from typing import Iterable
  5. import numpy as np
  6. import torch as th
  7. import torch.nn as nn
  8. import torch.nn.functional as F
  9. from ldm.modules.diffusionmodules.util import (
  10. checkpoint,
  11. conv_nd,
  12. linear,
  13. avg_pool_nd,
  14. zero_module,
  15. normalization,
  16. timestep_embedding,
  17. )
  18. from ldm.modules.attention import SpatialTransformer
  19. # dummy replace
  20. def convert_module_to_f16(x):
  21. pass
  22. def convert_module_to_f32(x):
  23. pass
  24. ## go
  25. class AttentionPool2d(nn.Module):
  26. """
  27. Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
  28. """
  29. def __init__(
  30. self,
  31. spacial_dim: int,
  32. embed_dim: int,
  33. num_heads_channels: int,
  34. output_dim: int = None,
  35. ):
  36. super().__init__()
  37. self.positional_embedding = nn.Parameter(th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5)
  38. self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
  39. self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
  40. self.num_heads = embed_dim // num_heads_channels
  41. self.attention = QKVAttention(self.num_heads)
  42. def forward(self, x):
  43. b, c, *_spatial = x.shape
  44. x = x.reshape(b, c, -1) # NC(HW)
  45. x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
  46. x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
  47. x = self.qkv_proj(x)
  48. x = self.attention(x)
  49. x = self.c_proj(x)
  50. return x[:, :, 0]
  51. class TimestepBlock(nn.Module):
  52. """
  53. Any module where forward() takes timestep embeddings as a second argument.
  54. """
  55. @abstractmethod
  56. def forward(self, x, emb):
  57. """
  58. Apply the module to `x` given `emb` timestep embeddings.
  59. """
  60. class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
  61. """
  62. A sequential module that passes timestep embeddings to the children that
  63. support it as an extra input.
  64. """
  65. def forward(self, x, emb, context=None):
  66. for layer in self:
  67. if isinstance(layer, TimestepBlock):
  68. x = layer(x, emb)
  69. elif isinstance(layer, SpatialTransformer):
  70. x = layer(x, context)
  71. else:
  72. x = layer(x)
  73. return x
  74. class Upsample(nn.Module):
  75. """
  76. An upsampling layer with an optional convolution.
  77. :param channels: channels in the inputs and outputs.
  78. :param use_conv: a bool determining if a convolution is applied.
  79. :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
  80. upsampling occurs in the inner-two dimensions.
  81. """
  82. def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1):
  83. super().__init__()
  84. self.channels = channels
  85. self.out_channels = out_channels or channels
  86. self.use_conv = use_conv
  87. self.dims = dims
  88. if use_conv:
  89. self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding)
  90. def forward(self, x):
  91. assert x.shape[1] == self.channels
  92. if self.dims == 3:
  93. x = F.interpolate(
  94. x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
  95. )
  96. else:
  97. x = F.interpolate(x, scale_factor=2, mode="nearest")
  98. if self.use_conv:
  99. x = self.conv(x)
  100. return x
  101. class TransposedUpsample(nn.Module):
  102. 'Learned 2x upsampling without padding'
  103. def __init__(self, channels, out_channels=None, ks=5):
  104. super().__init__()
  105. self.channels = channels
  106. self.out_channels = out_channels or channels
  107. self.up = nn.ConvTranspose2d(self.channels,self.out_channels,kernel_size=ks,stride=2)
  108. def forward(self,x):
  109. return self.up(x)
  110. class Downsample(nn.Module):
  111. """
  112. A downsampling layer with an optional convolution.
  113. :param channels: channels in the inputs and outputs.
  114. :param use_conv: a bool determining if a convolution is applied.
  115. :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
  116. downsampling occurs in the inner-two dimensions.
  117. """
  118. def __init__(self, channels, use_conv, dims=2, out_channels=None,padding=1):
  119. super().__init__()
  120. self.channels = channels
  121. self.out_channels = out_channels or channels
  122. self.use_conv = use_conv
  123. self.dims = dims
  124. stride = 2 if dims != 3 else (1, 2, 2)
  125. if use_conv:
  126. self.op = conv_nd(
  127. dims, self.channels, self.out_channels, 3, stride=stride, padding=padding
  128. )
  129. else:
  130. assert self.channels == self.out_channels
  131. self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
  132. def forward(self, x):
  133. assert x.shape[1] == self.channels
  134. return self.op(x)
  135. class ResBlock(TimestepBlock):
  136. """
  137. A residual block that can optionally change the number of channels.
  138. :param channels: the number of input channels.
  139. :param emb_channels: the number of timestep embedding channels.
  140. :param dropout: the rate of dropout.
  141. :param out_channels: if specified, the number of out channels.
  142. :param use_conv: if True and out_channels is specified, use a spatial
  143. convolution instead of a smaller 1x1 convolution to change the
  144. channels in the skip connection.
  145. :param dims: determines if the signal is 1D, 2D, or 3D.
  146. :param use_checkpoint: if True, use gradient checkpointing on this module.
  147. :param up: if True, use this block for upsampling.
  148. :param down: if True, use this block for downsampling.
  149. """
  150. def __init__(
  151. self,
  152. channels,
  153. emb_channels,
  154. dropout,
  155. out_channels=None,
  156. use_conv=False,
  157. use_scale_shift_norm=False,
  158. dims=2,
  159. use_checkpoint=False,
  160. up=False,
  161. down=False,
  162. ):
  163. super().__init__()
  164. self.channels = channels
  165. self.emb_channels = emb_channels
  166. self.dropout = dropout
  167. self.out_channels = out_channels or channels
  168. self.use_conv = use_conv
  169. self.use_checkpoint = use_checkpoint
  170. self.use_scale_shift_norm = use_scale_shift_norm
  171. self.in_layers = nn.Sequential(
  172. normalization(channels),
  173. nn.SiLU(),
  174. conv_nd(dims, channels, self.out_channels, 3, padding=1),
  175. )
  176. self.updown = up or down
  177. if up:
  178. self.h_upd = Upsample(channels, False, dims)
  179. self.x_upd = Upsample(channels, False, dims)
  180. elif down:
  181. self.h_upd = Downsample(channels, False, dims)
  182. self.x_upd = Downsample(channels, False, dims)
  183. else:
  184. self.h_upd = self.x_upd = nn.Identity()
  185. self.emb_layers = nn.Sequential(
  186. nn.SiLU(),
  187. linear(
  188. emb_channels,
  189. 2 * self.out_channels if use_scale_shift_norm else self.out_channels,
  190. ),
  191. )
  192. self.out_layers = nn.Sequential(
  193. normalization(self.out_channels),
  194. nn.SiLU(),
  195. nn.Dropout(p=dropout),
  196. zero_module(
  197. conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)
  198. ),
  199. )
  200. if self.out_channels == channels:
  201. self.skip_connection = nn.Identity()
  202. elif use_conv:
  203. self.skip_connection = conv_nd(
  204. dims, channels, self.out_channels, 3, padding=1
  205. )
  206. else:
  207. self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
  208. def forward(self, x, emb):
  209. """
  210. Apply the block to a Tensor, conditioned on a timestep embedding.
  211. :param x: an [N x C x ...] Tensor of features.
  212. :param emb: an [N x emb_channels] Tensor of timestep embeddings.
  213. :return: an [N x C x ...] Tensor of outputs.
  214. """
  215. return checkpoint(
  216. self._forward, (x, emb), self.parameters(), self.use_checkpoint
  217. )
  218. def _forward(self, x, emb):
  219. if self.updown:
  220. in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
  221. h = in_rest(x)
  222. h = self.h_upd(h)
  223. x = self.x_upd(x)
  224. h = in_conv(h)
  225. else:
  226. h = self.in_layers(x)
  227. emb_out = self.emb_layers(emb).type(h.dtype)
  228. while len(emb_out.shape) < len(h.shape):
  229. emb_out = emb_out[..., None]
  230. if self.use_scale_shift_norm:
  231. out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
  232. scale, shift = th.chunk(emb_out, 2, dim=1)
  233. h = out_norm(h) * (1 + scale) + shift
  234. h = out_rest(h)
  235. else:
  236. h = h + emb_out
  237. h = self.out_layers(h)
  238. return self.skip_connection(x) + h
  239. class AttentionBlock(nn.Module):
  240. """
  241. An attention block that allows spatial positions to attend to each other.
  242. Originally ported from here, but adapted to the N-d case.
  243. https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
  244. """
  245. def __init__(
  246. self,
  247. channels,
  248. num_heads=1,
  249. num_head_channels=-1,
  250. use_checkpoint=False,
  251. use_new_attention_order=False,
  252. ):
  253. super().__init__()
  254. self.channels = channels
  255. if num_head_channels == -1:
  256. self.num_heads = num_heads
  257. else:
  258. assert (
  259. channels % num_head_channels == 0
  260. ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"
  261. self.num_heads = channels // num_head_channels
  262. self.use_checkpoint = use_checkpoint
  263. self.norm = normalization(channels)
  264. self.qkv = conv_nd(1, channels, channels * 3, 1)
  265. if use_new_attention_order:
  266. # split qkv before split heads
  267. self.attention = QKVAttention(self.num_heads)
  268. else:
  269. # split heads before split qkv
  270. self.attention = QKVAttentionLegacy(self.num_heads)
  271. self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
  272. def forward(self, x):
  273. return checkpoint(self._forward, (x,), self.parameters(), True) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!!
  274. #return pt_checkpoint(self._forward, x) # pytorch
  275. def _forward(self, x):
  276. b, c, *spatial = x.shape
  277. x = x.reshape(b, c, -1)
  278. qkv = self.qkv(self.norm(x))
  279. h = self.attention(qkv)
  280. h = self.proj_out(h)
  281. return (x + h).reshape(b, c, *spatial)
  282. def count_flops_attn(model, _x, y):
  283. """
  284. A counter for the `thop` package to count the operations in an
  285. attention operation.
  286. Meant to be used like:
  287. macs, params = thop.profile(
  288. model,
  289. inputs=(inputs, timestamps),
  290. custom_ops={QKVAttention: QKVAttention.count_flops},
  291. )
  292. """
  293. b, c, *spatial = y[0].shape
  294. num_spatial = int(np.prod(spatial))
  295. # We perform two matmuls with the same number of ops.
  296. # The first computes the weight matrix, the second computes
  297. # the combination of the value vectors.
  298. matmul_ops = 2 * b * (num_spatial ** 2) * c
  299. model.total_ops += th.DoubleTensor([matmul_ops])
  300. class QKVAttentionLegacy(nn.Module):
  301. """
  302. A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
  303. """
  304. def __init__(self, n_heads):
  305. super().__init__()
  306. self.n_heads = n_heads
  307. def forward(self, qkv):
  308. """
  309. Apply QKV attention.
  310. :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
  311. :return: an [N x (H * C) x T] tensor after attention.
  312. """
  313. bs, width, length = qkv.shape
  314. assert width % (3 * self.n_heads) == 0
  315. ch = width // (3 * self.n_heads)
  316. q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
  317. scale = 1 / math.sqrt(math.sqrt(ch))
  318. weight = th.einsum(
  319. "bct,bcs->bts", q * scale, k * scale
  320. ) # More stable with f16 than dividing afterwards
  321. weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
  322. a = th.einsum("bts,bcs->bct", weight, v)
  323. return a.reshape(bs, -1, length)
  324. @staticmethod
  325. def count_flops(model, _x, y):
  326. return count_flops_attn(model, _x, y)
  327. class QKVAttention(nn.Module):
  328. """
  329. A module which performs QKV attention and splits in a different order.
  330. """
  331. def __init__(self, n_heads):
  332. super().__init__()
  333. self.n_heads = n_heads
  334. def forward(self, qkv):
  335. """
  336. Apply QKV attention.
  337. :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
  338. :return: an [N x (H * C) x T] tensor after attention.
  339. """
  340. bs, width, length = qkv.shape
  341. assert width % (3 * self.n_heads) == 0
  342. ch = width // (3 * self.n_heads)
  343. q, k, v = qkv.chunk(3, dim=1)
  344. scale = 1 / math.sqrt(math.sqrt(ch))
  345. weight = th.einsum(
  346. "bct,bcs->bts",
  347. (q * scale).view(bs * self.n_heads, ch, length),
  348. (k * scale).view(bs * self.n_heads, ch, length),
  349. ) # More stable with f16 than dividing afterwards
  350. weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
  351. a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
  352. return a.reshape(bs, -1, length)
  353. @staticmethod
  354. def count_flops(model, _x, y):
  355. return count_flops_attn(model, _x, y)
  356. class UNetModel(nn.Module):
  357. """
  358. The full UNet model with attention and timestep embedding.
  359. :param in_channels: channels in the input Tensor.
  360. :param model_channels: base channel count for the model.
  361. :param out_channels: channels in the output Tensor.
  362. :param num_res_blocks: number of residual blocks per downsample.
  363. :param attention_resolutions: a collection of downsample rates at which
  364. attention will take place. May be a set, list, or tuple.
  365. For example, if this contains 4, then at 4x downsampling, attention
  366. will be used.
  367. :param dropout: the dropout probability.
  368. :param channel_mult: channel multiplier for each level of the UNet.
  369. :param conv_resample: if True, use learned convolutions for upsampling and
  370. downsampling.
  371. :param dims: determines if the signal is 1D, 2D, or 3D.
  372. :param num_classes: if specified (as an int), then this model will be
  373. class-conditional with `num_classes` classes.
  374. :param use_checkpoint: use gradient checkpointing to reduce memory usage.
  375. :param num_heads: the number of attention heads in each attention layer.
  376. :param num_heads_channels: if specified, ignore num_heads and instead use
  377. a fixed channel width per attention head.
  378. :param num_heads_upsample: works with num_heads to set a different number
  379. of heads for upsampling. Deprecated.
  380. :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
  381. :param resblock_updown: use residual blocks for up/downsampling.
  382. :param use_new_attention_order: use a different attention pattern for potentially
  383. increased efficiency.
  384. """
  385. def __init__(
  386. self,
  387. image_size,
  388. in_channels,
  389. model_channels,
  390. out_channels,
  391. num_res_blocks,
  392. attention_resolutions,
  393. dropout=0,
  394. channel_mult=(1, 2, 4, 8),
  395. conv_resample=True,
  396. dims=2,
  397. num_classes=None,
  398. use_checkpoint=False,
  399. use_fp16=False,
  400. num_heads=-1,
  401. num_head_channels=-1,
  402. num_heads_upsample=-1,
  403. use_scale_shift_norm=False,
  404. resblock_updown=False,
  405. use_new_attention_order=False,
  406. use_spatial_transformer=False, # custom transformer support
  407. transformer_depth=1, # custom transformer support
  408. context_dim=None, # custom transformer support
  409. n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
  410. legacy=True,
  411. ):
  412. super().__init__()
  413. if use_spatial_transformer:
  414. assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
  415. if context_dim is not None:
  416. assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
  417. from omegaconf.listconfig import ListConfig
  418. if type(context_dim) == ListConfig:
  419. context_dim = list(context_dim)
  420. if num_heads_upsample == -1:
  421. num_heads_upsample = num_heads
  422. if num_heads == -1:
  423. assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
  424. if num_head_channels == -1:
  425. assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
  426. self.image_size = image_size
  427. self.in_channels = in_channels
  428. self.model_channels = model_channels
  429. self.out_channels = out_channels
  430. self.num_res_blocks = num_res_blocks
  431. self.attention_resolutions = attention_resolutions
  432. self.dropout = dropout
  433. self.channel_mult = channel_mult
  434. self.conv_resample = conv_resample
  435. self.num_classes = num_classes
  436. self.use_checkpoint = use_checkpoint
  437. self.dtype = th.float16 if use_fp16 else th.float32
  438. self.num_heads = num_heads
  439. self.num_head_channels = num_head_channels
  440. self.num_heads_upsample = num_heads_upsample
  441. self.predict_codebook_ids = n_embed is not None
  442. time_embed_dim = model_channels * 4
  443. self.time_embed = nn.Sequential(
  444. linear(model_channels, time_embed_dim),
  445. nn.SiLU(),
  446. linear(time_embed_dim, time_embed_dim),
  447. )
  448. if self.num_classes is not None:
  449. self.label_emb = nn.Embedding(num_classes, time_embed_dim)
  450. self.input_blocks = nn.ModuleList(
  451. [
  452. TimestepEmbedSequential(
  453. conv_nd(dims, in_channels, model_channels, 3, padding=1)
  454. )
  455. ]
  456. )
  457. self._feature_size = model_channels
  458. input_block_chans = [model_channels]
  459. ch = model_channels
  460. ds = 1
  461. for level, mult in enumerate(channel_mult):
  462. for _ in range(num_res_blocks):
  463. layers = [
  464. ResBlock(
  465. ch,
  466. time_embed_dim,
  467. dropout,
  468. out_channels=mult * model_channels,
  469. dims=dims,
  470. use_checkpoint=use_checkpoint,
  471. use_scale_shift_norm=use_scale_shift_norm,
  472. )
  473. ]
  474. ch = mult * model_channels
  475. if ds in attention_resolutions:
  476. if num_head_channels == -1:
  477. dim_head = ch // num_heads
  478. else:
  479. num_heads = ch // num_head_channels
  480. dim_head = num_head_channels
  481. if legacy:
  482. #num_heads = 1
  483. dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
  484. layers.append(
  485. AttentionBlock(
  486. ch,
  487. use_checkpoint=use_checkpoint,
  488. num_heads=num_heads,
  489. num_head_channels=dim_head,
  490. use_new_attention_order=use_new_attention_order,
  491. ) if not use_spatial_transformer else SpatialTransformer(
  492. ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
  493. )
  494. )
  495. self.input_blocks.append(TimestepEmbedSequential(*layers))
  496. self._feature_size += ch
  497. input_block_chans.append(ch)
  498. if level != len(channel_mult) - 1:
  499. out_ch = ch
  500. self.input_blocks.append(
  501. TimestepEmbedSequential(
  502. ResBlock(
  503. ch,
  504. time_embed_dim,
  505. dropout,
  506. out_channels=out_ch,
  507. dims=dims,
  508. use_checkpoint=use_checkpoint,
  509. use_scale_shift_norm=use_scale_shift_norm,
  510. down=True,
  511. )
  512. if resblock_updown
  513. else Downsample(
  514. ch, conv_resample, dims=dims, out_channels=out_ch
  515. )
  516. )
  517. )
  518. ch = out_ch
  519. input_block_chans.append(ch)
  520. ds *= 2
  521. self._feature_size += ch
  522. if num_head_channels == -1:
  523. dim_head = ch // num_heads
  524. else:
  525. num_heads = ch // num_head_channels
  526. dim_head = num_head_channels
  527. if legacy:
  528. #num_heads = 1
  529. dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
  530. self.middle_block = TimestepEmbedSequential(
  531. ResBlock(
  532. ch,
  533. time_embed_dim,
  534. dropout,
  535. dims=dims,
  536. use_checkpoint=use_checkpoint,
  537. use_scale_shift_norm=use_scale_shift_norm,
  538. ),
  539. AttentionBlock(
  540. ch,
  541. use_checkpoint=use_checkpoint,
  542. num_heads=num_heads,
  543. num_head_channels=dim_head,
  544. use_new_attention_order=use_new_attention_order,
  545. ) if not use_spatial_transformer else SpatialTransformer(
  546. ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
  547. ),
  548. ResBlock(
  549. ch,
  550. time_embed_dim,
  551. dropout,
  552. dims=dims,
  553. use_checkpoint=use_checkpoint,
  554. use_scale_shift_norm=use_scale_shift_norm,
  555. ),
  556. )
  557. self._feature_size += ch
  558. self.output_blocks = nn.ModuleList([])
  559. for level, mult in list(enumerate(channel_mult))[::-1]:
  560. for i in range(num_res_blocks + 1):
  561. ich = input_block_chans.pop()
  562. layers = [
  563. ResBlock(
  564. ch + ich,
  565. time_embed_dim,
  566. dropout,
  567. out_channels=model_channels * mult,
  568. dims=dims,
  569. use_checkpoint=use_checkpoint,
  570. use_scale_shift_norm=use_scale_shift_norm,
  571. )
  572. ]
  573. ch = model_channels * mult
  574. if ds in attention_resolutions:
  575. if num_head_channels == -1:
  576. dim_head = ch // num_heads
  577. else:
  578. num_heads = ch // num_head_channels
  579. dim_head = num_head_channels
  580. if legacy:
  581. #num_heads = 1
  582. dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
  583. layers.append(
  584. AttentionBlock(
  585. ch,
  586. use_checkpoint=use_checkpoint,
  587. num_heads=num_heads_upsample,
  588. num_head_channels=dim_head,
  589. use_new_attention_order=use_new_attention_order,
  590. ) if not use_spatial_transformer else SpatialTransformer(
  591. ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
  592. )
  593. )
  594. if level and i == num_res_blocks:
  595. out_ch = ch
  596. layers.append(
  597. ResBlock(
  598. ch,
  599. time_embed_dim,
  600. dropout,
  601. out_channels=out_ch,
  602. dims=dims,
  603. use_checkpoint=use_checkpoint,
  604. use_scale_shift_norm=use_scale_shift_norm,
  605. up=True,
  606. )
  607. if resblock_updown
  608. else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
  609. )
  610. ds //= 2
  611. self.output_blocks.append(TimestepEmbedSequential(*layers))
  612. self._feature_size += ch
  613. self.out = nn.Sequential(
  614. normalization(ch),
  615. nn.SiLU(),
  616. zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)),
  617. )
  618. if self.predict_codebook_ids:
  619. self.id_predictor = nn.Sequential(
  620. normalization(ch),
  621. conv_nd(dims, model_channels, n_embed, 1),
  622. #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
  623. )
  624. def convert_to_fp16(self):
  625. """
  626. Convert the torso of the model to float16.
  627. """
  628. self.input_blocks.apply(convert_module_to_f16)
  629. self.middle_block.apply(convert_module_to_f16)
  630. self.output_blocks.apply(convert_module_to_f16)
  631. def convert_to_fp32(self):
  632. """
  633. Convert the torso of the model to float32.
  634. """
  635. self.input_blocks.apply(convert_module_to_f32)
  636. self.middle_block.apply(convert_module_to_f32)
  637. self.output_blocks.apply(convert_module_to_f32)
  638. def forward(self, x, timesteps=None, context=None, y=None,**kwargs):
  639. """
  640. Apply the model to an input batch.
  641. :param x: an [N x C x ...] Tensor of inputs.
  642. :param timesteps: a 1-D batch of timesteps.
  643. :param context: conditioning plugged in via crossattn
  644. :param y: an [N] Tensor of labels, if class-conditional.
  645. :return: an [N x C x ...] Tensor of outputs.
  646. """
  647. assert (y is not None) == (
  648. self.num_classes is not None
  649. ), "must specify y if and only if the model is class-conditional"
  650. hs = []
  651. t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
  652. emb = self.time_embed(t_emb)
  653. if self.num_classes is not None:
  654. assert y.shape == (x.shape[0],)
  655. emb = emb + self.label_emb(y)
  656. h = x.type(self.dtype)
  657. for module in self.input_blocks:
  658. h = module(h, emb, context)
  659. hs.append(h)
  660. h = self.middle_block(h, emb, context)
  661. for module in self.output_blocks:
  662. h = th.cat([h, hs.pop()], dim=1)
  663. h = module(h, emb, context)
  664. h = h.type(x.dtype)
  665. if self.predict_codebook_ids:
  666. return self.id_predictor(h)
  667. else:
  668. return self.out(h)
  669. class EncoderUNetModel(nn.Module):
  670. """
  671. The half UNet model with attention and timestep embedding.
  672. For usage, see UNet.
  673. """
  674. def __init__(
  675. self,
  676. image_size,
  677. in_channels,
  678. model_channels,
  679. out_channels,
  680. num_res_blocks,
  681. attention_resolutions,
  682. dropout=0,
  683. channel_mult=(1, 2, 4, 8),
  684. conv_resample=True,
  685. dims=2,
  686. use_checkpoint=False,
  687. use_fp16=False,
  688. num_heads=1,
  689. num_head_channels=-1,
  690. num_heads_upsample=-1,
  691. use_scale_shift_norm=False,
  692. resblock_updown=False,
  693. use_new_attention_order=False,
  694. pool="adaptive",
  695. *args,
  696. **kwargs
  697. ):
  698. super().__init__()
  699. if num_heads_upsample == -1:
  700. num_heads_upsample = num_heads
  701. self.in_channels = in_channels
  702. self.model_channels = model_channels
  703. self.out_channels = out_channels
  704. self.num_res_blocks = num_res_blocks
  705. self.attention_resolutions = attention_resolutions
  706. self.dropout = dropout
  707. self.channel_mult = channel_mult
  708. self.conv_resample = conv_resample
  709. self.use_checkpoint = use_checkpoint
  710. self.dtype = th.float16 if use_fp16 else th.float32
  711. self.num_heads = num_heads
  712. self.num_head_channels = num_head_channels
  713. self.num_heads_upsample = num_heads_upsample
  714. time_embed_dim = model_channels * 4
  715. self.time_embed = nn.Sequential(
  716. linear(model_channels, time_embed_dim),
  717. nn.SiLU(),
  718. linear(time_embed_dim, time_embed_dim),
  719. )
  720. self.input_blocks = nn.ModuleList(
  721. [
  722. TimestepEmbedSequential(
  723. conv_nd(dims, in_channels, model_channels, 3, padding=1)
  724. )
  725. ]
  726. )
  727. self._feature_size = model_channels
  728. input_block_chans = [model_channels]
  729. ch = model_channels
  730. ds = 1
  731. for level, mult in enumerate(channel_mult):
  732. for _ in range(num_res_blocks):
  733. layers = [
  734. ResBlock(
  735. ch,
  736. time_embed_dim,
  737. dropout,
  738. out_channels=mult * model_channels,
  739. dims=dims,
  740. use_checkpoint=use_checkpoint,
  741. use_scale_shift_norm=use_scale_shift_norm,
  742. )
  743. ]
  744. ch = mult * model_channels
  745. if ds in attention_resolutions:
  746. layers.append(
  747. AttentionBlock(
  748. ch,
  749. use_checkpoint=use_checkpoint,
  750. num_heads=num_heads,
  751. num_head_channels=num_head_channels,
  752. use_new_attention_order=use_new_attention_order,
  753. )
  754. )
  755. self.input_blocks.append(TimestepEmbedSequential(*layers))
  756. self._feature_size += ch
  757. input_block_chans.append(ch)
  758. if level != len(channel_mult) - 1:
  759. out_ch = ch
  760. self.input_blocks.append(
  761. TimestepEmbedSequential(
  762. ResBlock(
  763. ch,
  764. time_embed_dim,
  765. dropout,
  766. out_channels=out_ch,
  767. dims=dims,
  768. use_checkpoint=use_checkpoint,
  769. use_scale_shift_norm=use_scale_shift_norm,
  770. down=True,
  771. )
  772. if resblock_updown
  773. else Downsample(
  774. ch, conv_resample, dims=dims, out_channels=out_ch
  775. )
  776. )
  777. )
  778. ch = out_ch
  779. input_block_chans.append(ch)
  780. ds *= 2
  781. self._feature_size += ch
  782. self.middle_block = TimestepEmbedSequential(
  783. ResBlock(
  784. ch,
  785. time_embed_dim,
  786. dropout,
  787. dims=dims,
  788. use_checkpoint=use_checkpoint,
  789. use_scale_shift_norm=use_scale_shift_norm,
  790. ),
  791. AttentionBlock(
  792. ch,
  793. use_checkpoint=use_checkpoint,
  794. num_heads=num_heads,
  795. num_head_channels=num_head_channels,
  796. use_new_attention_order=use_new_attention_order,
  797. ),
  798. ResBlock(
  799. ch,
  800. time_embed_dim,
  801. dropout,
  802. dims=dims,
  803. use_checkpoint=use_checkpoint,
  804. use_scale_shift_norm=use_scale_shift_norm,
  805. ),
  806. )
  807. self._feature_size += ch
  808. self.pool = pool
  809. if pool == "adaptive":
  810. self.out = nn.Sequential(
  811. normalization(ch),
  812. nn.SiLU(),
  813. nn.AdaptiveAvgPool2d((1, 1)),
  814. zero_module(conv_nd(dims, ch, out_channels, 1)),
  815. nn.Flatten(),
  816. )
  817. elif pool == "attention":
  818. assert num_head_channels != -1
  819. self.out = nn.Sequential(
  820. normalization(ch),
  821. nn.SiLU(),
  822. AttentionPool2d(
  823. (image_size // ds), ch, num_head_channels, out_channels
  824. ),
  825. )
  826. elif pool == "spatial":
  827. self.out = nn.Sequential(
  828. nn.Linear(self._feature_size, 2048),
  829. nn.ReLU(),
  830. nn.Linear(2048, self.out_channels),
  831. )
  832. elif pool == "spatial_v2":
  833. self.out = nn.Sequential(
  834. nn.Linear(self._feature_size, 2048),
  835. normalization(2048),
  836. nn.SiLU(),
  837. nn.Linear(2048, self.out_channels),
  838. )
  839. else:
  840. raise NotImplementedError(f"Unexpected {pool} pooling")
  841. def convert_to_fp16(self):
  842. """
  843. Convert the torso of the model to float16.
  844. """
  845. self.input_blocks.apply(convert_module_to_f16)
  846. self.middle_block.apply(convert_module_to_f16)
  847. def convert_to_fp32(self):
  848. """
  849. Convert the torso of the model to float32.
  850. """
  851. self.input_blocks.apply(convert_module_to_f32)
  852. self.middle_block.apply(convert_module_to_f32)
  853. def forward(self, x, timesteps):
  854. """
  855. Apply the model to an input batch.
  856. :param x: an [N x C x ...] Tensor of inputs.
  857. :param timesteps: a 1-D batch of timesteps.
  858. :return: an [N x K] Tensor of outputs.
  859. """
  860. emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
  861. results = []
  862. h = x.type(self.dtype)
  863. for module in self.input_blocks:
  864. h = module(h, emb)
  865. if self.pool.startswith("spatial"):
  866. results.append(h.type(x.dtype).mean(dim=(2, 3)))
  867. h = self.middle_block(h, emb)
  868. if self.pool.startswith("spatial"):
  869. results.append(h.type(x.dtype).mean(dim=(2, 3)))
  870. h = th.cat(results, axis=-1)
  871. return self.out(h)
  872. else:
  873. h = h.type(x.dtype)
  874. return self.out(h)