Spaces:
Runtime error
Runtime error
Keep demo files only (#6)
Browse files- Keep only the demo files. (2ed30fcbc11a7862c942c3ad78bcde83a08f049e)
Co-authored-by: Pedro Cuenca <pcuenq@users.noreply.huggingface.co>
This view is limited to 50 files because it contains too many changes. Β
See raw diff
- configs/generate.yaml +0 -99
- configs/train.yaml +0 -113
- dataset_creation/generate_img_dataset.py +0 -315
- dataset_creation/generate_txt_dataset.py +0 -113
- dataset_creation/prepare_dataset.py +0 -29
- dataset_creation/prepare_for_gpt.py +0 -25
- edit_cli.py +0 -128
- edit_dataset.py +0 -121
- environment.yaml +0 -38
- imgs/dataset.jpg +0 -0
- imgs/edit_app.jpg +0 -0
- imgs/prompt_app.jpg +0 -0
- main.py +0 -799
- metrics/clip_similarity.py +0 -47
- metrics/compute_metrics.py +0 -235
- prompt_app.py +0 -55
- requirements.txt +3 -24
- scripts/download_checkpoints.sh +0 -7
- scripts/download_data.sh +0 -27
- scripts/download_pretrained_sd.sh +0 -7
- stable_diffusion/LICENSE +0 -82
- stable_diffusion/README.md +0 -215
- stable_diffusion/Stable_Diffusion_v1_Model_Card.md +0 -144
- stable_diffusion/assets/a-painting-of-a-fire.png +0 -0
- stable_diffusion/assets/a-photograph-of-a-fire.png +0 -0
- stable_diffusion/assets/a-shirt-with-a-fire-printed-on-it.png +0 -0
- stable_diffusion/assets/a-shirt-with-the-inscription-'fire'.png +0 -0
- stable_diffusion/assets/a-watercolor-painting-of-a-fire.png +0 -0
- stable_diffusion/assets/birdhouse.png +0 -0
- stable_diffusion/assets/fire.png +0 -0
- stable_diffusion/assets/inpainting.png +0 -0
- stable_diffusion/assets/modelfigure.png +0 -0
- stable_diffusion/assets/rdm-preview.jpg +0 -0
- stable_diffusion/assets/reconstruction1.png +0 -0
- stable_diffusion/assets/reconstruction2.png +0 -0
- stable_diffusion/assets/results.gif.REMOVED.git-id +0 -1
- stable_diffusion/assets/rick.jpeg +0 -0
- stable_diffusion/assets/stable-samples/img2img/mountains-1.png +0 -0
- stable_diffusion/assets/stable-samples/img2img/mountains-2.png +0 -0
- stable_diffusion/assets/stable-samples/img2img/mountains-3.png +0 -0
- stable_diffusion/assets/stable-samples/img2img/sketch-mountains-input.jpg +0 -0
- stable_diffusion/assets/stable-samples/img2img/upscaling-in.png.REMOVED.git-id +0 -1
- stable_diffusion/assets/stable-samples/img2img/upscaling-out.png.REMOVED.git-id +0 -1
- stable_diffusion/assets/stable-samples/txt2img/000002025.png +0 -0
- stable_diffusion/assets/stable-samples/txt2img/000002035.png +0 -0
- stable_diffusion/assets/stable-samples/txt2img/merged-0005.png.REMOVED.git-id +0 -1
- stable_diffusion/assets/stable-samples/txt2img/merged-0006.png.REMOVED.git-id +0 -1
- stable_diffusion/assets/stable-samples/txt2img/merged-0007.png.REMOVED.git-id +0 -1
- stable_diffusion/assets/the-earth-is-on-fire,-oil-on-canvas.png +0 -0
- stable_diffusion/assets/txt2img-convsample.png +0 -0
configs/generate.yaml
DELETED
@@ -1,99 +0,0 @@
|
|
1 |
-
# File modified by authors of InstructPix2Pix from original (https://github.com/CompVis/stable-diffusion).
|
2 |
-
# See more details in LICENSE.
|
3 |
-
|
4 |
-
model:
|
5 |
-
base_learning_rate: 1.0e-04
|
6 |
-
target: ldm.models.diffusion.ddpm_edit.LatentDiffusion
|
7 |
-
params:
|
8 |
-
linear_start: 0.00085
|
9 |
-
linear_end: 0.0120
|
10 |
-
num_timesteps_cond: 1
|
11 |
-
log_every_t: 200
|
12 |
-
timesteps: 1000
|
13 |
-
first_stage_key: edited
|
14 |
-
cond_stage_key: edit
|
15 |
-
# image_size: 64
|
16 |
-
# image_size: 32
|
17 |
-
image_size: 16
|
18 |
-
channels: 4
|
19 |
-
cond_stage_trainable: false # Note: different from the one we trained before
|
20 |
-
conditioning_key: hybrid
|
21 |
-
monitor: val/loss_simple_ema
|
22 |
-
scale_factor: 0.18215
|
23 |
-
use_ema: true
|
24 |
-
load_ema: true
|
25 |
-
|
26 |
-
scheduler_config: # 10000 warmup steps
|
27 |
-
target: ldm.lr_scheduler.LambdaLinearScheduler
|
28 |
-
params:
|
29 |
-
warm_up_steps: [ 0 ]
|
30 |
-
cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
|
31 |
-
f_start: [ 1.e-6 ]
|
32 |
-
f_max: [ 1. ]
|
33 |
-
f_min: [ 1. ]
|
34 |
-
|
35 |
-
unet_config:
|
36 |
-
target: ldm.modules.diffusionmodules.openaimodel.UNetModel
|
37 |
-
params:
|
38 |
-
image_size: 32 # unused
|
39 |
-
in_channels: 8
|
40 |
-
out_channels: 4
|
41 |
-
model_channels: 320
|
42 |
-
attention_resolutions: [ 4, 2, 1 ]
|
43 |
-
num_res_blocks: 2
|
44 |
-
channel_mult: [ 1, 2, 4, 4 ]
|
45 |
-
num_heads: 8
|
46 |
-
use_spatial_transformer: True
|
47 |
-
transformer_depth: 1
|
48 |
-
context_dim: 768
|
49 |
-
use_checkpoint: True
|
50 |
-
legacy: False
|
51 |
-
|
52 |
-
first_stage_config:
|
53 |
-
target: ldm.models.autoencoder.AutoencoderKL
|
54 |
-
params:
|
55 |
-
embed_dim: 4
|
56 |
-
monitor: val/rec_loss
|
57 |
-
ddconfig:
|
58 |
-
double_z: true
|
59 |
-
z_channels: 4
|
60 |
-
resolution: 256
|
61 |
-
in_channels: 3
|
62 |
-
out_ch: 3
|
63 |
-
ch: 128
|
64 |
-
ch_mult:
|
65 |
-
- 1
|
66 |
-
- 2
|
67 |
-
- 4
|
68 |
-
- 4
|
69 |
-
num_res_blocks: 2
|
70 |
-
attn_resolutions: []
|
71 |
-
dropout: 0.0
|
72 |
-
lossconfig:
|
73 |
-
target: torch.nn.Identity
|
74 |
-
|
75 |
-
cond_stage_config:
|
76 |
-
target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
|
77 |
-
|
78 |
-
data:
|
79 |
-
target: main.DataModuleFromConfig
|
80 |
-
params:
|
81 |
-
batch_size: 128
|
82 |
-
num_workers: 1
|
83 |
-
wrap: false
|
84 |
-
validation:
|
85 |
-
target: edit_dataset.EditDataset
|
86 |
-
params:
|
87 |
-
path: data/clip-filtered-dataset
|
88 |
-
cache_dir: data/
|
89 |
-
cache_name: data_10k
|
90 |
-
split: val
|
91 |
-
min_text_sim: 0.2
|
92 |
-
min_image_sim: 0.75
|
93 |
-
min_direction_sim: 0.2
|
94 |
-
max_samples_per_prompt: 1
|
95 |
-
min_resize_res: 512
|
96 |
-
max_resize_res: 512
|
97 |
-
crop_res: 512
|
98 |
-
output_as_edit: False
|
99 |
-
real_input: True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
configs/train.yaml
DELETED
@@ -1,113 +0,0 @@
|
|
1 |
-
# File modified by authors of InstructPix2Pix from original (https://github.com/CompVis/stable-diffusion).
|
2 |
-
# See more details in LICENSE.
|
3 |
-
|
4 |
-
model:
|
5 |
-
base_learning_rate: 1.0e-04
|
6 |
-
target: ldm.models.diffusion.ddpm_edit.LatentDiffusion
|
7 |
-
params:
|
8 |
-
ckpt_path: stable_diffusion/models/ldm/stable-diffusion-v1/v1-5-pruned-emaonly.ckpt
|
9 |
-
linear_start: 0.00085
|
10 |
-
linear_end: 0.0120
|
11 |
-
num_timesteps_cond: 1
|
12 |
-
log_every_t: 200
|
13 |
-
timesteps: 1000
|
14 |
-
first_stage_key: edited
|
15 |
-
cond_stage_key: edit
|
16 |
-
image_size: 32
|
17 |
-
channels: 4
|
18 |
-
cond_stage_trainable: false # Note: different from the one we trained before
|
19 |
-
conditioning_key: hybrid
|
20 |
-
monitor: val/loss_simple_ema
|
21 |
-
scale_factor: 0.18215
|
22 |
-
use_ema: true
|
23 |
-
load_ema: false
|
24 |
-
|
25 |
-
scheduler_config: # 10000 warmup steps
|
26 |
-
target: ldm.lr_scheduler.LambdaLinearScheduler
|
27 |
-
params:
|
28 |
-
warm_up_steps: [ 0 ]
|
29 |
-
cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
|
30 |
-
f_start: [ 1.e-6 ]
|
31 |
-
f_max: [ 1. ]
|
32 |
-
f_min: [ 1. ]
|
33 |
-
|
34 |
-
unet_config:
|
35 |
-
target: ldm.modules.diffusionmodules.openaimodel.UNetModel
|
36 |
-
params:
|
37 |
-
image_size: 32 # unused
|
38 |
-
in_channels: 8
|
39 |
-
out_channels: 4
|
40 |
-
model_channels: 320
|
41 |
-
attention_resolutions: [ 4, 2, 1 ]
|
42 |
-
num_res_blocks: 2
|
43 |
-
channel_mult: [ 1, 2, 4, 4 ]
|
44 |
-
num_heads: 8
|
45 |
-
use_spatial_transformer: True
|
46 |
-
transformer_depth: 1
|
47 |
-
context_dim: 768
|
48 |
-
use_checkpoint: True
|
49 |
-
legacy: False
|
50 |
-
|
51 |
-
first_stage_config:
|
52 |
-
target: ldm.models.autoencoder.AutoencoderKL
|
53 |
-
params:
|
54 |
-
embed_dim: 4
|
55 |
-
monitor: val/rec_loss
|
56 |
-
ddconfig:
|
57 |
-
double_z: true
|
58 |
-
z_channels: 4
|
59 |
-
resolution: 256
|
60 |
-
in_channels: 3
|
61 |
-
out_ch: 3
|
62 |
-
ch: 128
|
63 |
-
ch_mult:
|
64 |
-
- 1
|
65 |
-
- 2
|
66 |
-
- 4
|
67 |
-
- 4
|
68 |
-
num_res_blocks: 2
|
69 |
-
attn_resolutions: []
|
70 |
-
dropout: 0.0
|
71 |
-
lossconfig:
|
72 |
-
target: torch.nn.Identity
|
73 |
-
|
74 |
-
cond_stage_config:
|
75 |
-
target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
|
76 |
-
|
77 |
-
data:
|
78 |
-
target: main.DataModuleFromConfig
|
79 |
-
params:
|
80 |
-
batch_size: 32
|
81 |
-
num_workers: 2
|
82 |
-
train:
|
83 |
-
target: edit_dataset.EditDataset
|
84 |
-
params:
|
85 |
-
path: data/clip-filtered-dataset
|
86 |
-
split: train
|
87 |
-
min_resize_res: 256
|
88 |
-
max_resize_res: 256
|
89 |
-
crop_res: 256
|
90 |
-
flip_prob: 0.5
|
91 |
-
validation:
|
92 |
-
target: edit_dataset.EditDataset
|
93 |
-
params:
|
94 |
-
path: data/clip-filtered-dataset
|
95 |
-
split: val
|
96 |
-
min_resize_res: 256
|
97 |
-
max_resize_res: 256
|
98 |
-
crop_res: 256
|
99 |
-
|
100 |
-
lightning:
|
101 |
-
callbacks:
|
102 |
-
image_logger:
|
103 |
-
target: main.ImageLogger
|
104 |
-
params:
|
105 |
-
batch_frequency: 2000
|
106 |
-
max_images: 2
|
107 |
-
increase_log_steps: False
|
108 |
-
|
109 |
-
trainer:
|
110 |
-
max_epochs: 2000
|
111 |
-
benchmark: True
|
112 |
-
accumulate_grad_batches: 4
|
113 |
-
check_val_every_n_epoch: 4
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
dataset_creation/generate_img_dataset.py
DELETED
@@ -1,315 +0,0 @@
|
|
1 |
-
import argparse
|
2 |
-
import json
|
3 |
-
import sys
|
4 |
-
from pathlib import Path
|
5 |
-
|
6 |
-
import k_diffusion
|
7 |
-
import numpy as np
|
8 |
-
import torch
|
9 |
-
import torch.nn as nn
|
10 |
-
from einops import rearrange, repeat
|
11 |
-
from omegaconf import OmegaConf
|
12 |
-
from PIL import Image
|
13 |
-
from pytorch_lightning import seed_everything
|
14 |
-
from tqdm import tqdm
|
15 |
-
|
16 |
-
sys.path.append("./")
|
17 |
-
sys.path.append("./stable_diffusion")
|
18 |
-
|
19 |
-
from ldm.modules.attention import CrossAttention
|
20 |
-
from ldm.util import instantiate_from_config
|
21 |
-
from metrics.clip_similarity import ClipSimilarity
|
22 |
-
|
23 |
-
|
24 |
-
################################################################################
|
25 |
-
# Modified K-diffusion Euler ancestral sampler with prompt-to-prompt.
|
26 |
-
# https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/sampling.py
|
27 |
-
|
28 |
-
|
29 |
-
def append_dims(x, target_dims):
|
30 |
-
"""Appends dimensions to the end of a tensor until it has target_dims dimensions."""
|
31 |
-
dims_to_append = target_dims - x.ndim
|
32 |
-
if dims_to_append < 0:
|
33 |
-
raise ValueError(f"input has {x.ndim} dims but target_dims is {target_dims}, which is less")
|
34 |
-
return x[(...,) + (None,) * dims_to_append]
|
35 |
-
|
36 |
-
|
37 |
-
def to_d(x, sigma, denoised):
|
38 |
-
"""Converts a denoiser output to a Karras ODE derivative."""
|
39 |
-
return (x - denoised) / append_dims(sigma, x.ndim)
|
40 |
-
|
41 |
-
|
42 |
-
def get_ancestral_step(sigma_from, sigma_to):
|
43 |
-
"""Calculates the noise level (sigma_down) to step down to and the amount
|
44 |
-
of noise to add (sigma_up) when doing an ancestral sampling step."""
|
45 |
-
sigma_up = min(sigma_to, (sigma_to**2 * (sigma_from**2 - sigma_to**2) / sigma_from**2) ** 0.5)
|
46 |
-
sigma_down = (sigma_to**2 - sigma_up**2) ** 0.5
|
47 |
-
return sigma_down, sigma_up
|
48 |
-
|
49 |
-
|
50 |
-
def sample_euler_ancestral(model, x, sigmas, prompt2prompt_threshold=0.0, **extra_args):
|
51 |
-
"""Ancestral sampling with Euler method steps."""
|
52 |
-
s_in = x.new_ones([x.shape[0]])
|
53 |
-
for i in range(len(sigmas) - 1):
|
54 |
-
prompt_to_prompt = prompt2prompt_threshold > i / (len(sigmas) - 2)
|
55 |
-
for m in model.modules():
|
56 |
-
if isinstance(m, CrossAttention):
|
57 |
-
m.prompt_to_prompt = prompt_to_prompt
|
58 |
-
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
59 |
-
sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1])
|
60 |
-
d = to_d(x, sigmas[i], denoised)
|
61 |
-
# Euler method
|
62 |
-
dt = sigma_down - sigmas[i]
|
63 |
-
x = x + d * dt
|
64 |
-
if sigmas[i + 1] > 0:
|
65 |
-
# Make noise the same across all samples in batch.
|
66 |
-
x = x + torch.randn_like(x[:1]) * sigma_up
|
67 |
-
return x
|
68 |
-
|
69 |
-
|
70 |
-
################################################################################
|
71 |
-
|
72 |
-
|
73 |
-
def load_model_from_config(config, ckpt, vae_ckpt=None, verbose=False):
|
74 |
-
print(f"Loading model from {ckpt}")
|
75 |
-
pl_sd = torch.load(ckpt, map_location="cpu")
|
76 |
-
if "global_step" in pl_sd:
|
77 |
-
print(f"Global Step: {pl_sd['global_step']}")
|
78 |
-
sd = pl_sd["state_dict"]
|
79 |
-
if vae_ckpt is not None:
|
80 |
-
print(f"Loading VAE from {vae_ckpt}")
|
81 |
-
vae_sd = torch.load(vae_ckpt, map_location="cpu")["state_dict"]
|
82 |
-
sd = {
|
83 |
-
k: vae_sd[k[len("first_stage_model.") :]] if k.startswith("first_stage_model.") else v
|
84 |
-
for k, v in sd.items()
|
85 |
-
}
|
86 |
-
model = instantiate_from_config(config.model)
|
87 |
-
m, u = model.load_state_dict(sd, strict=False)
|
88 |
-
if len(m) > 0 and verbose:
|
89 |
-
print("missing keys:")
|
90 |
-
print(m)
|
91 |
-
if len(u) > 0 and verbose:
|
92 |
-
print("unexpected keys:")
|
93 |
-
print(u)
|
94 |
-
return model
|
95 |
-
|
96 |
-
|
97 |
-
class CFGDenoiser(nn.Module):
|
98 |
-
def __init__(self, model):
|
99 |
-
super().__init__()
|
100 |
-
self.inner_model = model
|
101 |
-
|
102 |
-
def forward(self, x, sigma, uncond, cond, cfg_scale):
|
103 |
-
x_in = torch.cat([x] * 2)
|
104 |
-
sigma_in = torch.cat([sigma] * 2)
|
105 |
-
cond_in = torch.cat([uncond, cond])
|
106 |
-
uncond, cond = self.inner_model(x_in, sigma_in, cond=cond_in).chunk(2)
|
107 |
-
return uncond + (cond - uncond) * cfg_scale
|
108 |
-
|
109 |
-
|
110 |
-
def to_pil(image: torch.Tensor) -> Image.Image:
|
111 |
-
image = 255.0 * rearrange(image.cpu().numpy(), "c h w -> h w c")
|
112 |
-
image = Image.fromarray(image.astype(np.uint8))
|
113 |
-
return image
|
114 |
-
|
115 |
-
|
116 |
-
def main():
|
117 |
-
parser = argparse.ArgumentParser()
|
118 |
-
parser.add_argument(
|
119 |
-
"--out_dir",
|
120 |
-
type=str,
|
121 |
-
required=True,
|
122 |
-
help="Path to output dataset directory.",
|
123 |
-
)
|
124 |
-
parser.add_argument(
|
125 |
-
"--prompts_file",
|
126 |
-
type=str,
|
127 |
-
required=True,
|
128 |
-
help="Path to prompts .jsonl file.",
|
129 |
-
)
|
130 |
-
parser.add_argument(
|
131 |
-
"--ckpt",
|
132 |
-
type=str,
|
133 |
-
default="stable_diffusion/models/ldm/stable-diffusion-v1/v1-5-pruned-emaonly.ckpt",
|
134 |
-
help="Path to stable diffusion checkpoint.",
|
135 |
-
)
|
136 |
-
parser.add_argument(
|
137 |
-
"--vae-ckpt",
|
138 |
-
type=str,
|
139 |
-
default="stable_diffusion/models/ldm/stable-diffusion-v1/vae-ft-mse-840000-ema-pruned.ckpt",
|
140 |
-
help="Path to vae checkpoint.",
|
141 |
-
)
|
142 |
-
parser.add_argument(
|
143 |
-
"--steps",
|
144 |
-
type=int,
|
145 |
-
default=100,
|
146 |
-
help="Number of sampling steps.",
|
147 |
-
)
|
148 |
-
parser.add_argument(
|
149 |
-
"--n-samples",
|
150 |
-
type=int,
|
151 |
-
default=100,
|
152 |
-
help="Number of samples to generate per prompt (before CLIP filtering).",
|
153 |
-
)
|
154 |
-
parser.add_argument(
|
155 |
-
"--max-out-samples",
|
156 |
-
type=int,
|
157 |
-
default=4,
|
158 |
-
help="Max number of output samples to save per prompt (after CLIP filtering).",
|
159 |
-
)
|
160 |
-
parser.add_argument(
|
161 |
-
"--n-partitions",
|
162 |
-
type=int,
|
163 |
-
default=1,
|
164 |
-
help="Number of total partitions.",
|
165 |
-
)
|
166 |
-
parser.add_argument(
|
167 |
-
"--partition",
|
168 |
-
type=int,
|
169 |
-
default=0,
|
170 |
-
help="Partition index.",
|
171 |
-
)
|
172 |
-
parser.add_argument(
|
173 |
-
"--min-p2p",
|
174 |
-
type=float,
|
175 |
-
default=0.1,
|
176 |
-
help="Min prompt2prompt threshold (portion of denoising for which to fix self attention maps).",
|
177 |
-
)
|
178 |
-
parser.add_argument(
|
179 |
-
"--max-p2p",
|
180 |
-
type=float,
|
181 |
-
default=0.9,
|
182 |
-
help="Max prompt2prompt threshold (portion of denoising for which to fix self attention maps).",
|
183 |
-
)
|
184 |
-
parser.add_argument(
|
185 |
-
"--min-cfg",
|
186 |
-
type=float,
|
187 |
-
default=7.5,
|
188 |
-
help="Min classifier free guidance scale.",
|
189 |
-
)
|
190 |
-
parser.add_argument(
|
191 |
-
"--max-cfg",
|
192 |
-
type=float,
|
193 |
-
default=15,
|
194 |
-
help="Max classifier free guidance scale.",
|
195 |
-
)
|
196 |
-
parser.add_argument(
|
197 |
-
"--clip-threshold",
|
198 |
-
type=float,
|
199 |
-
default=0.2,
|
200 |
-
help="CLIP threshold for text-image similarity of each image.",
|
201 |
-
)
|
202 |
-
parser.add_argument(
|
203 |
-
"--clip-dir-threshold",
|
204 |
-
type=float,
|
205 |
-
default=0.2,
|
206 |
-
help="Directional CLIP threshold for similarity of change between pairs of text and pairs of images.",
|
207 |
-
)
|
208 |
-
parser.add_argument(
|
209 |
-
"--clip-img-threshold",
|
210 |
-
type=float,
|
211 |
-
default=0.7,
|
212 |
-
help="CLIP threshold for image-image similarity.",
|
213 |
-
)
|
214 |
-
opt = parser.parse_args()
|
215 |
-
|
216 |
-
global_seed = torch.randint(1 << 32, ()).item()
|
217 |
-
print(f"Global seed: {global_seed}")
|
218 |
-
seed_everything(global_seed)
|
219 |
-
|
220 |
-
model = load_model_from_config(
|
221 |
-
OmegaConf.load("stable_diffusion/configs/stable-diffusion/v1-inference.yaml"),
|
222 |
-
ckpt=opt.ckpt,
|
223 |
-
vae_ckpt=opt.vae_ckpt,
|
224 |
-
)
|
225 |
-
model.cuda().eval()
|
226 |
-
model_wrap = k_diffusion.external.CompVisDenoiser(model)
|
227 |
-
|
228 |
-
clip_similarity = ClipSimilarity().cuda()
|
229 |
-
|
230 |
-
out_dir = Path(opt.out_dir)
|
231 |
-
out_dir.mkdir(exist_ok=True, parents=True)
|
232 |
-
|
233 |
-
with open(opt.prompts_file) as fp:
|
234 |
-
prompts = [json.loads(line) for line in fp]
|
235 |
-
|
236 |
-
print(f"Partition index {opt.partition} ({opt.partition + 1} / {opt.n_partitions})")
|
237 |
-
prompts = np.array_split(list(enumerate(prompts)), opt.n_partitions)[opt.partition]
|
238 |
-
|
239 |
-
with torch.no_grad(), torch.autocast("cuda"), model.ema_scope():
|
240 |
-
uncond = model.get_learned_conditioning(2 * [""])
|
241 |
-
sigmas = model_wrap.get_sigmas(opt.steps)
|
242 |
-
|
243 |
-
for i, prompt in tqdm(prompts, desc="Prompts"):
|
244 |
-
prompt_dir = out_dir.joinpath(f"{i:07d}")
|
245 |
-
prompt_dir.mkdir(exist_ok=True)
|
246 |
-
|
247 |
-
with open(prompt_dir.joinpath("prompt.json"), "w") as fp:
|
248 |
-
json.dump(prompt, fp)
|
249 |
-
|
250 |
-
cond = model.get_learned_conditioning([prompt["caption"], prompt["output"]])
|
251 |
-
results = {}
|
252 |
-
|
253 |
-
with tqdm(total=opt.n_samples, desc="Samples") as progress_bar:
|
254 |
-
|
255 |
-
while len(results) < opt.n_samples:
|
256 |
-
seed = torch.randint(1 << 32, ()).item()
|
257 |
-
if seed in results:
|
258 |
-
continue
|
259 |
-
torch.manual_seed(seed)
|
260 |
-
|
261 |
-
x = torch.randn(1, 4, 512 // 8, 512 // 8, device="cuda") * sigmas[0]
|
262 |
-
x = repeat(x, "1 ... -> n ...", n=2)
|
263 |
-
|
264 |
-
model_wrap_cfg = CFGDenoiser(model_wrap)
|
265 |
-
p2p_threshold = opt.min_p2p + torch.rand(()).item() * (opt.max_p2p - opt.min_p2p)
|
266 |
-
cfg_scale = opt.min_cfg + torch.rand(()).item() * (opt.max_cfg - opt.min_cfg)
|
267 |
-
extra_args = {"cond": cond, "uncond": uncond, "cfg_scale": cfg_scale}
|
268 |
-
samples_ddim = sample_euler_ancestral(model_wrap_cfg, x, sigmas, p2p_threshold, **extra_args)
|
269 |
-
x_samples_ddim = model.decode_first_stage(samples_ddim)
|
270 |
-
x_samples_ddim = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0)
|
271 |
-
|
272 |
-
x0 = x_samples_ddim[0]
|
273 |
-
x1 = x_samples_ddim[1]
|
274 |
-
|
275 |
-
clip_sim_0, clip_sim_1, clip_sim_dir, clip_sim_image = clip_similarity(
|
276 |
-
x0[None], x1[None], [prompt["caption"]], [prompt["output"]]
|
277 |
-
)
|
278 |
-
|
279 |
-
results[seed] = dict(
|
280 |
-
image_0=to_pil(x0),
|
281 |
-
image_1=to_pil(x1),
|
282 |
-
p2p_threshold=p2p_threshold,
|
283 |
-
cfg_scale=cfg_scale,
|
284 |
-
clip_sim_0=clip_sim_0[0].item(),
|
285 |
-
clip_sim_1=clip_sim_1[0].item(),
|
286 |
-
clip_sim_dir=clip_sim_dir[0].item(),
|
287 |
-
clip_sim_image=clip_sim_image[0].item(),
|
288 |
-
)
|
289 |
-
|
290 |
-
progress_bar.update()
|
291 |
-
|
292 |
-
# CLIP filter to get best samples for each prompt.
|
293 |
-
metadata = [
|
294 |
-
(result["clip_sim_dir"], seed)
|
295 |
-
for seed, result in results.items()
|
296 |
-
if result["clip_sim_image"] >= opt.clip_img_threshold
|
297 |
-
and result["clip_sim_dir"] >= opt.clip_dir_threshold
|
298 |
-
and result["clip_sim_0"] >= opt.clip_threshold
|
299 |
-
and result["clip_sim_1"] >= opt.clip_threshold
|
300 |
-
]
|
301 |
-
metadata.sort(reverse=True)
|
302 |
-
for _, seed in metadata[: opt.max_out_samples]:
|
303 |
-
result = results[seed]
|
304 |
-
image_0 = result.pop("image_0")
|
305 |
-
image_1 = result.pop("image_1")
|
306 |
-
image_0.save(prompt_dir.joinpath(f"{seed}_0.jpg"), quality=100)
|
307 |
-
image_1.save(prompt_dir.joinpath(f"{seed}_1.jpg"), quality=100)
|
308 |
-
with open(prompt_dir.joinpath(f"metadata.jsonl"), "a") as fp:
|
309 |
-
fp.write(f"{json.dumps(dict(seed=seed, **result))}\n")
|
310 |
-
|
311 |
-
print("Done.")
|
312 |
-
|
313 |
-
|
314 |
-
if __name__ == "__main__":
|
315 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
dataset_creation/generate_txt_dataset.py
DELETED
@@ -1,113 +0,0 @@
|
|
1 |
-
from __future__ import annotations
|
2 |
-
|
3 |
-
import json
|
4 |
-
import time
|
5 |
-
from argparse import ArgumentParser
|
6 |
-
from pathlib import Path
|
7 |
-
from typing import Optional
|
8 |
-
|
9 |
-
import datasets
|
10 |
-
import numpy as np
|
11 |
-
import openai
|
12 |
-
from tqdm.auto import tqdm
|
13 |
-
|
14 |
-
|
15 |
-
DELIMITER_0 = "\n##\n"
|
16 |
-
DELIMITER_1 = "\n%%\n"
|
17 |
-
STOP = "\nEND"
|
18 |
-
|
19 |
-
|
20 |
-
def generate(
|
21 |
-
openai_model: str,
|
22 |
-
caption: str,
|
23 |
-
num_retries: int = 3,
|
24 |
-
max_tokens: int = 256,
|
25 |
-
temperature: float = 0.7,
|
26 |
-
top_p: float = 1.0,
|
27 |
-
frequency_penalty: float = 0.1,
|
28 |
-
presence_penalty: float = 0.0,
|
29 |
-
sleep_on_error: float = 1.0,
|
30 |
-
) -> Optional[tuple[str, str]]:
|
31 |
-
for _ in range(1 + num_retries):
|
32 |
-
try:
|
33 |
-
response = openai.Completion.create(
|
34 |
-
model=openai_model,
|
35 |
-
prompt=caption + DELIMITER_0,
|
36 |
-
temperature=temperature,
|
37 |
-
max_tokens=max_tokens,
|
38 |
-
top_p=top_p,
|
39 |
-
frequency_penalty=frequency_penalty,
|
40 |
-
presence_penalty=presence_penalty,
|
41 |
-
stop=[STOP],
|
42 |
-
)
|
43 |
-
except Exception as e:
|
44 |
-
print(e)
|
45 |
-
time.sleep(sleep_on_error)
|
46 |
-
continue
|
47 |
-
output = response["choices"][0]["text"].split(DELIMITER_1)
|
48 |
-
if len(output) == 2:
|
49 |
-
instruction, edited_caption = output
|
50 |
-
results = openai.Moderation.create([instruction, edited_caption])["results"]
|
51 |
-
if results[0]["flagged"] or results[1]["flagged"]:
|
52 |
-
continue
|
53 |
-
if caption.strip().strip(".!?").lower() != edited_caption.strip().strip(".!?").lower():
|
54 |
-
return instruction, edited_caption
|
55 |
-
|
56 |
-
|
57 |
-
def main(openai_model: str, num_samples: int, num_partitions: int, partition: int, seed: int):
|
58 |
-
dataset = datasets.load_dataset("ChristophSchuhmann/improved_aesthetics_6.5plus", split="train")
|
59 |
-
# Other datasets we considered that may be worth trying:
|
60 |
-
# dataset = datasets.load_dataset("ChristophSchuhmann/MS_COCO_2017_URL_TEXT", split="train")
|
61 |
-
# dataset = datasets.load_dataset("laion/laion-coco", split="train")
|
62 |
-
|
63 |
-
np.random.seed(seed)
|
64 |
-
permutation = np.array_split(np.random.permutation(len(dataset)), num_partitions)[partition]
|
65 |
-
dataset = dataset[permutation]
|
66 |
-
captions = dataset["TEXT"]
|
67 |
-
urls = dataset["URL"]
|
68 |
-
output_path = f"data/dataset=laion-aesthetics-6.5_model={openai_model}_samples={num_samples}_partition={partition}.jsonl" # fmt: skip
|
69 |
-
print(f"Prompt file path: {output_path}")
|
70 |
-
|
71 |
-
count = 0
|
72 |
-
caption_set = set()
|
73 |
-
url_set = set()
|
74 |
-
|
75 |
-
if Path(output_path).exists():
|
76 |
-
with open(output_path, "r") as f:
|
77 |
-
for line in tqdm(f, desc="Resuming from existing prompts"):
|
78 |
-
prompt = json.loads(line)
|
79 |
-
if prompt["caption"] not in caption_set and prompt["url"] not in url_set:
|
80 |
-
caption_set.add(prompt["caption"])
|
81 |
-
url_set.add(prompt["url"])
|
82 |
-
count += 1
|
83 |
-
|
84 |
-
with open(output_path, "a") as fp:
|
85 |
-
with tqdm(total=num_samples - count, desc="Generating instructions and edited captions") as progress_bar:
|
86 |
-
for caption, url in zip(captions, urls):
|
87 |
-
if caption in caption_set or url in url_set:
|
88 |
-
continue
|
89 |
-
if openai.Moderation.create(caption)["results"][0]["flagged"]:
|
90 |
-
continue
|
91 |
-
edit_output = generate(openai_model, caption)
|
92 |
-
if edit_output is not None:
|
93 |
-
edit, output = edit_output
|
94 |
-
fp.write(f"{json.dumps(dict(caption=caption, edit=edit, output=output, url=url))}\n")
|
95 |
-
count += 1
|
96 |
-
progress_bar.update()
|
97 |
-
caption_set.add(caption)
|
98 |
-
url_set.add(url)
|
99 |
-
if count == num_samples:
|
100 |
-
break
|
101 |
-
|
102 |
-
|
103 |
-
if __name__ == "__main__":
|
104 |
-
parser = ArgumentParser()
|
105 |
-
parser.add_argument("--openai-api-key", required=True, type=str)
|
106 |
-
parser.add_argument("--openai-model", required=True, type=str)
|
107 |
-
parser.add_argument("--num-samples", default=10000, type=int)
|
108 |
-
parser.add_argument("--num-partitions", default=1, type=int)
|
109 |
-
parser.add_argument("--partition", default=0, type=int)
|
110 |
-
parser.add_argument("--seed", default=0, type=int)
|
111 |
-
args = parser.parse_args()
|
112 |
-
openai.api_key = args.openai_api_key
|
113 |
-
main(args.openai_model, args.num_samples, args.num_partitions, args.partition, args.seed)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
dataset_creation/prepare_dataset.py
DELETED
@@ -1,29 +0,0 @@
|
|
1 |
-
import json
|
2 |
-
from argparse import ArgumentParser
|
3 |
-
from pathlib import Path
|
4 |
-
|
5 |
-
from tqdm.auto import tqdm
|
6 |
-
|
7 |
-
|
8 |
-
def main():
|
9 |
-
parser = ArgumentParser()
|
10 |
-
parser.add_argument("dataset_dir")
|
11 |
-
args = parser.parse_args()
|
12 |
-
dataset_dir = Path(args.dataset_dir)
|
13 |
-
|
14 |
-
seeds = []
|
15 |
-
with tqdm(desc="Listing dataset image seeds") as progress_bar:
|
16 |
-
for prompt_dir in dataset_dir.iterdir():
|
17 |
-
if prompt_dir.is_dir():
|
18 |
-
prompt_seeds = [image_path.name.split("_")[0] for image_path in sorted(prompt_dir.glob("*_0.jpg"))]
|
19 |
-
if len(prompt_seeds) > 0:
|
20 |
-
seeds.append((prompt_dir.name, prompt_seeds))
|
21 |
-
progress_bar.update()
|
22 |
-
seeds.sort()
|
23 |
-
|
24 |
-
with open(dataset_dir.joinpath("seeds.json"), "w") as f:
|
25 |
-
json.dump(seeds, f)
|
26 |
-
|
27 |
-
|
28 |
-
if __name__ == "__main__":
|
29 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
dataset_creation/prepare_for_gpt.py
DELETED
@@ -1,25 +0,0 @@
|
|
1 |
-
import json
|
2 |
-
from argparse import ArgumentParser
|
3 |
-
|
4 |
-
from generate_txt_dataset import DELIMITER_0, DELIMITER_1, STOP
|
5 |
-
|
6 |
-
|
7 |
-
def main(input_path: str, output_path: str):
|
8 |
-
with open(input_path) as f:
|
9 |
-
prompts = [json.loads(l) for l in f]
|
10 |
-
|
11 |
-
with open(output_path, "w") as f:
|
12 |
-
for prompt in prompts:
|
13 |
-
prompt_for_gpt = {
|
14 |
-
"prompt": f"{prompt['input']}{DELIMITER_0}",
|
15 |
-
"completion": f"{prompt['edit']}{DELIMITER_1}{prompt['output']}{STOP}",
|
16 |
-
}
|
17 |
-
f.write(f"{json.dumps(prompt_for_gpt)}\n")
|
18 |
-
|
19 |
-
|
20 |
-
if __name__ == "__main__":
|
21 |
-
parser = ArgumentParser()
|
22 |
-
parser.add_argument("--input-path", required=True, type=str)
|
23 |
-
parser.add_argument("--output-path", required=True, type=str)
|
24 |
-
args = parser.parse_args()
|
25 |
-
main(args.input_path, args.output_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
edit_cli.py
DELETED
@@ -1,128 +0,0 @@
|
|
1 |
-
from __future__ import annotations
|
2 |
-
|
3 |
-
import math
|
4 |
-
import random
|
5 |
-
import sys
|
6 |
-
from argparse import ArgumentParser
|
7 |
-
|
8 |
-
import einops
|
9 |
-
import k_diffusion as K
|
10 |
-
import numpy as np
|
11 |
-
import torch
|
12 |
-
import torch.nn as nn
|
13 |
-
from einops import rearrange
|
14 |
-
from omegaconf import OmegaConf
|
15 |
-
from PIL import Image, ImageOps
|
16 |
-
from torch import autocast
|
17 |
-
|
18 |
-
sys.path.append("./stable_diffusion")
|
19 |
-
|
20 |
-
from stable_diffusion.ldm.util import instantiate_from_config
|
21 |
-
|
22 |
-
|
23 |
-
class CFGDenoiser(nn.Module):
|
24 |
-
def __init__(self, model):
|
25 |
-
super().__init__()
|
26 |
-
self.inner_model = model
|
27 |
-
|
28 |
-
def forward(self, z, sigma, cond, uncond, text_cfg_scale, image_cfg_scale):
|
29 |
-
cfg_z = einops.repeat(z, "1 ... -> n ...", n=3)
|
30 |
-
cfg_sigma = einops.repeat(sigma, "1 ... -> n ...", n=3)
|
31 |
-
cfg_cond = {
|
32 |
-
"c_crossattn": [torch.cat([cond["c_crossattn"][0], uncond["c_crossattn"][0], uncond["c_crossattn"][0]])],
|
33 |
-
"c_concat": [torch.cat([cond["c_concat"][0], cond["c_concat"][0], uncond["c_concat"][0]])],
|
34 |
-
}
|
35 |
-
out_cond, out_img_cond, out_uncond = self.inner_model(cfg_z, cfg_sigma, cond=cfg_cond).chunk(3)
|
36 |
-
return out_uncond + text_cfg_scale * (out_cond - out_img_cond) + image_cfg_scale * (out_img_cond - out_uncond)
|
37 |
-
|
38 |
-
|
39 |
-
def load_model_from_config(config, ckpt, vae_ckpt=None, verbose=False):
|
40 |
-
print(f"Loading model from {ckpt}")
|
41 |
-
pl_sd = torch.load(ckpt, map_location="cpu")
|
42 |
-
if "global_step" in pl_sd:
|
43 |
-
print(f"Global Step: {pl_sd['global_step']}")
|
44 |
-
sd = pl_sd["state_dict"]
|
45 |
-
if vae_ckpt is not None:
|
46 |
-
print(f"Loading VAE from {vae_ckpt}")
|
47 |
-
vae_sd = torch.load(vae_ckpt, map_location="cpu")["state_dict"]
|
48 |
-
sd = {
|
49 |
-
k: vae_sd[k[len("first_stage_model.") :]] if k.startswith("first_stage_model.") else v
|
50 |
-
for k, v in sd.items()
|
51 |
-
}
|
52 |
-
model = instantiate_from_config(config.model)
|
53 |
-
m, u = model.load_state_dict(sd, strict=False)
|
54 |
-
if len(m) > 0 and verbose:
|
55 |
-
print("missing keys:")
|
56 |
-
print(m)
|
57 |
-
if len(u) > 0 and verbose:
|
58 |
-
print("unexpected keys:")
|
59 |
-
print(u)
|
60 |
-
return model
|
61 |
-
|
62 |
-
|
63 |
-
def main():
|
64 |
-
parser = ArgumentParser()
|
65 |
-
parser.add_argument("--resolution", default=512, type=int)
|
66 |
-
parser.add_argument("--steps", default=100, type=int)
|
67 |
-
parser.add_argument("--config", default="configs/generate.yaml", type=str)
|
68 |
-
parser.add_argument("--ckpt", default="checkpoints/instruct-pix2pix-00-22000.ckpt", type=str)
|
69 |
-
parser.add_argument("--vae-ckpt", default=None, type=str)
|
70 |
-
parser.add_argument("--input", required=True, type=str)
|
71 |
-
parser.add_argument("--output", required=True, type=str)
|
72 |
-
parser.add_argument("--edit", required=True, type=str)
|
73 |
-
parser.add_argument("--cfg-text", default=7.5, type=float)
|
74 |
-
parser.add_argument("--cfg-image", default=1.5, type=float)
|
75 |
-
parser.add_argument("--seed", type=int)
|
76 |
-
args = parser.parse_args()
|
77 |
-
|
78 |
-
config = OmegaConf.load(args.config)
|
79 |
-
model = load_model_from_config(config, args.ckpt, args.vae_ckpt)
|
80 |
-
model.eval().cuda()
|
81 |
-
model_wrap = K.external.CompVisDenoiser(model)
|
82 |
-
model_wrap_cfg = CFGDenoiser(model_wrap)
|
83 |
-
null_token = model.get_learned_conditioning([""])
|
84 |
-
|
85 |
-
seed = random.randint(0, 100000) if args.seed is None else args.seed
|
86 |
-
input_image = Image.open(args.input).convert("RGB")
|
87 |
-
width, height = input_image.size
|
88 |
-
factor = args.resolution / max(width, height)
|
89 |
-
factor = math.ceil(min(width, height) * factor / 64) * 64 / min(width, height)
|
90 |
-
width = int((width * factor) // 64) * 64
|
91 |
-
height = int((height * factor) // 64) * 64
|
92 |
-
input_image = ImageOps.fit(input_image, (width, height), method=Image.Resampling.LANCZOS)
|
93 |
-
|
94 |
-
if args.edit == "":
|
95 |
-
input_image.save(args.output)
|
96 |
-
return
|
97 |
-
|
98 |
-
with torch.no_grad(), autocast("cuda"), model.ema_scope():
|
99 |
-
cond = {}
|
100 |
-
cond["c_crossattn"] = [model.get_learned_conditioning([args.edit])]
|
101 |
-
input_image = 2 * torch.tensor(np.array(input_image)).float() / 255 - 1
|
102 |
-
input_image = rearrange(input_image, "h w c -> 1 c h w").to(model.device)
|
103 |
-
cond["c_concat"] = [model.encode_first_stage(input_image).mode()]
|
104 |
-
|
105 |
-
uncond = {}
|
106 |
-
uncond["c_crossattn"] = [null_token]
|
107 |
-
uncond["c_concat"] = [torch.zeros_like(cond["c_concat"][0])]
|
108 |
-
|
109 |
-
sigmas = model_wrap.get_sigmas(args.steps)
|
110 |
-
|
111 |
-
extra_args = {
|
112 |
-
"cond": cond,
|
113 |
-
"uncond": uncond,
|
114 |
-
"text_cfg_scale": args.cfg_text,
|
115 |
-
"image_cfg_scale": args.cfg_image,
|
116 |
-
}
|
117 |
-
torch.manual_seed(seed)
|
118 |
-
z = torch.randn_like(cond["c_concat"][0]) * sigmas[0]
|
119 |
-
z = K.sampling.sample_euler_ancestral(model_wrap_cfg, z, sigmas, extra_args=extra_args)
|
120 |
-
x = model.decode_first_stage(z)
|
121 |
-
x = torch.clamp((x + 1.0) / 2.0, min=0.0, max=1.0)
|
122 |
-
x = 255.0 * rearrange(x, "1 c h w -> h w c")
|
123 |
-
edited_image = Image.fromarray(x.type(torch.uint8).cpu().numpy())
|
124 |
-
edited_image.save(args.output)
|
125 |
-
|
126 |
-
|
127 |
-
if __name__ == "__main__":
|
128 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
edit_dataset.py
DELETED
@@ -1,121 +0,0 @@
|
|
1 |
-
from __future__ import annotations
|
2 |
-
|
3 |
-
import json
|
4 |
-
import math
|
5 |
-
from pathlib import Path
|
6 |
-
from typing import Any
|
7 |
-
|
8 |
-
import numpy as np
|
9 |
-
import torch
|
10 |
-
import torchvision
|
11 |
-
from einops import rearrange
|
12 |
-
from PIL import Image
|
13 |
-
from torch.utils.data import Dataset
|
14 |
-
|
15 |
-
|
16 |
-
class EditDataset(Dataset):
|
17 |
-
def __init__(
|
18 |
-
self,
|
19 |
-
path: str,
|
20 |
-
split: str = "train",
|
21 |
-
splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
|
22 |
-
min_resize_res: int = 256,
|
23 |
-
max_resize_res: int = 256,
|
24 |
-
crop_res: int = 256,
|
25 |
-
flip_prob: float = 0.0,
|
26 |
-
):
|
27 |
-
assert split in ("train", "val", "test")
|
28 |
-
assert sum(splits) == 1
|
29 |
-
self.path = path
|
30 |
-
self.min_resize_res = min_resize_res
|
31 |
-
self.max_resize_res = max_resize_res
|
32 |
-
self.crop_res = crop_res
|
33 |
-
self.flip_prob = flip_prob
|
34 |
-
|
35 |
-
with open(Path(self.path, "seeds.json")) as f:
|
36 |
-
self.seeds = json.load(f)
|
37 |
-
|
38 |
-
split_0, split_1 = {
|
39 |
-
"train": (0.0, splits[0]),
|
40 |
-
"val": (splits[0], splits[0] + splits[1]),
|
41 |
-
"test": (splits[0] + splits[1], 1.0),
|
42 |
-
}[split]
|
43 |
-
|
44 |
-
idx_0 = math.floor(split_0 * len(self.seeds))
|
45 |
-
idx_1 = math.floor(split_1 * len(self.seeds))
|
46 |
-
self.seeds = self.seeds[idx_0:idx_1]
|
47 |
-
|
48 |
-
def __len__(self) -> int:
|
49 |
-
return len(self.seeds)
|
50 |
-
|
51 |
-
def __getitem__(self, i: int) -> dict[str, Any]:
|
52 |
-
name, seeds = self.seeds[i]
|
53 |
-
propt_dir = Path(self.path, name)
|
54 |
-
seed = seeds[torch.randint(0, len(seeds), ()).item()]
|
55 |
-
with open(propt_dir.joinpath("prompt.json")) as fp:
|
56 |
-
prompt = json.load(fp)["edit"]
|
57 |
-
|
58 |
-
image_0 = Image.open(propt_dir.joinpath(f"{seed}_0.jpg"))
|
59 |
-
image_1 = Image.open(propt_dir.joinpath(f"{seed}_1.jpg"))
|
60 |
-
|
61 |
-
reize_res = torch.randint(self.min_resize_res, self.max_resize_res + 1, ()).item()
|
62 |
-
image_0 = image_0.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
|
63 |
-
image_1 = image_1.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
|
64 |
-
|
65 |
-
image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
|
66 |
-
image_1 = rearrange(2 * torch.tensor(np.array(image_1)).float() / 255 - 1, "h w c -> c h w")
|
67 |
-
|
68 |
-
crop = torchvision.transforms.RandomCrop(self.crop_res)
|
69 |
-
flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
|
70 |
-
image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
|
71 |
-
|
72 |
-
return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
|
73 |
-
|
74 |
-
|
75 |
-
class EditDatasetEval(Dataset):
|
76 |
-
def __init__(
|
77 |
-
self,
|
78 |
-
path: str,
|
79 |
-
split: str = "train",
|
80 |
-
splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
|
81 |
-
res: int = 256,
|
82 |
-
):
|
83 |
-
assert split in ("train", "val", "test")
|
84 |
-
assert sum(splits) == 1
|
85 |
-
self.path = path
|
86 |
-
self.res = res
|
87 |
-
|
88 |
-
with open(Path(self.path, "seeds.json")) as f:
|
89 |
-
self.seeds = json.load(f)
|
90 |
-
|
91 |
-
split_0, split_1 = {
|
92 |
-
"train": (0.0, splits[0]),
|
93 |
-
"val": (splits[0], splits[0] + splits[1]),
|
94 |
-
"test": (splits[0] + splits[1], 1.0),
|
95 |
-
}[split]
|
96 |
-
|
97 |
-
idx_0 = math.floor(split_0 * len(self.seeds))
|
98 |
-
idx_1 = math.floor(split_1 * len(self.seeds))
|
99 |
-
self.seeds = self.seeds[idx_0:idx_1]
|
100 |
-
|
101 |
-
def __len__(self) -> int:
|
102 |
-
return len(self.seeds)
|
103 |
-
|
104 |
-
def __getitem__(self, i: int) -> dict[str, Any]:
|
105 |
-
name, seeds = self.seeds[i]
|
106 |
-
propt_dir = Path(self.path, name)
|
107 |
-
seed = seeds[torch.randint(0, len(seeds), ()).item()]
|
108 |
-
with open(propt_dir.joinpath("prompt.json")) as fp:
|
109 |
-
prompt = json.load(fp)
|
110 |
-
edit = prompt["edit"]
|
111 |
-
input_prompt = prompt["input"]
|
112 |
-
output_prompt = prompt["output"]
|
113 |
-
|
114 |
-
image_0 = Image.open(propt_dir.joinpath(f"{seed}_0.jpg"))
|
115 |
-
|
116 |
-
reize_res = torch.randint(self.res, self.res + 1, ()).item()
|
117 |
-
image_0 = image_0.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
|
118 |
-
|
119 |
-
image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
|
120 |
-
|
121 |
-
return dict(image_0=image_0, input_prompt=input_prompt, edit=edit, output_prompt=output_prompt)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
environment.yaml
DELETED
@@ -1,38 +0,0 @@
|
|
1 |
-
# File modified by authors of InstructPix2Pix from original (https://github.com/CompVis/stable-diffusion).
|
2 |
-
# See more details in LICENSE.
|
3 |
-
|
4 |
-
name: ip2p
|
5 |
-
channels:
|
6 |
-
- pytorch
|
7 |
-
- defaults
|
8 |
-
dependencies:
|
9 |
-
- python=3.8.5
|
10 |
-
- pip=20.3
|
11 |
-
- cudatoolkit=11.3
|
12 |
-
- pytorch=1.11.0
|
13 |
-
- torchvision=0.12.0
|
14 |
-
- numpy=1.19.2
|
15 |
-
- pip:
|
16 |
-
- albumentations==0.4.3
|
17 |
-
- datasets==2.8.0
|
18 |
-
- diffusers
|
19 |
-
- opencv-python==4.1.2.30
|
20 |
-
- pudb==2019.2
|
21 |
-
- invisible-watermark
|
22 |
-
- imageio==2.9.0
|
23 |
-
- imageio-ffmpeg==0.4.2
|
24 |
-
- pytorch-lightning==1.4.2
|
25 |
-
- omegaconf==2.1.1
|
26 |
-
- test-tube>=0.7.5
|
27 |
-
- streamlit>=0.73.1
|
28 |
-
- einops==0.3.0
|
29 |
-
- torch-fidelity==0.3.0
|
30 |
-
- transformers==4.19.2
|
31 |
-
- torchmetrics==0.6.0
|
32 |
-
- kornia==0.6
|
33 |
-
- -e git+https://github.com/CompVis/taming-transformers.git@master#egg=taming-transformers
|
34 |
-
- -e git+https://github.com/openai/CLIP.git@main#egg=clip
|
35 |
-
- openai
|
36 |
-
- gradio
|
37 |
-
- seaborn
|
38 |
-
- git+https://github.com/crowsonkb/k-diffusion.git
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
imgs/dataset.jpg
DELETED
Binary file (100 kB)
|
|
imgs/edit_app.jpg
DELETED
Binary file (402 kB)
|
|
imgs/prompt_app.jpg
DELETED
Binary file (70.4 kB)
|
|
main.py
DELETED
@@ -1,799 +0,0 @@
|
|
1 |
-
import argparse, os, sys, datetime, glob
|
2 |
-
import numpy as np
|
3 |
-
import time
|
4 |
-
import torch
|
5 |
-
import torchvision
|
6 |
-
import pytorch_lightning as pl
|
7 |
-
import json
|
8 |
-
import pickle
|
9 |
-
|
10 |
-
from packaging import version
|
11 |
-
from omegaconf import OmegaConf
|
12 |
-
from torch.utils.data import DataLoader, Dataset
|
13 |
-
from functools import partial
|
14 |
-
from PIL import Image
|
15 |
-
|
16 |
-
import torch.distributed as dist
|
17 |
-
from pytorch_lightning import seed_everything
|
18 |
-
from pytorch_lightning.trainer import Trainer
|
19 |
-
from pytorch_lightning.callbacks import ModelCheckpoint, Callback, LearningRateMonitor
|
20 |
-
from pytorch_lightning.utilities.distributed import rank_zero_only
|
21 |
-
from pytorch_lightning.utilities import rank_zero_info
|
22 |
-
from pytorch_lightning.plugins import DDPPlugin
|
23 |
-
|
24 |
-
sys.path.append("./stable_diffusion")
|
25 |
-
|
26 |
-
from ldm.data.base import Txt2ImgIterableBaseDataset
|
27 |
-
from ldm.util import instantiate_from_config
|
28 |
-
|
29 |
-
|
30 |
-
def get_parser(**parser_kwargs):
|
31 |
-
def str2bool(v):
|
32 |
-
if isinstance(v, bool):
|
33 |
-
return v
|
34 |
-
if v.lower() in ("yes", "true", "t", "y", "1"):
|
35 |
-
return True
|
36 |
-
elif v.lower() in ("no", "false", "f", "n", "0"):
|
37 |
-
return False
|
38 |
-
else:
|
39 |
-
raise argparse.ArgumentTypeError("Boolean value expected.")
|
40 |
-
|
41 |
-
parser = argparse.ArgumentParser(**parser_kwargs)
|
42 |
-
parser.add_argument(
|
43 |
-
"-n",
|
44 |
-
"--name",
|
45 |
-
type=str,
|
46 |
-
const=True,
|
47 |
-
default="",
|
48 |
-
nargs="?",
|
49 |
-
help="postfix for logdir",
|
50 |
-
)
|
51 |
-
parser.add_argument(
|
52 |
-
"-r",
|
53 |
-
"--resume",
|
54 |
-
type=str,
|
55 |
-
const=True,
|
56 |
-
default="",
|
57 |
-
nargs="?",
|
58 |
-
help="resume from logdir or checkpoint in logdir",
|
59 |
-
)
|
60 |
-
parser.add_argument(
|
61 |
-
"-b",
|
62 |
-
"--base",
|
63 |
-
nargs="*",
|
64 |
-
metavar="base_config.yaml",
|
65 |
-
help="paths to base configs. Loaded from left-to-right. "
|
66 |
-
"Parameters can be overwritten or added with command-line options of the form `--key value`.",
|
67 |
-
default=list(),
|
68 |
-
)
|
69 |
-
parser.add_argument(
|
70 |
-
"-t",
|
71 |
-
"--train",
|
72 |
-
type=str2bool,
|
73 |
-
const=True,
|
74 |
-
default=False,
|
75 |
-
nargs="?",
|
76 |
-
help="train",
|
77 |
-
)
|
78 |
-
parser.add_argument(
|
79 |
-
"--no-test",
|
80 |
-
type=str2bool,
|
81 |
-
const=True,
|
82 |
-
default=False,
|
83 |
-
nargs="?",
|
84 |
-
help="disable test",
|
85 |
-
)
|
86 |
-
parser.add_argument(
|
87 |
-
"-p",
|
88 |
-
"--project",
|
89 |
-
help="name of new or path to existing project"
|
90 |
-
)
|
91 |
-
parser.add_argument(
|
92 |
-
"-d",
|
93 |
-
"--debug",
|
94 |
-
type=str2bool,
|
95 |
-
nargs="?",
|
96 |
-
const=True,
|
97 |
-
default=False,
|
98 |
-
help="enable post-mortem debugging",
|
99 |
-
)
|
100 |
-
parser.add_argument(
|
101 |
-
"-s",
|
102 |
-
"--seed",
|
103 |
-
type=int,
|
104 |
-
default=23,
|
105 |
-
help="seed for seed_everything",
|
106 |
-
)
|
107 |
-
parser.add_argument(
|
108 |
-
"-f",
|
109 |
-
"--postfix",
|
110 |
-
type=str,
|
111 |
-
default="",
|
112 |
-
help="post-postfix for default name",
|
113 |
-
)
|
114 |
-
parser.add_argument(
|
115 |
-
"-l",
|
116 |
-
"--logdir",
|
117 |
-
type=str,
|
118 |
-
default="logs",
|
119 |
-
help="directory for logging dat shit",
|
120 |
-
)
|
121 |
-
parser.add_argument(
|
122 |
-
"--scale_lr",
|
123 |
-
action="store_true",
|
124 |
-
default=False,
|
125 |
-
help="scale base-lr by ngpu * batch_size * n_accumulate",
|
126 |
-
)
|
127 |
-
return parser
|
128 |
-
|
129 |
-
|
130 |
-
def nondefault_trainer_args(opt):
|
131 |
-
parser = argparse.ArgumentParser()
|
132 |
-
parser = Trainer.add_argparse_args(parser)
|
133 |
-
args = parser.parse_args([])
|
134 |
-
return sorted(k for k in vars(args) if getattr(opt, k) != getattr(args, k))
|
135 |
-
|
136 |
-
|
137 |
-
class WrappedDataset(Dataset):
|
138 |
-
"""Wraps an arbitrary object with __len__ and __getitem__ into a pytorch dataset"""
|
139 |
-
|
140 |
-
def __init__(self, dataset):
|
141 |
-
self.data = dataset
|
142 |
-
|
143 |
-
def __len__(self):
|
144 |
-
return len(self.data)
|
145 |
-
|
146 |
-
def __getitem__(self, idx):
|
147 |
-
return self.data[idx]
|
148 |
-
|
149 |
-
|
150 |
-
def worker_init_fn(_):
|
151 |
-
worker_info = torch.utils.data.get_worker_info()
|
152 |
-
|
153 |
-
dataset = worker_info.dataset
|
154 |
-
worker_id = worker_info.id
|
155 |
-
|
156 |
-
if isinstance(dataset, Txt2ImgIterableBaseDataset):
|
157 |
-
split_size = dataset.num_records // worker_info.num_workers
|
158 |
-
# reset num_records to the true number to retain reliable length information
|
159 |
-
dataset.sample_ids = dataset.valid_ids[worker_id * split_size:(worker_id + 1) * split_size]
|
160 |
-
current_id = np.random.choice(len(np.random.get_state()[1]), 1)
|
161 |
-
return np.random.seed(np.random.get_state()[1][current_id] + worker_id)
|
162 |
-
else:
|
163 |
-
return np.random.seed(np.random.get_state()[1][0] + worker_id)
|
164 |
-
|
165 |
-
|
166 |
-
class DataModuleFromConfig(pl.LightningDataModule):
|
167 |
-
def __init__(self, batch_size, train=None, validation=None, test=None, predict=None,
|
168 |
-
wrap=False, num_workers=None, shuffle_test_loader=False, use_worker_init_fn=False,
|
169 |
-
shuffle_val_dataloader=False):
|
170 |
-
super().__init__()
|
171 |
-
self.batch_size = batch_size
|
172 |
-
self.dataset_configs = dict()
|
173 |
-
self.num_workers = num_workers if num_workers is not None else batch_size * 2
|
174 |
-
self.use_worker_init_fn = use_worker_init_fn
|
175 |
-
if train is not None:
|
176 |
-
self.dataset_configs["train"] = train
|
177 |
-
self.train_dataloader = self._train_dataloader
|
178 |
-
if validation is not None:
|
179 |
-
self.dataset_configs["validation"] = validation
|
180 |
-
self.val_dataloader = partial(self._val_dataloader, shuffle=shuffle_val_dataloader)
|
181 |
-
if test is not None:
|
182 |
-
self.dataset_configs["test"] = test
|
183 |
-
self.test_dataloader = partial(self._test_dataloader, shuffle=shuffle_test_loader)
|
184 |
-
if predict is not None:
|
185 |
-
self.dataset_configs["predict"] = predict
|
186 |
-
self.predict_dataloader = self._predict_dataloader
|
187 |
-
self.wrap = wrap
|
188 |
-
|
189 |
-
def prepare_data(self):
|
190 |
-
for data_cfg in self.dataset_configs.values():
|
191 |
-
instantiate_from_config(data_cfg)
|
192 |
-
|
193 |
-
def setup(self, stage=None):
|
194 |
-
self.datasets = dict(
|
195 |
-
(k, instantiate_from_config(self.dataset_configs[k]))
|
196 |
-
for k in self.dataset_configs)
|
197 |
-
if self.wrap:
|
198 |
-
for k in self.datasets:
|
199 |
-
self.datasets[k] = WrappedDataset(self.datasets[k])
|
200 |
-
|
201 |
-
def _train_dataloader(self):
|
202 |
-
is_iterable_dataset = isinstance(self.datasets['train'], Txt2ImgIterableBaseDataset)
|
203 |
-
if is_iterable_dataset or self.use_worker_init_fn:
|
204 |
-
init_fn = worker_init_fn
|
205 |
-
else:
|
206 |
-
init_fn = None
|
207 |
-
return DataLoader(self.datasets["train"], batch_size=self.batch_size,
|
208 |
-
num_workers=self.num_workers, shuffle=False if is_iterable_dataset else True,
|
209 |
-
worker_init_fn=init_fn, persistent_workers=True)
|
210 |
-
|
211 |
-
def _val_dataloader(self, shuffle=False):
|
212 |
-
if isinstance(self.datasets['validation'], Txt2ImgIterableBaseDataset) or self.use_worker_init_fn:
|
213 |
-
init_fn = worker_init_fn
|
214 |
-
else:
|
215 |
-
init_fn = None
|
216 |
-
return DataLoader(self.datasets["validation"],
|
217 |
-
batch_size=self.batch_size,
|
218 |
-
num_workers=self.num_workers,
|
219 |
-
worker_init_fn=init_fn,
|
220 |
-
shuffle=shuffle, persistent_workers=True)
|
221 |
-
|
222 |
-
def _test_dataloader(self, shuffle=False):
|
223 |
-
is_iterable_dataset = isinstance(self.datasets['train'], Txt2ImgIterableBaseDataset)
|
224 |
-
if is_iterable_dataset or self.use_worker_init_fn:
|
225 |
-
init_fn = worker_init_fn
|
226 |
-
else:
|
227 |
-
init_fn = None
|
228 |
-
|
229 |
-
# do not shuffle dataloader for iterable dataset
|
230 |
-
shuffle = shuffle and (not is_iterable_dataset)
|
231 |
-
|
232 |
-
return DataLoader(self.datasets["test"], batch_size=self.batch_size,
|
233 |
-
num_workers=self.num_workers, worker_init_fn=init_fn, shuffle=shuffle, persistent_workers=True)
|
234 |
-
|
235 |
-
def _predict_dataloader(self, shuffle=False):
|
236 |
-
if isinstance(self.datasets['predict'], Txt2ImgIterableBaseDataset) or self.use_worker_init_fn:
|
237 |
-
init_fn = worker_init_fn
|
238 |
-
else:
|
239 |
-
init_fn = None
|
240 |
-
return DataLoader(self.datasets["predict"], batch_size=self.batch_size,
|
241 |
-
num_workers=self.num_workers, worker_init_fn=init_fn, persistent_workers=True)
|
242 |
-
|
243 |
-
|
244 |
-
class SetupCallback(Callback):
|
245 |
-
def __init__(self, resume, now, logdir, ckptdir, cfgdir, config, lightning_config):
|
246 |
-
super().__init__()
|
247 |
-
self.resume = resume
|
248 |
-
self.now = now
|
249 |
-
self.logdir = logdir
|
250 |
-
self.ckptdir = ckptdir
|
251 |
-
self.cfgdir = cfgdir
|
252 |
-
self.config = config
|
253 |
-
self.lightning_config = lightning_config
|
254 |
-
|
255 |
-
def on_keyboard_interrupt(self, trainer, pl_module):
|
256 |
-
if trainer.global_rank == 0:
|
257 |
-
print("Summoning checkpoint.")
|
258 |
-
ckpt_path = os.path.join(self.ckptdir, "last.ckpt")
|
259 |
-
trainer.save_checkpoint(ckpt_path)
|
260 |
-
|
261 |
-
def on_pretrain_routine_start(self, trainer, pl_module):
|
262 |
-
if trainer.global_rank == 0:
|
263 |
-
# Create logdirs and save configs
|
264 |
-
# os.makedirs(self.logdir, exist_ok=True)
|
265 |
-
# os.makedirs(self.ckptdir, exist_ok=True)
|
266 |
-
# os.makedirs(self.cfgdir, exist_ok=True)
|
267 |
-
|
268 |
-
if "callbacks" in self.lightning_config:
|
269 |
-
if 'metrics_over_trainsteps_checkpoint' in self.lightning_config['callbacks']:
|
270 |
-
os.makedirs(os.path.join(self.ckptdir, 'trainstep_checkpoints'), exist_ok=True)
|
271 |
-
print("Project config")
|
272 |
-
print(OmegaConf.to_yaml(self.config))
|
273 |
-
OmegaConf.save(self.config,
|
274 |
-
os.path.join(self.cfgdir, "{}-project.yaml".format(self.now)))
|
275 |
-
|
276 |
-
print("Lightning config")
|
277 |
-
print(OmegaConf.to_yaml(self.lightning_config))
|
278 |
-
OmegaConf.save(OmegaConf.create({"lightning": self.lightning_config}),
|
279 |
-
os.path.join(self.cfgdir, "{}-lightning.yaml".format(self.now)))
|
280 |
-
|
281 |
-
def get_world_size():
|
282 |
-
if not dist.is_available():
|
283 |
-
return 1
|
284 |
-
if not dist.is_initialized():
|
285 |
-
return 1
|
286 |
-
return dist.get_world_size()
|
287 |
-
|
288 |
-
def all_gather(data):
|
289 |
-
"""
|
290 |
-
Run all_gather on arbitrary picklable data (not necessarily tensors)
|
291 |
-
Args:
|
292 |
-
data: any picklable object
|
293 |
-
Returns:
|
294 |
-
list[data]: list of data gathered from each rank
|
295 |
-
"""
|
296 |
-
world_size = get_world_size()
|
297 |
-
if world_size == 1:
|
298 |
-
return [data]
|
299 |
-
|
300 |
-
# serialized to a Tensor
|
301 |
-
origin_size = None
|
302 |
-
if not isinstance(data, torch.Tensor):
|
303 |
-
buffer = pickle.dumps(data)
|
304 |
-
storage = torch.ByteStorage.from_buffer(buffer)
|
305 |
-
tensor = torch.ByteTensor(storage).to("cuda")
|
306 |
-
else:
|
307 |
-
origin_size = data.size()
|
308 |
-
tensor = data.reshape(-1)
|
309 |
-
|
310 |
-
tensor_type = tensor.dtype
|
311 |
-
|
312 |
-
# obtain Tensor size of each rank
|
313 |
-
local_size = torch.LongTensor([tensor.numel()]).to("cuda")
|
314 |
-
size_list = [torch.LongTensor([0]).to("cuda") for _ in range(world_size)]
|
315 |
-
dist.all_gather(size_list, local_size)
|
316 |
-
size_list = [int(size.item()) for size in size_list]
|
317 |
-
max_size = max(size_list)
|
318 |
-
|
319 |
-
# receiving Tensor from all ranks
|
320 |
-
# we pad the tensor because torch all_gather does not support
|
321 |
-
# gathering tensors of different shapes
|
322 |
-
tensor_list = []
|
323 |
-
for _ in size_list:
|
324 |
-
tensor_list.append(torch.FloatTensor(size=(max_size,)).cuda().to(tensor_type))
|
325 |
-
if local_size != max_size:
|
326 |
-
padding = torch.FloatTensor(size=(max_size - local_size,)).cuda().to(tensor_type)
|
327 |
-
tensor = torch.cat((tensor, padding), dim=0)
|
328 |
-
dist.all_gather(tensor_list, tensor)
|
329 |
-
|
330 |
-
data_list = []
|
331 |
-
for size, tensor in zip(size_list, tensor_list):
|
332 |
-
if origin_size is None:
|
333 |
-
buffer = tensor.cpu().numpy().tobytes()[:size]
|
334 |
-
data_list.append(pickle.loads(buffer))
|
335 |
-
else:
|
336 |
-
buffer = tensor[:size]
|
337 |
-
data_list.append(buffer)
|
338 |
-
|
339 |
-
if origin_size is not None:
|
340 |
-
new_shape = [-1] + list(origin_size[1:])
|
341 |
-
resized_list = []
|
342 |
-
for data in data_list:
|
343 |
-
# suppose the difference of tensor size exist in first dimension
|
344 |
-
data = data.reshape(new_shape)
|
345 |
-
resized_list.append(data)
|
346 |
-
|
347 |
-
return resized_list
|
348 |
-
else:
|
349 |
-
return data_list
|
350 |
-
|
351 |
-
class ImageLogger(Callback):
|
352 |
-
def __init__(self, batch_frequency, max_images, clamp=True, increase_log_steps=True,
|
353 |
-
rescale=True, disabled=False, log_on_batch_idx=False, log_first_step=False,
|
354 |
-
log_images_kwargs=None):
|
355 |
-
super().__init__()
|
356 |
-
self.rescale = rescale
|
357 |
-
self.batch_freq = batch_frequency
|
358 |
-
self.max_images = max_images
|
359 |
-
self.logger_log_images = {
|
360 |
-
pl.loggers.TestTubeLogger: self._testtube,
|
361 |
-
}
|
362 |
-
self.log_steps = [2 ** n for n in range(6, int(np.log2(self.batch_freq)) + 1)]
|
363 |
-
if not increase_log_steps:
|
364 |
-
self.log_steps = [self.batch_freq]
|
365 |
-
self.clamp = clamp
|
366 |
-
self.disabled = disabled
|
367 |
-
self.log_on_batch_idx = log_on_batch_idx
|
368 |
-
self.log_images_kwargs = log_images_kwargs if log_images_kwargs else {}
|
369 |
-
self.log_first_step = log_first_step
|
370 |
-
|
371 |
-
@rank_zero_only
|
372 |
-
def _testtube(self, pl_module, images, batch_idx, split):
|
373 |
-
for k in images:
|
374 |
-
grid = torchvision.utils.make_grid(images[k])
|
375 |
-
grid = (grid + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w
|
376 |
-
|
377 |
-
tag = f"{split}/{k}"
|
378 |
-
pl_module.logger.experiment.add_image(
|
379 |
-
tag, grid,
|
380 |
-
global_step=pl_module.global_step)
|
381 |
-
|
382 |
-
@rank_zero_only
|
383 |
-
def log_local(self, save_dir, split, images, prompts,
|
384 |
-
global_step, current_epoch, batch_idx):
|
385 |
-
root = os.path.join(save_dir, "images", split)
|
386 |
-
names = {"reals": "before", "inputs": "after", "reconstruction": "before-vq", "samples": "after-gen"}
|
387 |
-
# print(root)
|
388 |
-
for k in images:
|
389 |
-
grid = torchvision.utils.make_grid(images[k], nrow=8)
|
390 |
-
if self.rescale:
|
391 |
-
grid = (grid + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w
|
392 |
-
grid = grid.transpose(0, 1).transpose(1, 2).squeeze(-1)
|
393 |
-
grid = grid.numpy()
|
394 |
-
grid = (grid * 255).astype(np.uint8)
|
395 |
-
filename = "gs-{:06}_e-{:06}_b-{:06}_{}.png".format(
|
396 |
-
global_step,
|
397 |
-
current_epoch,
|
398 |
-
batch_idx,
|
399 |
-
names[k])
|
400 |
-
path = os.path.join(root, filename)
|
401 |
-
os.makedirs(os.path.split(path)[0], exist_ok=True)
|
402 |
-
# print(path)
|
403 |
-
Image.fromarray(grid).save(path)
|
404 |
-
|
405 |
-
filename = "gs-{:06}_e-{:06}_b-{:06}_prompt.json".format(
|
406 |
-
global_step,
|
407 |
-
current_epoch,
|
408 |
-
batch_idx)
|
409 |
-
path = os.path.join(root, filename)
|
410 |
-
with open(path, "w") as f:
|
411 |
-
for p in prompts:
|
412 |
-
f.write(f"{json.dumps(p)}\n")
|
413 |
-
|
414 |
-
def log_img(self, pl_module, batch, batch_idx, split="train"):
|
415 |
-
check_idx = batch_idx if self.log_on_batch_idx else pl_module.global_step
|
416 |
-
if (self.check_frequency(check_idx) and # batch_idx % self.batch_freq == 0
|
417 |
-
hasattr(pl_module, "log_images") and
|
418 |
-
callable(pl_module.log_images) and
|
419 |
-
self.max_images > 0) or (split == "val" and batch_idx == 0):
|
420 |
-
logger = type(pl_module.logger)
|
421 |
-
|
422 |
-
is_train = pl_module.training
|
423 |
-
if is_train:
|
424 |
-
pl_module.eval()
|
425 |
-
|
426 |
-
with torch.no_grad():
|
427 |
-
images = pl_module.log_images(batch, split=split, **self.log_images_kwargs)
|
428 |
-
|
429 |
-
prompts = batch["edit"]["c_crossattn"][:self.max_images]
|
430 |
-
prompts = [p for ps in all_gather(prompts) for p in ps]
|
431 |
-
|
432 |
-
for k in images:
|
433 |
-
N = min(images[k].shape[0], self.max_images)
|
434 |
-
images[k] = images[k][:N]
|
435 |
-
images[k] = torch.cat(all_gather(images[k][:N]))
|
436 |
-
if isinstance(images[k], torch.Tensor):
|
437 |
-
images[k] = images[k].detach().cpu()
|
438 |
-
if self.clamp:
|
439 |
-
images[k] = torch.clamp(images[k], -1., 1.)
|
440 |
-
|
441 |
-
self.log_local(pl_module.logger.save_dir, split, images, prompts,
|
442 |
-
pl_module.global_step, pl_module.current_epoch, batch_idx)
|
443 |
-
|
444 |
-
logger_log_images = self.logger_log_images.get(logger, lambda *args, **kwargs: None)
|
445 |
-
logger_log_images(pl_module, images, pl_module.global_step, split)
|
446 |
-
|
447 |
-
if is_train:
|
448 |
-
pl_module.train()
|
449 |
-
|
450 |
-
def check_frequency(self, check_idx):
|
451 |
-
if ((check_idx % self.batch_freq) == 0 or (check_idx in self.log_steps)) and (
|
452 |
-
check_idx > 0 or self.log_first_step):
|
453 |
-
if len(self.log_steps) > 0:
|
454 |
-
self.log_steps.pop(0)
|
455 |
-
return True
|
456 |
-
return False
|
457 |
-
|
458 |
-
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
|
459 |
-
if not self.disabled and (pl_module.global_step > 0 or self.log_first_step):
|
460 |
-
self.log_img(pl_module, batch, batch_idx, split="train")
|
461 |
-
|
462 |
-
def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
|
463 |
-
if not self.disabled and pl_module.global_step > 0:
|
464 |
-
self.log_img(pl_module, batch, batch_idx, split="val")
|
465 |
-
if hasattr(pl_module, 'calibrate_grad_norm'):
|
466 |
-
if (pl_module.calibrate_grad_norm and batch_idx % 25 == 0) and batch_idx > 0:
|
467 |
-
self.log_gradients(trainer, pl_module, batch_idx=batch_idx)
|
468 |
-
|
469 |
-
|
470 |
-
class CUDACallback(Callback):
|
471 |
-
# see https://github.com/SeanNaren/minGPT/blob/master/mingpt/callback.py
|
472 |
-
def on_train_epoch_start(self, trainer, pl_module):
|
473 |
-
# Reset the memory use counter
|
474 |
-
torch.cuda.reset_peak_memory_stats(trainer.root_gpu)
|
475 |
-
torch.cuda.synchronize(trainer.root_gpu)
|
476 |
-
self.start_time = time.time()
|
477 |
-
|
478 |
-
def on_train_epoch_end(self, trainer, pl_module, outputs):
|
479 |
-
torch.cuda.synchronize(trainer.root_gpu)
|
480 |
-
max_memory = torch.cuda.max_memory_allocated(trainer.root_gpu) / 2 ** 20
|
481 |
-
epoch_time = time.time() - self.start_time
|
482 |
-
|
483 |
-
try:
|
484 |
-
max_memory = trainer.training_type_plugin.reduce(max_memory)
|
485 |
-
epoch_time = trainer.training_type_plugin.reduce(epoch_time)
|
486 |
-
|
487 |
-
rank_zero_info(f"Average Epoch time: {epoch_time:.2f} seconds")
|
488 |
-
rank_zero_info(f"Average Peak memory {max_memory:.2f}MiB")
|
489 |
-
except AttributeError:
|
490 |
-
pass
|
491 |
-
|
492 |
-
|
493 |
-
if __name__ == "__main__":
|
494 |
-
# custom parser to specify config files, train, test and debug mode,
|
495 |
-
# postfix, resume.
|
496 |
-
# `--key value` arguments are interpreted as arguments to the trainer.
|
497 |
-
# `nested.key=value` arguments are interpreted as config parameters.
|
498 |
-
# configs are merged from left-to-right followed by command line parameters.
|
499 |
-
|
500 |
-
# model:
|
501 |
-
# base_learning_rate: float
|
502 |
-
# target: path to lightning module
|
503 |
-
# params:
|
504 |
-
# key: value
|
505 |
-
# data:
|
506 |
-
# target: main.DataModuleFromConfig
|
507 |
-
# params:
|
508 |
-
# batch_size: int
|
509 |
-
# wrap: bool
|
510 |
-
# train:
|
511 |
-
# target: path to train dataset
|
512 |
-
# params:
|
513 |
-
# key: value
|
514 |
-
# validation:
|
515 |
-
# target: path to validation dataset
|
516 |
-
# params:
|
517 |
-
# key: value
|
518 |
-
# test:
|
519 |
-
# target: path to test dataset
|
520 |
-
# params:
|
521 |
-
# key: value
|
522 |
-
# lightning: (optional, has sane defaults and can be specified on cmdline)
|
523 |
-
# trainer:
|
524 |
-
# additional arguments to trainer
|
525 |
-
# logger:
|
526 |
-
# logger to instantiate
|
527 |
-
# modelcheckpoint:
|
528 |
-
# modelcheckpoint to instantiate
|
529 |
-
# callbacks:
|
530 |
-
# callback1:
|
531 |
-
# target: importpath
|
532 |
-
# params:
|
533 |
-
# key: value
|
534 |
-
|
535 |
-
now = datetime.datetime.now().strftime("%Y-%m-%dT%H-%M-%S")
|
536 |
-
|
537 |
-
# add cwd for convenience and to make classes in this file available when
|
538 |
-
# running as `python main.py`
|
539 |
-
# (in particular `main.DataModuleFromConfig`)
|
540 |
-
sys.path.append(os.getcwd())
|
541 |
-
|
542 |
-
parser = get_parser()
|
543 |
-
parser = Trainer.add_argparse_args(parser)
|
544 |
-
|
545 |
-
opt, unknown = parser.parse_known_args()
|
546 |
-
|
547 |
-
assert opt.name
|
548 |
-
cfg_fname = os.path.split(opt.base[0])[-1]
|
549 |
-
cfg_name = os.path.splitext(cfg_fname)[0]
|
550 |
-
nowname = f"{cfg_name}_{opt.name}"
|
551 |
-
logdir = os.path.join(opt.logdir, nowname)
|
552 |
-
ckpt = os.path.join(logdir, "checkpoints", "last.ckpt")
|
553 |
-
resume = False
|
554 |
-
|
555 |
-
if os.path.isfile(ckpt):
|
556 |
-
opt.resume_from_checkpoint = ckpt
|
557 |
-
base_configs = sorted(glob.glob(os.path.join(logdir, "configs/*.yaml")))
|
558 |
-
opt.base = base_configs + opt.base
|
559 |
-
_tmp = logdir.split("/")
|
560 |
-
nowname = _tmp[-1]
|
561 |
-
resume = True
|
562 |
-
|
563 |
-
ckptdir = os.path.join(logdir, "checkpoints")
|
564 |
-
cfgdir = os.path.join(logdir, "configs")
|
565 |
-
|
566 |
-
os.makedirs(logdir, exist_ok=True)
|
567 |
-
os.makedirs(ckptdir, exist_ok=True)
|
568 |
-
os.makedirs(cfgdir, exist_ok=True)
|
569 |
-
|
570 |
-
try:
|
571 |
-
# init and save configs
|
572 |
-
configs = [OmegaConf.load(cfg) for cfg in opt.base]
|
573 |
-
cli = OmegaConf.from_dotlist(unknown)
|
574 |
-
config = OmegaConf.merge(*configs, cli)
|
575 |
-
|
576 |
-
if resume:
|
577 |
-
# By default, when finetuning from Stable Diffusion, we load the EMA-only checkpoint to initialize all weights.
|
578 |
-
# If resuming InstructPix2Pix from a finetuning checkpoint, instead load both EMA and non-EMA weights.
|
579 |
-
config.model.params.load_ema = True
|
580 |
-
|
581 |
-
lightning_config = config.pop("lightning", OmegaConf.create())
|
582 |
-
# merge trainer cli with config
|
583 |
-
trainer_config = lightning_config.get("trainer", OmegaConf.create())
|
584 |
-
# default to ddp
|
585 |
-
trainer_config["accelerator"] = "ddp"
|
586 |
-
for k in nondefault_trainer_args(opt):
|
587 |
-
trainer_config[k] = getattr(opt, k)
|
588 |
-
if not "gpus" in trainer_config:
|
589 |
-
del trainer_config["accelerator"]
|
590 |
-
cpu = True
|
591 |
-
else:
|
592 |
-
gpuinfo = trainer_config["gpus"]
|
593 |
-
print(f"Running on GPUs {gpuinfo}")
|
594 |
-
cpu = False
|
595 |
-
trainer_opt = argparse.Namespace(**trainer_config)
|
596 |
-
lightning_config.trainer = trainer_config
|
597 |
-
|
598 |
-
# model
|
599 |
-
model = instantiate_from_config(config.model)
|
600 |
-
|
601 |
-
# trainer and callbacks
|
602 |
-
trainer_kwargs = dict()
|
603 |
-
|
604 |
-
# default logger configs
|
605 |
-
default_logger_cfgs = {
|
606 |
-
"wandb": {
|
607 |
-
"target": "pytorch_lightning.loggers.WandbLogger",
|
608 |
-
"params": {
|
609 |
-
"name": nowname,
|
610 |
-
"save_dir": logdir,
|
611 |
-
"id": nowname,
|
612 |
-
}
|
613 |
-
},
|
614 |
-
"testtube": {
|
615 |
-
"target": "pytorch_lightning.loggers.TestTubeLogger",
|
616 |
-
"params": {
|
617 |
-
"name": "testtube",
|
618 |
-
"save_dir": logdir,
|
619 |
-
}
|
620 |
-
},
|
621 |
-
}
|
622 |
-
default_logger_cfg = default_logger_cfgs["wandb"]
|
623 |
-
if "logger" in lightning_config:
|
624 |
-
logger_cfg = lightning_config.logger
|
625 |
-
else:
|
626 |
-
logger_cfg = OmegaConf.create()
|
627 |
-
logger_cfg = OmegaConf.merge(default_logger_cfg, logger_cfg)
|
628 |
-
trainer_kwargs["logger"] = instantiate_from_config(logger_cfg)
|
629 |
-
|
630 |
-
# modelcheckpoint - use TrainResult/EvalResult(checkpoint_on=metric) to
|
631 |
-
# specify which metric is used to determine best models
|
632 |
-
default_modelckpt_cfg = {
|
633 |
-
"target": "pytorch_lightning.callbacks.ModelCheckpoint",
|
634 |
-
"params": {
|
635 |
-
"dirpath": ckptdir,
|
636 |
-
"filename": "{epoch:06}",
|
637 |
-
"verbose": True,
|
638 |
-
"save_last": True,
|
639 |
-
}
|
640 |
-
}
|
641 |
-
|
642 |
-
if "modelcheckpoint" in lightning_config:
|
643 |
-
modelckpt_cfg = lightning_config.modelcheckpoint
|
644 |
-
else:
|
645 |
-
modelckpt_cfg = OmegaConf.create()
|
646 |
-
modelckpt_cfg = OmegaConf.merge(default_modelckpt_cfg, modelckpt_cfg)
|
647 |
-
print(f"Merged modelckpt-cfg: \n{modelckpt_cfg}")
|
648 |
-
if version.parse(pl.__version__) < version.parse('1.4.0'):
|
649 |
-
trainer_kwargs["checkpoint_callback"] = instantiate_from_config(modelckpt_cfg)
|
650 |
-
|
651 |
-
# add callback which sets up log directory
|
652 |
-
default_callbacks_cfg = {
|
653 |
-
"setup_callback": {
|
654 |
-
"target": "main.SetupCallback",
|
655 |
-
"params": {
|
656 |
-
"resume": opt.resume,
|
657 |
-
"now": now,
|
658 |
-
"logdir": logdir,
|
659 |
-
"ckptdir": ckptdir,
|
660 |
-
"cfgdir": cfgdir,
|
661 |
-
"config": config,
|
662 |
-
"lightning_config": lightning_config,
|
663 |
-
}
|
664 |
-
},
|
665 |
-
"image_logger": {
|
666 |
-
"target": "main.ImageLogger",
|
667 |
-
"params": {
|
668 |
-
"batch_frequency": 750,
|
669 |
-
"max_images": 4,
|
670 |
-
"clamp": True
|
671 |
-
}
|
672 |
-
},
|
673 |
-
"learning_rate_logger": {
|
674 |
-
"target": "main.LearningRateMonitor",
|
675 |
-
"params": {
|
676 |
-
"logging_interval": "step",
|
677 |
-
# "log_momentum": True
|
678 |
-
}
|
679 |
-
},
|
680 |
-
"cuda_callback": {
|
681 |
-
"target": "main.CUDACallback"
|
682 |
-
},
|
683 |
-
}
|
684 |
-
if version.parse(pl.__version__) >= version.parse('1.4.0'):
|
685 |
-
default_callbacks_cfg.update({'checkpoint_callback': modelckpt_cfg})
|
686 |
-
|
687 |
-
if "callbacks" in lightning_config:
|
688 |
-
callbacks_cfg = lightning_config.callbacks
|
689 |
-
else:
|
690 |
-
callbacks_cfg = OmegaConf.create()
|
691 |
-
|
692 |
-
print(
|
693 |
-
'Caution: Saving checkpoints every n train steps without deleting. This might require some free space.')
|
694 |
-
default_metrics_over_trainsteps_ckpt_dict = {
|
695 |
-
'metrics_over_trainsteps_checkpoint': {
|
696 |
-
"target": 'pytorch_lightning.callbacks.ModelCheckpoint',
|
697 |
-
'params': {
|
698 |
-
"dirpath": os.path.join(ckptdir, 'trainstep_checkpoints'),
|
699 |
-
"filename": "{epoch:06}-{step:09}",
|
700 |
-
"verbose": True,
|
701 |
-
'save_top_k': -1,
|
702 |
-
'every_n_train_steps': 1000,
|
703 |
-
'save_weights_only': True
|
704 |
-
}
|
705 |
-
}
|
706 |
-
}
|
707 |
-
default_callbacks_cfg.update(default_metrics_over_trainsteps_ckpt_dict)
|
708 |
-
|
709 |
-
callbacks_cfg = OmegaConf.merge(default_callbacks_cfg, callbacks_cfg)
|
710 |
-
if 'ignore_keys_callback' in callbacks_cfg and hasattr(trainer_opt, 'resume_from_checkpoint'):
|
711 |
-
callbacks_cfg.ignore_keys_callback.params['ckpt_path'] = trainer_opt.resume_from_checkpoint
|
712 |
-
elif 'ignore_keys_callback' in callbacks_cfg:
|
713 |
-
del callbacks_cfg['ignore_keys_callback']
|
714 |
-
|
715 |
-
trainer_kwargs["callbacks"] = [instantiate_from_config(callbacks_cfg[k]) for k in callbacks_cfg]
|
716 |
-
|
717 |
-
trainer = Trainer.from_argparse_args(trainer_opt, plugins=DDPPlugin(find_unused_parameters=False), **trainer_kwargs)
|
718 |
-
trainer.logdir = logdir ###
|
719 |
-
|
720 |
-
# data
|
721 |
-
data = instantiate_from_config(config.data)
|
722 |
-
# NOTE according to https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html
|
723 |
-
# calling these ourselves should not be necessary but it is.
|
724 |
-
# lightning still takes care of proper multiprocessing though
|
725 |
-
data.prepare_data()
|
726 |
-
data.setup()
|
727 |
-
print("#### Data #####")
|
728 |
-
for k in data.datasets:
|
729 |
-
print(f"{k}, {data.datasets[k].__class__.__name__}, {len(data.datasets[k])}")
|
730 |
-
|
731 |
-
# configure learning rate
|
732 |
-
bs, base_lr = config.data.params.batch_size, config.model.base_learning_rate
|
733 |
-
if not cpu:
|
734 |
-
ngpu = len(lightning_config.trainer.gpus.strip(",").split(','))
|
735 |
-
else:
|
736 |
-
ngpu = 1
|
737 |
-
if 'accumulate_grad_batches' in lightning_config.trainer:
|
738 |
-
accumulate_grad_batches = lightning_config.trainer.accumulate_grad_batches
|
739 |
-
else:
|
740 |
-
accumulate_grad_batches = 1
|
741 |
-
print(f"accumulate_grad_batches = {accumulate_grad_batches}")
|
742 |
-
lightning_config.trainer.accumulate_grad_batches = accumulate_grad_batches
|
743 |
-
if opt.scale_lr:
|
744 |
-
model.learning_rate = accumulate_grad_batches * ngpu * bs * base_lr
|
745 |
-
print(
|
746 |
-
"Setting learning rate to {:.2e} = {} (accumulate_grad_batches) * {} (num_gpus) * {} (batchsize) * {:.2e} (base_lr)".format(
|
747 |
-
model.learning_rate, accumulate_grad_batches, ngpu, bs, base_lr))
|
748 |
-
else:
|
749 |
-
model.learning_rate = base_lr
|
750 |
-
print("++++ NOT USING LR SCALING ++++")
|
751 |
-
print(f"Setting learning rate to {model.learning_rate:.2e}")
|
752 |
-
|
753 |
-
|
754 |
-
# allow checkpointing via USR1
|
755 |
-
def melk(*args, **kwargs):
|
756 |
-
# run all checkpoint hooks
|
757 |
-
if trainer.global_rank == 0:
|
758 |
-
print("Summoning checkpoint.")
|
759 |
-
ckpt_path = os.path.join(ckptdir, "last.ckpt")
|
760 |
-
trainer.save_checkpoint(ckpt_path)
|
761 |
-
|
762 |
-
|
763 |
-
def divein(*args, **kwargs):
|
764 |
-
if trainer.global_rank == 0:
|
765 |
-
import pudb;
|
766 |
-
pudb.set_trace()
|
767 |
-
|
768 |
-
|
769 |
-
import signal
|
770 |
-
|
771 |
-
signal.signal(signal.SIGUSR1, melk)
|
772 |
-
signal.signal(signal.SIGUSR2, divein)
|
773 |
-
|
774 |
-
# run
|
775 |
-
if opt.train:
|
776 |
-
try:
|
777 |
-
trainer.fit(model, data)
|
778 |
-
except Exception:
|
779 |
-
melk()
|
780 |
-
raise
|
781 |
-
if not opt.no_test and not trainer.interrupted:
|
782 |
-
trainer.test(model, data)
|
783 |
-
except Exception:
|
784 |
-
if opt.debug and trainer.global_rank == 0:
|
785 |
-
try:
|
786 |
-
import pudb as debugger
|
787 |
-
except ImportError:
|
788 |
-
import pdb as debugger
|
789 |
-
debugger.post_mortem()
|
790 |
-
raise
|
791 |
-
finally:
|
792 |
-
# move newly created debug project to debug_runs
|
793 |
-
if opt.debug and not opt.resume and trainer.global_rank == 0:
|
794 |
-
dst, name = os.path.split(logdir)
|
795 |
-
dst = os.path.join(dst, "debug_runs", name)
|
796 |
-
os.makedirs(os.path.split(dst)[0], exist_ok=True)
|
797 |
-
os.rename(logdir, dst)
|
798 |
-
if trainer.global_rank == 0:
|
799 |
-
print(trainer.profiler.summary())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
metrics/clip_similarity.py
DELETED
@@ -1,47 +0,0 @@
|
|
1 |
-
from __future__ import annotations
|
2 |
-
|
3 |
-
import clip
|
4 |
-
import torch
|
5 |
-
import torch.nn as nn
|
6 |
-
import torch.nn.functional as F
|
7 |
-
from einops import rearrange
|
8 |
-
|
9 |
-
|
10 |
-
class ClipSimilarity(nn.Module):
|
11 |
-
def __init__(self, name: str = "ViT-L/14"):
|
12 |
-
super().__init__()
|
13 |
-
assert name in ("RN50", "RN101", "RN50x4", "RN50x16", "RN50x64", "ViT-B/32", "ViT-B/16", "ViT-L/14", "ViT-L/14@336px") # fmt: skip
|
14 |
-
self.size = {"RN50x4": 288, "RN50x16": 384, "RN50x64": 448, "ViT-L/14@336px": 336}.get(name, 224)
|
15 |
-
|
16 |
-
self.model, _ = clip.load(name, device="cpu", download_root="./")
|
17 |
-
self.model.eval().requires_grad_(False)
|
18 |
-
|
19 |
-
self.register_buffer("mean", torch.tensor((0.48145466, 0.4578275, 0.40821073)))
|
20 |
-
self.register_buffer("std", torch.tensor((0.26862954, 0.26130258, 0.27577711)))
|
21 |
-
|
22 |
-
def encode_text(self, text: list[str]) -> torch.Tensor:
|
23 |
-
text = clip.tokenize(text, truncate=True).to(next(self.parameters()).device)
|
24 |
-
text_features = self.model.encode_text(text)
|
25 |
-
text_features = text_features / text_features.norm(dim=1, keepdim=True)
|
26 |
-
return text_features
|
27 |
-
|
28 |
-
def encode_image(self, image: torch.Tensor) -> torch.Tensor: # Input images in range [0, 1].
|
29 |
-
image = F.interpolate(image.float(), size=self.size, mode="bicubic", align_corners=False)
|
30 |
-
image = image - rearrange(self.mean, "c -> 1 c 1 1")
|
31 |
-
image = image / rearrange(self.std, "c -> 1 c 1 1")
|
32 |
-
image_features = self.model.encode_image(image)
|
33 |
-
image_features = image_features / image_features.norm(dim=1, keepdim=True)
|
34 |
-
return image_features
|
35 |
-
|
36 |
-
def forward(
|
37 |
-
self, image_0: torch.Tensor, image_1: torch.Tensor, text_0: list[str], text_1: list[str]
|
38 |
-
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
39 |
-
image_features_0 = self.encode_image(image_0)
|
40 |
-
image_features_1 = self.encode_image(image_1)
|
41 |
-
text_features_0 = self.encode_text(text_0)
|
42 |
-
text_features_1 = self.encode_text(text_1)
|
43 |
-
sim_0 = F.cosine_similarity(image_features_0, text_features_0)
|
44 |
-
sim_1 = F.cosine_similarity(image_features_1, text_features_1)
|
45 |
-
sim_direction = F.cosine_similarity(image_features_1 - image_features_0, text_features_1 - text_features_0)
|
46 |
-
sim_image = F.cosine_similarity(image_features_0, image_features_1)
|
47 |
-
return sim_0, sim_1, sim_direction, sim_image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
metrics/compute_metrics.py
DELETED
@@ -1,235 +0,0 @@
|
|
1 |
-
from __future__ import annotations
|
2 |
-
|
3 |
-
import math
|
4 |
-
import random
|
5 |
-
import sys
|
6 |
-
from argparse import ArgumentParser
|
7 |
-
|
8 |
-
import einops
|
9 |
-
import k_diffusion as K
|
10 |
-
import numpy as np
|
11 |
-
import torch
|
12 |
-
import torch.nn as nn
|
13 |
-
from tqdm.auto import tqdm
|
14 |
-
from einops import rearrange
|
15 |
-
from omegaconf import OmegaConf
|
16 |
-
from PIL import Image, ImageOps
|
17 |
-
from torch import autocast
|
18 |
-
|
19 |
-
import json
|
20 |
-
import matplotlib.pyplot as plt
|
21 |
-
import seaborn
|
22 |
-
from pathlib import Path
|
23 |
-
|
24 |
-
sys.path.append("./")
|
25 |
-
|
26 |
-
from clip_similarity import ClipSimilarity
|
27 |
-
from edit_dataset import EditDatasetEval
|
28 |
-
|
29 |
-
sys.path.append("./stable_diffusion")
|
30 |
-
|
31 |
-
from ldm.util import instantiate_from_config
|
32 |
-
|
33 |
-
|
34 |
-
class CFGDenoiser(nn.Module):
|
35 |
-
def __init__(self, model):
|
36 |
-
super().__init__()
|
37 |
-
self.inner_model = model
|
38 |
-
|
39 |
-
def forward(self, z, sigma, cond, uncond, text_cfg_scale, image_cfg_scale):
|
40 |
-
cfg_z = einops.repeat(z, "1 ... -> n ...", n=3)
|
41 |
-
cfg_sigma = einops.repeat(sigma, "1 ... -> n ...", n=3)
|
42 |
-
cfg_cond = {
|
43 |
-
"c_crossattn": [torch.cat([cond["c_crossattn"][0], uncond["c_crossattn"][0], uncond["c_crossattn"][0]])],
|
44 |
-
"c_concat": [torch.cat([cond["c_concat"][0], cond["c_concat"][0], uncond["c_concat"][0]])],
|
45 |
-
}
|
46 |
-
out_cond, out_img_cond, out_uncond = self.inner_model(cfg_z, cfg_sigma, cond=cfg_cond).chunk(3)
|
47 |
-
return out_uncond + text_cfg_scale * (out_cond - out_img_cond) + image_cfg_scale * (out_img_cond - out_uncond)
|
48 |
-
|
49 |
-
|
50 |
-
def load_model_from_config(config, ckpt, vae_ckpt=None, verbose=False):
|
51 |
-
print(f"Loading model from {ckpt}")
|
52 |
-
pl_sd = torch.load(ckpt, map_location="cpu")
|
53 |
-
if "global_step" in pl_sd:
|
54 |
-
print(f"Global Step: {pl_sd['global_step']}")
|
55 |
-
sd = pl_sd["state_dict"]
|
56 |
-
if vae_ckpt is not None:
|
57 |
-
print(f"Loading VAE from {vae_ckpt}")
|
58 |
-
vae_sd = torch.load(vae_ckpt, map_location="cpu")["state_dict"]
|
59 |
-
sd = {
|
60 |
-
k: vae_sd[k[len("first_stage_model.") :]] if k.startswith("first_stage_model.") else v
|
61 |
-
for k, v in sd.items()
|
62 |
-
}
|
63 |
-
model = instantiate_from_config(config.model)
|
64 |
-
m, u = model.load_state_dict(sd, strict=False)
|
65 |
-
if len(m) > 0 and verbose:
|
66 |
-
print("missing keys:")
|
67 |
-
print(m)
|
68 |
-
if len(u) > 0 and verbose:
|
69 |
-
print("unexpected keys:")
|
70 |
-
print(u)
|
71 |
-
return model
|
72 |
-
|
73 |
-
class ImageEditor(nn.Module):
|
74 |
-
def __init__(self, config, ckpt, vae_ckpt=None):
|
75 |
-
super().__init__()
|
76 |
-
|
77 |
-
config = OmegaConf.load(config)
|
78 |
-
self.model = load_model_from_config(config, ckpt, vae_ckpt)
|
79 |
-
self.model.eval().cuda()
|
80 |
-
self.model_wrap = K.external.CompVisDenoiser(self.model)
|
81 |
-
self.model_wrap_cfg = CFGDenoiser(self.model_wrap)
|
82 |
-
self.null_token = self.model.get_learned_conditioning([""])
|
83 |
-
|
84 |
-
def forward(
|
85 |
-
self,
|
86 |
-
image: torch.Tensor,
|
87 |
-
edit: str,
|
88 |
-
scale_txt: float = 7.5,
|
89 |
-
scale_img: float = 1.0,
|
90 |
-
steps: int = 100,
|
91 |
-
) -> torch.Tensor:
|
92 |
-
assert image.dim() == 3
|
93 |
-
assert image.size(1) % 64 == 0
|
94 |
-
assert image.size(2) % 64 == 0
|
95 |
-
with torch.no_grad(), autocast("cuda"), self.model.ema_scope():
|
96 |
-
cond = {
|
97 |
-
"c_crossattn": [self.model.get_learned_conditioning([edit])],
|
98 |
-
"c_concat": [self.model.encode_first_stage(image[None]).mode()],
|
99 |
-
}
|
100 |
-
uncond = {
|
101 |
-
"c_crossattn": [self.model.get_learned_conditioning([""])],
|
102 |
-
"c_concat": [torch.zeros_like(cond["c_concat"][0])],
|
103 |
-
}
|
104 |
-
extra_args = {
|
105 |
-
"uncond": uncond,
|
106 |
-
"cond": cond,
|
107 |
-
"image_cfg_scale": scale_img,
|
108 |
-
"text_cfg_scale": scale_txt,
|
109 |
-
}
|
110 |
-
sigmas = self.model_wrap.get_sigmas(steps)
|
111 |
-
x = torch.randn_like(cond["c_concat"][0]) * sigmas[0]
|
112 |
-
x = K.sampling.sample_euler_ancestral(self.model_wrap_cfg, x, sigmas, extra_args=extra_args)
|
113 |
-
x = self.model.decode_first_stage(x)[0]
|
114 |
-
return x
|
115 |
-
|
116 |
-
|
117 |
-
def compute_metrics(config,
|
118 |
-
model_path,
|
119 |
-
vae_ckpt,
|
120 |
-
data_path,
|
121 |
-
output_path,
|
122 |
-
scales_img,
|
123 |
-
scales_txt,
|
124 |
-
num_samples = 5000,
|
125 |
-
split = "test",
|
126 |
-
steps = 50,
|
127 |
-
res = 512,
|
128 |
-
seed = 0):
|
129 |
-
editor = ImageEditor(config, model_path, vae_ckpt).cuda()
|
130 |
-
clip_similarity = ClipSimilarity().cuda()
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
outpath = Path(output_path, f"n={num_samples}_p={split}_s={steps}_r={res}_e={seed}.jsonl")
|
135 |
-
Path(output_path).mkdir(parents=True, exist_ok=True)
|
136 |
-
|
137 |
-
for scale_txt in scales_txt:
|
138 |
-
for scale_img in scales_img:
|
139 |
-
dataset = EditDatasetEval(
|
140 |
-
path=data_path,
|
141 |
-
split=split,
|
142 |
-
res=res
|
143 |
-
)
|
144 |
-
assert num_samples <= len(dataset)
|
145 |
-
print(f'Processing t={scale_txt}, i={scale_img}')
|
146 |
-
torch.manual_seed(seed)
|
147 |
-
perm = torch.randperm(len(dataset))
|
148 |
-
count = 0
|
149 |
-
i = 0
|
150 |
-
|
151 |
-
sim_0_avg = 0
|
152 |
-
sim_1_avg = 0
|
153 |
-
sim_direction_avg = 0
|
154 |
-
sim_image_avg = 0
|
155 |
-
count = 0
|
156 |
-
|
157 |
-
pbar = tqdm(total=num_samples)
|
158 |
-
while count < num_samples:
|
159 |
-
|
160 |
-
idx = perm[i].item()
|
161 |
-
sample = dataset[idx]
|
162 |
-
i += 1
|
163 |
-
|
164 |
-
gen = editor(sample["image_0"].cuda(), sample["edit"], scale_txt=scale_txt, scale_img=scale_img, steps=steps)
|
165 |
-
|
166 |
-
sim_0, sim_1, sim_direction, sim_image = clip_similarity(
|
167 |
-
sample["image_0"][None].cuda(), gen[None].cuda(), [sample["input_prompt"]], [sample["output_prompt"]]
|
168 |
-
)
|
169 |
-
sim_0_avg += sim_0.item()
|
170 |
-
sim_1_avg += sim_1.item()
|
171 |
-
sim_direction_avg += sim_direction.item()
|
172 |
-
sim_image_avg += sim_image.item()
|
173 |
-
count += 1
|
174 |
-
pbar.update(count)
|
175 |
-
pbar.close()
|
176 |
-
|
177 |
-
sim_0_avg /= count
|
178 |
-
sim_1_avg /= count
|
179 |
-
sim_direction_avg /= count
|
180 |
-
sim_image_avg /= count
|
181 |
-
|
182 |
-
with open(outpath, "a") as f:
|
183 |
-
f.write(f"{json.dumps(dict(sim_0=sim_0_avg, sim_1=sim_1_avg, sim_direction=sim_direction_avg, sim_image=sim_image_avg, num_samples=num_samples, split=split, scale_txt=scale_txt, scale_img=scale_img, steps=steps, res=res, seed=seed))}\n")
|
184 |
-
return outpath
|
185 |
-
|
186 |
-
def plot_metrics(metrics_file, output_path):
|
187 |
-
|
188 |
-
with open(metrics_file, 'r') as f:
|
189 |
-
data = [json.loads(line) for line in f]
|
190 |
-
|
191 |
-
plt.rcParams.update({'font.size': 11.5})
|
192 |
-
seaborn.set_style("darkgrid")
|
193 |
-
plt.figure(figsize=(20.5* 0.7, 10.8* 0.7), dpi=200)
|
194 |
-
|
195 |
-
x = [d["sim_direction"] for d in data]
|
196 |
-
y = [d["sim_image"] for d in data]
|
197 |
-
|
198 |
-
plt.plot(x, y, marker='o', linewidth=2, markersize=4)
|
199 |
-
|
200 |
-
plt.xlabel("CLIP Text-Image Direction Similarity", labelpad=10)
|
201 |
-
plt.ylabel("CLIP Image Similarity", labelpad=10)
|
202 |
-
|
203 |
-
plt.savefig(Path(output_path) / Path("plot.pdf"), bbox_inches="tight")
|
204 |
-
|
205 |
-
def main():
|
206 |
-
parser = ArgumentParser()
|
207 |
-
parser.add_argument("--resolution", default=512, type=int)
|
208 |
-
parser.add_argument("--steps", default=100, type=int)
|
209 |
-
parser.add_argument("--config", default="configs/generate.yaml", type=str)
|
210 |
-
parser.add_argument("--output_path", default="analysis/", type=str)
|
211 |
-
parser.add_argument("--ckpt", default="checkpoints/instruct-pix2pix-00-22000.ckpt", type=str)
|
212 |
-
parser.add_argument("--dataset", default="data/clip-filtered-dataset/", type=str)
|
213 |
-
parser.add_argument("--vae-ckpt", default=None, type=str)
|
214 |
-
args = parser.parse_args()
|
215 |
-
|
216 |
-
scales_img = [1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2]
|
217 |
-
scales_txt = [7.5]
|
218 |
-
|
219 |
-
metrics_file = compute_metrics(
|
220 |
-
args.config,
|
221 |
-
args.ckpt,
|
222 |
-
args.vae_ckpt,
|
223 |
-
args.dataset,
|
224 |
-
args.output_path,
|
225 |
-
scales_img,
|
226 |
-
scales_txt
|
227 |
-
steps = args.steps
|
228 |
-
)
|
229 |
-
|
230 |
-
plot_metrics(metrics_file, args.output_path)
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
if __name__ == "__main__":
|
235 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
prompt_app.py
DELETED
@@ -1,55 +0,0 @@
|
|
1 |
-
from __future__ import annotations
|
2 |
-
|
3 |
-
from argparse import ArgumentParser
|
4 |
-
|
5 |
-
import datasets
|
6 |
-
import gradio as gr
|
7 |
-
import numpy as np
|
8 |
-
import openai
|
9 |
-
|
10 |
-
from dataset_creation.generate_txt_dataset import generate
|
11 |
-
|
12 |
-
|
13 |
-
def main(openai_model: str):
|
14 |
-
dataset = datasets.load_dataset("ChristophSchuhmann/improved_aesthetics_6.5plus", split="train")
|
15 |
-
captions = dataset[np.random.permutation(len(dataset))]["TEXT"]
|
16 |
-
index = 0
|
17 |
-
|
18 |
-
def click_random():
|
19 |
-
nonlocal index
|
20 |
-
output = captions[index]
|
21 |
-
index = (index + 1) % len(captions)
|
22 |
-
return output
|
23 |
-
|
24 |
-
def click_generate(input: str):
|
25 |
-
if input == "":
|
26 |
-
raise gr.Error("Input caption is missing!")
|
27 |
-
edit_output = generate(openai_model, input)
|
28 |
-
if edit_output is None:
|
29 |
-
return "Failed :(", "Failed :("
|
30 |
-
return edit_output
|
31 |
-
|
32 |
-
with gr.Blocks(css="footer {visibility: hidden}") as demo:
|
33 |
-
txt_input = gr.Textbox(lines=3, label="Input Caption", interactive=True, placeholder="Type image caption here...") # fmt: skip
|
34 |
-
txt_edit = gr.Textbox(lines=1, label="GPT-3 Instruction", interactive=False)
|
35 |
-
txt_output = gr.Textbox(lines=3, label="GPT3 Edited Caption", interactive=False)
|
36 |
-
|
37 |
-
with gr.Row():
|
38 |
-
clear_btn = gr.Button("Clear")
|
39 |
-
random_btn = gr.Button("Random Input")
|
40 |
-
generate_btn = gr.Button("Generate Instruction + Edited Caption")
|
41 |
-
|
42 |
-
clear_btn.click(fn=lambda: ("", "", ""), inputs=[], outputs=[txt_input, txt_edit, txt_output])
|
43 |
-
random_btn.click(fn=click_random, inputs=[], outputs=[txt_input])
|
44 |
-
generate_btn.click(fn=click_generate, inputs=[txt_input], outputs=[txt_edit, txt_output])
|
45 |
-
|
46 |
-
demo.launch(share=True)
|
47 |
-
|
48 |
-
|
49 |
-
if __name__ == "__main__":
|
50 |
-
parser = ArgumentParser()
|
51 |
-
parser.add_argument("--openai-api-key", required=True, type=str)
|
52 |
-
parser.add_argument("--openai-model", required=True, type=str)
|
53 |
-
args = parser.parse_args()
|
54 |
-
openai.api_key = args.openai_api_key
|
55 |
-
main(args.openai_model)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
@@ -1,27 +1,6 @@
|
|
|
|
1 |
torch
|
2 |
-
torchvision
|
3 |
-
numpy
|
4 |
-
albumentations==0.4.3
|
5 |
-
datasets==2.8.0
|
6 |
-
diffusers
|
7 |
-
opencv-python==4.1.2.30
|
8 |
-
pudb==2019.2
|
9 |
-
invisible-watermark
|
10 |
-
imageio==2.9.0
|
11 |
-
imageio-ffmpeg==0.4.2
|
12 |
-
pytorch-lightning==1.4.2
|
13 |
-
omegaconf==2.1.1
|
14 |
-
test-tube>=0.7.5
|
15 |
-
streamlit>=0.73.1
|
16 |
-
einops==0.3.0
|
17 |
-
torch-fidelity==0.3.0
|
18 |
transformers
|
19 |
-
torchmetrics==0.6.0
|
20 |
-
kornia==0.6
|
21 |
-
-e git+https://github.com/CompVis/taming-transformers.git@master#egg=taming-transformers
|
22 |
-
-e git+https://github.com/openai/CLIP.git@main#egg=clip
|
23 |
-
huggingface-hub
|
24 |
-
openai
|
25 |
-
seaborn
|
26 |
-
git+https://github.com/crowsonkb/k-diffusion.git
|
27 |
git+https://github.com/huggingface/diffusers
|
|
|
1 |
+
-f --extra-index-url https://download.pytorch.org/whl/cu116
|
2 |
torch
|
3 |
+
torchvision
|
4 |
+
numpy
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
transformers
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
git+https://github.com/huggingface/diffusers
|
scripts/download_checkpoints.sh
DELETED
@@ -1,7 +0,0 @@
|
|
1 |
-
#!/bin/bash
|
2 |
-
|
3 |
-
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
4 |
-
|
5 |
-
mkdir -p $SCRIPT_DIR/../checkpoints
|
6 |
-
|
7 |
-
curl http://instruct-pix2pix.eecs.berkeley.edu/instruct-pix2pix-00-22000.ckpt -o $SCRIPT_DIR/../checkpoints/instruct-pix2pix-00-22000.ckpt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
scripts/download_data.sh
DELETED
@@ -1,27 +0,0 @@
|
|
1 |
-
#!/bin/bash
|
2 |
-
|
3 |
-
# Make data folder relative to script location
|
4 |
-
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
5 |
-
|
6 |
-
mkdir -p $SCRIPT_DIR/../data
|
7 |
-
|
8 |
-
# Copy text datasets
|
9 |
-
wget -q --show-progress http://instruct-pix2pix.eecs.berkeley.edu/gpt-generated-prompts.jsonl -O $SCRIPT_DIR/../data/gpt-generated-prompts.jsonl
|
10 |
-
wget -q --show-progress http://instruct-pix2pix.eecs.berkeley.edu/human-written-prompts.jsonl -O $SCRIPT_DIR/../data/human-written-prompts.jsonl
|
11 |
-
|
12 |
-
# If dataset name isn't provided, exit.
|
13 |
-
if [ -z $1 ]
|
14 |
-
then
|
15 |
-
exit 0
|
16 |
-
fi
|
17 |
-
|
18 |
-
# Copy dataset files
|
19 |
-
mkdir $SCRIPT_DIR/../data/$1
|
20 |
-
wget -A zip,json -R "index.html*" -q --show-progress -r --no-parent http://instruct-pix2pix.eecs.berkeley.edu/$1/ -nd -P $SCRIPT_DIR/../data/$1/
|
21 |
-
|
22 |
-
# Unzip to folders
|
23 |
-
unzip $SCRIPT_DIR/../data/$1/\*.zip -d $SCRIPT_DIR/../data/$1/
|
24 |
-
|
25 |
-
# Cleanup
|
26 |
-
rm -f $SCRIPT_DIR/../data/$1/*.zip
|
27 |
-
rm -f $SCRIPT_DIR/../data/$1/*.html
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
scripts/download_pretrained_sd.sh
DELETED
@@ -1,7 +0,0 @@
|
|
1 |
-
#!/bin/bash
|
2 |
-
|
3 |
-
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
4 |
-
|
5 |
-
mkdir -p $SCRIPT_DIR/../stable_diffusion/models/ldm/stable-diffusion-v1
|
6 |
-
curl -L https://huggingface.co/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.ckpt -o $SCRIPT_DIR/../stable_diffusion/models/ldm/stable-diffusion-v1/v1-5-pruned-emaonly.ckpt
|
7 |
-
curl -L https://huggingface.co/stabilityai/sd-vae-ft-mse-original/resolve/main/vae-ft-mse-840000-ema-pruned.ckpt -o $SCRIPT_DIR/../stable_diffusion/models/ldm/stable-diffusion-v1/vae-ft-mse-840000-ema-pruned.ckpt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
stable_diffusion/LICENSE
DELETED
@@ -1,82 +0,0 @@
|
|
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
DELETED
@@ -1,215 +0,0 @@
|
|
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
DELETED
@@ -1,144 +0,0 @@
|
|
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
DELETED
Binary file (667 kB)
|
|
stable_diffusion/assets/a-photograph-of-a-fire.png
DELETED
Binary file (611 kB)
|
|
stable_diffusion/assets/a-shirt-with-a-fire-printed-on-it.png
DELETED
Binary file (624 kB)
|
|
stable_diffusion/assets/a-shirt-with-the-inscription-'fire'.png
DELETED
Binary file (561 kB)
|
|
stable_diffusion/assets/a-watercolor-painting-of-a-fire.png
DELETED
Binary file (722 kB)
|
|
stable_diffusion/assets/birdhouse.png
DELETED
Binary file (775 kB)
|
|
stable_diffusion/assets/fire.png
DELETED
Binary file (626 kB)
|
|
stable_diffusion/assets/inpainting.png
DELETED
Binary file (319 kB)
|
|
stable_diffusion/assets/modelfigure.png
DELETED
Binary file (73.8 kB)
|
|
stable_diffusion/assets/rdm-preview.jpg
DELETED
Binary file (327 kB)
|
|
stable_diffusion/assets/reconstruction1.png
DELETED
Binary file (807 kB)
|
|
stable_diffusion/assets/reconstruction2.png
DELETED
Binary file (981 kB)
|
|
stable_diffusion/assets/results.gif.REMOVED.git-id
DELETED
@@ -1 +0,0 @@
|
|
1 |
-
82b6590e670a32196093cc6333ea19e6547d07de
|
|
|
|
stable_diffusion/assets/rick.jpeg
DELETED
Binary file (232 kB)
|
|
stable_diffusion/assets/stable-samples/img2img/mountains-1.png
DELETED
Binary file (625 kB)
|
|
stable_diffusion/assets/stable-samples/img2img/mountains-2.png
DELETED
Binary file (658 kB)
|
|
stable_diffusion/assets/stable-samples/img2img/mountains-3.png
DELETED
Binary file (656 kB)
|
|
stable_diffusion/assets/stable-samples/img2img/sketch-mountains-input.jpg
DELETED
Binary file (179 kB)
|
|
stable_diffusion/assets/stable-samples/img2img/upscaling-in.png.REMOVED.git-id
DELETED
@@ -1 +0,0 @@
|
|
1 |
-
501c31c21751664957e69ce52cad1818b6d2f4ce
|
|
|
|
stable_diffusion/assets/stable-samples/img2img/upscaling-out.png.REMOVED.git-id
DELETED
@@ -1 +0,0 @@
|
|
1 |
-
1c4bb25a779f34d86b2d90e584ac67af91bb1303
|
|
|
|
stable_diffusion/assets/stable-samples/txt2img/000002025.png
DELETED
Binary file (968 kB)
|
|
stable_diffusion/assets/stable-samples/txt2img/000002035.png
DELETED
Binary file (996 kB)
|
|
stable_diffusion/assets/stable-samples/txt2img/merged-0005.png.REMOVED.git-id
DELETED
@@ -1 +0,0 @@
|
|
1 |
-
ca0a1af206555f0f208a1ab879e95efedc1b1c5b
|
|
|
|
stable_diffusion/assets/stable-samples/txt2img/merged-0006.png.REMOVED.git-id
DELETED
@@ -1 +0,0 @@
|
|
1 |
-
999f3703230580e8c89e9081abd6a1f8f50896d4
|
|
|
|
stable_diffusion/assets/stable-samples/txt2img/merged-0007.png.REMOVED.git-id
DELETED
@@ -1 +0,0 @@
|
|
1 |
-
af390acaf601283782d6f479d4cade4d78e30b26
|
|
|
|
stable_diffusion/assets/the-earth-is-on-fire,-oil-on-canvas.png
DELETED
Binary file (678 kB)
|
|
stable_diffusion/assets/txt2img-convsample.png
DELETED
Binary file (310 kB)
|
|