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|
4 |
+
os.system('git clone https://github.com/openai/CLIP')
|
5 |
+
os.system('git clone https://github.com/crowsonkb/guided-diffusion')
|
6 |
+
os.system('pip install -e ./CLIP')
|
7 |
+
os.system('pip install -e ./guided-diffusion')
|
8 |
+
os.system('pip install lpips')
|
9 |
+
os.system("curl -OL 'https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt'")
|
10 |
+
import io
|
11 |
+
import math
|
12 |
+
import sys
|
13 |
+
import lpips
|
14 |
+
from PIL import Image
|
15 |
+
import requests
|
16 |
+
import torch
|
17 |
+
from torch import nn
|
18 |
+
from torch.nn import functional as F
|
19 |
+
from torchvision import transforms
|
20 |
+
from torchvision.transforms import functional as TF
|
21 |
+
from tqdm.notebook import tqdm
|
22 |
+
sys.path.append('./CLIP')
|
23 |
+
sys.path.append('./guided-diffusion')
|
24 |
+
import clip
|
25 |
+
from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults
|
26 |
+
import numpy as np
|
27 |
+
import imageio
|
28 |
+
def fetch(url_or_path):
|
29 |
+
if str(url_or_path).startswith('http://') or str(url_or_path).startswith('https://'):
|
30 |
+
r = requests.get(url_or_path)
|
31 |
+
r.raise_for_status()
|
32 |
+
fd = io.BytesIO()
|
33 |
+
fd.write(r.content)
|
34 |
+
fd.seek(0)
|
35 |
+
return fd
|
36 |
+
return open(url_or_path, 'rb')
|
37 |
+
def parse_prompt(prompt):
|
38 |
+
if prompt.startswith('http://') or prompt.startswith('https://'):
|
39 |
+
vals = prompt.rsplit(':', 2)
|
40 |
+
vals = [vals[0] + ':' + vals[1], *vals[2:]]
|
41 |
+
else:
|
42 |
+
vals = prompt.rsplit(':', 1)
|
43 |
+
vals = vals + ['', '1'][len(vals):]
|
44 |
+
return vals[0], float(vals[1])
|
45 |
+
class MakeCutouts(nn.Module):
|
46 |
+
def __init__(self, cut_size, cutn, cut_pow=1.):
|
47 |
+
super().__init__()
|
48 |
+
self.cut_size = cut_size
|
49 |
+
self.cutn = cutn
|
50 |
+
self.cut_pow = cut_pow
|
51 |
+
def forward(self, input):
|
52 |
+
sideY, sideX = input.shape[2:4]
|
53 |
+
max_size = min(sideX, sideY)
|
54 |
+
min_size = min(sideX, sideY, self.cut_size)
|
55 |
+
cutouts = []
|
56 |
+
for _ in range(self.cutn):
|
57 |
+
size = int(torch.rand([])**self.cut_pow * (max_size - min_size) + min_size)
|
58 |
+
offsetx = torch.randint(0, sideX - size + 1, ())
|
59 |
+
offsety = torch.randint(0, sideY - size + 1, ())
|
60 |
+
cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]
|
61 |
+
cutouts.append(F.adaptive_avg_pool2d(cutout, self.cut_size))
|
62 |
+
return torch.cat(cutouts)
|
63 |
+
def spherical_dist_loss(x, y):
|
64 |
+
x = F.normalize(x, dim=-1)
|
65 |
+
y = F.normalize(y, dim=-1)
|
66 |
+
return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)
|
67 |
+
def tv_loss(input):
|
68 |
+
"""L2 total variation loss, as in Mahendran et al."""
|
69 |
+
input = F.pad(input, (0, 1, 0, 1), 'replicate')
|
70 |
+
x_diff = input[..., :-1, 1:] - input[..., :-1, :-1]
|
71 |
+
y_diff = input[..., 1:, :-1] - input[..., :-1, :-1]
|
72 |
+
return (x_diff**2 + y_diff**2).mean([1, 2, 3])
|
73 |
+
def range_loss(input):
|
74 |
+
return (input - input.clamp(-1, 1)).pow(2).mean([1, 2, 3])
|
75 |
+
|
76 |
+
def inference(text, init_image, skip_timesteps, clip_guidance_scale, tv_scale, range_scale, init_scale, seed, image_prompts,timestep_respacing, cutn):
|
77 |
+
# Model settings
|
78 |
+
model_config = model_and_diffusion_defaults()
|
79 |
+
model_config.update({
|
80 |
+
'attention_resolutions': '32, 16, 8',
|
81 |
+
'class_cond': False,
|
82 |
+
'diffusion_steps': 1000,
|
83 |
+
'rescale_timesteps': True,
|
84 |
+
'timestep_respacing': str(timestep_respacing), # Modify this value to decrease the number of
|
85 |
+
# timesteps.
|
86 |
+
'image_size': 256,
|
87 |
+
'learn_sigma': True,
|
88 |
+
'noise_schedule': 'linear',
|
89 |
+
'num_channels': 256,
|
90 |
+
'num_head_channels': 64,
|
91 |
+
'num_res_blocks': 2,
|
92 |
+
'resblock_updown': True,
|
93 |
+
'use_fp16': True,
|
94 |
+
'use_scale_shift_norm': True,
|
95 |
+
})
|
96 |
+
# Load models
|
97 |
+
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
|
98 |
+
print('Using device:', device)
|
99 |
+
model, diffusion = create_model_and_diffusion(**model_config)
|
100 |
+
model.load_state_dict(torch.load('256x256_diffusion_uncond.pt', map_location='cpu'))
|
101 |
+
model.requires_grad_(False).eval().to(device)
|
102 |
+
for name, param in model.named_parameters():
|
103 |
+
if 'qkv' in name or 'norm' in name or 'proj' in name:
|
104 |
+
param.requires_grad_()
|
105 |
+
if model_config['use_fp16']:
|
106 |
+
model.convert_to_fp16()
|
107 |
+
clip_model = clip.load('ViT-B/16', jit=False)[0].eval().requires_grad_(False).to(device)
|
108 |
+
clip_size = clip_model.visual.input_resolution
|
109 |
+
normalize = transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073],
|
110 |
+
std=[0.26862954, 0.26130258, 0.27577711])
|
111 |
+
lpips_model = lpips.LPIPS(net='vgg').to(device)
|
112 |
+
|
113 |
+
#def inference(text, init_image, skip_timesteps, clip_guidance_scale, tv_scale, range_scale, init_scale, seed, image_prompt):
|
114 |
+
all_frames = []
|
115 |
+
prompts = [text]
|
116 |
+
if image_prompts:
|
117 |
+
image_prompts = [image_prompts.name]
|
118 |
+
else:
|
119 |
+
image_prompts = []
|
120 |
+
batch_size = 1
|
121 |
+
clip_guidance_scale = clip_guidance_scale # Controls how much the image should look like the prompt.
|
122 |
+
tv_scale = tv_scale # Controls the smoothness of the final output.
|
123 |
+
range_scale = range_scale # Controls how far out of range RGB values are allowed to be.
|
124 |
+
cutn = cutn
|
125 |
+
n_batches = 1
|
126 |
+
if init_image:
|
127 |
+
init_image = init_image.name
|
128 |
+
else:
|
129 |
+
init_image = None # This can be an URL or Colab local path and must be in quotes.
|
130 |
+
skip_timesteps = skip_timesteps # This needs to be between approx. 200 and 500 when using an init image.
|
131 |
+
# Higher values make the output look more like the init.
|
132 |
+
init_scale = init_scale # This enhances the effect of the init image, a good value is 1000.
|
133 |
+
seed = seed
|
134 |
+
|
135 |
+
if seed is not None:
|
136 |
+
torch.manual_seed(seed)
|
137 |
+
make_cutouts = MakeCutouts(clip_size, cutn)
|
138 |
+
side_x = side_y = model_config['image_size']
|
139 |
+
target_embeds, weights = [], []
|
140 |
+
for prompt in prompts:
|
141 |
+
txt, weight = parse_prompt(prompt)
|
142 |
+
target_embeds.append(clip_model.encode_text(clip.tokenize(txt).to(device)).float())
|
143 |
+
weights.append(weight)
|
144 |
+
for prompt in image_prompts:
|
145 |
+
path, weight = parse_prompt(prompt)
|
146 |
+
img = Image.open(fetch(path)).convert('RGB')
|
147 |
+
img = TF.resize(img, min(side_x, side_y, *img.size), transforms.InterpolationMode.LANCZOS)
|
148 |
+
batch = make_cutouts(TF.to_tensor(img).unsqueeze(0).to(device))
|
149 |
+
embed = clip_model.encode_image(normalize(batch)).float()
|
150 |
+
target_embeds.append(embed)
|
151 |
+
weights.extend([weight / cutn] * cutn)
|
152 |
+
target_embeds = torch.cat(target_embeds)
|
153 |
+
weights = torch.tensor(weights, device=device)
|
154 |
+
if weights.sum().abs() < 1e-3:
|
155 |
+
raise RuntimeError('The weights must not sum to 0.')
|
156 |
+
weights /= weights.sum().abs()
|
157 |
+
init = None
|
158 |
+
if init_image is not None:
|
159 |
+
init = Image.open(fetch(init_image)).convert('RGB')
|
160 |
+
init = init.resize((side_x, side_y), Image.LANCZOS)
|
161 |
+
init = TF.to_tensor(init).to(device).unsqueeze(0).mul(2).sub(1)
|
162 |
+
cur_t = None
|
163 |
+
def cond_fn(x, t, y=None):
|
164 |
+
with torch.enable_grad():
|
165 |
+
x = x.detach().requires_grad_()
|
166 |
+
n = x.shape[0]
|
167 |
+
my_t = torch.ones([n], device=device, dtype=torch.long) * cur_t
|
168 |
+
out = diffusion.p_mean_variance(model, x, my_t, clip_denoised=False, model_kwargs={'y': y})
|
169 |
+
fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t]
|
170 |
+
x_in = out['pred_xstart'] * fac + x * (1 - fac)
|
171 |
+
clip_in = normalize(make_cutouts(x_in.add(1).div(2)))
|
172 |
+
image_embeds = clip_model.encode_image(clip_in).float()
|
173 |
+
dists = spherical_dist_loss(image_embeds.unsqueeze(1), target_embeds.unsqueeze(0))
|
174 |
+
dists = dists.view([cutn, n, -1])
|
175 |
+
losses = dists.mul(weights).sum(2).mean(0)
|
176 |
+
tv_losses = tv_loss(x_in)
|
177 |
+
range_losses = range_loss(out['pred_xstart'])
|
178 |
+
loss = losses.sum() * clip_guidance_scale + tv_losses.sum() * tv_scale + range_losses.sum() * range_scale
|
179 |
+
if init is not None and init_scale:
|
180 |
+
init_losses = lpips_model(x_in, init)
|
181 |
+
loss = loss + init_losses.sum() * init_scale
|
182 |
+
return -torch.autograd.grad(loss, x)[0]
|
183 |
+
if model_config['timestep_respacing'].startswith('ddim'):
|
184 |
+
sample_fn = diffusion.ddim_sample_loop_progressive
|
185 |
+
else:
|
186 |
+
sample_fn = diffusion.p_sample_loop_progressive
|
187 |
+
for i in range(n_batches):
|
188 |
+
cur_t = diffusion.num_timesteps - skip_timesteps - 1
|
189 |
+
samples = sample_fn(
|
190 |
+
model,
|
191 |
+
(batch_size, 3, side_y, side_x),
|
192 |
+
clip_denoised=False,
|
193 |
+
model_kwargs={},
|
194 |
+
cond_fn=cond_fn,
|
195 |
+
progress=True,
|
196 |
+
skip_timesteps=skip_timesteps,
|
197 |
+
init_image=init,
|
198 |
+
randomize_class=True,
|
199 |
+
)
|
200 |
+
for j, sample in enumerate(samples):
|
201 |
+
cur_t -= 1
|
202 |
+
if j % 1 == 0 or cur_t == -1:
|
203 |
+
print()
|
204 |
+
for k, image in enumerate(sample['pred_xstart']):
|
205 |
+
#filename = f'progress_{i * batch_size + k:05}.png'
|
206 |
+
img = TF.to_pil_image(image.add(1).div(2).clamp(0, 1))
|
207 |
+
all_frames.append(img)
|
208 |
+
tqdm.write(f'Batch {i}, step {j}, output {k}:')
|
209 |
+
#display.display(display.Image(filename))
|
210 |
+
writer = imageio.get_writer('video.mp4', fps=5)
|
211 |
+
for im in all_frames:
|
212 |
+
writer.append_data(np.array(im))
|
213 |
+
writer.close()
|
214 |
+
return img, 'video.mp4'
|
215 |
+
|
216 |
+
title = "CLIP Guided Diffusion HQ"
|
217 |
+
description = "Gradio demo for CLIP Guided Diffusion. To use it, simply add your text, or click one of the examples to load them. Read more at the links below."
|
218 |
+
article = "<p style='text-align: center'> By Katherine Crowson (https://github.com/crowsonkb, https://twitter.com/RiversHaveWings). It uses OpenAI's 256x256 unconditional ImageNet diffusion model (https://github.com/openai/guided-diffusion) together with CLIP (https://github.com/openai/CLIP) to connect text prompts with images. | <a href='https://colab.research.google.com/drive/12a_Wrfi2_gwwAuN3VvMTwVMz9TfqctNj' target='_blank'>Colab</a></p>"
|
219 |
+
iface = gr.Interface(inference, inputs=["text",gr.inputs.Image(type="file", label='initial image (optional)', optional=True),gr.inputs.Slider(minimum=0, maximum=45, step=1, default=10, label="skip_timesteps"), gr.inputs.Slider(minimum=0, maximum=3000, step=1, default=600, label="clip guidance scale (Controls how much the image should look like the prompt)"), gr.inputs.Slider(minimum=0, maximum=1000, step=1, default=0, label="tv_scale (Controls the smoothness of the final output)"), gr.inputs.Slider(minimum=0, maximum=1000, step=1, default=0, label="range_scale (Controls how far out of range RGB values are allowed to be)"), gr.inputs.Slider(minimum=0, maximum=1000, step=1, default=0, label="init_scale (This enhances the effect of the init image)"), gr.inputs.Number(default=0, label="Seed"), gr.inputs.Image(type="file", label='image prompt (optional)', optional=True), gr.inputs.Slider(minimum=50, maximum=500, step=1, default=50, label="timestep respacing"),gr.inputs.Slider(minimum=1, maximum=64, step=1, default=32, label="cutn")], outputs=["image","video"], title=title, description=description, article=article, examples=[["coral reef city by artistation artists", None, 0, 1000, 150, 50, 0, 0, None, 90, 32]],
|
220 |
+
enable_queue=True)
|
221 |
+
iface.launch()
|
requirements.txt
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch
|
2 |
+
torchvision
|
3 |
+
kornia
|
4 |
+
tqdm
|
5 |
+
clip-anytorch
|
6 |
+
requests
|
7 |
+
lpips
|
8 |
+
numpy
|
9 |
+
imageio
|
10 |
+
imageio-ffmpeg
|