InvokeAI 2.2.4.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. backend/__init__.py +0 -0
  2. backend/invoke_ai_web_server.py +1724 -0
  3. backend/modules/__init__.py +0 -0
  4. backend/modules/create_cmd_parser.py +55 -0
  5. backend/modules/get_canvas_generation_mode.py +117 -0
  6. backend/modules/parameters.py +71 -0
  7. backend/modules/parse_seed_weights.py +47 -0
  8. configs/INITIAL_MODELS.yaml +80 -0
  9. configs/models.yaml.example +29 -0
  10. configs/sd-concepts.txt +803 -0
  11. configs/stable-diffusion/v1-finetune.yaml +110 -0
  12. configs/stable-diffusion/v1-finetune_style.yaml +103 -0
  13. configs/stable-diffusion/v1-inference.yaml +79 -0
  14. configs/stable-diffusion/v1-inpainting-inference.yaml +79 -0
  15. configs/stable-diffusion/v1-m1-finetune.yaml +110 -0
  16. docs/assets/invoke-web-server-1.png +0 -0
  17. docs/assets/invoke_ai_banner.png +0 -0
  18. invokeai-2.2.4.5.data/data/assets/caution.png +0 -0
  19. invokeai-2.2.4.5.data/data/configs/INITIAL_MODELS.yaml +80 -0
  20. invokeai-2.2.4.5.data/data/configs/models.yaml.example +29 -0
  21. invokeai-2.2.4.5.data/data/configs/sd-concepts.txt +803 -0
  22. invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-finetune.yaml +110 -0
  23. invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-finetune_style.yaml +103 -0
  24. invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-inference.yaml +79 -0
  25. invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-inpainting-inference.yaml +79 -0
  26. invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-m1-finetune.yaml +110 -0
  27. invokeai-2.2.4.5.data/data/frontend/dist/assets/Inter-Bold.790c108b.ttf +0 -0
  28. invokeai-2.2.4.5.data/data/frontend/dist/assets/Inter.b9a8e5e2.ttf +0 -0
  29. invokeai-2.2.4.5.data/data/frontend/dist/assets/favicon.0d253ced.ico +0 -0
  30. invokeai-2.2.4.5.data/data/frontend/dist/assets/index-legacy-b741077f.js +48 -0
  31. invokeai-2.2.4.5.data/data/frontend/dist/assets/index.0dadf5d0.css +1 -0
  32. invokeai-2.2.4.5.data/data/frontend/dist/assets/index.21ff81eb.js +625 -0
  33. invokeai-2.2.4.5.data/data/frontend/dist/assets/logo.13003d72.png +0 -0
  34. invokeai-2.2.4.5.data/data/frontend/dist/assets/polyfills-legacy-dde3a68a.js +4 -0
  35. invokeai-2.2.4.5.data/data/frontend/dist/assets/polyfills.1ff60148.js +1 -0
  36. invokeai-2.2.4.5.data/data/frontend/dist/index.html +23 -0
  37. invokeai-2.2.4.5.data/data/scripts/configure_invokeai.py +797 -0
  38. invokeai-2.2.4.5.data/data/scripts/create_root.py +43 -0
  39. invokeai-2.2.4.5.data/data/scripts/dream.py +10 -0
  40. invokeai-2.2.4.5.data/data/scripts/images2prompt.py +30 -0
  41. invokeai-2.2.4.5.data/data/scripts/invoke.py +5 -0
  42. invokeai-2.2.4.5.data/data/scripts/legacy_api.py +681 -0
  43. invokeai-2.2.4.5.data/data/scripts/load_models.py +12 -0
  44. invokeai-2.2.4.5.data/data/scripts/merge_embeddings.py +124 -0
  45. invokeai-2.2.4.5.data/data/scripts/preload_models.py +12 -0
  46. invokeai-2.2.4.5.data/data/scripts/sd-metadata.py +22 -0
  47. invokeai-2.2.4.5.dist-info/LICENSE +21 -0
  48. invokeai-2.2.4.5.dist-info/LICENSE-ModelWeights.txt +294 -0
  49. invokeai-2.2.4.5.dist-info/METADATA +288 -0
  50. invokeai-2.2.4.5.dist-info/RECORD +169 -0
  51. invokeai-2.2.4.5.dist-info/WHEEL +5 -0
  52. invokeai-2.2.4.5.dist-info/entry_points.txt +4 -0
  53. invokeai-2.2.4.5.dist-info/top_level.txt +6 -0
  54. invokeai-2.2.4.5.dist-info/zip-safe +1 -0
  55. ldm/__init__.py +0 -0
  56. ldm/data/__init__.py +0 -0
  57. ldm/data/base.py +31 -0
  58. ldm/data/imagenet.py +466 -0
  59. ldm/data/lsun.py +126 -0
  60. ldm/data/personalized.py +202 -0
  61. ldm/data/personalized_style.py +169 -0
  62. ldm/generate.py +1159 -0
  63. ldm/invoke/CLI.py +960 -0
  64. ldm/invoke/__init__.py +3 -0
  65. ldm/invoke/args.py +1257 -0
  66. ldm/invoke/concepts_lib.py +169 -0
  67. ldm/invoke/conditioning.py +289 -0
  68. ldm/invoke/devices.py +27 -0
  69. ldm/invoke/generator/__init__.py +4 -0
  70. ldm/invoke/generator/base.py +335 -0
  71. ldm/invoke/generator/embiggen.py +501 -0
  72. ldm/invoke/generator/img2img.py +97 -0
  73. ldm/invoke/generator/inpaint.py +358 -0
  74. ldm/invoke/generator/omnibus.py +175 -0
  75. ldm/invoke/generator/txt2img.py +88 -0
  76. ldm/invoke/generator/txt2img2img.py +182 -0
  77. ldm/invoke/globals.py +31 -0
  78. ldm/invoke/image_util.py +70 -0
  79. ldm/invoke/log.py +66 -0
  80. ldm/invoke/model_cache.py +449 -0
  81. ldm/invoke/patchmatch.py +44 -0
  82. ldm/invoke/pngwriter.py +113 -0
  83. ldm/invoke/prompt_parser.py +655 -0
  84. ldm/invoke/readline.py +442 -0
  85. ldm/invoke/restoration/__init__.py +4 -0
  86. ldm/invoke/restoration/base.py +38 -0
  87. ldm/invoke/restoration/codeformer.py +103 -0
  88. ldm/invoke/restoration/codeformer_arch.py +276 -0
  89. ldm/invoke/restoration/gfpgan.py +84 -0
  90. ldm/invoke/restoration/outcrop.py +108 -0
  91. ldm/invoke/restoration/outpaint.py +92 -0
  92. ldm/invoke/restoration/realesrgan.py +90 -0
  93. ldm/invoke/restoration/vqgan_arch.py +435 -0
  94. ldm/invoke/seamless.py +30 -0
  95. ldm/invoke/server.py +282 -0
  96. ldm/invoke/server_legacy.py +246 -0
  97. ldm/invoke/txt2mask.py +136 -0
  98. ldm/lr_scheduler.py +143 -0
  99. ldm/models/__init__.py +0 -0
  100. ldm/models/autoencoder.py +596 -0
  101. ldm/models/diffusion/__init__.py +0 -0
  102. ldm/models/diffusion/classifier.py +355 -0
  103. ldm/models/diffusion/cross_attention_control.py +443 -0
  104. ldm/models/diffusion/cross_attention_map_saving.py +95 -0
  105. ldm/models/diffusion/ddim.py +111 -0
  106. ldm/models/diffusion/ddpm.py +2263 -0
  107. ldm/models/diffusion/ksampler.py +312 -0
  108. ldm/models/diffusion/plms.py +146 -0
  109. ldm/models/diffusion/sampler.py +450 -0
  110. ldm/models/diffusion/shared_invokeai_diffusion.py +244 -0
  111. ldm/modules/__init__.py +0 -0
  112. ldm/modules/attention.py +274 -0
  113. ldm/modules/diffusionmodules/__init__.py +0 -0
  114. ldm/modules/diffusionmodules/model.py +894 -0
  115. ldm/modules/diffusionmodules/openaimodel.py +1036 -0
  116. ldm/modules/diffusionmodules/util.py +314 -0
  117. ldm/modules/distributions/__init__.py +0 -0
  118. ldm/modules/distributions/distributions.py +104 -0
  119. ldm/modules/ema.py +88 -0
  120. ldm/modules/embedding_manager.py +413 -0
  121. ldm/modules/encoders/__init__.py +0 -0
  122. ldm/modules/encoders/modules.py +772 -0
  123. ldm/modules/image_degradation/__init__.py +6 -0
  124. ldm/modules/image_degradation/bsrgan.py +846 -0
  125. ldm/modules/image_degradation/bsrgan_light.py +751 -0
  126. ldm/modules/image_degradation/utils_image.py +1024 -0
  127. ldm/modules/losses/__init__.py +1 -0
  128. ldm/modules/losses/contperceptual.py +175 -0
  129. ldm/modules/losses/vqperceptual.py +240 -0
  130. ldm/modules/x_transformer.py +752 -0
  131. ldm/simplet2i.py +13 -0
  132. ldm/util.py +264 -0
  133. scripts/configure_invokeai.py +797 -0
  134. scripts/create_root.py +43 -0
  135. scripts/dream.py +10 -0
  136. scripts/images2prompt.py +30 -0
  137. scripts/invoke.py +5 -0
  138. scripts/legacy_api.py +681 -0
  139. scripts/load_models.py +12 -0
  140. scripts/merge_embeddings.py +124 -0
  141. scripts/orig_scripts/img2img.py +296 -0
  142. scripts/orig_scripts/inpaint.py +98 -0
  143. scripts/orig_scripts/knn2img.py +397 -0
  144. scripts/orig_scripts/sample_diffusion.py +313 -0
  145. scripts/orig_scripts/train_searcher.py +147 -0
  146. scripts/orig_scripts/txt2img.py +324 -0
  147. scripts/preload_models.py +12 -0
  148. scripts/sd-metadata.py +22 -0
  149. vendored/clip/clip/__init__.py +1 -0
  150. vendored/clip/clip/bpe_simple_vocab_16e6.txt.gz +0 -0
  151. vendored/clip/clip/clip.py +237 -0
  152. vendored/clip/clip/model.py +436 -0
  153. vendored/clip/clip/simple_tokenizer.py +132 -0
  154. vendored/clip/hubconf.py +42 -0
  155. vendored/clip/setup.py +21 -0
  156. vendored/clip/tests/test_consistency.py +25 -0
  157. vendored/clipseg/datasets/coco_wrapper.py +99 -0
  158. vendored/clipseg/datasets/pascal_zeroshot.py +60 -0
  159. vendored/clipseg/datasets/pfe_dataset.py +129 -0
  160. vendored/clipseg/datasets/phrasecut.py +380 -0
  161. vendored/clipseg/datasets/utils.py +68 -0
  162. vendored/clipseg/evaluation_utils.py +292 -0
  163. vendored/clipseg/general_utils.py +272 -0
  164. vendored/clipseg/metrics.py +271 -0
  165. vendored/clipseg/models/clipseg.py +538 -0
  166. vendored/clipseg/models/vitseg.py +286 -0
  167. vendored/clipseg/score.py +453 -0
  168. vendored/clipseg/setup.py +30 -0
  169. vendored/clipseg/training.py +266 -0
@@ -0,0 +1,1036 @@
1
+ from abc import abstractmethod
2
+ from functools import partial
3
+ import math
4
+ from typing import Iterable
5
+
6
+ import numpy as np
7
+ import torch as th
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+
11
+ from ldm.modules.diffusionmodules.util import (
12
+ checkpoint,
13
+ conv_nd,
14
+ linear,
15
+ avg_pool_nd,
16
+ zero_module,
17
+ normalization,
18
+ timestep_embedding,
19
+ )
20
+ from ldm.modules.attention import SpatialTransformer
21
+
22
+
23
+ # dummy replace
24
+ def convert_module_to_f16(x):
25
+ pass
26
+
27
+
28
+ def convert_module_to_f32(x):
29
+ pass
30
+
31
+
32
+ ## go
33
+ class AttentionPool2d(nn.Module):
34
+ """
35
+ Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ spacial_dim: int,
41
+ embed_dim: int,
42
+ num_heads_channels: int,
43
+ output_dim: int = None,
44
+ ):
45
+ super().__init__()
46
+ self.positional_embedding = nn.Parameter(
47
+ th.randn(embed_dim, spacial_dim**2 + 1) / embed_dim**0.5
48
+ )
49
+ self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
50
+ self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
51
+ self.num_heads = embed_dim // num_heads_channels
52
+ self.attention = QKVAttention(self.num_heads)
53
+
54
+ def forward(self, x):
55
+ b, c, *_spatial = x.shape
56
+ x = x.reshape(b, c, -1) # NC(HW)
57
+ x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
58
+ x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
59
+ x = self.qkv_proj(x)
60
+ x = self.attention(x)
61
+ x = self.c_proj(x)
62
+ return x[:, :, 0]
63
+
64
+
65
+ class TimestepBlock(nn.Module):
66
+ """
67
+ Any module where forward() takes timestep embeddings as a second argument.
68
+ """
69
+
70
+ @abstractmethod
71
+ def forward(self, x, emb):
72
+ """
73
+ Apply the module to `x` given `emb` timestep embeddings.
74
+ """
75
+
76
+
77
+ class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
78
+ """
79
+ A sequential module that passes timestep embeddings to the children that
80
+ support it as an extra input.
81
+ """
82
+
83
+ def forward(self, x, emb, context=None):
84
+ for layer in self:
85
+ if isinstance(layer, TimestepBlock):
86
+ x = layer(x, emb)
87
+ elif isinstance(layer, SpatialTransformer):
88
+ x = layer(x, context)
89
+ else:
90
+ x = layer(x)
91
+ return x
92
+
93
+
94
+ class Upsample(nn.Module):
95
+ """
96
+ An upsampling layer with an optional convolution.
97
+ :param channels: channels in the inputs and outputs.
98
+ :param use_conv: a bool determining if a convolution is applied.
99
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
100
+ upsampling occurs in the inner-two dimensions.
101
+ """
102
+
103
+ def __init__(
104
+ self, channels, use_conv, dims=2, out_channels=None, padding=1
105
+ ):
106
+ super().__init__()
107
+ self.channels = channels
108
+ self.out_channels = out_channels or channels
109
+ self.use_conv = use_conv
110
+ self.dims = dims
111
+ if use_conv:
112
+ self.conv = conv_nd(
113
+ dims, self.channels, self.out_channels, 3, padding=padding
114
+ )
115
+
116
+ def forward(self, x):
117
+ assert x.shape[1] == self.channels
118
+ if self.dims == 3:
119
+ x = F.interpolate(
120
+ x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode='nearest'
121
+ )
122
+ else:
123
+ x = F.interpolate(x, scale_factor=2, mode='nearest')
124
+ if self.use_conv:
125
+ x = self.conv(x)
126
+ return x
127
+
128
+
129
+ class TransposedUpsample(nn.Module):
130
+ """Learned 2x upsampling without padding"""
131
+
132
+ def __init__(self, channels, out_channels=None, ks=5):
133
+ super().__init__()
134
+ self.channels = channels
135
+ self.out_channels = out_channels or channels
136
+
137
+ self.up = nn.ConvTranspose2d(
138
+ self.channels, self.out_channels, kernel_size=ks, stride=2
139
+ )
140
+
141
+ def forward(self, x):
142
+ return self.up(x)
143
+
144
+
145
+ class Downsample(nn.Module):
146
+ """
147
+ A downsampling layer with an optional convolution.
148
+ :param channels: channels in the inputs and outputs.
149
+ :param use_conv: a bool determining if a convolution is applied.
150
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
151
+ downsampling occurs in the inner-two dimensions.
152
+ """
153
+
154
+ def __init__(
155
+ self, channels, use_conv, dims=2, out_channels=None, padding=1
156
+ ):
157
+ super().__init__()
158
+ self.channels = channels
159
+ self.out_channels = out_channels or channels
160
+ self.use_conv = use_conv
161
+ self.dims = dims
162
+ stride = 2 if dims != 3 else (1, 2, 2)
163
+ if use_conv:
164
+ self.op = conv_nd(
165
+ dims,
166
+ self.channels,
167
+ self.out_channels,
168
+ 3,
169
+ stride=stride,
170
+ padding=padding,
171
+ )
172
+ else:
173
+ assert self.channels == self.out_channels
174
+ self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
175
+
176
+ def forward(self, x):
177
+ assert x.shape[1] == self.channels
178
+ return self.op(x)
179
+
180
+
181
+ class ResBlock(TimestepBlock):
182
+ """
183
+ A residual block that can optionally change the number of channels.
184
+ :param channels: the number of input channels.
185
+ :param emb_channels: the number of timestep embedding channels.
186
+ :param dropout: the rate of dropout.
187
+ :param out_channels: if specified, the number of out channels.
188
+ :param use_conv: if True and out_channels is specified, use a spatial
189
+ convolution instead of a smaller 1x1 convolution to change the
190
+ channels in the skip connection.
191
+ :param dims: determines if the signal is 1D, 2D, or 3D.
192
+ :param use_checkpoint: if True, use gradient checkpointing on this module.
193
+ :param up: if True, use this block for upsampling.
194
+ :param down: if True, use this block for downsampling.
195
+ """
196
+
197
+ def __init__(
198
+ self,
199
+ channels,
200
+ emb_channels,
201
+ dropout,
202
+ out_channels=None,
203
+ use_conv=False,
204
+ use_scale_shift_norm=False,
205
+ dims=2,
206
+ use_checkpoint=False,
207
+ up=False,
208
+ down=False,
209
+ ):
210
+ super().__init__()
211
+ self.channels = channels
212
+ self.emb_channels = emb_channels
213
+ self.dropout = dropout
214
+ self.out_channels = out_channels or channels
215
+ self.use_conv = use_conv
216
+ self.use_checkpoint = use_checkpoint
217
+ self.use_scale_shift_norm = use_scale_shift_norm
218
+
219
+ self.in_layers = nn.Sequential(
220
+ normalization(channels),
221
+ nn.SiLU(),
222
+ conv_nd(dims, channels, self.out_channels, 3, padding=1),
223
+ )
224
+
225
+ self.updown = up or down
226
+
227
+ if up:
228
+ self.h_upd = Upsample(channels, False, dims)
229
+ self.x_upd = Upsample(channels, False, dims)
230
+ elif down:
231
+ self.h_upd = Downsample(channels, False, dims)
232
+ self.x_upd = Downsample(channels, False, dims)
233
+ else:
234
+ self.h_upd = self.x_upd = nn.Identity()
235
+
236
+ self.emb_layers = nn.Sequential(
237
+ nn.SiLU(),
238
+ linear(
239
+ emb_channels,
240
+ 2 * self.out_channels
241
+ if use_scale_shift_norm
242
+ else self.out_channels,
243
+ ),
244
+ )
245
+ self.out_layers = nn.Sequential(
246
+ normalization(self.out_channels),
247
+ nn.SiLU(),
248
+ nn.Dropout(p=dropout),
249
+ zero_module(
250
+ conv_nd(
251
+ dims, self.out_channels, self.out_channels, 3, padding=1
252
+ )
253
+ ),
254
+ )
255
+
256
+ if self.out_channels == channels:
257
+ self.skip_connection = nn.Identity()
258
+ elif use_conv:
259
+ self.skip_connection = conv_nd(
260
+ dims, channels, self.out_channels, 3, padding=1
261
+ )
262
+ else:
263
+ self.skip_connection = conv_nd(
264
+ dims, channels, self.out_channels, 1
265
+ )
266
+
267
+ def forward(self, x, emb):
268
+ """
269
+ Apply the block to a Tensor, conditioned on a timestep embedding.
270
+ :param x: an [N x C x ...] Tensor of features.
271
+ :param emb: an [N x emb_channels] Tensor of timestep embeddings.
272
+ :return: an [N x C x ...] Tensor of outputs.
273
+ """
274
+ return checkpoint(
275
+ self._forward, (x, emb), self.parameters(), self.use_checkpoint
276
+ )
277
+
278
+ def _forward(self, x, emb):
279
+ if self.updown:
280
+ in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
281
+ h = in_rest(x)
282
+ h = self.h_upd(h)
283
+ x = self.x_upd(x)
284
+ h = in_conv(h)
285
+ else:
286
+ h = self.in_layers(x)
287
+ emb_out = self.emb_layers(emb).type(h.dtype)
288
+ while len(emb_out.shape) < len(h.shape):
289
+ emb_out = emb_out[..., None]
290
+ if self.use_scale_shift_norm:
291
+ out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
292
+ scale, shift = th.chunk(emb_out, 2, dim=1)
293
+ h = out_norm(h) * (1 + scale) + shift
294
+ h = out_rest(h)
295
+ else:
296
+ h = h + emb_out
297
+ h = self.out_layers(h)
298
+ return self.skip_connection(x) + h
299
+
300
+
301
+ class AttentionBlock(nn.Module):
302
+ """
303
+ An attention block that allows spatial positions to attend to each other.
304
+ Originally ported from here, but adapted to the N-d case.
305
+ https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
306
+ """
307
+
308
+ def __init__(
309
+ self,
310
+ channels,
311
+ num_heads=1,
312
+ num_head_channels=-1,
313
+ use_checkpoint=False,
314
+ use_new_attention_order=False,
315
+ ):
316
+ super().__init__()
317
+ self.channels = channels
318
+ if num_head_channels == -1:
319
+ self.num_heads = num_heads
320
+ else:
321
+ assert (
322
+ channels % num_head_channels == 0
323
+ ), f'q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}'
324
+ self.num_heads = channels // num_head_channels
325
+ self.use_checkpoint = use_checkpoint
326
+ self.norm = normalization(channels)
327
+ self.qkv = conv_nd(1, channels, channels * 3, 1)
328
+ if use_new_attention_order:
329
+ # split qkv before split heads
330
+ self.attention = QKVAttention(self.num_heads)
331
+ else:
332
+ # split heads before split qkv
333
+ self.attention = QKVAttentionLegacy(self.num_heads)
334
+
335
+ self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
336
+
337
+ def forward(self, x):
338
+ return checkpoint(
339
+ self._forward, (x,), self.parameters(), True
340
+ ) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!!
341
+ # return pt_checkpoint(self._forward, x) # pytorch
342
+
343
+ def _forward(self, x):
344
+ b, c, *spatial = x.shape
345
+ x = x.reshape(b, c, -1)
346
+ qkv = self.qkv(self.norm(x))
347
+ h = self.attention(qkv)
348
+ h = self.proj_out(h)
349
+ return (x + h).reshape(b, c, *spatial)
350
+
351
+
352
+ def count_flops_attn(model, _x, y):
353
+ """
354
+ A counter for the `thop` package to count the operations in an
355
+ attention operation.
356
+ Meant to be used like:
357
+ macs, params = thop.profile(
358
+ model,
359
+ inputs=(inputs, timestamps),
360
+ custom_ops={QKVAttention: QKVAttention.count_flops},
361
+ )
362
+ """
363
+ b, c, *spatial = y[0].shape
364
+ num_spatial = int(np.prod(spatial))
365
+ # We perform two matmuls with the same number of ops.
366
+ # The first computes the weight matrix, the second computes
367
+ # the combination of the value vectors.
368
+ matmul_ops = 2 * b * (num_spatial**2) * c
369
+ model.total_ops += th.DoubleTensor([matmul_ops])
370
+
371
+
372
+ class QKVAttentionLegacy(nn.Module):
373
+ """
374
+ A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
375
+ """
376
+
377
+ def __init__(self, n_heads):
378
+ super().__init__()
379
+ self.n_heads = n_heads
380
+
381
+ def forward(self, qkv):
382
+ """
383
+ Apply QKV attention.
384
+ :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
385
+ :return: an [N x (H * C) x T] tensor after attention.
386
+ """
387
+ bs, width, length = qkv.shape
388
+ assert width % (3 * self.n_heads) == 0
389
+ ch = width // (3 * self.n_heads)
390
+ q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(
391
+ ch, dim=1
392
+ )
393
+ scale = 1 / math.sqrt(math.sqrt(ch))
394
+ weight = th.einsum(
395
+ 'bct,bcs->bts', q * scale, k * scale
396
+ ) # More stable with f16 than dividing afterwards
397
+ weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
398
+ a = th.einsum('bts,bcs->bct', weight, v)
399
+ return a.reshape(bs, -1, length)
400
+
401
+ @staticmethod
402
+ def count_flops(model, _x, y):
403
+ return count_flops_attn(model, _x, y)
404
+
405
+
406
+ class QKVAttention(nn.Module):
407
+ """
408
+ A module which performs QKV attention and splits in a different order.
409
+ """
410
+
411
+ def __init__(self, n_heads):
412
+ super().__init__()
413
+ self.n_heads = n_heads
414
+
415
+ def forward(self, qkv):
416
+ """
417
+ Apply QKV attention.
418
+ :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
419
+ :return: an [N x (H * C) x T] tensor after attention.
420
+ """
421
+ bs, width, length = qkv.shape
422
+ assert width % (3 * self.n_heads) == 0
423
+ ch = width // (3 * self.n_heads)
424
+ q, k, v = qkv.chunk(3, dim=1)
425
+ scale = 1 / math.sqrt(math.sqrt(ch))
426
+ weight = th.einsum(
427
+ 'bct,bcs->bts',
428
+ (q * scale).view(bs * self.n_heads, ch, length),
429
+ (k * scale).view(bs * self.n_heads, ch, length),
430
+ ) # More stable with f16 than dividing afterwards
431
+ weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
432
+ a = th.einsum(
433
+ 'bts,bcs->bct', weight, v.reshape(bs * self.n_heads, ch, length)
434
+ )
435
+ return a.reshape(bs, -1, length)
436
+
437
+ @staticmethod
438
+ def count_flops(model, _x, y):
439
+ return count_flops_attn(model, _x, y)
440
+
441
+
442
+ class UNetModel(nn.Module):
443
+ """
444
+ The full UNet model with attention and timestep embedding.
445
+ :param in_channels: channels in the input Tensor.
446
+ :param model_channels: base channel count for the model.
447
+ :param out_channels: channels in the output Tensor.
448
+ :param num_res_blocks: number of residual blocks per downsample.
449
+ :param attention_resolutions: a collection of downsample rates at which
450
+ attention will take place. May be a set, list, or tuple.
451
+ For example, if this contains 4, then at 4x downsampling, attention
452
+ will be used.
453
+ :param dropout: the dropout probability.
454
+ :param channel_mult: channel multiplier for each level of the UNet.
455
+ :param conv_resample: if True, use learned convolutions for upsampling and
456
+ downsampling.
457
+ :param dims: determines if the signal is 1D, 2D, or 3D.
458
+ :param num_classes: if specified (as an int), then this model will be
459
+ class-conditional with `num_classes` classes.
460
+ :param use_checkpoint: use gradient checkpointing to reduce memory usage.
461
+ :param num_heads: the number of attention heads in each attention layer.
462
+ :param num_heads_channels: if specified, ignore num_heads and instead use
463
+ a fixed channel width per attention head.
464
+ :param num_heads_upsample: works with num_heads to set a different number
465
+ of heads for upsampling. Deprecated.
466
+ :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
467
+ :param resblock_updown: use residual blocks for up/downsampling.
468
+ :param use_new_attention_order: use a different attention pattern for potentially
469
+ increased efficiency.
470
+ """
471
+
472
+ def __init__(
473
+ self,
474
+ image_size,
475
+ in_channels,
476
+ model_channels,
477
+ out_channels,
478
+ num_res_blocks,
479
+ attention_resolutions,
480
+ dropout=0,
481
+ channel_mult=(1, 2, 4, 8),
482
+ conv_resample=True,
483
+ dims=2,
484
+ num_classes=None,
485
+ use_checkpoint=False,
486
+ use_fp16=False,
487
+ num_heads=-1,
488
+ num_head_channels=-1,
489
+ num_heads_upsample=-1,
490
+ use_scale_shift_norm=False,
491
+ resblock_updown=False,
492
+ use_new_attention_order=False,
493
+ use_spatial_transformer=False, # custom transformer support
494
+ transformer_depth=1, # custom transformer support
495
+ context_dim=None, # custom transformer support
496
+ n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
497
+ legacy=True,
498
+ ):
499
+ super().__init__()
500
+ if use_spatial_transformer:
501
+ assert (
502
+ context_dim is not None
503
+ ), 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
504
+
505
+ if context_dim is not None:
506
+ assert (
507
+ use_spatial_transformer
508
+ ), 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
509
+ from omegaconf.listconfig import ListConfig
510
+
511
+ if type(context_dim) == ListConfig:
512
+ context_dim = list(context_dim)
513
+
514
+ if num_heads_upsample == -1:
515
+ num_heads_upsample = num_heads
516
+
517
+ if num_heads == -1:
518
+ assert (
519
+ num_head_channels != -1
520
+ ), 'Either num_heads or num_head_channels has to be set'
521
+
522
+ if num_head_channels == -1:
523
+ assert (
524
+ num_heads != -1
525
+ ), 'Either num_heads or num_head_channels has to be set'
526
+
527
+ self.image_size = image_size
528
+ self.in_channels = in_channels
529
+ self.model_channels = model_channels
530
+ self.out_channels = out_channels
531
+ self.num_res_blocks = num_res_blocks
532
+ self.attention_resolutions = attention_resolutions
533
+ self.dropout = dropout
534
+ self.channel_mult = channel_mult
535
+ self.conv_resample = conv_resample
536
+ self.num_classes = num_classes
537
+ self.use_checkpoint = use_checkpoint
538
+ self.dtype = th.float16 if use_fp16 else th.float32
539
+ self.num_heads = num_heads
540
+ self.num_head_channels = num_head_channels
541
+ self.num_heads_upsample = num_heads_upsample
542
+ self.predict_codebook_ids = n_embed is not None
543
+
544
+ time_embed_dim = model_channels * 4
545
+ self.time_embed = nn.Sequential(
546
+ linear(model_channels, time_embed_dim),
547
+ nn.SiLU(),
548
+ linear(time_embed_dim, time_embed_dim),
549
+ )
550
+
551
+ if self.num_classes is not None:
552
+ self.label_emb = nn.Embedding(num_classes, time_embed_dim)
553
+
554
+ self.input_blocks = nn.ModuleList(
555
+ [
556
+ TimestepEmbedSequential(
557
+ conv_nd(dims, in_channels, model_channels, 3, padding=1)
558
+ )
559
+ ]
560
+ )
561
+ self._feature_size = model_channels
562
+ input_block_chans = [model_channels]
563
+ ch = model_channels
564
+ ds = 1
565
+ for level, mult in enumerate(channel_mult):
566
+ for _ in range(num_res_blocks):
567
+ layers = [
568
+ ResBlock(
569
+ ch,
570
+ time_embed_dim,
571
+ dropout,
572
+ out_channels=mult * model_channels,
573
+ dims=dims,
574
+ use_checkpoint=use_checkpoint,
575
+ use_scale_shift_norm=use_scale_shift_norm,
576
+ )
577
+ ]
578
+ ch = mult * model_channels
579
+ if ds in attention_resolutions:
580
+ if num_head_channels == -1:
581
+ dim_head = ch // num_heads
582
+ else:
583
+ num_heads = ch // num_head_channels
584
+ dim_head = num_head_channels
585
+ if legacy:
586
+ # num_heads = 1
587
+ dim_head = (
588
+ ch // num_heads
589
+ if use_spatial_transformer
590
+ else num_head_channels
591
+ )
592
+ layers.append(
593
+ AttentionBlock(
594
+ ch,
595
+ use_checkpoint=use_checkpoint,
596
+ num_heads=num_heads,
597
+ num_head_channels=dim_head,
598
+ use_new_attention_order=use_new_attention_order,
599
+ )
600
+ if not use_spatial_transformer
601
+ else SpatialTransformer(
602
+ ch,
603
+ num_heads,
604
+ dim_head,
605
+ depth=transformer_depth,
606
+ context_dim=context_dim,
607
+ )
608
+ )
609
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
610
+ self._feature_size += ch
611
+ input_block_chans.append(ch)
612
+ if level != len(channel_mult) - 1:
613
+ out_ch = ch
614
+ self.input_blocks.append(
615
+ TimestepEmbedSequential(
616
+ ResBlock(
617
+ ch,
618
+ time_embed_dim,
619
+ dropout,
620
+ out_channels=out_ch,
621
+ dims=dims,
622
+ use_checkpoint=use_checkpoint,
623
+ use_scale_shift_norm=use_scale_shift_norm,
624
+ down=True,
625
+ )
626
+ if resblock_updown
627
+ else Downsample(
628
+ ch, conv_resample, dims=dims, out_channels=out_ch
629
+ )
630
+ )
631
+ )
632
+ ch = out_ch
633
+ input_block_chans.append(ch)
634
+ ds *= 2
635
+ self._feature_size += ch
636
+
637
+ if num_head_channels == -1:
638
+ dim_head = ch // num_heads
639
+ else:
640
+ num_heads = ch // num_head_channels
641
+ dim_head = num_head_channels
642
+ if legacy:
643
+ # num_heads = 1
644
+ dim_head = (
645
+ ch // num_heads
646
+ if use_spatial_transformer
647
+ else num_head_channels
648
+ )
649
+ self.middle_block = TimestepEmbedSequential(
650
+ ResBlock(
651
+ ch,
652
+ time_embed_dim,
653
+ dropout,
654
+ dims=dims,
655
+ use_checkpoint=use_checkpoint,
656
+ use_scale_shift_norm=use_scale_shift_norm,
657
+ ),
658
+ AttentionBlock(
659
+ ch,
660
+ use_checkpoint=use_checkpoint,
661
+ num_heads=num_heads,
662
+ num_head_channels=dim_head,
663
+ use_new_attention_order=use_new_attention_order,
664
+ )
665
+ if not use_spatial_transformer
666
+ else SpatialTransformer(
667
+ ch,
668
+ num_heads,
669
+ dim_head,
670
+ depth=transformer_depth,
671
+ context_dim=context_dim,
672
+ ),
673
+ ResBlock(
674
+ ch,
675
+ time_embed_dim,
676
+ dropout,
677
+ dims=dims,
678
+ use_checkpoint=use_checkpoint,
679
+ use_scale_shift_norm=use_scale_shift_norm,
680
+ ),
681
+ )
682
+ self._feature_size += ch
683
+
684
+ self.output_blocks = nn.ModuleList([])
685
+ for level, mult in list(enumerate(channel_mult))[::-1]:
686
+ for i in range(num_res_blocks + 1):
687
+ ich = input_block_chans.pop()
688
+ layers = [
689
+ ResBlock(
690
+ ch + ich,
691
+ time_embed_dim,
692
+ dropout,
693
+ out_channels=model_channels * mult,
694
+ dims=dims,
695
+ use_checkpoint=use_checkpoint,
696
+ use_scale_shift_norm=use_scale_shift_norm,
697
+ )
698
+ ]
699
+ ch = model_channels * mult
700
+ if ds in attention_resolutions:
701
+ if num_head_channels == -1:
702
+ dim_head = ch // num_heads
703
+ else:
704
+ num_heads = ch // num_head_channels
705
+ dim_head = num_head_channels
706
+ if legacy:
707
+ # num_heads = 1
708
+ dim_head = (
709
+ ch // num_heads
710
+ if use_spatial_transformer
711
+ else num_head_channels
712
+ )
713
+ layers.append(
714
+ AttentionBlock(
715
+ ch,
716
+ use_checkpoint=use_checkpoint,
717
+ num_heads=num_heads_upsample,
718
+ num_head_channels=dim_head,
719
+ use_new_attention_order=use_new_attention_order,
720
+ )
721
+ if not use_spatial_transformer
722
+ else SpatialTransformer(
723
+ ch,
724
+ num_heads,
725
+ dim_head,
726
+ depth=transformer_depth,
727
+ context_dim=context_dim,
728
+ )
729
+ )
730
+ if level and i == num_res_blocks:
731
+ out_ch = ch
732
+ layers.append(
733
+ ResBlock(
734
+ ch,
735
+ time_embed_dim,
736
+ dropout,
737
+ out_channels=out_ch,
738
+ dims=dims,
739
+ use_checkpoint=use_checkpoint,
740
+ use_scale_shift_norm=use_scale_shift_norm,
741
+ up=True,
742
+ )
743
+ if resblock_updown
744
+ else Upsample(
745
+ ch, conv_resample, dims=dims, out_channels=out_ch
746
+ )
747
+ )
748
+ ds //= 2
749
+ self.output_blocks.append(TimestepEmbedSequential(*layers))
750
+ self._feature_size += ch
751
+
752
+ self.out = nn.Sequential(
753
+ normalization(ch),
754
+ nn.SiLU(),
755
+ zero_module(
756
+ conv_nd(dims, model_channels, out_channels, 3, padding=1)
757
+ ),
758
+ )
759
+ if self.predict_codebook_ids:
760
+ self.id_predictor = nn.Sequential(
761
+ normalization(ch),
762
+ conv_nd(dims, model_channels, n_embed, 1),
763
+ # nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
764
+ )
765
+
766
+ def convert_to_fp16(self):
767
+ """
768
+ Convert the torso of the model to float16.
769
+ """
770
+ self.input_blocks.apply(convert_module_to_f16)
771
+ self.middle_block.apply(convert_module_to_f16)
772
+ self.output_blocks.apply(convert_module_to_f16)
773
+
774
+ def convert_to_fp32(self):
775
+ """
776
+ Convert the torso of the model to float32.
777
+ """
778
+ self.input_blocks.apply(convert_module_to_f32)
779
+ self.middle_block.apply(convert_module_to_f32)
780
+ self.output_blocks.apply(convert_module_to_f32)
781
+
782
+ def forward(self, x, timesteps=None, context=None, y=None, **kwargs):
783
+ """
784
+ Apply the model to an input batch.
785
+ :param x: an [N x C x ...] Tensor of inputs.
786
+ :param timesteps: a 1-D batch of timesteps.
787
+ :param context: conditioning plugged in via crossattn
788
+ :param y: an [N] Tensor of labels, if class-conditional.
789
+ :return: an [N x C x ...] Tensor of outputs.
790
+ """
791
+ assert (y is not None) == (
792
+ self.num_classes is not None
793
+ ), 'must specify y if and only if the model is class-conditional'
794
+ hs = []
795
+ t_emb = timestep_embedding(
796
+ timesteps, self.model_channels, repeat_only=False
797
+ )
798
+ emb = self.time_embed(t_emb)
799
+
800
+ if self.num_classes is not None:
801
+ assert y.shape == (x.shape[0],)
802
+ emb = emb + self.label_emb(y)
803
+
804
+ h = x.type(self.dtype)
805
+ for module in self.input_blocks:
806
+ h = module(h, emb, context)
807
+ hs.append(h)
808
+ h = self.middle_block(h, emb, context)
809
+ for module in self.output_blocks:
810
+ h = th.cat([h, hs.pop()], dim=1)
811
+ h = module(h, emb, context)
812
+ h = h.type(x.dtype)
813
+ if self.predict_codebook_ids:
814
+ return self.id_predictor(h)
815
+ else:
816
+ return self.out(h)
817
+
818
+
819
+ class EncoderUNetModel(nn.Module):
820
+ """
821
+ The half UNet model with attention and timestep embedding.
822
+ For usage, see UNet.
823
+ """
824
+
825
+ def __init__(
826
+ self,
827
+ image_size,
828
+ in_channels,
829
+ model_channels,
830
+ out_channels,
831
+ num_res_blocks,
832
+ attention_resolutions,
833
+ dropout=0,
834
+ channel_mult=(1, 2, 4, 8),
835
+ conv_resample=True,
836
+ dims=2,
837
+ use_checkpoint=False,
838
+ use_fp16=False,
839
+ num_heads=1,
840
+ num_head_channels=-1,
841
+ num_heads_upsample=-1,
842
+ use_scale_shift_norm=False,
843
+ resblock_updown=False,
844
+ use_new_attention_order=False,
845
+ pool='adaptive',
846
+ *args,
847
+ **kwargs,
848
+ ):
849
+ super().__init__()
850
+
851
+ if num_heads_upsample == -1:
852
+ num_heads_upsample = num_heads
853
+
854
+ self.in_channels = in_channels
855
+ self.model_channels = model_channels
856
+ self.out_channels = out_channels
857
+ self.num_res_blocks = num_res_blocks
858
+ self.attention_resolutions = attention_resolutions
859
+ self.dropout = dropout
860
+ self.channel_mult = channel_mult
861
+ self.conv_resample = conv_resample
862
+ self.use_checkpoint = use_checkpoint
863
+ self.dtype = th.float16 if use_fp16 else th.float32
864
+ self.num_heads = num_heads
865
+ self.num_head_channels = num_head_channels
866
+ self.num_heads_upsample = num_heads_upsample
867
+
868
+ time_embed_dim = model_channels * 4
869
+ self.time_embed = nn.Sequential(
870
+ linear(model_channels, time_embed_dim),
871
+ nn.SiLU(),
872
+ linear(time_embed_dim, time_embed_dim),
873
+ )
874
+
875
+ self.input_blocks = nn.ModuleList(
876
+ [
877
+ TimestepEmbedSequential(
878
+ conv_nd(dims, in_channels, model_channels, 3, padding=1)
879
+ )
880
+ ]
881
+ )
882
+ self._feature_size = model_channels
883
+ input_block_chans = [model_channels]
884
+ ch = model_channels
885
+ ds = 1
886
+ for level, mult in enumerate(channel_mult):
887
+ for _ in range(num_res_blocks):
888
+ layers = [
889
+ ResBlock(
890
+ ch,
891
+ time_embed_dim,
892
+ dropout,
893
+ out_channels=mult * model_channels,
894
+ dims=dims,
895
+ use_checkpoint=use_checkpoint,
896
+ use_scale_shift_norm=use_scale_shift_norm,
897
+ )
898
+ ]
899
+ ch = mult * model_channels
900
+ if ds in attention_resolutions:
901
+ layers.append(
902
+ AttentionBlock(
903
+ ch,
904
+ use_checkpoint=use_checkpoint,
905
+ num_heads=num_heads,
906
+ num_head_channels=num_head_channels,
907
+ use_new_attention_order=use_new_attention_order,
908
+ )
909
+ )
910
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
911
+ self._feature_size += ch
912
+ input_block_chans.append(ch)
913
+ if level != len(channel_mult) - 1:
914
+ out_ch = ch
915
+ self.input_blocks.append(
916
+ TimestepEmbedSequential(
917
+ ResBlock(
918
+ ch,
919
+ time_embed_dim,
920
+ dropout,
921
+ out_channels=out_ch,
922
+ dims=dims,
923
+ use_checkpoint=use_checkpoint,
924
+ use_scale_shift_norm=use_scale_shift_norm,
925
+ down=True,
926
+ )
927
+ if resblock_updown
928
+ else Downsample(
929
+ ch, conv_resample, dims=dims, out_channels=out_ch
930
+ )
931
+ )
932
+ )
933
+ ch = out_ch
934
+ input_block_chans.append(ch)
935
+ ds *= 2
936
+ self._feature_size += ch
937
+
938
+ self.middle_block = TimestepEmbedSequential(
939
+ ResBlock(
940
+ ch,
941
+ time_embed_dim,
942
+ dropout,
943
+ dims=dims,
944
+ use_checkpoint=use_checkpoint,
945
+ use_scale_shift_norm=use_scale_shift_norm,
946
+ ),
947
+ AttentionBlock(
948
+ ch,
949
+ use_checkpoint=use_checkpoint,
950
+ num_heads=num_heads,
951
+ num_head_channels=num_head_channels,
952
+ use_new_attention_order=use_new_attention_order,
953
+ ),
954
+ ResBlock(
955
+ ch,
956
+ time_embed_dim,
957
+ dropout,
958
+ dims=dims,
959
+ use_checkpoint=use_checkpoint,
960
+ use_scale_shift_norm=use_scale_shift_norm,
961
+ ),
962
+ )
963
+ self._feature_size += ch
964
+ self.pool = pool
965
+ if pool == 'adaptive':
966
+ self.out = nn.Sequential(
967
+ normalization(ch),
968
+ nn.SiLU(),
969
+ nn.AdaptiveAvgPool2d((1, 1)),
970
+ zero_module(conv_nd(dims, ch, out_channels, 1)),
971
+ nn.Flatten(),
972
+ )
973
+ elif pool == 'attention':
974
+ assert num_head_channels != -1
975
+ self.out = nn.Sequential(
976
+ normalization(ch),
977
+ nn.SiLU(),
978
+ AttentionPool2d(
979
+ (image_size // ds), ch, num_head_channels, out_channels
980
+ ),
981
+ )
982
+ elif pool == 'spatial':
983
+ self.out = nn.Sequential(
984
+ nn.Linear(self._feature_size, 2048),
985
+ nn.ReLU(),
986
+ nn.Linear(2048, self.out_channels),
987
+ )
988
+ elif pool == 'spatial_v2':
989
+ self.out = nn.Sequential(
990
+ nn.Linear(self._feature_size, 2048),
991
+ normalization(2048),
992
+ nn.SiLU(),
993
+ nn.Linear(2048, self.out_channels),
994
+ )
995
+ else:
996
+ raise NotImplementedError(f'Unexpected {pool} pooling')
997
+
998
+ def convert_to_fp16(self):
999
+ """
1000
+ Convert the torso of the model to float16.
1001
+ """
1002
+ self.input_blocks.apply(convert_module_to_f16)
1003
+ self.middle_block.apply(convert_module_to_f16)
1004
+
1005
+ def convert_to_fp32(self):
1006
+ """
1007
+ Convert the torso of the model to float32.
1008
+ """
1009
+ self.input_blocks.apply(convert_module_to_f32)
1010
+ self.middle_block.apply(convert_module_to_f32)
1011
+
1012
+ def forward(self, x, timesteps):
1013
+ """
1014
+ Apply the model to an input batch.
1015
+ :param x: an [N x C x ...] Tensor of inputs.
1016
+ :param timesteps: a 1-D batch of timesteps.
1017
+ :return: an [N x K] Tensor of outputs.
1018
+ """
1019
+ emb = self.time_embed(
1020
+ timestep_embedding(timesteps, self.model_channels)
1021
+ )
1022
+
1023
+ results = []
1024
+ h = x.type(self.dtype)
1025
+ for module in self.input_blocks:
1026
+ h = module(h, emb)
1027
+ if self.pool.startswith('spatial'):
1028
+ results.append(h.type(x.dtype).mean(dim=(2, 3)))
1029
+ h = self.middle_block(h, emb)
1030
+ if self.pool.startswith('spatial'):
1031
+ results.append(h.type(x.dtype).mean(dim=(2, 3)))
1032
+ h = th.cat(results, axis=-1)
1033
+ return self.out(h)
1034
+ else:
1035
+ h = h.type(x.dtype)
1036
+ return self.out(h)