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,397 @@
1
+ import argparse, os, sys, glob
2
+ import torch
3
+ import torch.nn as nn
4
+ import numpy as np
5
+ from omegaconf import OmegaConf
6
+ from PIL import Image
7
+ from tqdm import tqdm, trange
8
+ from itertools import islice
9
+ from einops import rearrange, repeat
10
+ from torchvision.utils import make_grid
11
+ import scann
12
+ import time
13
+ from multiprocessing import cpu_count
14
+
15
+ from ldm.util import instantiate_from_config, parallel_data_prefetch
16
+ from ldm.models.diffusion.ddim import DDIMSampler
17
+ from ldm.models.diffusion.plms import PLMSSampler
18
+ from ldm.modules.encoders.modules import FrozenClipImageEmbedder, FrozenCLIPTextEmbedder
19
+
20
+ DATABASES = [
21
+ "openimages",
22
+ "artbench-art_nouveau",
23
+ "artbench-baroque",
24
+ "artbench-expressionism",
25
+ "artbench-impressionism",
26
+ "artbench-post_impressionism",
27
+ "artbench-realism",
28
+ "artbench-romanticism",
29
+ "artbench-renaissance",
30
+ "artbench-surrealism",
31
+ "artbench-ukiyo_e",
32
+ ]
33
+
34
+
35
+ def chunk(it, size):
36
+ it = iter(it)
37
+ return iter(lambda: tuple(islice(it, size)), ())
38
+
39
+
40
+ def load_model_from_config(config, ckpt, verbose=False):
41
+ print(f"Loading model from {ckpt}")
42
+ pl_sd = torch.load(ckpt, map_location="cpu")
43
+ if "global_step" in pl_sd:
44
+ print(f"Global Step: {pl_sd['global_step']}")
45
+ sd = pl_sd["state_dict"]
46
+ model = instantiate_from_config(config.model)
47
+ m, u = model.load_state_dict(sd, strict=False)
48
+ if len(m) > 0 and verbose:
49
+ print("missing keys:")
50
+ print(m)
51
+ if len(u) > 0 and verbose:
52
+ print("unexpected keys:")
53
+ print(u)
54
+
55
+ model.cuda()
56
+ model.eval()
57
+ return model
58
+
59
+
60
+ class Searcher(object):
61
+ def __init__(self, database, retriever_version='ViT-L/14'):
62
+ assert database in DATABASES
63
+ # self.database = self.load_database(database)
64
+ self.database_name = database
65
+ self.searcher_savedir = f'data/rdm/searchers/{self.database_name}'
66
+ self.database_path = f'data/rdm/retrieval_databases/{self.database_name}'
67
+ self.retriever = self.load_retriever(version=retriever_version)
68
+ self.database = {'embedding': [],
69
+ 'img_id': [],
70
+ 'patch_coords': []}
71
+ self.load_database()
72
+ self.load_searcher()
73
+
74
+ def train_searcher(self, k,
75
+ metric='dot_product',
76
+ searcher_savedir=None):
77
+
78
+ print('Start training searcher')
79
+ searcher = scann.scann_ops_pybind.builder(self.database['embedding'] /
80
+ np.linalg.norm(self.database['embedding'], axis=1)[:, np.newaxis],
81
+ k, metric)
82
+ self.searcher = searcher.score_brute_force().build()
83
+ print('Finish training searcher')
84
+
85
+ if searcher_savedir is not None:
86
+ print(f'Save trained searcher under "{searcher_savedir}"')
87
+ os.makedirs(searcher_savedir, exist_ok=True)
88
+ self.searcher.serialize(searcher_savedir)
89
+
90
+ def load_single_file(self, saved_embeddings):
91
+ compressed = np.load(saved_embeddings)
92
+ self.database = {key: compressed[key] for key in compressed.files}
93
+ print('Finished loading of clip embeddings.')
94
+
95
+ def load_multi_files(self, data_archive):
96
+ out_data = {key: [] for key in self.database}
97
+ for d in tqdm(data_archive, desc=f'Loading datapool from {len(data_archive)} individual files.'):
98
+ for key in d.files:
99
+ out_data[key].append(d[key])
100
+
101
+ return out_data
102
+
103
+ def load_database(self):
104
+
105
+ print(f'Load saved patch embedding from "{self.database_path}"')
106
+ file_content = glob.glob(os.path.join(self.database_path, '*.npz'))
107
+
108
+ if len(file_content) == 1:
109
+ self.load_single_file(file_content[0])
110
+ elif len(file_content) > 1:
111
+ data = [np.load(f) for f in file_content]
112
+ prefetched_data = parallel_data_prefetch(self.load_multi_files, data,
113
+ n_proc=min(len(data), cpu_count()), target_data_type='dict')
114
+
115
+ self.database = {key: np.concatenate([od[key] for od in prefetched_data], axis=1)[0] for key in
116
+ self.database}
117
+ else:
118
+ raise ValueError(f'No npz-files in specified path "{self.database_path}" is this directory existing?')
119
+
120
+ print(f'Finished loading of retrieval database of length {self.database["embedding"].shape[0]}.')
121
+
122
+ def load_retriever(self, version='ViT-L/14', ):
123
+ model = FrozenClipImageEmbedder(model=version)
124
+ if torch.cuda.is_available():
125
+ model.cuda()
126
+ model.eval()
127
+ return model
128
+
129
+ def load_searcher(self):
130
+ print(f'load searcher for database {self.database_name} from {self.searcher_savedir}')
131
+ self.searcher = scann.scann_ops_pybind.load_searcher(self.searcher_savedir)
132
+ print('Finished loading searcher.')
133
+
134
+ def search(self, x, k):
135
+ if self.searcher is None and self.database['embedding'].shape[0] < 2e4:
136
+ self.train_searcher(k) # quickly fit searcher on the fly for small databases
137
+ assert self.searcher is not None, 'Cannot search with uninitialized searcher'
138
+ if isinstance(x, torch.Tensor):
139
+ x = x.detach().cpu().numpy()
140
+ if len(x.shape) == 3:
141
+ x = x[:, 0]
142
+ query_embeddings = x / np.linalg.norm(x, axis=1)[:, np.newaxis]
143
+
144
+ start = time.time()
145
+ nns, distances = self.searcher.search_batched(query_embeddings, final_num_neighbors=k)
146
+ end = time.time()
147
+
148
+ out_embeddings = self.database['embedding'][nns]
149
+ out_img_ids = self.database['img_id'][nns]
150
+ out_pc = self.database['patch_coords'][nns]
151
+
152
+ out = {'nn_embeddings': out_embeddings / np.linalg.norm(out_embeddings, axis=-1)[..., np.newaxis],
153
+ 'img_ids': out_img_ids,
154
+ 'patch_coords': out_pc,
155
+ 'queries': x,
156
+ 'exec_time': end - start,
157
+ 'nns': nns,
158
+ 'q_embeddings': query_embeddings}
159
+
160
+ return out
161
+
162
+ def __call__(self, x, n):
163
+ return self.search(x, n)
164
+
165
+
166
+ if __name__ == "__main__":
167
+ parser = argparse.ArgumentParser()
168
+ # TODO: add n_neighbors and modes (text-only, text-image-retrieval, image-image retrieval etc)
169
+ # TODO: add 'image variation' mode when knn=0 but a single image is given instead of a text prompt?
170
+ parser.add_argument(
171
+ "--prompt",
172
+ type=str,
173
+ nargs="?",
174
+ default="a painting of a virus monster playing guitar",
175
+ help="the prompt to render"
176
+ )
177
+
178
+ parser.add_argument(
179
+ "--outdir",
180
+ type=str,
181
+ nargs="?",
182
+ help="dir to write results to",
183
+ default="outputs/txt2img-samples"
184
+ )
185
+
186
+ parser.add_argument(
187
+ "--skip_grid",
188
+ action='store_true',
189
+ help="do not save a grid, only individual samples. Helpful when evaluating lots of samples",
190
+ )
191
+
192
+ parser.add_argument(
193
+ "--ddim_steps",
194
+ type=int,
195
+ default=50,
196
+ help="number of ddim sampling steps",
197
+ )
198
+
199
+ parser.add_argument(
200
+ "--n_repeat",
201
+ type=int,
202
+ default=1,
203
+ help="number of repeats in CLIP latent space",
204
+ )
205
+
206
+ parser.add_argument(
207
+ "--plms",
208
+ action='store_true',
209
+ help="use plms sampling",
210
+ )
211
+
212
+ parser.add_argument(
213
+ "--ddim_eta",
214
+ type=float,
215
+ default=0.0,
216
+ help="ddim eta (eta=0.0 corresponds to deterministic sampling",
217
+ )
218
+ parser.add_argument(
219
+ "--n_iter",
220
+ type=int,
221
+ default=1,
222
+ help="sample this often",
223
+ )
224
+
225
+ parser.add_argument(
226
+ "--H",
227
+ type=int,
228
+ default=768,
229
+ help="image height, in pixel space",
230
+ )
231
+
232
+ parser.add_argument(
233
+ "--W",
234
+ type=int,
235
+ default=768,
236
+ help="image width, in pixel space",
237
+ )
238
+
239
+ parser.add_argument(
240
+ "--n_samples",
241
+ type=int,
242
+ default=3,
243
+ help="how many samples to produce for each given prompt. A.k.a batch size",
244
+ )
245
+
246
+ parser.add_argument(
247
+ "--n_rows",
248
+ type=int,
249
+ default=0,
250
+ help="rows in the grid (default: n_samples)",
251
+ )
252
+
253
+ parser.add_argument(
254
+ "--scale",
255
+ type=float,
256
+ default=5.0,
257
+ help="unconditional guidance scale: eps = eps(x, empty) + scale * (eps(x, cond) - eps(x, empty))",
258
+ )
259
+
260
+ parser.add_argument(
261
+ "--from-file",
262
+ type=str,
263
+ help="if specified, load prompts from this file",
264
+ )
265
+
266
+ parser.add_argument(
267
+ "--config",
268
+ type=str,
269
+ default="configs/retrieval-augmented-diffusion/768x768.yaml",
270
+ help="path to config which constructs model",
271
+ )
272
+
273
+ parser.add_argument(
274
+ "--ckpt",
275
+ type=str,
276
+ default="models/rdm/rdm768x768/model.ckpt",
277
+ help="path to checkpoint of model",
278
+ )
279
+
280
+ parser.add_argument(
281
+ "--clip_type",
282
+ type=str,
283
+ default="ViT-L/14",
284
+ help="which CLIP model to use for retrieval and NN encoding",
285
+ )
286
+ parser.add_argument(
287
+ "--database",
288
+ type=str,
289
+ default='artbench-surrealism',
290
+ choices=DATABASES,
291
+ help="The database used for the search, only applied when --use_neighbors=True",
292
+ )
293
+ parser.add_argument(
294
+ "--use_neighbors",
295
+ default=False,
296
+ action='store_true',
297
+ help="Include neighbors in addition to text prompt for conditioning",
298
+ )
299
+ parser.add_argument(
300
+ "--knn",
301
+ default=10,
302
+ type=int,
303
+ help="The number of included neighbors, only applied when --use_neighbors=True",
304
+ )
305
+
306
+ opt = parser.parse_args()
307
+
308
+ config = OmegaConf.load(f"{opt.config}")
309
+ model = load_model_from_config(config, f"{opt.ckpt}")
310
+
311
+ device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
312
+ model = model.to(device)
313
+
314
+ clip_text_encoder = FrozenCLIPTextEmbedder(opt.clip_type).to(device)
315
+
316
+ if opt.plms:
317
+ sampler = PLMSSampler(model)
318
+ else:
319
+ sampler = DDIMSampler(model)
320
+
321
+ os.makedirs(opt.outdir, exist_ok=True)
322
+ outpath = opt.outdir
323
+
324
+ batch_size = opt.n_samples
325
+ n_rows = opt.n_rows if opt.n_rows > 0 else batch_size
326
+ if not opt.from_file:
327
+ prompt = opt.prompt
328
+ assert prompt is not None
329
+ data = [batch_size * [prompt]]
330
+
331
+ else:
332
+ print(f"reading prompts from {opt.from_file}")
333
+ with open(opt.from_file, "r") as f:
334
+ data = f.read().splitlines()
335
+ data = list(chunk(data, batch_size))
336
+
337
+ sample_path = os.path.join(outpath, "samples")
338
+ os.makedirs(sample_path, exist_ok=True)
339
+ base_count = len(os.listdir(sample_path))
340
+ grid_count = len(os.listdir(outpath)) - 1
341
+
342
+ print(f"sampling scale for cfg is {opt.scale:.2f}")
343
+
344
+ searcher = None
345
+ if opt.use_neighbors:
346
+ searcher = Searcher(opt.database)
347
+
348
+ with torch.no_grad():
349
+ with model.ema_scope():
350
+ for n in trange(opt.n_iter, desc="Sampling"):
351
+ all_samples = list()
352
+ for prompts in tqdm(data, desc="data"):
353
+ print("sampling prompts:", prompts)
354
+ if isinstance(prompts, tuple):
355
+ prompts = list(prompts)
356
+ c = clip_text_encoder.encode(prompts)
357
+ uc = None
358
+ if searcher is not None:
359
+ nn_dict = searcher(c, opt.knn)
360
+ c = torch.cat([c, torch.from_numpy(nn_dict['nn_embeddings']).cuda()], dim=1)
361
+ if opt.scale != 1.0:
362
+ uc = torch.zeros_like(c)
363
+ if isinstance(prompts, tuple):
364
+ prompts = list(prompts)
365
+ shape = [16, opt.H // 16, opt.W // 16] # note: currently hardcoded for f16 model
366
+ samples_ddim, _ = sampler.sample(S=opt.ddim_steps,
367
+ conditioning=c,
368
+ batch_size=c.shape[0],
369
+ shape=shape,
370
+ verbose=False,
371
+ unconditional_guidance_scale=opt.scale,
372
+ unconditional_conditioning=uc,
373
+ eta=opt.ddim_eta,
374
+ )
375
+
376
+ x_samples_ddim = model.decode_first_stage(samples_ddim)
377
+ x_samples_ddim = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0)
378
+
379
+ for x_sample in x_samples_ddim:
380
+ x_sample = 255. * rearrange(x_sample.cpu().numpy(), 'c h w -> h w c')
381
+ Image.fromarray(x_sample.astype(np.uint8)).save(
382
+ os.path.join(sample_path, f"{base_count:05}.png"))
383
+ base_count += 1
384
+ all_samples.append(x_samples_ddim)
385
+
386
+ if not opt.skip_grid:
387
+ # additionally, save as grid
388
+ grid = torch.stack(all_samples, 0)
389
+ grid = rearrange(grid, 'n b c h w -> (n b) c h w')
390
+ grid = make_grid(grid, nrow=n_rows)
391
+
392
+ # to image
393
+ grid = 255. * rearrange(grid, 'c h w -> h w c').cpu().numpy()
394
+ Image.fromarray(grid.astype(np.uint8)).save(os.path.join(outpath, f'grid-{grid_count:04}.png'))
395
+ grid_count += 1
396
+
397
+ print(f"Your samples are ready and waiting for you here: \n{outpath} \nEnjoy.")
@@ -0,0 +1,313 @@
1
+ import argparse, os, sys, glob, datetime, yaml
2
+ import torch
3
+ import time
4
+ import numpy as np
5
+ from tqdm import trange
6
+
7
+ from omegaconf import OmegaConf
8
+ from PIL import Image
9
+
10
+ from ldm.models.diffusion.ddim import DDIMSampler
11
+ from ldm.util import instantiate_from_config
12
+
13
+ rescale = lambda x: (x + 1.) / 2.
14
+
15
+ def custom_to_pil(x):
16
+ x = x.detach().cpu()
17
+ x = torch.clamp(x, -1., 1.)
18
+ x = (x + 1.) / 2.
19
+ x = x.permute(1, 2, 0).numpy()
20
+ x = (255 * x).astype(np.uint8)
21
+ x = Image.fromarray(x)
22
+ if not x.mode == "RGB":
23
+ x = x.convert("RGB")
24
+ return x
25
+
26
+
27
+ def custom_to_np(x):
28
+ # saves the batch in adm style as in https://github.com/openai/guided-diffusion/blob/main/scripts/image_sample.py
29
+ sample = x.detach().cpu()
30
+ sample = ((sample + 1) * 127.5).clamp(0, 255).to(torch.uint8)
31
+ sample = sample.permute(0, 2, 3, 1)
32
+ sample = sample.contiguous()
33
+ return sample
34
+
35
+
36
+ def logs2pil(logs, keys=["sample"]):
37
+ imgs = dict()
38
+ for k in logs:
39
+ try:
40
+ if len(logs[k].shape) == 4:
41
+ img = custom_to_pil(logs[k][0, ...])
42
+ elif len(logs[k].shape) == 3:
43
+ img = custom_to_pil(logs[k])
44
+ else:
45
+ print(f"Unknown format for key {k}. ")
46
+ img = None
47
+ except:
48
+ img = None
49
+ imgs[k] = img
50
+ return imgs
51
+
52
+
53
+ @torch.no_grad()
54
+ def convsample(model, shape, return_intermediates=True,
55
+ verbose=True,
56
+ make_prog_row=False):
57
+
58
+
59
+ if not make_prog_row:
60
+ return model.p_sample_loop(None, shape,
61
+ return_intermediates=return_intermediates, verbose=verbose)
62
+ else:
63
+ return model.progressive_denoising(
64
+ None, shape, verbose=True
65
+ )
66
+
67
+
68
+ @torch.no_grad()
69
+ def convsample_ddim(model, steps, shape, eta=1.0
70
+ ):
71
+ ddim = DDIMSampler(model)
72
+ bs = shape[0]
73
+ shape = shape[1:]
74
+ samples, intermediates = ddim.sample(steps, batch_size=bs, shape=shape, eta=eta, verbose=False,)
75
+ return samples, intermediates
76
+
77
+
78
+ @torch.no_grad()
79
+ def make_convolutional_sample(model, batch_size, vanilla=False, custom_steps=None, eta=1.0,):
80
+
81
+
82
+ log = dict()
83
+
84
+ shape = [batch_size,
85
+ model.model.diffusion_model.in_channels,
86
+ model.model.diffusion_model.image_size,
87
+ model.model.diffusion_model.image_size]
88
+
89
+ with model.ema_scope("Plotting"):
90
+ t0 = time.time()
91
+ if vanilla:
92
+ sample, progrow = convsample(model, shape,
93
+ make_prog_row=True)
94
+ else:
95
+ sample, intermediates = convsample_ddim(model, steps=custom_steps, shape=shape,
96
+ eta=eta)
97
+
98
+ t1 = time.time()
99
+
100
+ x_sample = model.decode_first_stage(sample)
101
+
102
+ log["sample"] = x_sample
103
+ log["time"] = t1 - t0
104
+ log['throughput'] = sample.shape[0] / (t1 - t0)
105
+ print(f'Throughput for this batch: {log["throughput"]}')
106
+ return log
107
+
108
+ def run(model, logdir, batch_size=50, vanilla=False, custom_steps=None, eta=None, n_samples=50000, nplog=None):
109
+ if vanilla:
110
+ print(f'Using Vanilla DDPM sampling with {model.num_timesteps} sampling steps.')
111
+ else:
112
+ print(f'Using DDIM sampling with {custom_steps} sampling steps and eta={eta}')
113
+
114
+
115
+ tstart = time.time()
116
+ n_saved = len(glob.glob(os.path.join(logdir,'*.png')))-1
117
+ # path = logdir
118
+ if model.cond_stage_model is None:
119
+ all_images = []
120
+
121
+ print(f"Running unconditional sampling for {n_samples} samples")
122
+ for _ in trange(n_samples // batch_size, desc="Sampling Batches (unconditional)"):
123
+ logs = make_convolutional_sample(model, batch_size=batch_size,
124
+ vanilla=vanilla, custom_steps=custom_steps,
125
+ eta=eta)
126
+ n_saved = save_logs(logs, logdir, n_saved=n_saved, key="sample")
127
+ all_images.extend([custom_to_np(logs["sample"])])
128
+ if n_saved >= n_samples:
129
+ print(f'Finish after generating {n_saved} samples')
130
+ break
131
+ all_img = np.concatenate(all_images, axis=0)
132
+ all_img = all_img[:n_samples]
133
+ shape_str = "x".join([str(x) for x in all_img.shape])
134
+ nppath = os.path.join(nplog, f"{shape_str}-samples.npz")
135
+ np.savez(nppath, all_img)
136
+
137
+ else:
138
+ raise NotImplementedError('Currently only sampling for unconditional models supported.')
139
+
140
+ print(f"sampling of {n_saved} images finished in {(time.time() - tstart) / 60.:.2f} minutes.")
141
+
142
+
143
+ def save_logs(logs, path, n_saved=0, key="sample", np_path=None):
144
+ for k in logs:
145
+ if k == key:
146
+ batch = logs[key]
147
+ if np_path is None:
148
+ for x in batch:
149
+ img = custom_to_pil(x)
150
+ imgpath = os.path.join(path, f"{key}_{n_saved:06}.png")
151
+ img.save(imgpath)
152
+ n_saved += 1
153
+ else:
154
+ npbatch = custom_to_np(batch)
155
+ shape_str = "x".join([str(x) for x in npbatch.shape])
156
+ nppath = os.path.join(np_path, f"{n_saved}-{shape_str}-samples.npz")
157
+ np.savez(nppath, npbatch)
158
+ n_saved += npbatch.shape[0]
159
+ return n_saved
160
+
161
+
162
+ def get_parser():
163
+ parser = argparse.ArgumentParser()
164
+ parser.add_argument(
165
+ "-r",
166
+ "--resume",
167
+ type=str,
168
+ nargs="?",
169
+ help="load from logdir or checkpoint in logdir",
170
+ )
171
+ parser.add_argument(
172
+ "-n",
173
+ "--n_samples",
174
+ type=int,
175
+ nargs="?",
176
+ help="number of samples to draw",
177
+ default=50000
178
+ )
179
+ parser.add_argument(
180
+ "-e",
181
+ "--eta",
182
+ type=float,
183
+ nargs="?",
184
+ help="eta for ddim sampling (0.0 yields deterministic sampling)",
185
+ default=1.0
186
+ )
187
+ parser.add_argument(
188
+ "-v",
189
+ "--vanilla_sample",
190
+ default=False,
191
+ action='store_true',
192
+ help="vanilla sampling (default option is DDIM sampling)?",
193
+ )
194
+ parser.add_argument(
195
+ "-l",
196
+ "--logdir",
197
+ type=str,
198
+ nargs="?",
199
+ help="extra logdir",
200
+ default="none"
201
+ )
202
+ parser.add_argument(
203
+ "-c",
204
+ "--custom_steps",
205
+ type=int,
206
+ nargs="?",
207
+ help="number of steps for ddim and fastdpm sampling",
208
+ default=50
209
+ )
210
+ parser.add_argument(
211
+ "--batch_size",
212
+ type=int,
213
+ nargs="?",
214
+ help="the bs",
215
+ default=10
216
+ )
217
+ return parser
218
+
219
+
220
+ def load_model_from_config(config, sd):
221
+ model = instantiate_from_config(config)
222
+ model.load_state_dict(sd,strict=False)
223
+ model.cuda()
224
+ model.eval()
225
+ return model
226
+
227
+
228
+ def load_model(config, ckpt, gpu, eval_mode):
229
+ if ckpt:
230
+ print(f"Loading model from {ckpt}")
231
+ pl_sd = torch.load(ckpt, map_location="cpu")
232
+ global_step = pl_sd["global_step"]
233
+ else:
234
+ pl_sd = {"state_dict": None}
235
+ global_step = None
236
+ model = load_model_from_config(config.model,
237
+ pl_sd["state_dict"])
238
+
239
+ return model, global_step
240
+
241
+
242
+ if __name__ == "__main__":
243
+ now = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
244
+ sys.path.append(os.getcwd())
245
+ command = " ".join(sys.argv)
246
+
247
+ parser = get_parser()
248
+ opt, unknown = parser.parse_known_args()
249
+ ckpt = None
250
+
251
+ if not os.path.exists(opt.resume):
252
+ raise ValueError("Cannot find {}".format(opt.resume))
253
+ if os.path.isfile(opt.resume):
254
+ # paths = opt.resume.split("/")
255
+ try:
256
+ logdir = '/'.join(opt.resume.split('/')[:-1])
257
+ # idx = len(paths)-paths[::-1].index("logs")+1
258
+ print(f'Logdir is {logdir}')
259
+ except ValueError:
260
+ paths = opt.resume.split("/")
261
+ idx = -2 # take a guess: path/to/logdir/checkpoints/model.ckpt
262
+ logdir = "/".join(paths[:idx])
263
+ ckpt = opt.resume
264
+ else:
265
+ assert os.path.isdir(opt.resume), f"{opt.resume} is not a directory"
266
+ logdir = opt.resume.rstrip("/")
267
+ ckpt = os.path.join(logdir, "model.ckpt")
268
+
269
+ base_configs = sorted(glob.glob(os.path.join(logdir, "config.yaml")))
270
+ opt.base = base_configs
271
+
272
+ configs = [OmegaConf.load(cfg) for cfg in opt.base]
273
+ cli = OmegaConf.from_dotlist(unknown)
274
+ config = OmegaConf.merge(*configs, cli)
275
+
276
+ gpu = True
277
+ eval_mode = True
278
+
279
+ if opt.logdir != "none":
280
+ locallog = logdir.split(os.sep)[-1]
281
+ if locallog == "": locallog = logdir.split(os.sep)[-2]
282
+ print(f"Switching logdir from '{logdir}' to '{os.path.join(opt.logdir, locallog)}'")
283
+ logdir = os.path.join(opt.logdir, locallog)
284
+
285
+ print(config)
286
+
287
+ model, global_step = load_model(config, ckpt, gpu, eval_mode)
288
+ print(f"global step: {global_step}")
289
+ print(75 * "=")
290
+ print("logging to:")
291
+ logdir = os.path.join(logdir, "samples", f"{global_step:08}", now)
292
+ imglogdir = os.path.join(logdir, "img")
293
+ numpylogdir = os.path.join(logdir, "numpy")
294
+
295
+ os.makedirs(imglogdir)
296
+ os.makedirs(numpylogdir)
297
+ print(logdir)
298
+ print(75 * "=")
299
+
300
+ # write config out
301
+ sampling_file = os.path.join(logdir, "sampling_config.yaml")
302
+ sampling_conf = vars(opt)
303
+
304
+ with open(sampling_file, 'w') as f:
305
+ yaml.dump(sampling_conf, f, default_flow_style=False)
306
+ print(sampling_conf)
307
+
308
+
309
+ run(model, imglogdir, eta=opt.eta,
310
+ vanilla=opt.vanilla_sample, n_samples=opt.n_samples, custom_steps=opt.custom_steps,
311
+ batch_size=opt.batch_size, nplog=numpylogdir)
312
+
313
+ print("done.")