openaimodel.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  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. ):
  411. super().__init__()
  412. if use_spatial_transformer:
  413. assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
  414. if context_dim is not None:
  415. assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
  416. if num_heads_upsample == -1:
  417. num_heads_upsample = num_heads
  418. self.image_size = image_size
  419. self.in_channels = in_channels
  420. self.model_channels = model_channels
  421. self.out_channels = out_channels
  422. self.num_res_blocks = num_res_blocks
  423. self.attention_resolutions = attention_resolutions
  424. self.dropout = dropout
  425. self.channel_mult = channel_mult
  426. self.conv_resample = conv_resample
  427. self.num_classes = num_classes
  428. self.use_checkpoint = use_checkpoint
  429. self.dtype = th.float16 if use_fp16 else th.float32
  430. self.num_heads = num_heads
  431. self.num_head_channels = num_head_channels
  432. self.num_heads_upsample = num_heads_upsample
  433. self.predict_codebook_ids = n_embed is not None
  434. time_embed_dim = model_channels * 4
  435. self.time_embed = nn.Sequential(
  436. linear(model_channels, time_embed_dim),
  437. nn.SiLU(),
  438. linear(time_embed_dim, time_embed_dim),
  439. )
  440. if self.num_classes is not None:
  441. self.label_emb = nn.Embedding(num_classes, time_embed_dim)
  442. self.input_blocks = nn.ModuleList(
  443. [
  444. TimestepEmbedSequential(
  445. conv_nd(dims, in_channels, model_channels, 3, padding=1)
  446. )
  447. ]
  448. )
  449. self._feature_size = model_channels
  450. input_block_chans = [model_channels]
  451. ch = model_channels
  452. ds = 1
  453. for level, mult in enumerate(channel_mult):
  454. for _ in range(num_res_blocks):
  455. layers = [
  456. ResBlock(
  457. ch,
  458. time_embed_dim,
  459. dropout,
  460. out_channels=mult * model_channels,
  461. dims=dims,
  462. use_checkpoint=use_checkpoint,
  463. use_scale_shift_norm=use_scale_shift_norm,
  464. )
  465. ]
  466. ch = mult * model_channels
  467. if ds in attention_resolutions:
  468. dim_head = ch // num_heads
  469. layers.append(
  470. AttentionBlock(
  471. ch,
  472. use_checkpoint=use_checkpoint,
  473. num_heads=num_heads,
  474. num_head_channels=num_head_channels,
  475. use_new_attention_order=use_new_attention_order,
  476. ) if not use_spatial_transformer else SpatialTransformer(
  477. ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
  478. )
  479. )
  480. self.input_blocks.append(TimestepEmbedSequential(*layers))
  481. self._feature_size += ch
  482. input_block_chans.append(ch)
  483. if level != len(channel_mult) - 1:
  484. out_ch = ch
  485. self.input_blocks.append(
  486. TimestepEmbedSequential(
  487. ResBlock(
  488. ch,
  489. time_embed_dim,
  490. dropout,
  491. out_channels=out_ch,
  492. dims=dims,
  493. use_checkpoint=use_checkpoint,
  494. use_scale_shift_norm=use_scale_shift_norm,
  495. down=True,
  496. )
  497. if resblock_updown
  498. else Downsample(
  499. ch, conv_resample, dims=dims, out_channels=out_ch
  500. )
  501. )
  502. )
  503. ch = out_ch
  504. input_block_chans.append(ch)
  505. ds *= 2
  506. self._feature_size += ch
  507. dim_head = ch // num_heads
  508. self.middle_block = TimestepEmbedSequential(
  509. ResBlock(
  510. ch,
  511. time_embed_dim,
  512. dropout,
  513. dims=dims,
  514. use_checkpoint=use_checkpoint,
  515. use_scale_shift_norm=use_scale_shift_norm,
  516. ),
  517. AttentionBlock(
  518. ch,
  519. use_checkpoint=use_checkpoint,
  520. num_heads=num_heads,
  521. num_head_channels=num_head_channels,
  522. use_new_attention_order=use_new_attention_order,
  523. ) if not use_spatial_transformer else SpatialTransformer(
  524. ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
  525. ),
  526. ResBlock(
  527. ch,
  528. time_embed_dim,
  529. dropout,
  530. dims=dims,
  531. use_checkpoint=use_checkpoint,
  532. use_scale_shift_norm=use_scale_shift_norm,
  533. ),
  534. )
  535. self._feature_size += ch
  536. self.output_blocks = nn.ModuleList([])
  537. for level, mult in list(enumerate(channel_mult))[::-1]:
  538. for i in range(num_res_blocks + 1):
  539. ich = input_block_chans.pop()
  540. layers = [
  541. ResBlock(
  542. ch + ich,
  543. time_embed_dim,
  544. dropout,
  545. out_channels=model_channels * mult,
  546. dims=dims,
  547. use_checkpoint=use_checkpoint,
  548. use_scale_shift_norm=use_scale_shift_norm,
  549. )
  550. ]
  551. ch = model_channels * mult
  552. if ds in attention_resolutions:
  553. dim_head = ch // num_heads
  554. layers.append(
  555. AttentionBlock(
  556. ch,
  557. use_checkpoint=use_checkpoint,
  558. num_heads=num_heads_upsample,
  559. num_head_channels=num_head_channels,
  560. use_new_attention_order=use_new_attention_order,
  561. ) if not use_spatial_transformer else SpatialTransformer(
  562. ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
  563. )
  564. )
  565. if level and i == num_res_blocks:
  566. out_ch = ch
  567. layers.append(
  568. ResBlock(
  569. ch,
  570. time_embed_dim,
  571. dropout,
  572. out_channels=out_ch,
  573. dims=dims,
  574. use_checkpoint=use_checkpoint,
  575. use_scale_shift_norm=use_scale_shift_norm,
  576. up=True,
  577. )
  578. if resblock_updown
  579. else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
  580. )
  581. ds //= 2
  582. self.output_blocks.append(TimestepEmbedSequential(*layers))
  583. self._feature_size += ch
  584. self.out = nn.Sequential(
  585. normalization(ch),
  586. nn.SiLU(),
  587. zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)),
  588. )
  589. if self.predict_codebook_ids:
  590. self.id_predictor = nn.Sequential(
  591. normalization(ch),
  592. conv_nd(dims, model_channels, n_embed, 1),
  593. #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
  594. )
  595. def convert_to_fp16(self):
  596. """
  597. Convert the torso of the model to float16.
  598. """
  599. self.input_blocks.apply(convert_module_to_f16)
  600. self.middle_block.apply(convert_module_to_f16)
  601. self.output_blocks.apply(convert_module_to_f16)
  602. def convert_to_fp32(self):
  603. """
  604. Convert the torso of the model to float32.
  605. """
  606. self.input_blocks.apply(convert_module_to_f32)
  607. self.middle_block.apply(convert_module_to_f32)
  608. self.output_blocks.apply(convert_module_to_f32)
  609. def forward(self, x, timesteps=None, context=None, y=None,**kwargs):
  610. """
  611. Apply the model to an input batch.
  612. :param x: an [N x C x ...] Tensor of inputs.
  613. :param timesteps: a 1-D batch of timesteps.
  614. :param context: conditioning plugged in via crossattn
  615. :param y: an [N] Tensor of labels, if class-conditional.
  616. :return: an [N x C x ...] Tensor of outputs.
  617. """
  618. assert (y is not None) == (
  619. self.num_classes is not None
  620. ), "must specify y if and only if the model is class-conditional"
  621. assert timesteps is not None, 'need to implement no-timestep usage'
  622. hs = []
  623. t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
  624. emb = self.time_embed(t_emb)
  625. if self.num_classes is not None:
  626. assert y.shape == (x.shape[0],)
  627. emb = emb + self.label_emb(y)
  628. h = x.type(self.dtype)
  629. for module in self.input_blocks:
  630. h = module(h, emb, context)
  631. hs.append(h)
  632. h = self.middle_block(h, emb, context)
  633. for module in self.output_blocks:
  634. h = th.cat([h, hs.pop()], dim=1)
  635. h = module(h, emb, context)
  636. h = h.type(x.dtype)
  637. if self.predict_codebook_ids:
  638. #return self.out(h), self.id_predictor(h)
  639. return self.id_predictor(h)
  640. else:
  641. return self.out(h)
  642. class EncoderUNetModel(nn.Module):
  643. # TODO: do we use it ?
  644. """
  645. The half UNet model with attention and timestep embedding.
  646. For usage, see UNet.
  647. """
  648. def __init__(
  649. self,
  650. image_size,
  651. in_channels,
  652. model_channels,
  653. out_channels,
  654. num_res_blocks,
  655. attention_resolutions,
  656. dropout=0,
  657. channel_mult=(1, 2, 4, 8),
  658. conv_resample=True,
  659. dims=2,
  660. use_checkpoint=False,
  661. use_fp16=False,
  662. num_heads=1,
  663. num_head_channels=-1,
  664. num_heads_upsample=-1,
  665. use_scale_shift_norm=False,
  666. resblock_updown=False,
  667. use_new_attention_order=False,
  668. pool="adaptive",
  669. *args,
  670. **kwargs
  671. ):
  672. super().__init__()
  673. if num_heads_upsample == -1:
  674. num_heads_upsample = num_heads
  675. self.in_channels = in_channels
  676. self.model_channels = model_channels
  677. self.out_channels = out_channels
  678. self.num_res_blocks = num_res_blocks
  679. self.attention_resolutions = attention_resolutions
  680. self.dropout = dropout
  681. self.channel_mult = channel_mult
  682. self.conv_resample = conv_resample
  683. self.use_checkpoint = use_checkpoint
  684. self.dtype = th.float16 if use_fp16 else th.float32
  685. self.num_heads = num_heads
  686. self.num_head_channels = num_head_channels
  687. self.num_heads_upsample = num_heads_upsample
  688. time_embed_dim = model_channels * 4
  689. self.time_embed = nn.Sequential(
  690. linear(model_channels, time_embed_dim),
  691. nn.SiLU(),
  692. linear(time_embed_dim, time_embed_dim),
  693. )
  694. self.input_blocks = nn.ModuleList(
  695. [
  696. TimestepEmbedSequential(
  697. conv_nd(dims, in_channels, model_channels, 3, padding=1)
  698. )
  699. ]
  700. )
  701. self._feature_size = model_channels
  702. input_block_chans = [model_channels]
  703. ch = model_channels
  704. ds = 1
  705. for level, mult in enumerate(channel_mult):
  706. for _ in range(num_res_blocks):
  707. layers = [
  708. ResBlock(
  709. ch,
  710. time_embed_dim,
  711. dropout,
  712. out_channels=mult * model_channels,
  713. dims=dims,
  714. use_checkpoint=use_checkpoint,
  715. use_scale_shift_norm=use_scale_shift_norm,
  716. )
  717. ]
  718. ch = mult * model_channels
  719. if ds in attention_resolutions:
  720. layers.append(
  721. AttentionBlock(
  722. ch,
  723. use_checkpoint=use_checkpoint,
  724. num_heads=num_heads,
  725. num_head_channels=num_head_channels,
  726. use_new_attention_order=use_new_attention_order,
  727. )
  728. )
  729. self.input_blocks.append(TimestepEmbedSequential(*layers))
  730. self._feature_size += ch
  731. input_block_chans.append(ch)
  732. if level != len(channel_mult) - 1:
  733. out_ch = ch
  734. self.input_blocks.append(
  735. TimestepEmbedSequential(
  736. ResBlock(
  737. ch,
  738. time_embed_dim,
  739. dropout,
  740. out_channels=out_ch,
  741. dims=dims,
  742. use_checkpoint=use_checkpoint,
  743. use_scale_shift_norm=use_scale_shift_norm,
  744. down=True,
  745. )
  746. if resblock_updown
  747. else Downsample(
  748. ch, conv_resample, dims=dims, out_channels=out_ch
  749. )
  750. )
  751. )
  752. ch = out_ch
  753. input_block_chans.append(ch)
  754. ds *= 2
  755. self._feature_size += ch
  756. self.middle_block = TimestepEmbedSequential(
  757. ResBlock(
  758. ch,
  759. time_embed_dim,
  760. dropout,
  761. dims=dims,
  762. use_checkpoint=use_checkpoint,
  763. use_scale_shift_norm=use_scale_shift_norm,
  764. ),
  765. AttentionBlock(
  766. ch,
  767. use_checkpoint=use_checkpoint,
  768. num_heads=num_heads,
  769. num_head_channels=num_head_channels,
  770. use_new_attention_order=use_new_attention_order,
  771. ),
  772. ResBlock(
  773. ch,
  774. time_embed_dim,
  775. dropout,
  776. dims=dims,
  777. use_checkpoint=use_checkpoint,
  778. use_scale_shift_norm=use_scale_shift_norm,
  779. ),
  780. )
  781. self._feature_size += ch
  782. self.pool = pool
  783. if pool == "adaptive":
  784. self.out = nn.Sequential(
  785. normalization(ch),
  786. nn.SiLU(),
  787. nn.AdaptiveAvgPool2d((1, 1)),
  788. zero_module(conv_nd(dims, ch, out_channels, 1)),
  789. nn.Flatten(),
  790. )
  791. elif pool == "attention":
  792. assert num_head_channels != -1
  793. self.out = nn.Sequential(
  794. normalization(ch),
  795. nn.SiLU(),
  796. AttentionPool2d(
  797. (image_size // ds), ch, num_head_channels, out_channels
  798. ),
  799. )
  800. elif pool == "spatial":
  801. self.out = nn.Sequential(
  802. nn.Linear(self._feature_size, 2048),
  803. nn.ReLU(),
  804. nn.Linear(2048, self.out_channels),
  805. )
  806. elif pool == "spatial_v2":
  807. self.out = nn.Sequential(
  808. nn.Linear(self._feature_size, 2048),
  809. normalization(2048),
  810. nn.SiLU(),
  811. nn.Linear(2048, self.out_channels),
  812. )
  813. else:
  814. raise NotImplementedError(f"Unexpected {pool} pooling")
  815. def convert_to_fp16(self):
  816. """
  817. Convert the torso of the model to float16.
  818. """
  819. self.input_blocks.apply(convert_module_to_f16)
  820. self.middle_block.apply(convert_module_to_f16)
  821. def convert_to_fp32(self):
  822. """
  823. Convert the torso of the model to float32.
  824. """
  825. self.input_blocks.apply(convert_module_to_f32)
  826. self.middle_block.apply(convert_module_to_f32)
  827. def forward(self, x, timesteps):
  828. """
  829. Apply the model to an input batch.
  830. :param x: an [N x C x ...] Tensor of inputs.
  831. :param timesteps: a 1-D batch of timesteps.
  832. :return: an [N x K] Tensor of outputs.
  833. """
  834. emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
  835. results = []
  836. h = x.type(self.dtype)
  837. for module in self.input_blocks:
  838. h = module(h, emb)
  839. if self.pool.startswith("spatial"):
  840. results.append(h.type(x.dtype).mean(dim=(2, 3)))
  841. h = self.middle_block(h, emb)
  842. if self.pool.startswith("spatial"):
  843. results.append(h.type(x.dtype).mean(dim=(2, 3)))
  844. h = th.cat(results, axis=-1)
  845. return self.out(h)
  846. else:
  847. h = h.type(x.dtype)
  848. return self.out(h)