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,752 @@
1
+ """shout-out to https://github.com/lucidrains/x-transformers/tree/main/x_transformers"""
2
+ import torch
3
+ from torch import nn, einsum
4
+ import torch.nn.functional as F
5
+ from functools import partial
6
+ from inspect import isfunction
7
+ from collections import namedtuple
8
+ from einops import rearrange, repeat, reduce
9
+
10
+ # constants
11
+
12
+ DEFAULT_DIM_HEAD = 64
13
+
14
+ Intermediates = namedtuple(
15
+ 'Intermediates', ['pre_softmax_attn', 'post_softmax_attn']
16
+ )
17
+
18
+ LayerIntermediates = namedtuple(
19
+ 'Intermediates', ['hiddens', 'attn_intermediates']
20
+ )
21
+
22
+
23
+ class AbsolutePositionalEmbedding(nn.Module):
24
+ def __init__(self, dim, max_seq_len):
25
+ super().__init__()
26
+ self.emb = nn.Embedding(max_seq_len, dim)
27
+ self.init_()
28
+
29
+ def init_(self):
30
+ nn.init.normal_(self.emb.weight, std=0.02)
31
+
32
+ def forward(self, x):
33
+ n = torch.arange(x.shape[1], device=x.device)
34
+ return self.emb(n)[None, :, :]
35
+
36
+
37
+ class FixedPositionalEmbedding(nn.Module):
38
+ def __init__(self, dim):
39
+ super().__init__()
40
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim))
41
+ self.register_buffer('inv_freq', inv_freq)
42
+
43
+ def forward(self, x, seq_dim=1, offset=0):
44
+ t = (
45
+ torch.arange(x.shape[seq_dim], device=x.device).type_as(
46
+ self.inv_freq
47
+ )
48
+ + offset
49
+ )
50
+ sinusoid_inp = torch.einsum('i , j -> i j', t, self.inv_freq)
51
+ emb = torch.cat((sinusoid_inp.sin(), sinusoid_inp.cos()), dim=-1)
52
+ return emb[None, :, :]
53
+
54
+
55
+ # helpers
56
+
57
+
58
+ def exists(val):
59
+ return val is not None
60
+
61
+
62
+ def default(val, d):
63
+ if exists(val):
64
+ return val
65
+ return d() if isfunction(d) else d
66
+
67
+
68
+ def always(val):
69
+ def inner(*args, **kwargs):
70
+ return val
71
+
72
+ return inner
73
+
74
+
75
+ def not_equals(val):
76
+ def inner(x):
77
+ return x != val
78
+
79
+ return inner
80
+
81
+
82
+ def equals(val):
83
+ def inner(x):
84
+ return x == val
85
+
86
+ return inner
87
+
88
+
89
+ def max_neg_value(tensor):
90
+ return -torch.finfo(tensor.dtype).max
91
+
92
+
93
+ # keyword argument helpers
94
+
95
+
96
+ def pick_and_pop(keys, d):
97
+ values = list(map(lambda key: d.pop(key), keys))
98
+ return dict(zip(keys, values))
99
+
100
+
101
+ def group_dict_by_key(cond, d):
102
+ return_val = [dict(), dict()]
103
+ for key in d.keys():
104
+ match = bool(cond(key))
105
+ ind = int(not match)
106
+ return_val[ind][key] = d[key]
107
+ return (*return_val,)
108
+
109
+
110
+ def string_begins_with(prefix, str):
111
+ return str.startswith(prefix)
112
+
113
+
114
+ def group_by_key_prefix(prefix, d):
115
+ return group_dict_by_key(partial(string_begins_with, prefix), d)
116
+
117
+
118
+ def groupby_prefix_and_trim(prefix, d):
119
+ kwargs_with_prefix, kwargs = group_dict_by_key(
120
+ partial(string_begins_with, prefix), d
121
+ )
122
+ kwargs_without_prefix = dict(
123
+ map(
124
+ lambda x: (x[0][len(prefix) :], x[1]),
125
+ tuple(kwargs_with_prefix.items()),
126
+ )
127
+ )
128
+ return kwargs_without_prefix, kwargs
129
+
130
+
131
+ # classes
132
+ class Scale(nn.Module):
133
+ def __init__(self, value, fn):
134
+ super().__init__()
135
+ self.value = value
136
+ self.fn = fn
137
+
138
+ def forward(self, x, **kwargs):
139
+ x, *rest = self.fn(x, **kwargs)
140
+ return (x * self.value, *rest)
141
+
142
+
143
+ class Rezero(nn.Module):
144
+ def __init__(self, fn):
145
+ super().__init__()
146
+ self.fn = fn
147
+ self.g = nn.Parameter(torch.zeros(1))
148
+
149
+ def forward(self, x, **kwargs):
150
+ x, *rest = self.fn(x, **kwargs)
151
+ return (x * self.g, *rest)
152
+
153
+
154
+ class ScaleNorm(nn.Module):
155
+ def __init__(self, dim, eps=1e-5):
156
+ super().__init__()
157
+ self.scale = dim**-0.5
158
+ self.eps = eps
159
+ self.g = nn.Parameter(torch.ones(1))
160
+
161
+ def forward(self, x):
162
+ norm = torch.norm(x, dim=-1, keepdim=True) * self.scale
163
+ return x / norm.clamp(min=self.eps) * self.g
164
+
165
+
166
+ class RMSNorm(nn.Module):
167
+ def __init__(self, dim, eps=1e-8):
168
+ super().__init__()
169
+ self.scale = dim**-0.5
170
+ self.eps = eps
171
+ self.g = nn.Parameter(torch.ones(dim))
172
+
173
+ def forward(self, x):
174
+ norm = torch.norm(x, dim=-1, keepdim=True) * self.scale
175
+ return x / norm.clamp(min=self.eps) * self.g
176
+
177
+
178
+ class Residual(nn.Module):
179
+ def forward(self, x, residual):
180
+ return x + residual
181
+
182
+
183
+ class GRUGating(nn.Module):
184
+ def __init__(self, dim):
185
+ super().__init__()
186
+ self.gru = nn.GRUCell(dim, dim)
187
+
188
+ def forward(self, x, residual):
189
+ gated_output = self.gru(
190
+ rearrange(x, 'b n d -> (b n) d'),
191
+ rearrange(residual, 'b n d -> (b n) d'),
192
+ )
193
+
194
+ return gated_output.reshape_as(x)
195
+
196
+
197
+ # feedforward
198
+
199
+
200
+ class GEGLU(nn.Module):
201
+ def __init__(self, dim_in, dim_out):
202
+ super().__init__()
203
+ self.proj = nn.Linear(dim_in, dim_out * 2)
204
+
205
+ def forward(self, x):
206
+ x, gate = self.proj(x).chunk(2, dim=-1)
207
+ return x * F.gelu(gate)
208
+
209
+
210
+ class FeedForward(nn.Module):
211
+ def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.0):
212
+ super().__init__()
213
+ inner_dim = int(dim * mult)
214
+ dim_out = default(dim_out, dim)
215
+ project_in = (
216
+ nn.Sequential(nn.Linear(dim, inner_dim), nn.GELU())
217
+ if not glu
218
+ else GEGLU(dim, inner_dim)
219
+ )
220
+
221
+ self.net = nn.Sequential(
222
+ project_in, nn.Dropout(dropout), nn.Linear(inner_dim, dim_out)
223
+ )
224
+
225
+ def forward(self, x):
226
+ return self.net(x)
227
+
228
+
229
+ # attention.
230
+ class Attention(nn.Module):
231
+ def __init__(
232
+ self,
233
+ dim,
234
+ dim_head=DEFAULT_DIM_HEAD,
235
+ heads=8,
236
+ causal=False,
237
+ mask=None,
238
+ talking_heads=False,
239
+ sparse_topk=None,
240
+ use_entmax15=False,
241
+ num_mem_kv=0,
242
+ dropout=0.0,
243
+ on_attn=False,
244
+ ):
245
+ super().__init__()
246
+ if use_entmax15:
247
+ raise NotImplementedError(
248
+ 'Check out entmax activation instead of softmax activation!'
249
+ )
250
+ self.scale = dim_head**-0.5
251
+ self.heads = heads
252
+ self.causal = causal
253
+ self.mask = mask
254
+
255
+ inner_dim = dim_head * heads
256
+
257
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
258
+ self.to_k = nn.Linear(dim, inner_dim, bias=False)
259
+ self.to_v = nn.Linear(dim, inner_dim, bias=False)
260
+ self.dropout = nn.Dropout(dropout)
261
+
262
+ # talking heads
263
+ self.talking_heads = talking_heads
264
+ if talking_heads:
265
+ self.pre_softmax_proj = nn.Parameter(torch.randn(heads, heads))
266
+ self.post_softmax_proj = nn.Parameter(torch.randn(heads, heads))
267
+
268
+ # explicit topk sparse attention
269
+ self.sparse_topk = sparse_topk
270
+
271
+ # entmax
272
+ # self.attn_fn = entmax15 if use_entmax15 else F.softmax
273
+ self.attn_fn = F.softmax
274
+
275
+ # add memory key / values
276
+ self.num_mem_kv = num_mem_kv
277
+ if num_mem_kv > 0:
278
+ self.mem_k = nn.Parameter(torch.randn(heads, num_mem_kv, dim_head))
279
+ self.mem_v = nn.Parameter(torch.randn(heads, num_mem_kv, dim_head))
280
+
281
+ # attention on attention
282
+ self.attn_on_attn = on_attn
283
+ self.to_out = (
284
+ nn.Sequential(nn.Linear(inner_dim, dim * 2), nn.GLU())
285
+ if on_attn
286
+ else nn.Linear(inner_dim, dim)
287
+ )
288
+
289
+ def forward(
290
+ self,
291
+ x,
292
+ context=None,
293
+ mask=None,
294
+ context_mask=None,
295
+ rel_pos=None,
296
+ sinusoidal_emb=None,
297
+ prev_attn=None,
298
+ mem=None,
299
+ ):
300
+ b, n, _, h, talking_heads, device = (
301
+ *x.shape,
302
+ self.heads,
303
+ self.talking_heads,
304
+ x.device,
305
+ )
306
+ kv_input = default(context, x)
307
+
308
+ q_input = x
309
+ k_input = kv_input
310
+ v_input = kv_input
311
+
312
+ if exists(mem):
313
+ k_input = torch.cat((mem, k_input), dim=-2)
314
+ v_input = torch.cat((mem, v_input), dim=-2)
315
+
316
+ if exists(sinusoidal_emb):
317
+ # in shortformer, the query would start at a position offset depending on the past cached memory
318
+ offset = k_input.shape[-2] - q_input.shape[-2]
319
+ q_input = q_input + sinusoidal_emb(q_input, offset=offset)
320
+ k_input = k_input + sinusoidal_emb(k_input)
321
+
322
+ q = self.to_q(q_input)
323
+ k = self.to_k(k_input)
324
+ v = self.to_v(v_input)
325
+
326
+ q, k, v = map(
327
+ lambda t: rearrange(t, 'b n (h d) -> b h n d', h=h), (q, k, v)
328
+ )
329
+
330
+ input_mask = None
331
+ if any(map(exists, (mask, context_mask))):
332
+ q_mask = default(
333
+ mask, lambda: torch.ones((b, n), device=device).bool()
334
+ )
335
+ k_mask = q_mask if not exists(context) else context_mask
336
+ k_mask = default(
337
+ k_mask,
338
+ lambda: torch.ones((b, k.shape[-2]), device=device).bool(),
339
+ )
340
+ q_mask = rearrange(q_mask, 'b i -> b () i ()')
341
+ k_mask = rearrange(k_mask, 'b j -> b () () j')
342
+ input_mask = q_mask * k_mask
343
+
344
+ if self.num_mem_kv > 0:
345
+ mem_k, mem_v = map(
346
+ lambda t: repeat(t, 'h n d -> b h n d', b=b),
347
+ (self.mem_k, self.mem_v),
348
+ )
349
+ k = torch.cat((mem_k, k), dim=-2)
350
+ v = torch.cat((mem_v, v), dim=-2)
351
+ if exists(input_mask):
352
+ input_mask = F.pad(
353
+ input_mask, (self.num_mem_kv, 0), value=True
354
+ )
355
+
356
+ dots = einsum('b h i d, b h j d -> b h i j', q, k) * self.scale
357
+ mask_value = max_neg_value(dots)
358
+
359
+ if exists(prev_attn):
360
+ dots = dots + prev_attn
361
+
362
+ pre_softmax_attn = dots
363
+
364
+ if talking_heads:
365
+ dots = einsum(
366
+ 'b h i j, h k -> b k i j', dots, self.pre_softmax_proj
367
+ ).contiguous()
368
+
369
+ if exists(rel_pos):
370
+ dots = rel_pos(dots)
371
+
372
+ if exists(input_mask):
373
+ dots.masked_fill_(~input_mask, mask_value)
374
+ del input_mask
375
+
376
+ if self.causal:
377
+ i, j = dots.shape[-2:]
378
+ r = torch.arange(i, device=device)
379
+ mask = rearrange(r, 'i -> () () i ()') < rearrange(
380
+ r, 'j -> () () () j'
381
+ )
382
+ mask = F.pad(mask, (j - i, 0), value=False)
383
+ dots.masked_fill_(mask, mask_value)
384
+ del mask
385
+
386
+ if exists(self.sparse_topk) and self.sparse_topk < dots.shape[-1]:
387
+ top, _ = dots.topk(self.sparse_topk, dim=-1)
388
+ vk = top[..., -1].unsqueeze(-1).expand_as(dots)
389
+ mask = dots < vk
390
+ dots.masked_fill_(mask, mask_value)
391
+ del mask
392
+
393
+ attn = self.attn_fn(dots, dim=-1)
394
+ post_softmax_attn = attn
395
+
396
+ attn = self.dropout(attn)
397
+
398
+ if talking_heads:
399
+ attn = einsum(
400
+ 'b h i j, h k -> b k i j', attn, self.post_softmax_proj
401
+ ).contiguous()
402
+
403
+ out = einsum('b h i j, b h j d -> b h i d', attn, v)
404
+ out = rearrange(out, 'b h n d -> b n (h d)')
405
+
406
+ intermediates = Intermediates(
407
+ pre_softmax_attn=pre_softmax_attn,
408
+ post_softmax_attn=post_softmax_attn,
409
+ )
410
+
411
+ return self.to_out(out), intermediates
412
+
413
+
414
+ class AttentionLayers(nn.Module):
415
+ def __init__(
416
+ self,
417
+ dim,
418
+ depth,
419
+ heads=8,
420
+ causal=False,
421
+ cross_attend=False,
422
+ only_cross=False,
423
+ use_scalenorm=False,
424
+ use_rmsnorm=False,
425
+ use_rezero=False,
426
+ rel_pos_num_buckets=32,
427
+ rel_pos_max_distance=128,
428
+ position_infused_attn=False,
429
+ custom_layers=None,
430
+ sandwich_coef=None,
431
+ par_ratio=None,
432
+ residual_attn=False,
433
+ cross_residual_attn=False,
434
+ macaron=False,
435
+ pre_norm=True,
436
+ gate_residual=False,
437
+ **kwargs,
438
+ ):
439
+ super().__init__()
440
+ ff_kwargs, kwargs = groupby_prefix_and_trim('ff_', kwargs)
441
+ attn_kwargs, _ = groupby_prefix_and_trim('attn_', kwargs)
442
+
443
+ dim_head = attn_kwargs.get('dim_head', DEFAULT_DIM_HEAD)
444
+
445
+ self.dim = dim
446
+ self.depth = depth
447
+ self.layers = nn.ModuleList([])
448
+
449
+ self.has_pos_emb = position_infused_attn
450
+ self.pia_pos_emb = (
451
+ FixedPositionalEmbedding(dim) if position_infused_attn else None
452
+ )
453
+ self.rotary_pos_emb = always(None)
454
+
455
+ assert (
456
+ rel_pos_num_buckets <= rel_pos_max_distance
457
+ ), 'number of relative position buckets must be less than the relative position max distance'
458
+ self.rel_pos = None
459
+
460
+ self.pre_norm = pre_norm
461
+
462
+ self.residual_attn = residual_attn
463
+ self.cross_residual_attn = cross_residual_attn
464
+
465
+ norm_class = ScaleNorm if use_scalenorm else nn.LayerNorm
466
+ norm_class = RMSNorm if use_rmsnorm else norm_class
467
+ norm_fn = partial(norm_class, dim)
468
+
469
+ norm_fn = nn.Identity if use_rezero else norm_fn
470
+ branch_fn = Rezero if use_rezero else None
471
+
472
+ if cross_attend and not only_cross:
473
+ default_block = ('a', 'c', 'f')
474
+ elif cross_attend and only_cross:
475
+ default_block = ('c', 'f')
476
+ else:
477
+ default_block = ('a', 'f')
478
+
479
+ if macaron:
480
+ default_block = ('f',) + default_block
481
+
482
+ if exists(custom_layers):
483
+ layer_types = custom_layers
484
+ elif exists(par_ratio):
485
+ par_depth = depth * len(default_block)
486
+ assert 1 < par_ratio <= par_depth, 'par ratio out of range'
487
+ default_block = tuple(filter(not_equals('f'), default_block))
488
+ par_attn = par_depth // par_ratio
489
+ depth_cut = (
490
+ par_depth * 2 // 3
491
+ ) # 2 / 3 attention layer cutoff suggested by PAR paper
492
+ par_width = (depth_cut + depth_cut // par_attn) // par_attn
493
+ assert (
494
+ len(default_block) <= par_width
495
+ ), 'default block is too large for par_ratio'
496
+ par_block = default_block + ('f',) * (
497
+ par_width - len(default_block)
498
+ )
499
+ par_head = par_block * par_attn
500
+ layer_types = par_head + ('f',) * (par_depth - len(par_head))
501
+ elif exists(sandwich_coef):
502
+ assert (
503
+ sandwich_coef > 0 and sandwich_coef <= depth
504
+ ), 'sandwich coefficient should be less than the depth'
505
+ layer_types = (
506
+ ('a',) * sandwich_coef
507
+ + default_block * (depth - sandwich_coef)
508
+ + ('f',) * sandwich_coef
509
+ )
510
+ else:
511
+ layer_types = default_block * depth
512
+
513
+ self.layer_types = layer_types
514
+ self.num_attn_layers = len(list(filter(equals('a'), layer_types)))
515
+
516
+ for layer_type in self.layer_types:
517
+ if layer_type == 'a':
518
+ layer = Attention(
519
+ dim, heads=heads, causal=causal, **attn_kwargs
520
+ )
521
+ elif layer_type == 'c':
522
+ layer = Attention(dim, heads=heads, **attn_kwargs)
523
+ elif layer_type == 'f':
524
+ layer = FeedForward(dim, **ff_kwargs)
525
+ layer = layer if not macaron else Scale(0.5, layer)
526
+ else:
527
+ raise Exception(f'invalid layer type {layer_type}')
528
+
529
+ if isinstance(layer, Attention) and exists(branch_fn):
530
+ layer = branch_fn(layer)
531
+
532
+ if gate_residual:
533
+ residual_fn = GRUGating(dim)
534
+ else:
535
+ residual_fn = Residual()
536
+
537
+ self.layers.append(nn.ModuleList([norm_fn(), layer, residual_fn]))
538
+
539
+ def forward(
540
+ self,
541
+ x,
542
+ context=None,
543
+ mask=None,
544
+ context_mask=None,
545
+ mems=None,
546
+ return_hiddens=False,
547
+ **kwargs,
548
+ ):
549
+ hiddens = []
550
+ intermediates = []
551
+ prev_attn = None
552
+ prev_cross_attn = None
553
+
554
+ mems = mems.copy() if exists(mems) else [None] * self.num_attn_layers
555
+
556
+ for ind, (layer_type, (norm, block, residual_fn)) in enumerate(
557
+ zip(self.layer_types, self.layers)
558
+ ):
559
+ is_last = ind == (len(self.layers) - 1)
560
+
561
+ if layer_type == 'a':
562
+ hiddens.append(x)
563
+ layer_mem = mems.pop(0)
564
+
565
+ residual = x
566
+
567
+ if self.pre_norm:
568
+ x = norm(x)
569
+
570
+ if layer_type == 'a':
571
+ out, inter = block(
572
+ x,
573
+ mask=mask,
574
+ sinusoidal_emb=self.pia_pos_emb,
575
+ rel_pos=self.rel_pos,
576
+ prev_attn=prev_attn,
577
+ mem=layer_mem,
578
+ )
579
+ elif layer_type == 'c':
580
+ out, inter = block(
581
+ x,
582
+ context=context,
583
+ mask=mask,
584
+ context_mask=context_mask,
585
+ prev_attn=prev_cross_attn,
586
+ )
587
+ elif layer_type == 'f':
588
+ out = block(x)
589
+
590
+ x = residual_fn(out, residual)
591
+
592
+ if layer_type in ('a', 'c'):
593
+ intermediates.append(inter)
594
+
595
+ if layer_type == 'a' and self.residual_attn:
596
+ prev_attn = inter.pre_softmax_attn
597
+ elif layer_type == 'c' and self.cross_residual_attn:
598
+ prev_cross_attn = inter.pre_softmax_attn
599
+
600
+ if not self.pre_norm and not is_last:
601
+ x = norm(x)
602
+
603
+ if return_hiddens:
604
+ intermediates = LayerIntermediates(
605
+ hiddens=hiddens, attn_intermediates=intermediates
606
+ )
607
+
608
+ return x, intermediates
609
+
610
+ return x
611
+
612
+
613
+ class Encoder(AttentionLayers):
614
+ def __init__(self, **kwargs):
615
+ assert 'causal' not in kwargs, 'cannot set causality on encoder'
616
+ super().__init__(causal=False, **kwargs)
617
+
618
+
619
+ class TransformerWrapper(nn.Module):
620
+ def __init__(
621
+ self,
622
+ *,
623
+ num_tokens,
624
+ max_seq_len,
625
+ attn_layers,
626
+ emb_dim=None,
627
+ max_mem_len=0.0,
628
+ emb_dropout=0.0,
629
+ num_memory_tokens=None,
630
+ tie_embedding=False,
631
+ use_pos_emb=True,
632
+ ):
633
+ super().__init__()
634
+ assert isinstance(
635
+ attn_layers, AttentionLayers
636
+ ), 'attention layers must be one of Encoder or Decoder'
637
+
638
+ dim = attn_layers.dim
639
+ emb_dim = default(emb_dim, dim)
640
+
641
+ self.max_seq_len = max_seq_len
642
+ self.max_mem_len = max_mem_len
643
+ self.num_tokens = num_tokens
644
+
645
+ self.token_emb = nn.Embedding(num_tokens, emb_dim)
646
+ self.pos_emb = (
647
+ AbsolutePositionalEmbedding(emb_dim, max_seq_len)
648
+ if (use_pos_emb and not attn_layers.has_pos_emb)
649
+ else always(0)
650
+ )
651
+ self.emb_dropout = nn.Dropout(emb_dropout)
652
+
653
+ self.project_emb = (
654
+ nn.Linear(emb_dim, dim) if emb_dim != dim else nn.Identity()
655
+ )
656
+ self.attn_layers = attn_layers
657
+ self.norm = nn.LayerNorm(dim)
658
+
659
+ self.init_()
660
+
661
+ self.to_logits = (
662
+ nn.Linear(dim, num_tokens)
663
+ if not tie_embedding
664
+ else lambda t: t @ self.token_emb.weight.t()
665
+ )
666
+
667
+ # memory tokens (like [cls]) from Memory Transformers paper
668
+ num_memory_tokens = default(num_memory_tokens, 0)
669
+ self.num_memory_tokens = num_memory_tokens
670
+ if num_memory_tokens > 0:
671
+ self.memory_tokens = nn.Parameter(
672
+ torch.randn(num_memory_tokens, dim)
673
+ )
674
+
675
+ # let funnel encoder know number of memory tokens, if specified
676
+ if hasattr(attn_layers, 'num_memory_tokens'):
677
+ attn_layers.num_memory_tokens = num_memory_tokens
678
+
679
+ def init_(self):
680
+ nn.init.normal_(self.token_emb.weight, std=0.02)
681
+
682
+ def forward(
683
+ self,
684
+ x,
685
+ return_embeddings=False,
686
+ mask=None,
687
+ return_mems=False,
688
+ return_attn=False,
689
+ mems=None,
690
+ embedding_manager=None,
691
+ **kwargs,
692
+ ):
693
+ b, n, device, num_mem = *x.shape, x.device, self.num_memory_tokens
694
+
695
+ embedded_x = self.token_emb(x)
696
+
697
+ if embedding_manager:
698
+ x = embedding_manager(x, embedded_x)
699
+ else:
700
+ x = embedded_x
701
+
702
+ x = x + self.pos_emb(x)
703
+ x = self.emb_dropout(x)
704
+
705
+ x = self.project_emb(x)
706
+
707
+ if num_mem > 0:
708
+ mem = repeat(self.memory_tokens, 'n d -> b n d', b=b)
709
+ x = torch.cat((mem, x), dim=1)
710
+
711
+ # auto-handle masking after appending memory tokens
712
+ if exists(mask):
713
+ mask = F.pad(mask, (num_mem, 0), value=True)
714
+
715
+ x, intermediates = self.attn_layers(
716
+ x, mask=mask, mems=mems, return_hiddens=True, **kwargs
717
+ )
718
+ x = self.norm(x)
719
+
720
+ mem, x = x[:, :num_mem], x[:, num_mem:]
721
+
722
+ out = self.to_logits(x) if not return_embeddings else x
723
+
724
+ if return_mems:
725
+ hiddens = intermediates.hiddens
726
+ new_mems = (
727
+ list(
728
+ map(
729
+ lambda pair: torch.cat(pair, dim=-2),
730
+ zip(mems, hiddens),
731
+ )
732
+ )
733
+ if exists(mems)
734
+ else hiddens
735
+ )
736
+ new_mems = list(
737
+ map(
738
+ lambda t: t[..., -self.max_mem_len :, :].detach(), new_mems
739
+ )
740
+ )
741
+ return out, new_mems
742
+
743
+ if return_attn:
744
+ attn_maps = list(
745
+ map(
746
+ lambda t: t.post_softmax_attn,
747
+ intermediates.attn_intermediates,
748
+ )
749
+ )
750
+ return out, attn_maps
751
+
752
+ return out