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