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,147 @@
1
+ import os, sys
2
+ import numpy as np
3
+ import scann
4
+ import argparse
5
+ import glob
6
+ from multiprocessing import cpu_count
7
+ from tqdm import tqdm
8
+
9
+ from ldm.util import parallel_data_prefetch
10
+
11
+
12
+ def search_bruteforce(searcher):
13
+ return searcher.score_brute_force().build()
14
+
15
+
16
+ def search_partioned_ah(searcher, dims_per_block, aiq_threshold, reorder_k,
17
+ partioning_trainsize, num_leaves, num_leaves_to_search):
18
+ return searcher.tree(num_leaves=num_leaves,
19
+ num_leaves_to_search=num_leaves_to_search,
20
+ training_sample_size=partioning_trainsize). \
21
+ score_ah(dims_per_block, anisotropic_quantization_threshold=aiq_threshold).reorder(reorder_k).build()
22
+
23
+
24
+ def search_ah(searcher, dims_per_block, aiq_threshold, reorder_k):
25
+ return searcher.score_ah(dims_per_block, anisotropic_quantization_threshold=aiq_threshold).reorder(
26
+ reorder_k).build()
27
+
28
+ def load_datapool(dpath):
29
+
30
+
31
+ def load_single_file(saved_embeddings):
32
+ compressed = np.load(saved_embeddings)
33
+ database = {key: compressed[key] for key in compressed.files}
34
+ return database
35
+
36
+ def load_multi_files(data_archive):
37
+ database = {key: [] for key in data_archive[0].files}
38
+ for d in tqdm(data_archive, desc=f'Loading datapool from {len(data_archive)} individual files.'):
39
+ for key in d.files:
40
+ database[key].append(d[key])
41
+
42
+ return database
43
+
44
+ print(f'Load saved patch embedding from "{dpath}"')
45
+ file_content = glob.glob(os.path.join(dpath, '*.npz'))
46
+
47
+ if len(file_content) == 1:
48
+ data_pool = load_single_file(file_content[0])
49
+ elif len(file_content) > 1:
50
+ data = [np.load(f) for f in file_content]
51
+ prefetched_data = parallel_data_prefetch(load_multi_files, data,
52
+ n_proc=min(len(data), cpu_count()), target_data_type='dict')
53
+
54
+ data_pool = {key: np.concatenate([od[key] for od in prefetched_data], axis=1)[0] for key in prefetched_data[0].keys()}
55
+ else:
56
+ raise ValueError(f'No npz-files in specified path "{dpath}" is this directory existing?')
57
+
58
+ print(f'Finished loading of retrieval database of length {data_pool["embedding"].shape[0]}.')
59
+ return data_pool
60
+
61
+
62
+ def train_searcher(opt,
63
+ metric='dot_product',
64
+ partioning_trainsize=None,
65
+ reorder_k=None,
66
+ # todo tune
67
+ aiq_thld=0.2,
68
+ dims_per_block=2,
69
+ num_leaves=None,
70
+ num_leaves_to_search=None,):
71
+
72
+ data_pool = load_datapool(opt.database)
73
+ k = opt.knn
74
+
75
+ if not reorder_k:
76
+ reorder_k = 2 * k
77
+
78
+ # normalize
79
+ # embeddings =
80
+ searcher = scann.scann_ops_pybind.builder(data_pool['embedding'] / np.linalg.norm(data_pool['embedding'], axis=1)[:, np.newaxis], k, metric)
81
+ pool_size = data_pool['embedding'].shape[0]
82
+
83
+ print(*(['#'] * 100))
84
+ print('Initializing scaNN searcher with the following values:')
85
+ print(f'k: {k}')
86
+ print(f'metric: {metric}')
87
+ print(f'reorder_k: {reorder_k}')
88
+ print(f'anisotropic_quantization_threshold: {aiq_thld}')
89
+ print(f'dims_per_block: {dims_per_block}')
90
+ print(*(['#'] * 100))
91
+ print('Start training searcher....')
92
+ print(f'N samples in pool is {pool_size}')
93
+
94
+ # this reflects the recommended design choices proposed at
95
+ # https://github.com/google-research/google-research/blob/aca5f2e44e301af172590bb8e65711f0c9ee0cfd/scann/docs/algorithms.md
96
+ if pool_size < 2e4:
97
+ print('Using brute force search.')
98
+ searcher = search_bruteforce(searcher)
99
+ elif 2e4 <= pool_size and pool_size < 1e5:
100
+ print('Using asymmetric hashing search and reordering.')
101
+ searcher = search_ah(searcher, dims_per_block, aiq_thld, reorder_k)
102
+ else:
103
+ print('Using using partioning, asymmetric hashing search and reordering.')
104
+
105
+ if not partioning_trainsize:
106
+ partioning_trainsize = data_pool['embedding'].shape[0] // 10
107
+ if not num_leaves:
108
+ num_leaves = int(np.sqrt(pool_size))
109
+
110
+ if not num_leaves_to_search:
111
+ num_leaves_to_search = max(num_leaves // 20, 1)
112
+
113
+ print('Partitioning params:')
114
+ print(f'num_leaves: {num_leaves}')
115
+ print(f'num_leaves_to_search: {num_leaves_to_search}')
116
+ # self.searcher = self.search_ah(searcher, dims_per_block, aiq_thld, reorder_k)
117
+ searcher = search_partioned_ah(searcher, dims_per_block, aiq_thld, reorder_k,
118
+ partioning_trainsize, num_leaves, num_leaves_to_search)
119
+
120
+ print('Finish training searcher')
121
+ searcher_savedir = opt.target_path
122
+ os.makedirs(searcher_savedir, exist_ok=True)
123
+ searcher.serialize(searcher_savedir)
124
+ print(f'Saved trained searcher under "{searcher_savedir}"')
125
+
126
+ if __name__ == '__main__':
127
+ sys.path.append(os.getcwd())
128
+ parser = argparse.ArgumentParser()
129
+ parser.add_argument('--database',
130
+ '-d',
131
+ default='data/rdm/retrieval_databases/openimages',
132
+ type=str,
133
+ help='path to folder containing the clip feature of the database')
134
+ parser.add_argument('--target_path',
135
+ '-t',
136
+ default='data/rdm/searchers/openimages',
137
+ type=str,
138
+ help='path to the target folder where the searcher shall be stored.')
139
+ parser.add_argument('--knn',
140
+ '-k',
141
+ default=20,
142
+ type=int,
143
+ help='number of nearest neighbors, for which the searcher shall be optimized')
144
+
145
+ opt, _ = parser.parse_known_args()
146
+
147
+ train_searcher(opt,)
@@ -0,0 +1,324 @@
1
+ import argparse, os, sys, glob
2
+ import torch
3
+ import numpy as np
4
+ from omegaconf import OmegaConf
5
+ from PIL import Image
6
+ from tqdm import tqdm, trange
7
+ from itertools import islice
8
+ from einops import rearrange
9
+ from torchvision.utils import make_grid
10
+ import time
11
+ from pytorch_lightning import seed_everything
12
+ from torch import autocast
13
+ from contextlib import contextmanager, nullcontext
14
+
15
+ import k_diffusion as K
16
+ import torch.nn as nn
17
+
18
+ from ldm.util import instantiate_from_config
19
+ from ldm.models.diffusion.ddim import DDIMSampler
20
+ from ldm.models.diffusion.plms import PLMSSampler
21
+ from ldm.invoke.devices import choose_torch_device
22
+
23
+ def chunk(it, size):
24
+ it = iter(it)
25
+ return iter(lambda: tuple(islice(it, size)), ())
26
+
27
+
28
+ def load_model_from_config(config, ckpt, verbose=False):
29
+ print(f"Loading model from {ckpt}")
30
+ pl_sd = torch.load(ckpt, map_location="cpu")
31
+ if "global_step" in pl_sd:
32
+ print(f"Global Step: {pl_sd['global_step']}")
33
+ sd = pl_sd["state_dict"]
34
+ model = instantiate_from_config(config.model)
35
+ m, u = model.load_state_dict(sd, strict=False)
36
+ if len(m) > 0 and verbose:
37
+ print("missing keys:")
38
+ print(m)
39
+ if len(u) > 0 and verbose:
40
+ print("unexpected keys:")
41
+ print(u)
42
+
43
+ model.to(choose_torch_device())
44
+ model.eval()
45
+ return model
46
+
47
+
48
+ def main():
49
+ parser = argparse.ArgumentParser()
50
+
51
+ parser.add_argument(
52
+ "--prompt",
53
+ type=str,
54
+ nargs="?",
55
+ default="a painting of a virus monster playing guitar",
56
+ help="the prompt to render"
57
+ )
58
+ parser.add_argument(
59
+ "--outdir",
60
+ type=str,
61
+ nargs="?",
62
+ help="dir to write results to",
63
+ default="outputs/txt2img-samples"
64
+ )
65
+ parser.add_argument(
66
+ "--skip_grid",
67
+ action='store_true',
68
+ help="do not save a grid, only individual samples. Helpful when evaluating lots of samples",
69
+ )
70
+ parser.add_argument(
71
+ "--skip_save",
72
+ action='store_true',
73
+ help="do not save individual samples. For speed measurements.",
74
+ )
75
+ parser.add_argument(
76
+ "--ddim_steps",
77
+ type=int,
78
+ default=50,
79
+ help="number of ddim sampling steps",
80
+ )
81
+ parser.add_argument(
82
+ "--plms",
83
+ action='store_true',
84
+ help="use plms sampling",
85
+ )
86
+ parser.add_argument(
87
+ "--klms",
88
+ action='store_true',
89
+ help="use klms sampling",
90
+ )
91
+ parser.add_argument(
92
+ "--laion400m",
93
+ action='store_true',
94
+ help="uses the LAION400M model",
95
+ )
96
+ parser.add_argument(
97
+ "--fixed_code",
98
+ action='store_true',
99
+ help="if enabled, uses the same starting code across samples ",
100
+ )
101
+ parser.add_argument(
102
+ "--ddim_eta",
103
+ type=float,
104
+ default=0.0,
105
+ help="ddim eta (eta=0.0 corresponds to deterministic sampling",
106
+ )
107
+ parser.add_argument(
108
+ "--n_iter",
109
+ type=int,
110
+ default=2,
111
+ help="sample this often",
112
+ )
113
+ parser.add_argument(
114
+ "--H",
115
+ type=int,
116
+ default=512,
117
+ help="image height, in pixel space",
118
+ )
119
+ parser.add_argument(
120
+ "--W",
121
+ type=int,
122
+ default=512,
123
+ help="image width, in pixel space",
124
+ )
125
+ parser.add_argument(
126
+ "--C",
127
+ type=int,
128
+ default=4,
129
+ help="latent channels",
130
+ )
131
+ parser.add_argument(
132
+ "--f",
133
+ type=int,
134
+ default=8,
135
+ help="downsampling factor",
136
+ )
137
+ parser.add_argument(
138
+ "--n_samples",
139
+ type=int,
140
+ default=3,
141
+ help="how many samples to produce for each given prompt. A.k.a. batch size",
142
+ )
143
+ parser.add_argument(
144
+ "--n_rows",
145
+ type=int,
146
+ default=0,
147
+ help="rows in the grid (default: n_samples)",
148
+ )
149
+ parser.add_argument(
150
+ "--scale",
151
+ type=float,
152
+ default=7.5,
153
+ help="unconditional guidance scale: eps = eps(x, empty) + scale * (eps(x, cond) - eps(x, empty))",
154
+ )
155
+ parser.add_argument(
156
+ "--from-file",
157
+ type=str,
158
+ help="if specified, load prompts from this file",
159
+ )
160
+ parser.add_argument(
161
+ "--config",
162
+ type=str,
163
+ default="configs/stable-diffusion/v1-inference.yaml",
164
+ help="path to config which constructs model",
165
+ )
166
+ parser.add_argument(
167
+ "--ckpt",
168
+ type=str,
169
+ default="models/ldm/stable-diffusion-v1/model.ckpt",
170
+ help="path to checkpoint of model",
171
+ )
172
+ parser.add_argument(
173
+ "--seed",
174
+ type=int,
175
+ default=42,
176
+ help="the seed (for reproducible sampling)",
177
+ )
178
+ parser.add_argument(
179
+ "--precision",
180
+ type=str,
181
+ help="evaluate at this precision",
182
+ choices=["full", "autocast"],
183
+ default="autocast"
184
+ )
185
+ opt = parser.parse_args()
186
+
187
+ if opt.laion400m:
188
+ print("Falling back to LAION 400M model...")
189
+ opt.config = "configs/latent-diffusion/txt2img-1p4B-eval.yaml"
190
+ opt.ckpt = "models/ldm/text2img-large/model.ckpt"
191
+ opt.outdir = "outputs/txt2img-samples-laion400m"
192
+
193
+
194
+ config = OmegaConf.load(f"{opt.config}")
195
+ model = load_model_from_config(config, f"{opt.ckpt}")
196
+
197
+ seed_everything(opt.seed)
198
+
199
+ device = torch.device(choose_torch_device())
200
+ model = model.to(device)
201
+
202
+ #for klms
203
+ model_wrap = K.external.CompVisDenoiser(model)
204
+ class CFGDenoiser(nn.Module):
205
+ def __init__(self, model):
206
+ super().__init__()
207
+ self.inner_model = model
208
+
209
+ def forward(self, x, sigma, uncond, cond, cond_scale):
210
+ x_in = torch.cat([x] * 2)
211
+ sigma_in = torch.cat([sigma] * 2)
212
+ cond_in = torch.cat([uncond, cond])
213
+ uncond, cond = self.inner_model(x_in, sigma_in, cond=cond_in).chunk(2)
214
+ return uncond + (cond - uncond) * cond_scale
215
+
216
+ if opt.plms:
217
+ sampler = PLMSSampler(model)
218
+ else:
219
+ sampler = DDIMSampler(model)
220
+
221
+ os.makedirs(opt.outdir, exist_ok=True)
222
+ outpath = opt.outdir
223
+
224
+ batch_size = opt.n_samples
225
+ n_rows = opt.n_rows if opt.n_rows > 0 else batch_size
226
+ if not opt.from_file:
227
+ prompt = opt.prompt
228
+ assert prompt is not None
229
+ data = [batch_size * [prompt]]
230
+
231
+ else:
232
+ print(f"reading prompts from {opt.from_file}")
233
+ with open(opt.from_file, "r") as f:
234
+ data = f.read().splitlines()
235
+ if (len(data) >= batch_size):
236
+ data = list(chunk(data, batch_size))
237
+ else:
238
+ while (len(data) < batch_size):
239
+ data.append(data[-1])
240
+ data = [data]
241
+
242
+ sample_path = os.path.join(outpath, "samples")
243
+ os.makedirs(sample_path, exist_ok=True)
244
+ base_count = len(os.listdir(sample_path))
245
+ grid_count = len(os.listdir(outpath)) - 1
246
+
247
+ start_code = None
248
+ if opt.fixed_code:
249
+ shape = [opt.n_samples, opt.C, opt.H // opt.f, opt.W // opt.f]
250
+ if device.type == 'mps':
251
+ start_code = torch.randn(shape, device='cpu').to(device)
252
+ else:
253
+ torch.randn(shape, device=device)
254
+
255
+ precision_scope = autocast if opt.precision=="autocast" else nullcontext
256
+ if device.type in ['mps', 'cpu']:
257
+ precision_scope = nullcontext # have to use f32 on mps
258
+ with torch.no_grad():
259
+ with precision_scope(device.type):
260
+ with model.ema_scope():
261
+ tic = time.time()
262
+ all_samples = list()
263
+ for n in trange(opt.n_iter, desc="Sampling"):
264
+ for prompts in tqdm(data, desc="data"):
265
+ uc = None
266
+ if opt.scale != 1.0:
267
+ uc = model.get_learned_conditioning(batch_size * [""])
268
+ if isinstance(prompts, tuple):
269
+ prompts = list(prompts)
270
+ c = model.get_learned_conditioning(prompts)
271
+ shape = [opt.C, opt.H // opt.f, opt.W // opt.f]
272
+
273
+ if not opt.klms:
274
+ samples_ddim, _ = sampler.sample(S=opt.ddim_steps,
275
+ conditioning=c,
276
+ batch_size=opt.n_samples,
277
+ shape=shape,
278
+ verbose=False,
279
+ unconditional_guidance_scale=opt.scale,
280
+ unconditional_conditioning=uc,
281
+ eta=opt.ddim_eta,
282
+ x_T=start_code)
283
+ else:
284
+ sigmas = model_wrap.get_sigmas(opt.ddim_steps)
285
+ if start_code:
286
+ x = start_code
287
+ else:
288
+ x = torch.randn([opt.n_samples, *shape], device=device) * sigmas[0] # for GPU draw
289
+ model_wrap_cfg = CFGDenoiser(model_wrap)
290
+ extra_args = {'cond': c, 'uncond': uc, 'cond_scale': opt.scale}
291
+ samples_ddim = K.sampling.sample_lms(model_wrap_cfg, x, sigmas, extra_args=extra_args)
292
+
293
+ x_samples_ddim = model.decode_first_stage(samples_ddim)
294
+ x_samples_ddim = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0)
295
+
296
+ if not opt.skip_save:
297
+ for x_sample in x_samples_ddim:
298
+ x_sample = 255. * rearrange(x_sample.cpu().numpy(), 'c h w -> h w c')
299
+ Image.fromarray(x_sample.astype(np.uint8)).save(
300
+ os.path.join(sample_path, f"{base_count:05}.png"))
301
+ base_count += 1
302
+
303
+ if not opt.skip_grid:
304
+ all_samples.append(x_samples_ddim)
305
+
306
+ if not opt.skip_grid:
307
+ # additionally, save as grid
308
+ grid = torch.stack(all_samples, 0)
309
+ grid = rearrange(grid, 'n b c h w -> (n b) c h w')
310
+ grid = make_grid(grid, nrow=n_rows)
311
+
312
+ # to image
313
+ grid = 255. * rearrange(grid, 'c h w -> h w c').cpu().numpy()
314
+ Image.fromarray(grid.astype(np.uint8)).save(os.path.join(outpath, f'grid-{grid_count:04}.png'))
315
+ grid_count += 1
316
+
317
+ toc = time.time()
318
+
319
+ print(f"Your samples are ready and waiting for you here: \n{outpath} \n"
320
+ f" \nEnjoy.")
321
+
322
+
323
+ if __name__ == "__main__":
324
+ main()
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env python
2
+ # Copyright (c) 2022 Lincoln D. Stein (https://github.com/lstein)
3
+ # Before running stable-diffusion on an internet-isolated machine,
4
+ # run this script from one with internet connectivity. The
5
+ # two machines must share a common .cache directory.
6
+
7
+ import warnings
8
+ import configure_invokeai
9
+
10
+ if __name__ == '__main__':
11
+ configure_invokeai.main()
12
+
scripts/sd-metadata.py ADDED
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env python
2
+
3
+ import sys
4
+ import json
5
+ from ldm.invoke.pngwriter import retrieve_metadata
6
+
7
+ if len(sys.argv) < 2:
8
+ print("Usage: file2prompt.py <file1.png> <file2.png> <file3.png>...")
9
+ print("This script opens up the indicated invoke.py-generated PNG file(s) and prints out their metadata.")
10
+ exit(-1)
11
+
12
+ filenames = sys.argv[1:]
13
+ for f in filenames:
14
+ try:
15
+ metadata = retrieve_metadata(f)
16
+ print(f'{f}:\n',json.dumps(metadata['sd-metadata'], indent=4))
17
+ except FileNotFoundError:
18
+ sys.stderr.write(f'{f} not found\n')
19
+ continue
20
+ except PermissionError:
21
+ sys.stderr.write(f'{f} could not be opened due to inadequate permissions\n')
22
+ continue
@@ -0,0 +1 @@
1
+ from .clip import *