LiruiZhao commited on
Commit
2d0e22d
1 Parent(s): 85f5071
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. app.py +370 -125
  2. checkpoints/epoch=000041-step=000010999.ckpt +3 -0
  3. stable_diffusion/LICENSE +82 -0
  4. stable_diffusion/README.md +215 -0
  5. stable_diffusion/Stable_Diffusion_v1_Model_Card.md +144 -0
  6. stable_diffusion/assets/a-painting-of-a-fire.png +0 -0
  7. stable_diffusion/assets/a-photograph-of-a-fire.png +0 -0
  8. stable_diffusion/assets/a-shirt-with-a-fire-printed-on-it.png +0 -0
  9. stable_diffusion/assets/a-shirt-with-the-inscription-'fire'.png +0 -0
  10. stable_diffusion/assets/a-watercolor-painting-of-a-fire.png +0 -0
  11. stable_diffusion/assets/birdhouse.png +0 -0
  12. stable_diffusion/assets/fire.png +0 -0
  13. stable_diffusion/assets/inpainting.png +0 -0
  14. stable_diffusion/assets/modelfigure.png +0 -0
  15. stable_diffusion/assets/rdm-preview.jpg +0 -0
  16. stable_diffusion/assets/reconstruction1.png +0 -0
  17. stable_diffusion/assets/reconstruction2.png +0 -0
  18. stable_diffusion/assets/results.gif.REMOVED.git-id +1 -0
  19. stable_diffusion/assets/rick.jpeg +0 -0
  20. stable_diffusion/assets/stable-samples/img2img/mountains-1.png +0 -0
  21. stable_diffusion/assets/stable-samples/img2img/mountains-2.png +0 -0
  22. stable_diffusion/assets/stable-samples/img2img/mountains-3.png +0 -0
  23. stable_diffusion/assets/stable-samples/img2img/sketch-mountains-input.jpg +0 -0
  24. stable_diffusion/assets/stable-samples/img2img/upscaling-in.png.REMOVED.git-id +1 -0
  25. stable_diffusion/assets/stable-samples/img2img/upscaling-out.png.REMOVED.git-id +1 -0
  26. stable_diffusion/assets/stable-samples/txt2img/000002025.png +0 -0
  27. stable_diffusion/assets/stable-samples/txt2img/000002035.png +0 -0
  28. stable_diffusion/assets/stable-samples/txt2img/merged-0005.png.REMOVED.git-id +1 -0
  29. stable_diffusion/assets/stable-samples/txt2img/merged-0006.png.REMOVED.git-id +1 -0
  30. stable_diffusion/assets/stable-samples/txt2img/merged-0007.png.REMOVED.git-id +1 -0
  31. stable_diffusion/assets/the-earth-is-on-fire,-oil-on-canvas.png +0 -0
  32. stable_diffusion/assets/txt2img-convsample.png +0 -0
  33. stable_diffusion/assets/txt2img-preview.png.REMOVED.git-id +1 -0
  34. stable_diffusion/assets/v1-variants-scores.jpg +0 -0
  35. stable_diffusion/configs/autoencoder/autoencoder_kl_16x16x16.yaml +54 -0
  36. stable_diffusion/configs/autoencoder/autoencoder_kl_32x32x4.yaml +53 -0
  37. stable_diffusion/configs/autoencoder/autoencoder_kl_64x64x3.yaml +54 -0
  38. stable_diffusion/configs/autoencoder/autoencoder_kl_8x8x64.yaml +53 -0
  39. stable_diffusion/configs/latent-diffusion/celebahq-ldm-vq-4.yaml +86 -0
  40. stable_diffusion/configs/latent-diffusion/cin-ldm-vq-f8.yaml +98 -0
  41. stable_diffusion/configs/latent-diffusion/cin256-v2.yaml +68 -0
  42. stable_diffusion/configs/latent-diffusion/ffhq-ldm-vq-4.yaml +85 -0
  43. stable_diffusion/configs/latent-diffusion/lsun_bedrooms-ldm-vq-4.yaml +85 -0
  44. stable_diffusion/configs/latent-diffusion/lsun_churches-ldm-kl-8.yaml +91 -0
  45. stable_diffusion/configs/latent-diffusion/txt2img-1p4B-eval.yaml +71 -0
  46. stable_diffusion/configs/retrieval-augmented-diffusion/768x768.yaml +68 -0
  47. stable_diffusion/configs/stable-diffusion/v1-inference.yaml +70 -0
  48. stable_diffusion/data/DejaVuSans.ttf +0 -0
  49. stable_diffusion/data/example_conditioning/superresolution/sample_0.jpg +0 -0
  50. stable_diffusion/data/example_conditioning/text_conditional/sample_0.txt +1 -0
app.py CHANGED
@@ -1,146 +1,391 @@
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
 
2
  import numpy as np
3
- import random
4
- from diffusers import DiffusionPipeline
5
  import torch
 
 
 
 
 
 
 
6
 
7
- device = "cuda" if torch.cuda.is_available() else "cpu"
8
 
9
- if torch.cuda.is_available():
10
- torch.cuda.max_memory_allocated(device=device)
11
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
12
- pipe.enable_xformers_memory_efficient_attention()
13
- pipe = pipe.to(device)
14
- else:
15
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", use_safetensors=True)
16
- pipe = pipe.to(device)
17
 
18
- MAX_SEED = np.iinfo(np.int32).max
19
- MAX_IMAGE_SIZE = 1024
 
 
20
 
21
- def infer(prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
- if randomize_seed:
24
- seed = random.randint(0, MAX_SEED)
25
-
26
- generator = torch.Generator().manual_seed(seed)
27
-
28
- image = pipe(
29
- prompt = prompt,
30
- negative_prompt = negative_prompt,
31
- guidance_scale = guidance_scale,
32
- num_inference_steps = num_inference_steps,
33
- width = width,
34
- height = height,
35
- generator = generator
36
- ).images[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
- return image
39
-
40
- examples = [
41
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
42
- "An astronaut riding a green horse",
43
- "A delicious ceviche cheesecake slice",
44
- ]
45
-
46
- css="""
47
- #col-container {
48
- margin: 0 auto;
49
- max-width: 520px;
50
- }
51
- """
52
-
53
- if torch.cuda.is_available():
54
- power_device = "GPU"
55
- else:
56
- power_device = "CPU"
57
-
58
- with gr.Blocks(css=css) as demo:
59
 
60
- with gr.Column(elem_id="col-container"):
61
- gr.Markdown(f"""
62
- # Text-to-Image Gradio Template
63
- Currently running on {power_device}.
64
- """)
65
 
66
- with gr.Row():
67
-
68
- prompt = gr.Text(
69
- label="Prompt",
70
- show_label=False,
71
- max_lines=1,
72
- placeholder="Enter your prompt",
73
- container=False,
74
- )
75
-
76
- run_button = gr.Button("Run", scale=0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
- result = gr.Image(label="Result", show_label=False)
79
-
80
- with gr.Accordion("Advanced Settings", open=False):
81
-
82
- negative_prompt = gr.Text(
83
- label="Negative prompt",
84
- max_lines=1,
85
- placeholder="Enter a negative prompt",
86
- visible=False,
87
- )
88
-
89
- seed = gr.Slider(
90
- label="Seed",
91
- minimum=0,
92
- maximum=MAX_SEED,
93
- step=1,
94
- value=0,
95
- )
96
-
97
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
98
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  with gr.Row():
100
-
101
- width = gr.Slider(
102
- label="Width",
103
- minimum=256,
104
- maximum=MAX_IMAGE_SIZE,
105
- step=32,
106
- value=512,
107
- )
108
-
109
- height = gr.Slider(
110
- label="Height",
111
- minimum=256,
112
- maximum=MAX_IMAGE_SIZE,
113
- step=32,
114
- value=512,
115
- )
116
-
117
  with gr.Row():
118
-
119
- guidance_scale = gr.Slider(
120
- label="Guidance scale",
121
- minimum=0.0,
122
- maximum=10.0,
123
- step=0.1,
124
- value=0.0,
 
125
  )
126
-
127
- num_inference_steps = gr.Slider(
128
- label="Number of inference steps",
129
- minimum=1,
130
- maximum=12,
131
- step=1,
132
- value=2,
 
133
  )
134
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  gr.Examples(
136
- examples = examples,
137
- inputs = [prompt]
 
 
 
138
  )
139
-
140
- run_button.click(
141
- fn = infer,
142
- inputs = [prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
143
- outputs = [result]
 
 
 
 
 
 
 
 
 
144
  )
 
 
 
 
 
 
 
 
 
 
145
 
146
  demo.queue().launch()
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import random
5
+ import sys
6
+ from argparse import ArgumentParser
7
+
8
+ from tqdm.auto import trange
9
+ import einops
10
  import gradio as gr
11
+ import k_diffusion as K
12
  import numpy as np
 
 
13
  import torch
14
+ import torch.nn as nn
15
+ from einops import rearrange
16
+ from omegaconf import OmegaConf
17
+ from PIL import Image, ImageOps, ImageFilter
18
+ from torch import autocast
19
+ import cv2
20
+ import imageio
21
 
22
+ sys.path.append("./stable_diffusion")
23
 
24
+ from stable_diffusion.ldm.util import instantiate_from_config
 
 
 
 
 
 
 
25
 
26
+ class CFGDenoiser(nn.Module):
27
+ def __init__(self, model):
28
+ super().__init__()
29
+ self.inner_model = model
30
 
31
+ def forward(self, z_0, z_1, sigma, cond, uncond, text_cfg_scale, image_cfg_scale):
32
+ cfg_z_0 = einops.repeat(z_0, "1 ... -> n ...", n=3)
33
+ cfg_z_1 = einops.repeat(z_1, "1 ... -> n ...", n=3)
34
+ cfg_sigma = einops.repeat(sigma, "1 ... -> n ...", n=3)
35
+ cfg_cond = {
36
+ "c_crossattn": [torch.cat([cond["c_crossattn"][0], uncond["c_crossattn"][0], uncond["c_crossattn"][0]])],
37
+ "c_concat": [torch.cat([cond["c_concat"][0], cond["c_concat"][0], uncond["c_concat"][0]])],
38
+ }
39
+ output_0, output_1 = self.inner_model(cfg_z_0, cfg_z_1, cfg_sigma, cond=cfg_cond)
40
+ out_cond_0, out_img_cond_0, out_uncond_0 = output_0.chunk(3)
41
+ out_cond_1, _, _ = output_1.chunk(3)
42
+ return out_uncond_0 + text_cfg_scale * (out_cond_0 - out_img_cond_0) + image_cfg_scale * (out_img_cond_0 - out_uncond_0), \
43
+ out_cond_1
44
 
45
+ def load_model_from_config(config, ckpt, vae_ckpt=None, verbose=False):
46
+ print(f"Loading model from {ckpt}")
47
+ pl_sd = torch.load(ckpt, map_location="cpu")
48
+ if "global_step" in pl_sd:
49
+ print(f"Global Step: {pl_sd['global_step']}")
50
+ sd = pl_sd["state_dict"]
51
+ if vae_ckpt is not None:
52
+ print(f"Loading VAE from {vae_ckpt}")
53
+ vae_sd = torch.load(vae_ckpt, map_location="cpu")["state_dict"]
54
+ sd = {
55
+ k: vae_sd[k[len("first_stage_model.") :]] if k.startswith("first_stage_model.") else v
56
+ for k, v in sd.items()
57
+ }
58
+ model = instantiate_from_config(config.model)
59
+ m, u = model.load_state_dict(sd, strict=True)
60
+ if len(m) > 0 and verbose:
61
+ print("missing keys:")
62
+ print(m)
63
+ if len(u) > 0 and verbose:
64
+ print("unexpected keys:")
65
+ print(u)
66
+ return model
67
+
68
+ def append_dims(x, target_dims):
69
+ """Appends dimensions to the end of a tensor until it has target_dims dimensions."""
70
+ dims_to_append = target_dims - x.ndim
71
+ if dims_to_append < 0:
72
+ raise ValueError(f'input has {x.ndim} dims but target_dims is {target_dims}, which is less')
73
+ return x[(...,) + (None,) * dims_to_append]
74
+
75
+ class CompVisDenoiser(K.external.CompVisDenoiser):
76
+ def __init__(self, model, quantize=False, device='cpu'):
77
+ super().__init__( model, quantize, device)
78
 
79
+ def get_eps(self, *args, **kwargs):
80
+ return self.inner_model.apply_model(*args, **kwargs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
+ def forward(self, input_0, input_1, sigma, **kwargs):
83
+ c_out, c_in = [append_dims(x, input_0.ndim) for x in self.get_scalings(sigma)]
84
+ # eps_0, eps_1 = self.get_eps(input_0 * c_in, input_1 * c_in, self.sigma_to_t(sigma), **kwargs)
85
+ eps_0, eps_1 = self.get_eps(input_0 * c_in, self.sigma_to_t(sigma), **kwargs)
 
86
 
87
+ return input_0 + eps_0 * c_out, eps_1
88
+
89
+ def to_d(x, sigma, denoised):
90
+ """Converts a denoiser output to a Karras ODE derivative."""
91
+ return (x - denoised) / append_dims(sigma, x.ndim)
92
+
93
+ def default_noise_sampler(x):
94
+ return lambda sigma, sigma_next: torch.randn_like(x)
95
+
96
+ def get_ancestral_step(sigma_from, sigma_to, eta=1.):
97
+ """Calculates the noise level (sigma_down) to step down to and the amount
98
+ of noise to add (sigma_up) when doing an ancestral sampling step."""
99
+ if not eta:
100
+ return sigma_to, 0.
101
+ sigma_up = min(sigma_to, eta * (sigma_to ** 2 * (sigma_from ** 2 - sigma_to ** 2) / sigma_from ** 2) ** 0.5)
102
+ sigma_down = (sigma_to ** 2 - sigma_up ** 2) ** 0.5
103
+ return sigma_down, sigma_up
104
+
105
+ def decode_mask(mask, height = 256, width = 256):
106
+ mask = nn.functional.interpolate(mask, size=(height, width), mode="bilinear", align_corners=False)
107
+ mask = torch.where(mask > 0, 1, -1) # Thresholding step
108
+ mask = torch.clamp((mask + 1.0) / 2.0, min=0.0, max=1.0)
109
+ mask = 255.0 * rearrange(mask, "1 c h w -> h w c")
110
+ mask = torch.cat([mask, mask, mask], dim=-1)
111
+ mask = mask.type(torch.uint8).cpu().numpy()
112
+ return mask
113
+
114
+ @torch.no_grad()
115
+ def sample_euler_ancestral(model, x_0, x_1, sigmas, height, width, extra_args=None, disable=None, eta=1., s_noise=1., noise_sampler=None):
116
+ """Ancestral sampling with Euler method steps."""
117
+ extra_args = {} if extra_args is None else extra_args
118
+ noise_sampler = default_noise_sampler(x_0) if noise_sampler is None else noise_sampler
119
+ s_in = x_0.new_ones([x_0.shape[0]])
120
+
121
+ mask_list = []
122
+ image_list = []
123
+ for i in trange(len(sigmas) - 1, disable=disable):
124
+ denoised_0, denoised_1 = model(x_0, x_1, sigmas[i] * s_in, **extra_args)
125
+ image_list.append(denoised_0)
126
+
127
+ sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta)
128
+ d_0 = to_d(x_0, sigmas[i], denoised_0)
129
+
130
+ # Euler method
131
+ dt = sigma_down - sigmas[i]
132
+ x_0 = x_0 + d_0 * dt
133
+
134
+ if sigmas[i + 1] > 0:
135
+ x_0 = x_0 + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up
136
+
137
+ x_1 = denoised_1
138
+ mask_list.append(decode_mask(x_1, height, width))
139
+
140
+ image_list = torch.cat(image_list, dim=0)
141
+
142
+ return x_0, x_1, image_list, mask_list
143
+
144
+ parser = ArgumentParser()
145
+ parser.add_argument("--resolution", default=512, type=int)
146
+ parser.add_argument("--config", default="configs/generate_diffree.yaml", type=str)
147
+ parser.add_argument("--ckpt", default="checkpoints/epoch=000041-step=000010999.ckpt", type=str)
148
+ parser.add_argument("--vae-ckpt", default=None, type=str)
149
+ args = parser.parse_args()
150
+
151
+ config = OmegaConf.load(args.config)
152
+ model = load_model_from_config(config, args.ckpt, args.vae_ckpt)
153
+ model.eval().cuda()
154
+ model_wrap = CompVisDenoiser(model)
155
+ model_wrap_cfg = CFGDenoiser(model_wrap)
156
+ null_token = model.get_learned_conditioning([""])
157
+
158
+ def generate(
159
+ input_image: Image.Image,
160
+ instruction: str,
161
+ steps: int,
162
+ randomize_seed: bool,
163
+ seed: int,
164
+ randomize_cfg: bool,
165
+ text_cfg_scale: float,
166
+ image_cfg_scale: float,
167
+ ):
168
+ seed = random.randint(0, 100000) if randomize_seed else seed
169
+ text_cfg_scale = round(random.uniform(6.0, 9.0), ndigits=2) if randomize_cfg else text_cfg_scale
170
+ image_cfg_scale = round(random.uniform(1.2, 1.8), ndigits=2) if randomize_cfg else image_cfg_scale
171
+
172
+ width, height = input_image.size
173
+ factor = args.resolution / max(width, height)
174
+ factor = math.ceil(min(width, height) * factor / 64) * 64 / min(width, height)
175
+ width = int((width * factor) // 64) * 64
176
+ height = int((height * factor) // 64) * 64
177
+ input_image = ImageOps.fit(input_image, (width, height), method=Image.Resampling.LANCZOS)
178
+ input_image_copy = input_image.convert("RGB")
179
+
180
+ if instruction == "":
181
+ return [input_image, seed]
182
+
183
+ with torch.no_grad(), autocast("cuda"), model.ema_scope():
184
+ cond = {}
185
+ cond["c_crossattn"] = [model.get_learned_conditioning([instruction])]
186
+ input_image = 2 * torch.tensor(np.array(input_image)).float() / 255 - 1
187
+ input_image = rearrange(input_image, "h w c -> 1 c h w").to(model.device)
188
+ cond["c_concat"] = [model.encode_first_stage(input_image).mode()]
189
+
190
+ uncond = {}
191
+ uncond["c_crossattn"] = [null_token]
192
+ uncond["c_concat"] = [torch.zeros_like(cond["c_concat"][0])]
193
+
194
+ sigmas = model_wrap.get_sigmas(steps)
195
+
196
+ extra_args = {
197
+ "cond": cond,
198
+ "uncond": uncond,
199
+ "text_cfg_scale": text_cfg_scale,
200
+ "image_cfg_scale": image_cfg_scale,
201
+ }
202
+ torch.manual_seed(seed)
203
+ z_0 = torch.randn_like(cond["c_concat"][0]) * sigmas[0]
204
+ z_1 = torch.randn_like(cond["c_concat"][0]) * sigmas[0]
205
+
206
+ z_0, z_1, image_list, mask_list = sample_euler_ancestral(model_wrap_cfg, z_0, z_1, sigmas, height, width, extra_args=extra_args)
207
+
208
+ x_0 = model.decode_first_stage(z_0)
209
+
210
+ if model.first_stage_downsample:
211
+ x_1 = nn.functional.interpolate(z_1, size=(height, width), mode="bilinear", align_corners=False)
212
+ x_1 = torch.where(x_1 > 0, 1, -1) # Thresholding step
213
+ else:
214
+ x_1 = model.decode_first_stage(z_1)
215
+
216
+ x_0 = torch.clamp((x_0 + 1.0) / 2.0, min=0.0, max=1.0)
217
+ x_1 = torch.clamp((x_1 + 1.0) / 2.0, min=0.0, max=1.0)
218
+ x_0 = 255.0 * rearrange(x_0, "1 c h w -> h w c")
219
+ x_1 = 255.0 * rearrange(x_1, "1 c h w -> h w c")
220
+ x_1 = torch.cat([x_1, x_1, x_1], dim=-1)
221
+ edited_image = Image.fromarray(x_0.type(torch.uint8).cpu().numpy())
222
+ edited_mask = Image.fromarray(x_1.type(torch.uint8).cpu().numpy())
223
+
224
+
225
+ image_video = []
226
+
227
+ batch_size = 50
228
+ for i in range(0, len(image_list), batch_size):
229
+ if i + batch_size < len(image_list):
230
+ tmp_image_list = image_list[i:i+batch_size]
231
+ else:
232
+ tmp_image_list = image_list[i:]
233
+ tmp_image_list = model.decode_first_stage(tmp_image_list)
234
+ tmp_image_list = torch.clamp((tmp_image_list + 1.0) / 2.0, min=0.0, max=1.0)
235
+ tmp_image_list = 255.0 * rearrange(tmp_image_list, "b c h w -> b h w c")
236
+ tmp_image_list = tmp_image_list.type(torch.uint8).cpu().numpy()
237
+ # image list to image
238
+ for image in tmp_image_list:
239
+ image_video.append(image)
240
+
241
 
242
+ # for i,image in enumerate(mask_list):
243
+ # Image.fromarray(image).save(f"test/mask_{i}.png")
244
+
245
+ image_video_path = "image.mp4"
246
+ fps = 30
247
+ with imageio.get_writer(image_video_path, fps=fps) as video:
248
+ for image in image_video:
249
+ video.append_data(image)
250
+
251
+
252
+ # 对edited_mask做膨胀
253
+
254
+ edited_mask_copy = edited_mask.copy()
255
+ kernel = np.ones((3, 3), np.uint8)
256
+ edited_mask = cv2.dilate(np.array(edited_mask), kernel, iterations=3)
257
+ edited_mask = Image.fromarray(edited_mask)
258
+
259
+
260
+ m_img = edited_mask.filter(ImageFilter.GaussianBlur(radius=3))
261
+ m_img = np.asarray(m_img).astype('float') / 255.0
262
+ img_np = np.asarray(input_image_copy).astype('float') / 255.0
263
+ ours_np = np.asarray(edited_image).astype('float') / 255.0
264
+
265
+ mix_image_np = m_img * ours_np + (1 - m_img) * img_np
266
+ mix_image = Image.fromarray((mix_image_np * 255).astype(np.uint8)).convert('RGB')
267
+
268
+
269
+ red = np.array(mix_image).astype('float') * 1
270
+ red[:, :, 0] = 180.0
271
+ red[:, :, 2] = 0
272
+ red[:, :, 1] = 0
273
+ mix_result_with_red_mask = np.array(mix_image)
274
+ mix_result_with_red_mask = Image.fromarray(
275
+ (mix_result_with_red_mask.astype('float') * (1 - m_img.astype('float') / 2.0) +
276
+ m_img.astype('float') / 2.0 * red).astype('uint8'))
277
+
278
+
279
+
280
+ mask_video_path = "mask.mp4"
281
+ fps = 30
282
+ with imageio.get_writer(mask_video_path, fps=fps) as video:
283
+ for image in mask_list:
284
+ video.append_data(image)
285
+
286
+ return [int(seed), text_cfg_scale, image_cfg_scale, edited_image, mix_image, edited_mask_copy, mask_video_path, image_video_path, input_image_copy, mix_result_with_red_mask]
287
+
288
+ def reset():
289
+ return [100, "Randomize Seed", 1372, "Fix CFG", 7.5, 1.5, None, None, None, None, None, None, None]
290
+
291
+ def get_example():
292
+ return [
293
+ ["test/dufu.png", "sunglasses", 100, "Fix Seed", 1372, "Fix CFG", 7.5, 1.5],
294
+ ["test/dufu.png", "black and white suit", 100, "Fix Seed", 1372, "Fix CFG", 7.5, 1.5],
295
+ ["test/dufu.png", "blue medical mask", 100, "Fix Seed", 1372, "Fix CFG", 7.5, 1.5],
296
+ ["test/girl.jpeg", "diamond necklace", 100, "Fix Seed", 1372, "Fix CFG", 7.5, 1.5],
297
+ ["test/girl.jpeg", "shiny golden crown", 100, "Fix Seed", 1372, "Fix CFG", 7.5, 1.5],
298
+ ["test/girl.jpeg", "swimming duckling", 100, "Fix Seed", 1372, "Fix CFG", 7.5, 1.5],
299
+ ["test/girl.jpeg", "reflective sunglasses", 100, "Fix Seed", 1372, "Fix CFG", 7.5, 1.5],
300
+ ["test/girl.jpeg", "the queen's crown", 100, "Fix Seed", 1372, "Fix CFG", 7.5, 1.5],
301
+ ["test/girl.jpeg", "gorgeous yellow gown", 100, "Fix Seed", 1372, "Fix CFG", 7.5, 1.5],
302
+ ["test/iron_man.jpg", "sunglasses", 100, "Fix Seed", 1372, "Fix CFG", 7.5, 1.5]
303
+ ]
304
+
305
+ with gr.Blocks(css="footer {visibility: hidden}") as demo:
306
+ with gr.Row():
307
+ gr.Markdown(
308
+ "<div align='center'><font size='14'>Diffree: Text-Guided Shape Free Object Inpainting with Diffusion Model</font></div>" # noqa
309
+ )
310
+
311
+ with gr.Row():
312
+ with gr.Column(scale=1, min_width=100):
313
  with gr.Row():
314
+ input_image = gr.Image(label="Input Image", type="pil", interactive=True)
315
+ with gr.Row():
316
+ instruction = gr.Textbox(lines=1, label="Object description", interactive=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
317
  with gr.Row():
318
+ steps = gr.Number(value=100, precision=0, label="Steps", interactive=True)
319
+ randomize_seed = gr.Radio(
320
+ ["Fix Seed", "Randomize Seed"],
321
+ value="Randomize Seed",
322
+ type="index",
323
+ label="Seed Selection",
324
+ show_label=False,
325
+ interactive=True,
326
  )
327
+ seed = gr.Number(value=1372, precision=0, label="Seed", interactive=True)
328
+ randomize_cfg = gr.Radio(
329
+ ["Fix CFG", "Randomize CFG"],
330
+ value="Fix CFG",
331
+ type="index",
332
+ label="CFG Selection",
333
+ show_label=False,
334
+ interactive=True,
335
  )
336
+ text_cfg_scale = gr.Number(value=7.5, label=f"Text CFG", interactive=True)
337
+ image_cfg_scale = gr.Number(value=1.5, label=f"Image CFG", interactive=True)
338
+ with gr.Row():
339
+ generate_button = gr.Button("Generate")
340
+ reset_button = gr.Button("Reset")
341
+ with gr.Column(scale=1, min_width=100):
342
+ with gr.Column():
343
+ mix_image = gr.Image(label=f"Mix Image", type="pil", interactive=False)
344
+ with gr.Column():
345
+ edited_mask = gr.Image(label=f"Output Mask", type="pil", interactive=False)
346
+
347
+
348
+ with gr.Accordion('More outputs', open=False):
349
+ with gr.Row():
350
+ image_video = gr.Video(label="Real-time Image Output")
351
+ mask_video = gr.Video(label="Real-time Mask Output")
352
+ with gr.Row():
353
+ original_image = gr.Image(label=f"Original Image", type="pil", interactive=False)
354
+ edited_image = gr.Image(label=f"Output Image", type="pil", interactive=False)
355
+ mix_result_with_red_mask = gr.Image(label=f"Mix Image With Red Mask", type="pil", interactive=False)
356
+
357
+ with gr.Row():
358
  gr.Examples(
359
+ examples=get_example(),
360
+ fn=generate,
361
+ inputs=[input_image, instruction, steps, randomize_seed, seed, randomize_cfg, text_cfg_scale, image_cfg_scale],
362
+ outputs=[seed, text_cfg_scale, image_cfg_scale, edited_image, mix_image, edited_mask, mask_video, image_video, original_image, mix_result_with_red_mask],
363
+ cache_examples=True,
364
  )
365
+
366
+ generate_button.click(
367
+ fn=generate,
368
+ inputs=[
369
+ input_image,
370
+ instruction,
371
+ steps,
372
+ randomize_seed,
373
+ seed,
374
+ randomize_cfg,
375
+ text_cfg_scale,
376
+ image_cfg_scale,
377
+ ],
378
+ outputs=[seed, text_cfg_scale, image_cfg_scale, edited_image, mix_image, edited_mask, mask_video, image_video, original_image, mix_result_with_red_mask],
379
  )
380
+ reset_button.click(
381
+ fn=reset,
382
+ inputs=[],
383
+ outputs=[steps, randomize_seed, seed, randomize_cfg, text_cfg_scale, image_cfg_scale, edited_image, mix_image, edited_mask, mask_video, image_video, original_image, mix_result_with_red_mask],
384
+ )
385
+
386
+
387
+ # demo.queue(concurrency_count=1)
388
+ # demo.launch(share=True)
389
+
390
 
391
  demo.queue().launch()
checkpoints/epoch=000041-step=000010999.ckpt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d1147206d6dc17d94d2e1651231a4a9654a6e5b30fa920ec6cfa15964fa0d1b9
3
+ size 7720451618
stable_diffusion/LICENSE ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2022 Robin Rombach and Patrick Esser and contributors
2
+
3
+ CreativeML Open RAIL-M
4
+ dated August 22, 2022
5
+
6
+ Section I: PREAMBLE
7
+
8
+ Multimodal generative models are being widely adopted and used, and have the potential to transform the way artists, among other individuals, conceive and benefit from AI or ML technologies as a tool for content creation.
9
+
10
+ Notwithstanding the current and potential benefits that these artifacts can bring to society at large, there are also concerns about potential misuses of them, either due to their technical limitations or ethical considerations.
11
+
12
+ In short, this license strives for both the open and responsible downstream use of the accompanying model. When it comes to the open character, we took inspiration from open source permissive licenses regarding the grant of IP rights. Referring to the downstream responsible use, we added use-based restrictions not permitting the use of the Model in very specific scenarios, in order for the licensor to be able to enforce the license in case potential misuses of the Model may occur. At the same time, we strive to promote open and responsible research on generative models for art and content generation.
13
+
14
+ Even though downstream derivative versions of the model could be released under different licensing terms, the latter will always have to include - at minimum - the same use-based restrictions as the ones in the original license (this license). We believe in the intersection between open and responsible AI development; thus, this License aims to strike a balance between both in order to enable responsible open-science in the field of AI.
15
+
16
+ This License governs the use of the model (and its derivatives) and is informed by the model card associated with the model.
17
+
18
+ NOW THEREFORE, You and Licensor agree as follows:
19
+
20
+ 1. Definitions
21
+
22
+ - "License" means the terms and conditions for use, reproduction, and Distribution as defined in this document.
23
+ - "Data" means a collection of information and/or content extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License.
24
+ - "Output" means the results of operating a Model as embodied in informational content resulting therefrom.
25
+ - "Model" means any accompanying machine-learning based assemblies (including checkpoints), consisting of learnt weights, parameters (including optimizer states), corresponding to the model architecture as embodied in the Complementary Material, that have been trained or tuned, in whole or in part on the Data, using the Complementary Material.
26
+ - "Derivatives of the Model" means all modifications to the Model, works based on the Model, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of the Model, to the other model, in order to cause the other model to perform similarly to the Model, including - but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by the Model for training the other model.
27
+ - "Complementary Material" means the accompanying source code and scripts used to define, run, load, benchmark or evaluate the Model, and used to prepare data for training or evaluation, if any. This includes any accompanying documentation, tutorials, examples, etc, if any.
28
+ - "Distribution" means any transmission, reproduction, publication or other sharing of the Model or Derivatives of the Model to a third party, including providing the Model as a hosted service made available by electronic or other remote means - e.g. API-based or web access.
29
+ - "Licensor" means the copyright owner or entity authorized by the copyright owner that is granting the License, including the persons or entities that may have rights in the Model and/or distributing the Model.
30
+ - "You" (or "Your") means an individual or Legal Entity exercising permissions granted by this License and/or making use of the Model for whichever purpose and in any field of use, including usage of the Model in an end-use application - e.g. chatbot, translator, image generator.
31
+ - "Third Parties" means individuals or legal entities that are not under common control with Licensor or You.
32
+ - "Contribution" means any work of authorship, including the original version of the Model and any modifications or additions to that Model or Derivatives of the Model thereof, that is intentionally submitted to Licensor for inclusion in the Model by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Model, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
33
+ - "Contributor" means Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Model.
34
+
35
+ Section II: INTELLECTUAL PROPERTY RIGHTS
36
+
37
+ Both copyright and patent grants apply to the Model, Derivatives of the Model and Complementary Material. The Model and Derivatives of the Model are subject to additional terms as described in Section III.
38
+
39
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare, publicly display, publicly perform, sublicense, and distribute the Complementary Material, the Model, and Derivatives of the Model.
40
+ 3. Grant of Patent License. Subject to the terms and conditions of this License and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this paragraph) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model and the Complementary Material, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Model to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model and/or Complementary Material or a Contribution incorporated within the Model and/or Complementary Material constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for the Model and/or Work shall terminate as of the date such litigation is asserted or filed.
41
+
42
+ Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION
43
+
44
+ 4. Distribution and Redistribution. You may host for Third Party remote access purposes (e.g. software-as-a-service), reproduce and distribute copies of the Model or Derivatives of the Model thereof in any medium, with or without modifications, provided that You meet the following conditions:
45
+ Use-based restrictions as referenced in paragraph 5 MUST be included as an enforceable provision by You in any type of legal agreement (e.g. a license) governing the use and/or distribution of the Model or Derivatives of the Model, and You shall give notice to subsequent users You Distribute to, that the Model or Derivatives of the Model are subject to paragraph 5. This provision does not apply to the use of Complementary Material.
46
+ You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License;
47
+ You must cause any modified files to carry prominent notices stating that You changed the files;
48
+ You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of the Model, Derivatives of the Model.
49
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions - respecting paragraph 4.a. - for use, reproduction, or Distribution of Your modifications, or for any such Derivatives of the Model as a whole, provided Your use, reproduction, and Distribution of the Model otherwise complies with the conditions stated in this License.
50
+ 5. Use-based restrictions. The restrictions set forth in Attachment A are considered Use-based restrictions. Therefore You cannot use the Model and the Derivatives of the Model for the specified restricted uses. You may use the Model subject to this License, including only for lawful purposes and in accordance with the License. Use may include creating any content with, finetuning, updating, running, training, evaluating and/or reparametrizing the Model. You shall require all of Your users who use the Model or a Derivative of the Model to comply with the terms of this paragraph (paragraph 5).
51
+ 6. The Output You Generate. Except as set forth herein, Licensor claims no rights in the Output You generate using the Model. You are accountable for the Output you generate and its subsequent uses. No use of the output can contravene any provision as stated in the License.
52
+
53
+ Section IV: OTHER PROVISIONS
54
+
55
+ 7. Updates and Runtime Restrictions. To the maximum extent permitted by law, Licensor reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License, update the Model through electronic means, or modify the Output of the Model based on updates. You shall undertake reasonable efforts to use the latest version of the Model.
56
+ 8. Trademarks and related. Nothing in this License permits You to make use of Licensors’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by the Licensors.
57
+ 9. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Model and the Complementary Material (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Model, Derivatives of the Model, and the Complementary Material and assume any risks associated with Your exercise of permissions under this License.
58
+ 10. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Model and the Complementary Material (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
59
+ 11. Accepting Warranty or Additional Liability. While redistributing the Model, Derivatives of the Model and the Complementary Material thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
60
+ 12. If any provision of this License is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.
61
+
62
+ END OF TERMS AND CONDITIONS
63
+
64
+
65
+
66
+
67
+ Attachment A
68
+
69
+ Use Restrictions
70
+
71
+ You agree not to use the Model or Derivatives of the Model:
72
+ - In any way that violates any applicable national, federal, state, local or international law or regulation;
73
+ - For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
74
+ - To generate or disseminate verifiably false information and/or content with the purpose of harming others;
75
+ - To generate or disseminate personal identifiable information that can be used to harm an individual;
76
+ - To defame, disparage or otherwise harass others;
77
+ - For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation;
78
+ - For any use intended to or which has the effect of discriminating against or harming individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics;
79
+ - To exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;
80
+ - For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories;
81
+ - To provide medical advice and medical results interpretation;
82
+ - To generate or disseminate information for the purpose to be used for administration of justice, law enforcement, immigration or asylum processes, such as predicting an individual will commit fraud/crime commitment (e.g. by text profiling, drawing causal relationships between assertions made in documents, indiscriminate and arbitrarily-targeted use).
stable_diffusion/README.md ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stable Diffusion
2
+ *Stable Diffusion was made possible thanks to a collaboration with [Stability AI](https://stability.ai/) and [Runway](https://runwayml.com/) and builds upon our previous work:*
3
+
4
+ [**High-Resolution Image Synthesis with Latent Diffusion Models**](https://ommer-lab.com/research/latent-diffusion-models/)<br/>
5
+ [Robin Rombach](https://github.com/rromb)\*,
6
+ [Andreas Blattmann](https://github.com/ablattmann)\*,
7
+ [Dominik Lorenz](https://github.com/qp-qp)\,
8
+ [Patrick Esser](https://github.com/pesser),
9
+ [Björn Ommer](https://hci.iwr.uni-heidelberg.de/Staff/bommer)<br/>
10
+ _[CVPR '22 Oral](https://openaccess.thecvf.com/content/CVPR2022/html/Rombach_High-Resolution_Image_Synthesis_With_Latent_Diffusion_Models_CVPR_2022_paper.html) |
11
+ [GitHub](https://github.com/CompVis/latent-diffusion) | [arXiv](https://arxiv.org/abs/2112.10752) | [Project page](https://ommer-lab.com/research/latent-diffusion-models/)_
12
+
13
+ ![txt2img-stable2](assets/stable-samples/txt2img/merged-0006.png)
14
+ [Stable Diffusion](#stable-diffusion-v1) is a latent text-to-image diffusion
15
+ model.
16
+ Thanks to a generous compute donation from [Stability AI](https://stability.ai/) and support from [LAION](https://laion.ai/), we were able to train a Latent Diffusion Model on 512x512 images from a subset of the [LAION-5B](https://laion.ai/blog/laion-5b/) database.
17
+ Similar to Google's [Imagen](https://arxiv.org/abs/2205.11487),
18
+ this model uses a frozen CLIP ViT-L/14 text encoder to condition the model on text prompts.
19
+ With its 860M UNet and 123M text encoder, the model is relatively lightweight and runs on a GPU with at least 10GB VRAM.
20
+ See [this section](#stable-diffusion-v1) below and the [model card](https://huggingface.co/CompVis/stable-diffusion).
21
+
22
+
23
+ ## Requirements
24
+ A suitable [conda](https://conda.io/) environment named `ldm` can be created
25
+ and activated with:
26
+
27
+ ```
28
+ conda env create -f environment.yaml
29
+ conda activate ldm
30
+ ```
31
+
32
+ You can also update an existing [latent diffusion](https://github.com/CompVis/latent-diffusion) environment by running
33
+
34
+ ```
35
+ conda install pytorch torchvision -c pytorch
36
+ pip install transformers==4.19.2 diffusers invisible-watermark
37
+ pip install -e .
38
+ ```
39
+
40
+
41
+ ## Stable Diffusion v1
42
+
43
+ Stable Diffusion v1 refers to a specific configuration of the model
44
+ architecture that uses a downsampling-factor 8 autoencoder with an 860M UNet
45
+ and CLIP ViT-L/14 text encoder for the diffusion model. The model was pretrained on 256x256 images and
46
+ then finetuned on 512x512 images.
47
+
48
+ *Note: Stable Diffusion v1 is a general text-to-image diffusion model and therefore mirrors biases and (mis-)conceptions that are present
49
+ in its training data.
50
+ Details on the training procedure and data, as well as the intended use of the model can be found in the corresponding [model card](Stable_Diffusion_v1_Model_Card.md).*
51
+
52
+ The weights are available via [the CompVis organization at Hugging Face](https://huggingface.co/CompVis) under [a license which contains specific use-based restrictions to prevent misuse and harm as informed by the model card, but otherwise remains permissive](LICENSE). While commercial use is permitted under the terms of the license, **we do not recommend using the provided weights for services or products without additional safety mechanisms and considerations**, since there are [known limitations and biases](Stable_Diffusion_v1_Model_Card.md#limitations-and-bias) of the weights, and research on safe and ethical deployment of general text-to-image models is an ongoing effort. **The weights are research artifacts and should be treated as such.**
53
+
54
+ [The CreativeML OpenRAIL M license](LICENSE) is an [Open RAIL M license](https://www.licenses.ai/blog/2022/8/18/naming-convention-of-responsible-ai-licenses), adapted from the work that [BigScience](https://bigscience.huggingface.co/) and [the RAIL Initiative](https://www.licenses.ai/) are jointly carrying in the area of responsible AI licensing. See also [the article about the BLOOM Open RAIL license](https://bigscience.huggingface.co/blog/the-bigscience-rail-license) on which our license is based.
55
+
56
+ ### Weights
57
+
58
+ We currently provide the following checkpoints:
59
+
60
+ - `sd-v1-1.ckpt`: 237k steps at resolution `256x256` on [laion2B-en](https://huggingface.co/datasets/laion/laion2B-en).
61
+ 194k steps at resolution `512x512` on [laion-high-resolution](https://huggingface.co/datasets/laion/laion-high-resolution) (170M examples from LAION-5B with resolution `>= 1024x1024`).
62
+ - `sd-v1-2.ckpt`: Resumed from `sd-v1-1.ckpt`.
63
+ 515k steps at resolution `512x512` on [laion-aesthetics v2 5+](https://laion.ai/blog/laion-aesthetics/) (a subset of laion2B-en with estimated aesthetics score `> 5.0`, and additionally
64
+ filtered to images with an original size `>= 512x512`, and an estimated watermark probability `< 0.5`. The watermark estimate is from the [LAION-5B](https://laion.ai/blog/laion-5b/) metadata, the aesthetics score is estimated using the [LAION-Aesthetics Predictor V2](https://github.com/christophschuhmann/improved-aesthetic-predictor)).
65
+ - `sd-v1-3.ckpt`: Resumed from `sd-v1-2.ckpt`. 195k steps at resolution `512x512` on "laion-aesthetics v2 5+" and 10\% dropping of the text-conditioning to improve [classifier-free guidance sampling](https://arxiv.org/abs/2207.12598).
66
+ - `sd-v1-4.ckpt`: Resumed from `sd-v1-2.ckpt`. 225k steps at resolution `512x512` on "laion-aesthetics v2 5+" and 10\% dropping of the text-conditioning to improve [classifier-free guidance sampling](https://arxiv.org/abs/2207.12598).
67
+
68
+ Evaluations with different classifier-free guidance scales (1.5, 2.0, 3.0, 4.0,
69
+ 5.0, 6.0, 7.0, 8.0) and 50 PLMS sampling
70
+ steps show the relative improvements of the checkpoints:
71
+ ![sd evaluation results](assets/v1-variants-scores.jpg)
72
+
73
+
74
+
75
+ ### Text-to-Image with Stable Diffusion
76
+ ![txt2img-stable2](assets/stable-samples/txt2img/merged-0005.png)
77
+ ![txt2img-stable2](assets/stable-samples/txt2img/merged-0007.png)
78
+
79
+ Stable Diffusion is a latent diffusion model conditioned on the (non-pooled) text embeddings of a CLIP ViT-L/14 text encoder.
80
+ We provide a [reference script for sampling](#reference-sampling-script), but
81
+ there also exists a [diffusers integration](#diffusers-integration), which we
82
+ expect to see more active community development.
83
+
84
+ #### Reference Sampling Script
85
+
86
+ We provide a reference sampling script, which incorporates
87
+
88
+ - a [Safety Checker Module](https://github.com/CompVis/stable-diffusion/pull/36),
89
+ to reduce the probability of explicit outputs,
90
+ - an [invisible watermarking](https://github.com/ShieldMnt/invisible-watermark)
91
+ of the outputs, to help viewers [identify the images as machine-generated](scripts/tests/test_watermark.py).
92
+
93
+ After [obtaining the `stable-diffusion-v1-*-original` weights](#weights), link them
94
+ ```
95
+ mkdir -p models/ldm/stable-diffusion-v1/
96
+ ln -s <path/to/model.ckpt> models/ldm/stable-diffusion-v1/model.ckpt
97
+ ```
98
+ and sample with
99
+ ```
100
+ python scripts/txt2img.py --prompt "a photograph of an astronaut riding a horse" --plms
101
+ ```
102
+
103
+ By default, this uses a guidance scale of `--scale 7.5`, [Katherine Crowson's implementation](https://github.com/CompVis/latent-diffusion/pull/51) of the [PLMS](https://arxiv.org/abs/2202.09778) sampler,
104
+ and renders images of size 512x512 (which it was trained on) in 50 steps. All supported arguments are listed below (type `python scripts/txt2img.py --help`).
105
+
106
+
107
+ ```commandline
108
+ usage: txt2img.py [-h] [--prompt [PROMPT]] [--outdir [OUTDIR]] [--skip_grid] [--skip_save] [--ddim_steps DDIM_STEPS] [--plms] [--laion400m] [--fixed_code] [--ddim_eta DDIM_ETA]
109
+ [--n_iter N_ITER] [--H H] [--W W] [--C C] [--f F] [--n_samples N_SAMPLES] [--n_rows N_ROWS] [--scale SCALE] [--from-file FROM_FILE] [--config CONFIG] [--ckpt CKPT]
110
+ [--seed SEED] [--precision {full,autocast}]
111
+
112
+ optional arguments:
113
+ -h, --help show this help message and exit
114
+ --prompt [PROMPT] the prompt to render
115
+ --outdir [OUTDIR] dir to write results to
116
+ --skip_grid do not save a grid, only individual samples. Helpful when evaluating lots of samples
117
+ --skip_save do not save individual samples. For speed measurements.
118
+ --ddim_steps DDIM_STEPS
119
+ number of ddim sampling steps
120
+ --plms use plms sampling
121
+ --laion400m uses the LAION400M model
122
+ --fixed_code if enabled, uses the same starting code across samples
123
+ --ddim_eta DDIM_ETA ddim eta (eta=0.0 corresponds to deterministic sampling
124
+ --n_iter N_ITER sample this often
125
+ --H H image height, in pixel space
126
+ --W W image width, in pixel space
127
+ --C C latent channels
128
+ --f F downsampling factor
129
+ --n_samples N_SAMPLES
130
+ how many samples to produce for each given prompt. A.k.a. batch size
131
+ --n_rows N_ROWS rows in the grid (default: n_samples)
132
+ --scale SCALE unconditional guidance scale: eps = eps(x, empty) + scale * (eps(x, cond) - eps(x, empty))
133
+ --from-file FROM_FILE
134
+ if specified, load prompts from this file
135
+ --config CONFIG path to config which constructs model
136
+ --ckpt CKPT path to checkpoint of model
137
+ --seed SEED the seed (for reproducible sampling)
138
+ --precision {full,autocast}
139
+ evaluate at this precision
140
+ ```
141
+ Note: The inference config for all v1 versions is designed to be used with EMA-only checkpoints.
142
+ For this reason `use_ema=False` is set in the configuration, otherwise the code will try to switch from
143
+ non-EMA to EMA weights. If you want to examine the effect of EMA vs no EMA, we provide "full" checkpoints
144
+ which contain both types of weights. For these, `use_ema=False` will load and use the non-EMA weights.
145
+
146
+
147
+ #### Diffusers Integration
148
+
149
+ A simple way to download and sample Stable Diffusion is by using the [diffusers library](https://github.com/huggingface/diffusers/tree/main#new--stable-diffusion-is-now-fully-compatible-with-diffusers):
150
+ ```py
151
+ # make sure you're logged in with `huggingface-cli login`
152
+ from torch import autocast
153
+ from diffusers import StableDiffusionPipeline
154
+
155
+ pipe = StableDiffusionPipeline.from_pretrained(
156
+ "CompVis/stable-diffusion-v1-4",
157
+ use_auth_token=True
158
+ ).to("cuda")
159
+
160
+ prompt = "a photo of an astronaut riding a horse on mars"
161
+ with autocast("cuda"):
162
+ image = pipe(prompt)["sample"][0]
163
+
164
+ image.save("astronaut_rides_horse.png")
165
+ ```
166
+
167
+
168
+ ### Image Modification with Stable Diffusion
169
+
170
+ By using a diffusion-denoising mechanism as first proposed by [SDEdit](https://arxiv.org/abs/2108.01073), the model can be used for different
171
+ tasks such as text-guided image-to-image translation and upscaling. Similar to the txt2img sampling script,
172
+ we provide a script to perform image modification with Stable Diffusion.
173
+
174
+ The following describes an example where a rough sketch made in [Pinta](https://www.pinta-project.com/) is converted into a detailed artwork.
175
+ ```
176
+ python scripts/img2img.py --prompt "A fantasy landscape, trending on artstation" --init-img <path-to-img.jpg> --strength 0.8
177
+ ```
178
+ Here, strength is a value between 0.0 and 1.0, that controls the amount of noise that is added to the input image.
179
+ Values that approach 1.0 allow for lots of variations but will also produce images that are not semantically consistent with the input. See the following example.
180
+
181
+ **Input**
182
+
183
+ ![sketch-in](assets/stable-samples/img2img/sketch-mountains-input.jpg)
184
+
185
+ **Outputs**
186
+
187
+ ![out3](assets/stable-samples/img2img/mountains-3.png)
188
+ ![out2](assets/stable-samples/img2img/mountains-2.png)
189
+
190
+ This procedure can, for example, also be used to upscale samples from the base model.
191
+
192
+
193
+ ## Comments
194
+
195
+ - Our codebase for the diffusion models builds heavily on [OpenAI's ADM codebase](https://github.com/openai/guided-diffusion)
196
+ and [https://github.com/lucidrains/denoising-diffusion-pytorch](https://github.com/lucidrains/denoising-diffusion-pytorch).
197
+ Thanks for open-sourcing!
198
+
199
+ - The implementation of the transformer encoder is from [x-transformers](https://github.com/lucidrains/x-transformers) by [lucidrains](https://github.com/lucidrains?tab=repositories).
200
+
201
+
202
+ ## BibTeX
203
+
204
+ ```
205
+ @misc{rombach2021highresolution,
206
+ title={High-Resolution Image Synthesis with Latent Diffusion Models},
207
+ author={Robin Rombach and Andreas Blattmann and Dominik Lorenz and Patrick Esser and Björn Ommer},
208
+ year={2021},
209
+ eprint={2112.10752},
210
+ archivePrefix={arXiv},
211
+ primaryClass={cs.CV}
212
+ }
213
+ ```
214
+
215
+
stable_diffusion/Stable_Diffusion_v1_Model_Card.md ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stable Diffusion v1 Model Card
2
+ This model card focuses on the model associated with the Stable Diffusion model, available [here](https://github.com/CompVis/stable-diffusion).
3
+
4
+ ## Model Details
5
+ - **Developed by:** Robin Rombach, Patrick Esser
6
+ - **Model type:** Diffusion-based text-to-image generation model
7
+ - **Language(s):** English
8
+ - **License:** [Proprietary](LICENSE)
9
+ - **Model Description:** This is a model that can be used to generate and modify images based on text prompts. It is a [Latent Diffusion Model](https://arxiv.org/abs/2112.10752) that uses a fixed, pretrained text encoder ([CLIP ViT-L/14](https://arxiv.org/abs/2103.00020)) as suggested in the [Imagen paper](https://arxiv.org/abs/2205.11487).
10
+ - **Resources for more information:** [GitHub Repository](https://github.com/CompVis/stable-diffusion), [Paper](https://arxiv.org/abs/2112.10752).
11
+ - **Cite as:**
12
+
13
+ @InProceedings{Rombach_2022_CVPR,
14
+ author = {Rombach, Robin and Blattmann, Andreas and Lorenz, Dominik and Esser, Patrick and Ommer, Bj\"orn},
15
+ title = {High-Resolution Image Synthesis With Latent Diffusion Models},
16
+ booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)},
17
+ month = {June},
18
+ year = {2022},
19
+ pages = {10684-10695}
20
+ }
21
+
22
+ # Uses
23
+
24
+ ## Direct Use
25
+ The model is intended for research purposes only. Possible research areas and
26
+ tasks include
27
+
28
+ - Safe deployment of models which have the potential to generate harmful content.
29
+ - Probing and understanding the limitations and biases of generative models.
30
+ - Generation of artworks and use in design and other artistic processes.
31
+ - Applications in educational or creative tools.
32
+ - Research on generative models.
33
+
34
+ Excluded uses are described below.
35
+
36
+ ### Misuse, Malicious Use, and Out-of-Scope Use
37
+ _Note: This section is taken from the [DALLE-MINI model card](https://huggingface.co/dalle-mini/dalle-mini), but applies in the same way to Stable Diffusion v1_.
38
+
39
+ The model should not be used to intentionally create or disseminate images that create hostile or alienating environments for people. This includes generating images that people would foreseeably find disturbing, distressing, or offensive; or content that propagates historical or current stereotypes.
40
+
41
+ #### Out-of-Scope Use
42
+ The model was not trained to be factual or true representations of people or events, and therefore using the model to generate such content is out-of-scope for the abilities of this model.
43
+
44
+ #### Misuse and Malicious Use
45
+ Using the model to generate content that is cruel to individuals is a misuse of this model. This includes, but is not limited to:
46
+
47
+ - Generating demeaning, dehumanizing, or otherwise harmful representations of people or their environments, cultures, religions, etc.
48
+ - Intentionally promoting or propagating discriminatory content or harmful stereotypes.
49
+ - Impersonating individuals without their consent.
50
+ - Sexual content without consent of the people who might see it.
51
+ - Mis- and disinformation
52
+ - Representations of egregious violence and gore
53
+ - Sharing of copyrighted or licensed material in violation of its terms of use.
54
+ - Sharing content that is an alteration of copyrighted or licensed material in violation of its terms of use.
55
+
56
+ ## Limitations and Bias
57
+
58
+ ### Limitations
59
+
60
+ - The model does not achieve perfect photorealism
61
+ - The model cannot render legible text
62
+ - The model does not perform well on more difficult tasks which involve compositionality, such as rendering an image corresponding to “A red cube on top of a blue sphere”
63
+ - Faces and people in general may not be generated properly.
64
+ - The model was trained mainly with English captions and will not work as well in other languages.
65
+ - The autoencoding part of the model is lossy
66
+ - The model was trained on a large-scale dataset
67
+ [LAION-5B](https://laion.ai/blog/laion-5b/) which contains adult material
68
+ and is not fit for product use without additional safety mechanisms and
69
+ considerations.
70
+ - No additional measures were used to deduplicate the dataset. As a result, we observe some degree of memorization for images that are duplicated in the training data.
71
+ The training data can be searched at [https://rom1504.github.io/clip-retrieval/](https://rom1504.github.io/clip-retrieval/) to possibly assist in the detection of memorized images.
72
+
73
+ ### Bias
74
+ While the capabilities of image generation models are impressive, they can also reinforce or exacerbate social biases.
75
+ Stable Diffusion v1 was primarily trained on subsets of [LAION-2B(en)](https://laion.ai/blog/laion-5b/),
76
+ which consists of images that are limited to English descriptions.
77
+ Texts and images from communities and cultures that use other languages are likely to be insufficiently accounted for.
78
+ This affects the overall output of the model, as white and western cultures are often set as the default. Further, the
79
+ ability of the model to generate content with non-English prompts is significantly worse than with English-language prompts.
80
+ Stable Diffusion v1 mirrors and exacerbates biases to such a degree that viewer discretion must be advised irrespective of the input or its intent.
81
+
82
+
83
+ ## Training
84
+
85
+ **Training Data**
86
+ The model developers used the following dataset for training the model:
87
+
88
+ - LAION-5B and subsets thereof (see next section)
89
+
90
+ **Training Procedure**
91
+ Stable Diffusion v1 is a latent diffusion model which combines an autoencoder with a diffusion model that is trained in the latent space of the autoencoder. During training,
92
+
93
+ - Images are encoded through an encoder, which turns images into latent representations. The autoencoder uses a relative downsampling factor of 8 and maps images of shape H x W x 3 to latents of shape H/f x W/f x 4
94
+ - Text prompts are encoded through a ViT-L/14 text-encoder.
95
+ - The non-pooled output of the text encoder is fed into the UNet backbone of the latent diffusion model via cross-attention.
96
+ - The loss is a reconstruction objective between the noise that was added to the latent and the prediction made by the UNet.
97
+
98
+ We currently provide the following checkpoints:
99
+
100
+ - `sd-v1-1.ckpt`: 237k steps at resolution `256x256` on [laion2B-en](https://huggingface.co/datasets/laion/laion2B-en).
101
+ 194k steps at resolution `512x512` on [laion-high-resolution](https://huggingface.co/datasets/laion/laion-high-resolution) (170M examples from LAION-5B with resolution `>= 1024x1024`).
102
+ - `sd-v1-2.ckpt`: Resumed from `sd-v1-1.ckpt`.
103
+ 515k steps at resolution `512x512` on [laion-aesthetics v2 5+](https://laion.ai/blog/laion-aesthetics/) (a subset of laion2B-en with estimated aesthetics score `> 5.0`, and additionally
104
+ filtered to images with an original size `>= 512x512`, and an estimated watermark probability `< 0.5`. The watermark estimate is from the [LAION-5B](https://laion.ai/blog/laion-5b/) metadata, the aesthetics score is estimated using the [LAION-Aesthetics Predictor V2](https://github.com/christophschuhmann/improved-aesthetic-predictor)).
105
+ - `sd-v1-3.ckpt`: Resumed from `sd-v1-2.ckpt`. 195k steps at resolution `512x512` on "laion-aesthetics v2 5+" and 10\% dropping of the text-conditioning to improve [classifier-free guidance sampling](https://arxiv.org/abs/2207.12598).
106
+ - `sd-v1-4.ckpt`: Resumed from `sd-v1-2.ckpt`. 225k steps at resolution `512x512` on "laion-aesthetics v2 5+" and 10\% dropping of the text-conditioning to improve [classifier-free guidance sampling](https://arxiv.org/abs/2207.12598).
107
+
108
+ - **Hardware:** 32 x 8 x A100 GPUs
109
+ - **Optimizer:** AdamW
110
+ - **Gradient Accumulations**: 2
111
+ - **Batch:** 32 x 8 x 2 x 4 = 2048
112
+ - **Learning rate:** warmup to 0.0001 for 10,000 steps and then kept constant
113
+
114
+ ## Evaluation Results
115
+ Evaluations with different classifier-free guidance scales (1.5, 2.0, 3.0, 4.0,
116
+ 5.0, 6.0, 7.0, 8.0) and 50 PLMS sampling
117
+ steps show the relative improvements of the checkpoints:
118
+
119
+ ![pareto](assets/v1-variants-scores.jpg)
120
+
121
+ Evaluated using 50 PLMS steps and 10000 random prompts from the COCO2017 validation set, evaluated at 512x512 resolution. Not optimized for FID scores.
122
+
123
+ ## Environmental Impact
124
+
125
+ **Stable Diffusion v1** **Estimated Emissions**
126
+ Based on that information, we estimate the following CO2 emissions using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700). The hardware, runtime, cloud provider, and compute region were utilized to estimate the carbon impact.
127
+
128
+ - **Hardware Type:** A100 PCIe 40GB
129
+ - **Hours used:** 150000
130
+ - **Cloud Provider:** AWS
131
+ - **Compute Region:** US-east
132
+ - **Carbon Emitted (Power consumption x Time x Carbon produced based on location of power grid):** 11250 kg CO2 eq.
133
+
134
+ ## Citation
135
+ @InProceedings{Rombach_2022_CVPR,
136
+ author = {Rombach, Robin and Blattmann, Andreas and Lorenz, Dominik and Esser, Patrick and Ommer, Bj\"orn},
137
+ title = {High-Resolution Image Synthesis With Latent Diffusion Models},
138
+ booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)},
139
+ month = {June},
140
+ year = {2022},
141
+ pages = {10684-10695}
142
+ }
143
+
144
+ *This model card was written by: Robin Rombach and Patrick Esser and is based on the [DALL-E Mini model card](https://huggingface.co/dalle-mini/dalle-mini).*
stable_diffusion/assets/a-painting-of-a-fire.png ADDED
stable_diffusion/assets/a-photograph-of-a-fire.png ADDED
stable_diffusion/assets/a-shirt-with-a-fire-printed-on-it.png ADDED
stable_diffusion/assets/a-shirt-with-the-inscription-'fire'.png ADDED
stable_diffusion/assets/a-watercolor-painting-of-a-fire.png ADDED
stable_diffusion/assets/birdhouse.png ADDED
stable_diffusion/assets/fire.png ADDED
stable_diffusion/assets/inpainting.png ADDED
stable_diffusion/assets/modelfigure.png ADDED
stable_diffusion/assets/rdm-preview.jpg ADDED
stable_diffusion/assets/reconstruction1.png ADDED
stable_diffusion/assets/reconstruction2.png ADDED
stable_diffusion/assets/results.gif.REMOVED.git-id ADDED
@@ -0,0 +1 @@
 
 
1
+ 82b6590e670a32196093cc6333ea19e6547d07de
stable_diffusion/assets/rick.jpeg ADDED
stable_diffusion/assets/stable-samples/img2img/mountains-1.png ADDED
stable_diffusion/assets/stable-samples/img2img/mountains-2.png ADDED
stable_diffusion/assets/stable-samples/img2img/mountains-3.png ADDED
stable_diffusion/assets/stable-samples/img2img/sketch-mountains-input.jpg ADDED
stable_diffusion/assets/stable-samples/img2img/upscaling-in.png.REMOVED.git-id ADDED
@@ -0,0 +1 @@
 
 
1
+ 501c31c21751664957e69ce52cad1818b6d2f4ce
stable_diffusion/assets/stable-samples/img2img/upscaling-out.png.REMOVED.git-id ADDED
@@ -0,0 +1 @@
 
 
1
+ 1c4bb25a779f34d86b2d90e584ac67af91bb1303
stable_diffusion/assets/stable-samples/txt2img/000002025.png ADDED
stable_diffusion/assets/stable-samples/txt2img/000002035.png ADDED
stable_diffusion/assets/stable-samples/txt2img/merged-0005.png.REMOVED.git-id ADDED
@@ -0,0 +1 @@
 
 
1
+ ca0a1af206555f0f208a1ab879e95efedc1b1c5b
stable_diffusion/assets/stable-samples/txt2img/merged-0006.png.REMOVED.git-id ADDED
@@ -0,0 +1 @@
 
 
1
+ 999f3703230580e8c89e9081abd6a1f8f50896d4
stable_diffusion/assets/stable-samples/txt2img/merged-0007.png.REMOVED.git-id ADDED
@@ -0,0 +1 @@
 
 
1
+ af390acaf601283782d6f479d4cade4d78e30b26
stable_diffusion/assets/the-earth-is-on-fire,-oil-on-canvas.png ADDED
stable_diffusion/assets/txt2img-convsample.png ADDED
stable_diffusion/assets/txt2img-preview.png.REMOVED.git-id ADDED
@@ -0,0 +1 @@
 
 
1
+ 51ee1c235dfdc63d4c41de7d303d03730e43c33c
stable_diffusion/assets/v1-variants-scores.jpg ADDED
stable_diffusion/configs/autoencoder/autoencoder_kl_16x16x16.yaml ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 4.5e-6
3
+ target: ldm.models.autoencoder.AutoencoderKL
4
+ params:
5
+ monitor: "val/rec_loss"
6
+ embed_dim: 16
7
+ lossconfig:
8
+ target: ldm.modules.losses.LPIPSWithDiscriminator
9
+ params:
10
+ disc_start: 50001
11
+ kl_weight: 0.000001
12
+ disc_weight: 0.5
13
+
14
+ ddconfig:
15
+ double_z: True
16
+ z_channels: 16
17
+ resolution: 256
18
+ in_channels: 3
19
+ out_ch: 3
20
+ ch: 128
21
+ ch_mult: [ 1,1,2,2,4] # num_down = len(ch_mult)-1
22
+ num_res_blocks: 2
23
+ attn_resolutions: [16]
24
+ dropout: 0.0
25
+
26
+
27
+ data:
28
+ target: main.DataModuleFromConfig
29
+ params:
30
+ batch_size: 12
31
+ wrap: True
32
+ train:
33
+ target: ldm.data.imagenet.ImageNetSRTrain
34
+ params:
35
+ size: 256
36
+ degradation: pil_nearest
37
+ validation:
38
+ target: ldm.data.imagenet.ImageNetSRValidation
39
+ params:
40
+ size: 256
41
+ degradation: pil_nearest
42
+
43
+ lightning:
44
+ callbacks:
45
+ image_logger:
46
+ target: main.ImageLogger
47
+ params:
48
+ batch_frequency: 1000
49
+ max_images: 8
50
+ increase_log_steps: True
51
+
52
+ trainer:
53
+ benchmark: True
54
+ accumulate_grad_batches: 2
stable_diffusion/configs/autoencoder/autoencoder_kl_32x32x4.yaml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 4.5e-6
3
+ target: ldm.models.autoencoder.AutoencoderKL
4
+ params:
5
+ monitor: "val/rec_loss"
6
+ embed_dim: 4
7
+ lossconfig:
8
+ target: ldm.modules.losses.LPIPSWithDiscriminator
9
+ params:
10
+ disc_start: 50001
11
+ kl_weight: 0.000001
12
+ disc_weight: 0.5
13
+
14
+ ddconfig:
15
+ double_z: True
16
+ z_channels: 4
17
+ resolution: 256
18
+ in_channels: 3
19
+ out_ch: 3
20
+ ch: 128
21
+ ch_mult: [ 1,2,4,4 ] # num_down = len(ch_mult)-1
22
+ num_res_blocks: 2
23
+ attn_resolutions: [ ]
24
+ dropout: 0.0
25
+
26
+ data:
27
+ target: main.DataModuleFromConfig
28
+ params:
29
+ batch_size: 12
30
+ wrap: True
31
+ train:
32
+ target: ldm.data.imagenet.ImageNetSRTrain
33
+ params:
34
+ size: 256
35
+ degradation: pil_nearest
36
+ validation:
37
+ target: ldm.data.imagenet.ImageNetSRValidation
38
+ params:
39
+ size: 256
40
+ degradation: pil_nearest
41
+
42
+ lightning:
43
+ callbacks:
44
+ image_logger:
45
+ target: main.ImageLogger
46
+ params:
47
+ batch_frequency: 1000
48
+ max_images: 8
49
+ increase_log_steps: True
50
+
51
+ trainer:
52
+ benchmark: True
53
+ accumulate_grad_batches: 2
stable_diffusion/configs/autoencoder/autoencoder_kl_64x64x3.yaml ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 4.5e-6
3
+ target: ldm.models.autoencoder.AutoencoderKL
4
+ params:
5
+ monitor: "val/rec_loss"
6
+ embed_dim: 3
7
+ lossconfig:
8
+ target: ldm.modules.losses.LPIPSWithDiscriminator
9
+ params:
10
+ disc_start: 50001
11
+ kl_weight: 0.000001
12
+ disc_weight: 0.5
13
+
14
+ ddconfig:
15
+ double_z: True
16
+ z_channels: 3
17
+ resolution: 256
18
+ in_channels: 3
19
+ out_ch: 3
20
+ ch: 128
21
+ ch_mult: [ 1,2,4 ] # num_down = len(ch_mult)-1
22
+ num_res_blocks: 2
23
+ attn_resolutions: [ ]
24
+ dropout: 0.0
25
+
26
+
27
+ data:
28
+ target: main.DataModuleFromConfig
29
+ params:
30
+ batch_size: 12
31
+ wrap: True
32
+ train:
33
+ target: ldm.data.imagenet.ImageNetSRTrain
34
+ params:
35
+ size: 256
36
+ degradation: pil_nearest
37
+ validation:
38
+ target: ldm.data.imagenet.ImageNetSRValidation
39
+ params:
40
+ size: 256
41
+ degradation: pil_nearest
42
+
43
+ lightning:
44
+ callbacks:
45
+ image_logger:
46
+ target: main.ImageLogger
47
+ params:
48
+ batch_frequency: 1000
49
+ max_images: 8
50
+ increase_log_steps: True
51
+
52
+ trainer:
53
+ benchmark: True
54
+ accumulate_grad_batches: 2
stable_diffusion/configs/autoencoder/autoencoder_kl_8x8x64.yaml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 4.5e-6
3
+ target: ldm.models.autoencoder.AutoencoderKL
4
+ params:
5
+ monitor: "val/rec_loss"
6
+ embed_dim: 64
7
+ lossconfig:
8
+ target: ldm.modules.losses.LPIPSWithDiscriminator
9
+ params:
10
+ disc_start: 50001
11
+ kl_weight: 0.000001
12
+ disc_weight: 0.5
13
+
14
+ ddconfig:
15
+ double_z: True
16
+ z_channels: 64
17
+ resolution: 256
18
+ in_channels: 3
19
+ out_ch: 3
20
+ ch: 128
21
+ ch_mult: [ 1,1,2,2,4,4] # num_down = len(ch_mult)-1
22
+ num_res_blocks: 2
23
+ attn_resolutions: [16,8]
24
+ dropout: 0.0
25
+
26
+ data:
27
+ target: main.DataModuleFromConfig
28
+ params:
29
+ batch_size: 12
30
+ wrap: True
31
+ train:
32
+ target: ldm.data.imagenet.ImageNetSRTrain
33
+ params:
34
+ size: 256
35
+ degradation: pil_nearest
36
+ validation:
37
+ target: ldm.data.imagenet.ImageNetSRValidation
38
+ params:
39
+ size: 256
40
+ degradation: pil_nearest
41
+
42
+ lightning:
43
+ callbacks:
44
+ image_logger:
45
+ target: main.ImageLogger
46
+ params:
47
+ batch_frequency: 1000
48
+ max_images: 8
49
+ increase_log_steps: True
50
+
51
+ trainer:
52
+ benchmark: True
53
+ accumulate_grad_batches: 2
stable_diffusion/configs/latent-diffusion/celebahq-ldm-vq-4.yaml ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 2.0e-06
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.0015
6
+ linear_end: 0.0195
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: image
11
+ image_size: 64
12
+ channels: 3
13
+ monitor: val/loss_simple_ema
14
+
15
+ unet_config:
16
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
17
+ params:
18
+ image_size: 64
19
+ in_channels: 3
20
+ out_channels: 3
21
+ model_channels: 224
22
+ attention_resolutions:
23
+ # note: this isn\t actually the resolution but
24
+ # the downsampling factor, i.e. this corresnponds to
25
+ # attention on spatial resolution 8,16,32, as the
26
+ # spatial reolution of the latents is 64 for f4
27
+ - 8
28
+ - 4
29
+ - 2
30
+ num_res_blocks: 2
31
+ channel_mult:
32
+ - 1
33
+ - 2
34
+ - 3
35
+ - 4
36
+ num_head_channels: 32
37
+ first_stage_config:
38
+ target: ldm.models.autoencoder.VQModelInterface
39
+ params:
40
+ embed_dim: 3
41
+ n_embed: 8192
42
+ ckpt_path: models/first_stage_models/vq-f4/model.ckpt
43
+ ddconfig:
44
+ double_z: false
45
+ z_channels: 3
46
+ resolution: 256
47
+ in_channels: 3
48
+ out_ch: 3
49
+ ch: 128
50
+ ch_mult:
51
+ - 1
52
+ - 2
53
+ - 4
54
+ num_res_blocks: 2
55
+ attn_resolutions: []
56
+ dropout: 0.0
57
+ lossconfig:
58
+ target: torch.nn.Identity
59
+ cond_stage_config: __is_unconditional__
60
+ data:
61
+ target: main.DataModuleFromConfig
62
+ params:
63
+ batch_size: 48
64
+ num_workers: 5
65
+ wrap: false
66
+ train:
67
+ target: taming.data.faceshq.CelebAHQTrain
68
+ params:
69
+ size: 256
70
+ validation:
71
+ target: taming.data.faceshq.CelebAHQValidation
72
+ params:
73
+ size: 256
74
+
75
+
76
+ lightning:
77
+ callbacks:
78
+ image_logger:
79
+ target: main.ImageLogger
80
+ params:
81
+ batch_frequency: 5000
82
+ max_images: 8
83
+ increase_log_steps: False
84
+
85
+ trainer:
86
+ benchmark: True
stable_diffusion/configs/latent-diffusion/cin-ldm-vq-f8.yaml ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 1.0e-06
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.0015
6
+ linear_end: 0.0195
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: image
11
+ cond_stage_key: class_label
12
+ image_size: 32
13
+ channels: 4
14
+ cond_stage_trainable: true
15
+ conditioning_key: crossattn
16
+ monitor: val/loss_simple_ema
17
+ unet_config:
18
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
19
+ params:
20
+ image_size: 32
21
+ in_channels: 4
22
+ out_channels: 4
23
+ model_channels: 256
24
+ attention_resolutions:
25
+ #note: this isn\t actually the resolution but
26
+ # the downsampling factor, i.e. this corresnponds to
27
+ # attention on spatial resolution 8,16,32, as the
28
+ # spatial reolution of the latents is 32 for f8
29
+ - 4
30
+ - 2
31
+ - 1
32
+ num_res_blocks: 2
33
+ channel_mult:
34
+ - 1
35
+ - 2
36
+ - 4
37
+ num_head_channels: 32
38
+ use_spatial_transformer: true
39
+ transformer_depth: 1
40
+ context_dim: 512
41
+ first_stage_config:
42
+ target: ldm.models.autoencoder.VQModelInterface
43
+ params:
44
+ embed_dim: 4
45
+ n_embed: 16384
46
+ ckpt_path: configs/first_stage_models/vq-f8/model.yaml
47
+ ddconfig:
48
+ double_z: false
49
+ z_channels: 4
50
+ resolution: 256
51
+ in_channels: 3
52
+ out_ch: 3
53
+ ch: 128
54
+ ch_mult:
55
+ - 1
56
+ - 2
57
+ - 2
58
+ - 4
59
+ num_res_blocks: 2
60
+ attn_resolutions:
61
+ - 32
62
+ dropout: 0.0
63
+ lossconfig:
64
+ target: torch.nn.Identity
65
+ cond_stage_config:
66
+ target: ldm.modules.encoders.modules.ClassEmbedder
67
+ params:
68
+ embed_dim: 512
69
+ key: class_label
70
+ data:
71
+ target: main.DataModuleFromConfig
72
+ params:
73
+ batch_size: 64
74
+ num_workers: 12
75
+ wrap: false
76
+ train:
77
+ target: ldm.data.imagenet.ImageNetTrain
78
+ params:
79
+ config:
80
+ size: 256
81
+ validation:
82
+ target: ldm.data.imagenet.ImageNetValidation
83
+ params:
84
+ config:
85
+ size: 256
86
+
87
+
88
+ lightning:
89
+ callbacks:
90
+ image_logger:
91
+ target: main.ImageLogger
92
+ params:
93
+ batch_frequency: 5000
94
+ max_images: 8
95
+ increase_log_steps: False
96
+
97
+ trainer:
98
+ benchmark: True
stable_diffusion/configs/latent-diffusion/cin256-v2.yaml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 0.0001
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.0015
6
+ linear_end: 0.0195
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: image
11
+ cond_stage_key: class_label
12
+ image_size: 64
13
+ channels: 3
14
+ cond_stage_trainable: true
15
+ conditioning_key: crossattn
16
+ monitor: val/loss
17
+ use_ema: False
18
+
19
+ unet_config:
20
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
21
+ params:
22
+ image_size: 64
23
+ in_channels: 3
24
+ out_channels: 3
25
+ model_channels: 192
26
+ attention_resolutions:
27
+ - 8
28
+ - 4
29
+ - 2
30
+ num_res_blocks: 2
31
+ channel_mult:
32
+ - 1
33
+ - 2
34
+ - 3
35
+ - 5
36
+ num_heads: 1
37
+ use_spatial_transformer: true
38
+ transformer_depth: 1
39
+ context_dim: 512
40
+
41
+ first_stage_config:
42
+ target: ldm.models.autoencoder.VQModelInterface
43
+ params:
44
+ embed_dim: 3
45
+ n_embed: 8192
46
+ ddconfig:
47
+ double_z: false
48
+ z_channels: 3
49
+ resolution: 256
50
+ in_channels: 3
51
+ out_ch: 3
52
+ ch: 128
53
+ ch_mult:
54
+ - 1
55
+ - 2
56
+ - 4
57
+ num_res_blocks: 2
58
+ attn_resolutions: []
59
+ dropout: 0.0
60
+ lossconfig:
61
+ target: torch.nn.Identity
62
+
63
+ cond_stage_config:
64
+ target: ldm.modules.encoders.modules.ClassEmbedder
65
+ params:
66
+ n_classes: 1001
67
+ embed_dim: 512
68
+ key: class_label
stable_diffusion/configs/latent-diffusion/ffhq-ldm-vq-4.yaml ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 2.0e-06
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.0015
6
+ linear_end: 0.0195
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: image
11
+ image_size: 64
12
+ channels: 3
13
+ monitor: val/loss_simple_ema
14
+ unet_config:
15
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
16
+ params:
17
+ image_size: 64
18
+ in_channels: 3
19
+ out_channels: 3
20
+ model_channels: 224
21
+ attention_resolutions:
22
+ # note: this isn\t actually the resolution but
23
+ # the downsampling factor, i.e. this corresnponds to
24
+ # attention on spatial resolution 8,16,32, as the
25
+ # spatial reolution of the latents is 64 for f4
26
+ - 8
27
+ - 4
28
+ - 2
29
+ num_res_blocks: 2
30
+ channel_mult:
31
+ - 1
32
+ - 2
33
+ - 3
34
+ - 4
35
+ num_head_channels: 32
36
+ first_stage_config:
37
+ target: ldm.models.autoencoder.VQModelInterface
38
+ params:
39
+ embed_dim: 3
40
+ n_embed: 8192
41
+ ckpt_path: configs/first_stage_models/vq-f4/model.yaml
42
+ ddconfig:
43
+ double_z: false
44
+ z_channels: 3
45
+ resolution: 256
46
+ in_channels: 3
47
+ out_ch: 3
48
+ ch: 128
49
+ ch_mult:
50
+ - 1
51
+ - 2
52
+ - 4
53
+ num_res_blocks: 2
54
+ attn_resolutions: []
55
+ dropout: 0.0
56
+ lossconfig:
57
+ target: torch.nn.Identity
58
+ cond_stage_config: __is_unconditional__
59
+ data:
60
+ target: main.DataModuleFromConfig
61
+ params:
62
+ batch_size: 42
63
+ num_workers: 5
64
+ wrap: false
65
+ train:
66
+ target: taming.data.faceshq.FFHQTrain
67
+ params:
68
+ size: 256
69
+ validation:
70
+ target: taming.data.faceshq.FFHQValidation
71
+ params:
72
+ size: 256
73
+
74
+
75
+ lightning:
76
+ callbacks:
77
+ image_logger:
78
+ target: main.ImageLogger
79
+ params:
80
+ batch_frequency: 5000
81
+ max_images: 8
82
+ increase_log_steps: False
83
+
84
+ trainer:
85
+ benchmark: True
stable_diffusion/configs/latent-diffusion/lsun_bedrooms-ldm-vq-4.yaml ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 2.0e-06
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.0015
6
+ linear_end: 0.0195
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: image
11
+ image_size: 64
12
+ channels: 3
13
+ monitor: val/loss_simple_ema
14
+ unet_config:
15
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
16
+ params:
17
+ image_size: 64
18
+ in_channels: 3
19
+ out_channels: 3
20
+ model_channels: 224
21
+ attention_resolutions:
22
+ # note: this isn\t actually the resolution but
23
+ # the downsampling factor, i.e. this corresnponds to
24
+ # attention on spatial resolution 8,16,32, as the
25
+ # spatial reolution of the latents is 64 for f4
26
+ - 8
27
+ - 4
28
+ - 2
29
+ num_res_blocks: 2
30
+ channel_mult:
31
+ - 1
32
+ - 2
33
+ - 3
34
+ - 4
35
+ num_head_channels: 32
36
+ first_stage_config:
37
+ target: ldm.models.autoencoder.VQModelInterface
38
+ params:
39
+ ckpt_path: configs/first_stage_models/vq-f4/model.yaml
40
+ embed_dim: 3
41
+ n_embed: 8192
42
+ ddconfig:
43
+ double_z: false
44
+ z_channels: 3
45
+ resolution: 256
46
+ in_channels: 3
47
+ out_ch: 3
48
+ ch: 128
49
+ ch_mult:
50
+ - 1
51
+ - 2
52
+ - 4
53
+ num_res_blocks: 2
54
+ attn_resolutions: []
55
+ dropout: 0.0
56
+ lossconfig:
57
+ target: torch.nn.Identity
58
+ cond_stage_config: __is_unconditional__
59
+ data:
60
+ target: main.DataModuleFromConfig
61
+ params:
62
+ batch_size: 48
63
+ num_workers: 5
64
+ wrap: false
65
+ train:
66
+ target: ldm.data.lsun.LSUNBedroomsTrain
67
+ params:
68
+ size: 256
69
+ validation:
70
+ target: ldm.data.lsun.LSUNBedroomsValidation
71
+ params:
72
+ size: 256
73
+
74
+
75
+ lightning:
76
+ callbacks:
77
+ image_logger:
78
+ target: main.ImageLogger
79
+ params:
80
+ batch_frequency: 5000
81
+ max_images: 8
82
+ increase_log_steps: False
83
+
84
+ trainer:
85
+ benchmark: True
stable_diffusion/configs/latent-diffusion/lsun_churches-ldm-kl-8.yaml ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 5.0e-5 # set to target_lr by starting main.py with '--scale_lr False'
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.0015
6
+ linear_end: 0.0155
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ loss_type: l1
11
+ first_stage_key: "image"
12
+ cond_stage_key: "image"
13
+ image_size: 32
14
+ channels: 4
15
+ cond_stage_trainable: False
16
+ concat_mode: False
17
+ scale_by_std: True
18
+ monitor: 'val/loss_simple_ema'
19
+
20
+ scheduler_config: # 10000 warmup steps
21
+ target: ldm.lr_scheduler.LambdaLinearScheduler
22
+ params:
23
+ warm_up_steps: [10000]
24
+ cycle_lengths: [10000000000000]
25
+ f_start: [1.e-6]
26
+ f_max: [1.]
27
+ f_min: [ 1.]
28
+
29
+ unet_config:
30
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
31
+ params:
32
+ image_size: 32
33
+ in_channels: 4
34
+ out_channels: 4
35
+ model_channels: 192
36
+ attention_resolutions: [ 1, 2, 4, 8 ] # 32, 16, 8, 4
37
+ num_res_blocks: 2
38
+ channel_mult: [ 1,2,2,4,4 ] # 32, 16, 8, 4, 2
39
+ num_heads: 8
40
+ use_scale_shift_norm: True
41
+ resblock_updown: True
42
+
43
+ first_stage_config:
44
+ target: ldm.models.autoencoder.AutoencoderKL
45
+ params:
46
+ embed_dim: 4
47
+ monitor: "val/rec_loss"
48
+ ckpt_path: "models/first_stage_models/kl-f8/model.ckpt"
49
+ ddconfig:
50
+ double_z: True
51
+ z_channels: 4
52
+ resolution: 256
53
+ in_channels: 3
54
+ out_ch: 3
55
+ ch: 128
56
+ ch_mult: [ 1,2,4,4 ] # num_down = len(ch_mult)-1
57
+ num_res_blocks: 2
58
+ attn_resolutions: [ ]
59
+ dropout: 0.0
60
+ lossconfig:
61
+ target: torch.nn.Identity
62
+
63
+ cond_stage_config: "__is_unconditional__"
64
+
65
+ data:
66
+ target: main.DataModuleFromConfig
67
+ params:
68
+ batch_size: 96
69
+ num_workers: 5
70
+ wrap: False
71
+ train:
72
+ target: ldm.data.lsun.LSUNChurchesTrain
73
+ params:
74
+ size: 256
75
+ validation:
76
+ target: ldm.data.lsun.LSUNChurchesValidation
77
+ params:
78
+ size: 256
79
+
80
+ lightning:
81
+ callbacks:
82
+ image_logger:
83
+ target: main.ImageLogger
84
+ params:
85
+ batch_frequency: 5000
86
+ max_images: 8
87
+ increase_log_steps: False
88
+
89
+
90
+ trainer:
91
+ benchmark: True
stable_diffusion/configs/latent-diffusion/txt2img-1p4B-eval.yaml ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 5.0e-05
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.00085
6
+ linear_end: 0.012
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: image
11
+ cond_stage_key: caption
12
+ image_size: 32
13
+ channels: 4
14
+ cond_stage_trainable: true
15
+ conditioning_key: crossattn
16
+ monitor: val/loss_simple_ema
17
+ scale_factor: 0.18215
18
+ use_ema: False
19
+
20
+ unet_config:
21
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
22
+ params:
23
+ image_size: 32
24
+ in_channels: 4
25
+ out_channels: 4
26
+ model_channels: 320
27
+ attention_resolutions:
28
+ - 4
29
+ - 2
30
+ - 1
31
+ num_res_blocks: 2
32
+ channel_mult:
33
+ - 1
34
+ - 2
35
+ - 4
36
+ - 4
37
+ num_heads: 8
38
+ use_spatial_transformer: true
39
+ transformer_depth: 1
40
+ context_dim: 1280
41
+ use_checkpoint: true
42
+ legacy: False
43
+
44
+ first_stage_config:
45
+ target: ldm.models.autoencoder.AutoencoderKL
46
+ params:
47
+ embed_dim: 4
48
+ monitor: val/rec_loss
49
+ ddconfig:
50
+ double_z: true
51
+ z_channels: 4
52
+ resolution: 256
53
+ in_channels: 3
54
+ out_ch: 3
55
+ ch: 128
56
+ ch_mult:
57
+ - 1
58
+ - 2
59
+ - 4
60
+ - 4
61
+ num_res_blocks: 2
62
+ attn_resolutions: []
63
+ dropout: 0.0
64
+ lossconfig:
65
+ target: torch.nn.Identity
66
+
67
+ cond_stage_config:
68
+ target: ldm.modules.encoders.modules.BERTEmbedder
69
+ params:
70
+ n_embed: 1280
71
+ n_layer: 32
stable_diffusion/configs/retrieval-augmented-diffusion/768x768.yaml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 0.0001
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.0015
6
+ linear_end: 0.015
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: jpg
11
+ cond_stage_key: nix
12
+ image_size: 48
13
+ channels: 16
14
+ cond_stage_trainable: false
15
+ conditioning_key: crossattn
16
+ monitor: val/loss_simple_ema
17
+ scale_by_std: false
18
+ scale_factor: 0.22765929
19
+ unet_config:
20
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
21
+ params:
22
+ image_size: 48
23
+ in_channels: 16
24
+ out_channels: 16
25
+ model_channels: 448
26
+ attention_resolutions:
27
+ - 4
28
+ - 2
29
+ - 1
30
+ num_res_blocks: 2
31
+ channel_mult:
32
+ - 1
33
+ - 2
34
+ - 3
35
+ - 4
36
+ use_scale_shift_norm: false
37
+ resblock_updown: false
38
+ num_head_channels: 32
39
+ use_spatial_transformer: true
40
+ transformer_depth: 1
41
+ context_dim: 768
42
+ use_checkpoint: true
43
+ first_stage_config:
44
+ target: ldm.models.autoencoder.AutoencoderKL
45
+ params:
46
+ monitor: val/rec_loss
47
+ embed_dim: 16
48
+ ddconfig:
49
+ double_z: true
50
+ z_channels: 16
51
+ resolution: 256
52
+ in_channels: 3
53
+ out_ch: 3
54
+ ch: 128
55
+ ch_mult:
56
+ - 1
57
+ - 1
58
+ - 2
59
+ - 2
60
+ - 4
61
+ num_res_blocks: 2
62
+ attn_resolutions:
63
+ - 16
64
+ dropout: 0.0
65
+ lossconfig:
66
+ target: torch.nn.Identity
67
+ cond_stage_config:
68
+ target: torch.nn.Identity
stable_diffusion/configs/stable-diffusion/v1-inference.yaml ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 1.0e-04
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.00085
6
+ linear_end: 0.0120
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: "jpg"
11
+ cond_stage_key: "txt"
12
+ image_size: 64
13
+ channels: 4
14
+ cond_stage_trainable: false # Note: different from the one we trained before
15
+ conditioning_key: crossattn
16
+ monitor: val/loss_simple_ema
17
+ scale_factor: 0.18215
18
+ use_ema: False
19
+
20
+ scheduler_config: # 10000 warmup steps
21
+ target: ldm.lr_scheduler.LambdaLinearScheduler
22
+ params:
23
+ warm_up_steps: [ 10000 ]
24
+ cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
25
+ f_start: [ 1.e-6 ]
26
+ f_max: [ 1. ]
27
+ f_min: [ 1. ]
28
+
29
+ unet_config:
30
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
31
+ params:
32
+ image_size: 32 # unused
33
+ in_channels: 4
34
+ out_channels: 4
35
+ model_channels: 320
36
+ attention_resolutions: [ 4, 2, 1 ]
37
+ num_res_blocks: 2
38
+ channel_mult: [ 1, 2, 4, 4 ]
39
+ num_heads: 8
40
+ use_spatial_transformer: True
41
+ transformer_depth: 1
42
+ context_dim: 768
43
+ use_checkpoint: True
44
+ legacy: False
45
+
46
+ first_stage_config:
47
+ target: ldm.models.autoencoder.AutoencoderKL
48
+ params:
49
+ embed_dim: 4
50
+ monitor: val/rec_loss
51
+ ddconfig:
52
+ double_z: true
53
+ z_channels: 4
54
+ resolution: 256
55
+ in_channels: 3
56
+ out_ch: 3
57
+ ch: 128
58
+ ch_mult:
59
+ - 1
60
+ - 2
61
+ - 4
62
+ - 4
63
+ num_res_blocks: 2
64
+ attn_resolutions: []
65
+ dropout: 0.0
66
+ lossconfig:
67
+ target: torch.nn.Identity
68
+
69
+ cond_stage_config:
70
+ target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
stable_diffusion/data/DejaVuSans.ttf ADDED
Binary file (757 kB). View file
 
stable_diffusion/data/example_conditioning/superresolution/sample_0.jpg ADDED
stable_diffusion/data/example_conditioning/text_conditional/sample_0.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ A basket of cerries