-
Notifications
You must be signed in to change notification settings - Fork 2
/
test.py
185 lines (149 loc) · 7.61 KB
/
test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
import argparse, os, sys, glob
import PIL
import torch
import torch.nn as nn
import numpy as np
from omegaconf import OmegaConf
from PIL import Image
from tqdm import tqdm, trange
from itertools import islice
from einops import rearrange, repeat
from torchvision.utils import make_grid
from torch import autocast
from contextlib import nullcontext
import time
from pytorch_lightning import seed_everything
sys.path.append(os.path.dirname(sys.path[0]))
from ldm.util import instantiate_from_config
from ldm.models.diffusion.ddim import DDIMSampler
from ldm.models.diffusion.plms import PLMSSampler
from transformers import CLIPProcessor, CLIPModel
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
def chunk(it, size):
it = iter(it)
return iter(lambda: tuple(islice(it, size)), ())
def load_model_from_config(config, ckpt, verbose=False):
print(f"Loading model from {ckpt}")
pl_sd = torch.load(ckpt, map_location="cpu")
if "global_step" in pl_sd:
print(f"Global Step: {pl_sd['global_step']}")
sd = pl_sd["state_dict"]
model = instantiate_from_config(config.model)
m, u = model.load_state_dict(sd, strict=False)
if len(m) > 0 and verbose:
print("missing keys:")
print(m)
if len(u) > 0 and verbose:
print("unexpected keys:")
print(u)
model.to(device)
model.eval()
return model
def load_img(path):
image = Image.open(path).convert("RGB")
w, h = image.size
print(f"loaded input image of size ({w}, {h}) from {path}")
w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
image = image.resize((512, 512), resample=PIL.Image.LANCZOS)
image = np.array(image).astype(np.float32) / 255.0
image = image[None].transpose(0, 3, 1, 2)
image = torch.from_numpy(image)
return 2.*image - 1.
config="configs/stable-diffusion/v1-inference.yaml"
ckpt="models/sd/sd-v1-4.ckpt"
config = OmegaConf.load(f"{config}")
model = load_model_from_config(config, f"{ckpt}")
sampler = DDIMSampler(model)
def main(prompt = '', content_dir = '', style_dir='',ddim_steps = 50,strength = 0.5, model = None, seed=42):
ddim_eta=0.0
n_iter=1
C=4
f=8
n_samples=1
n_rows=0
scale=10.0
precision="autocast"
outdir="outputs/img2img-samples/test"
seed_everything(seed)
os.makedirs(outdir, exist_ok=True)
outpath = outdir
batch_size = n_samples
n_rows = n_rows if n_rows > 0 else batch_size
data = [batch_size * [prompt]]
sample_path = os.path.join(outpath, "samples")
os.makedirs(sample_path, exist_ok=True)
base_count = len(os.listdir(sample_path))
grid_count = len(os.listdir(outpath)) + 10
style_image = load_img(style_dir).to(device)
style_image = repeat(style_image, '1 ... -> b ...', b=batch_size)
style_latent = model.get_first_stage_encoding(model.encode_first_stage(style_image)) # move to latent space
content_name = content_dir.split('/')[-1].split('.')[0]
content_image = load_img(content_dir).to(device)
content_image = repeat(content_image, '1 ... -> b ...', b=batch_size)
content_latent = model.get_first_stage_encoding(model.encode_first_stage(content_image)) # move to latent space
init_latent = content_latent
sampler.make_schedule(ddim_num_steps=ddim_steps, ddim_eta=ddim_eta, verbose=False)
assert 0. <= strength <= 1., 'can only work with strength in [0.0, 1.0]'
t_enc = int(strength * ddim_steps)
print(f"target t_enc is {t_enc} steps")
precision_scope = autocast if precision == "autocast" else nullcontext
with torch.no_grad():
with precision_scope("cuda"):
with model.ema_scope():
tic = time.time()
all_samples = list()
for n in trange(n_iter, desc="Sampling"):
for prompts in tqdm(data, desc="data"):
uc = None
if scale != 1.0:
uc = model.get_learned_conditioning(batch_size * [""], style_image)
if isinstance(prompts, tuple):
prompts = list(prompts)
c= model.get_learned_conditioning(prompts, style_image)
# img2img
# stochastic encode
# z_enc = sampler.stochastic_encode(init_latent, torch.tensor([t_enc]*batch_size).to(device))
# stochastic inversion
t_enc = int(strength * 1000)
x_noisy = model.q_sample(x_start=init_latent, t=torch.tensor([t_enc]*batch_size).to(device))
model_output = model.apply_model(x_noisy, torch.tensor([t_enc]*batch_size).to(device), c)
z_enc = sampler.stochastic_encode(init_latent, torch.tensor([t_enc]*batch_size).to(device),\
noise = model_output, use_original_steps = True)
t_enc = int(strength * ddim_steps)
samples = sampler.decode(z_enc, c, t_enc,
unconditional_guidance_scale=scale,
unconditional_conditioning=uc,)
# print(z_enc.shape, uc.shape, t_enc)
# txt2img
# noise =torch.randn_like(content_latent)
# samples, intermediates =sampler.sample(ddim_steps,1,(4,512,512),c,verbose=False, eta=1.,x_T = noise,
# unconditional_guidance_scale=scale,
# unconditional_conditioning=uc,)
x_samples = model.decode_first_stage(samples)
x_samples = torch.clamp((x_samples + 1.0) / 2.0, min=0.0, max=1.0)
for x_sample in x_samples:
x_sample = 255. * rearrange(x_sample.cpu().numpy(), 'c h w -> h w c')
base_count += 1
all_samples.append(x_samples)
# additionally, save as grid
grid = torch.stack(all_samples, 0)
grid = rearrange(grid, 'n b c h w -> (n b) c h w')
grid = make_grid(grid, nrow=n_rows)
# to image
grid = 255. * rearrange(grid, 'c h w -> h w c').cpu().numpy()
output = Image.fromarray(grid.astype(np.uint8))
# output.save(os.path.join(outpath, content_name+'-'+prompt+f'-{grid_count:04}.png'))
output.save(os.path.join(outpath, content_name + 'stylized.jpg'))
# Image.fromarray(grid.astype(np.uint8)).save(os.path.join(outpath, f'grid-{grid_count:04}.png'))
grid_count += 1
toc = time.time()
return output
model.embedding_manager.load('./logs/vangoh-trainA2023-03-20T20-42-15_test/checkpoints/embeddings.pt')
model.cond_stage_model.mapper.load_state_dict(torch.load('./logs/vangoh-trainA2023-03-20T20-42-15_test/checkpoints/Mapper.pt', map_location='cpu'))
model = model.to(device)
model = model.eval()
# for i in range(6227):
# contentdir = "./comparison2/" + str(i) + ".jpg"
# main(prompt = '*', content_dir = contentdir, style_dir = contentdir, ddim_steps = 50, strength = 0.7, seed=42, model = model)
contentdir = "./images/" + "style.jpg"
main(prompt = 'a painting by Van gogh*', content_dir = contentdir, style_dir = contentdir, ddim_steps = 50, strength = 0.7, seed=42, model = model)