Commit
·
a67c790
1
Parent(s):
47017f5
Adding guidance
Browse files
app.py
CHANGED
|
@@ -3,6 +3,7 @@ import torch
|
|
| 3 |
import gradio as gr
|
| 4 |
from tqdm import tqdm
|
| 5 |
from PIL import Image
|
|
|
|
| 6 |
from torchvision import transforms as tfms
|
| 7 |
from transformers import CLIPTextModel, CLIPTokenizer, logging
|
| 8 |
from diffusers import AutoencoderKL, LMSDiscreteScheduler, UNet2DConditionModel
|
|
@@ -53,6 +54,8 @@ token_emb_layer_with_art.load_state_dict({'weight': torch.cat((token_emb_layer.s
|
|
| 53 |
tony_diterlizzi_s_planescape_art_embed['<tony-diterlizzi-planescape>'].unsqueeze(0).to(torch_device)))})
|
| 54 |
token_emb_layer_with_art = token_emb_layer_with_art.to(torch_device)
|
| 55 |
|
|
|
|
|
|
|
| 56 |
def set_timesteps(scheduler, num_inference_steps):
|
| 57 |
scheduler.set_timesteps(num_inference_steps)
|
| 58 |
scheduler.timesteps = scheduler.timesteps.to(torch.float32)
|
|
@@ -148,7 +151,106 @@ def generate_with_embs(num_inference_steps, guidance_scale, seed, text_input, te
|
|
| 148 |
|
| 149 |
return latents_to_pil(latents)[0]
|
| 150 |
|
| 151 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
prompt = text + " the style of " + style_token_dict[style]
|
| 153 |
|
| 154 |
# Tokenize
|
|
@@ -165,26 +267,34 @@ def inference(text, style, inference_step, guidance_scale, seed):
|
|
| 165 |
modified_output_embeddings = get_output_embeds(input_embeddings)
|
| 166 |
|
| 167 |
# And generate an image with this:
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
-
return
|
| 171 |
|
| 172 |
title = "Stable Diffusion with Textual Inversion"
|
| 173 |
description = "A simple Gradio interface to infer Stable Diffusion and generate images with different art style"
|
| 174 |
-
examples = [["A sweet potato farm", 'Concept', 10, 1.5, 1],
|
| 175 |
-
["Sky full of cotton candy", 'Realistic', 10, 3.5, 2],
|
| 176 |
-
["Kittens in the bathtub", 'Line', 10, 5.5, 3],
|
| 177 |
-
["Water skiing on a lake", 'Ricky', 10, 7.5, 4],
|
| 178 |
-
["Miniature pet elephant", 'Plane Scape', 10, 9.5, 5]]
|
| 179 |
|
| 180 |
demo = gr.Interface(inference,
|
| 181 |
inputs = [gr.Textbox(label="Prompt", type="text"),
|
| 182 |
gr.Dropdown(label="Style", choices=['Concept', 'Realistic', 'Line',
|
| 183 |
'Ricky', 'Plane Scape'], value="Concept"),
|
| 184 |
-
gr.Slider(10, 30, 10, step =
|
| 185 |
gr.Slider(1, 10, 7.5, step = 0.1, label="Guidance scale"),
|
| 186 |
-
gr.Slider(0, 10000, 1, step = 1, label="Seed")
|
| 187 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
title=title,
|
| 189 |
description=description,
|
| 190 |
examples=examples)
|
|
|
|
| 3 |
import gradio as gr
|
| 4 |
from tqdm import tqdm
|
| 5 |
from PIL import Image
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
from torchvision import transforms as tfms
|
| 8 |
from transformers import CLIPTextModel, CLIPTokenizer, logging
|
| 9 |
from diffusers import AutoencoderKL, LMSDiscreteScheduler, UNet2DConditionModel
|
|
|
|
| 54 |
tony_diterlizzi_s_planescape_art_embed['<tony-diterlizzi-planescape>'].unsqueeze(0).to(torch_device)))})
|
| 55 |
token_emb_layer_with_art = token_emb_layer_with_art.to(torch_device)
|
| 56 |
|
| 57 |
+
grayscale_transformer = tfms.Grayscale(num_output_channels=3)
|
| 58 |
+
|
| 59 |
def set_timesteps(scheduler, num_inference_steps):
|
| 60 |
scheduler.set_timesteps(num_inference_steps)
|
| 61 |
scheduler.timesteps = scheduler.timesteps.to(torch.float32)
|
|
|
|
| 151 |
|
| 152 |
return latents_to_pil(latents)[0]
|
| 153 |
|
| 154 |
+
def guide_loss(images, loss_type='grayscale'):
|
| 155 |
+
# grayscale loss
|
| 156 |
+
if loss_type == 'grayscale':
|
| 157 |
+
transformed_imgs = grayscale_transformer(images)
|
| 158 |
+
error = torch.abs(transformed_imgs - images).mean()
|
| 159 |
+
|
| 160 |
+
# brightness loss
|
| 161 |
+
elif loss_type == 'bright':
|
| 162 |
+
transformed_imgs = tfms.functional.adjust_brightness(images, brightness_factor=3)
|
| 163 |
+
error = torch.abs(transformed_imgs - images).mean()
|
| 164 |
+
|
| 165 |
+
# contrast loss
|
| 166 |
+
elif loss_type == 'contrast':
|
| 167 |
+
transformed_imgs = tfms.functional.adjust_contrast(images, contrast_factor=10)
|
| 168 |
+
error = torch.abs(transformed_imgs - images).mean()
|
| 169 |
+
|
| 170 |
+
# symmetry loss - Flip the image along the width
|
| 171 |
+
elif loss_type == "symmetry":
|
| 172 |
+
flipped_image = torch.flip(images, [3])
|
| 173 |
+
error = F.mse_loss(images, flipped_image)
|
| 174 |
+
|
| 175 |
+
# saturation loss
|
| 176 |
+
elif loss_type == 'saturation':
|
| 177 |
+
transformed_imgs = tfms.functional.adjust_saturation(images,saturation_factor = 10)
|
| 178 |
+
error = torch.abs(transformed_imgs - images).mean()
|
| 179 |
+
|
| 180 |
+
return error
|
| 181 |
+
|
| 182 |
+
def generate_with_guide_loss(num_inference_steps, guidance_scale, seed, text_input, text_embeddings, loss_type, loss_scale):
|
| 183 |
+
height = 512 # default height of Stable Diffusion
|
| 184 |
+
width = 512 # default width of Stable Diffusion
|
| 185 |
+
generator = torch.manual_seed(seed) # Seed generator to create the inital latent noise
|
| 186 |
+
batch_size = 1
|
| 187 |
+
|
| 188 |
+
# And the uncond. input as before:
|
| 189 |
+
max_length = text_input.input_ids.shape[-1]
|
| 190 |
+
uncond_input = tokenizer(
|
| 191 |
+
[""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
|
| 192 |
+
)
|
| 193 |
+
with torch.no_grad():
|
| 194 |
+
uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]
|
| 195 |
+
text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
|
| 196 |
+
|
| 197 |
+
# Prep Scheduler
|
| 198 |
+
set_timesteps(scheduler, num_inference_steps)
|
| 199 |
+
|
| 200 |
+
# Prep latents
|
| 201 |
+
latents = torch.randn(
|
| 202 |
+
(batch_size, unet.in_channels, height // 8, width // 8),
|
| 203 |
+
generator=generator,
|
| 204 |
+
)
|
| 205 |
+
latents = latents.to(torch_device)
|
| 206 |
+
latents = latents * scheduler.init_noise_sigma
|
| 207 |
+
|
| 208 |
+
# Loop
|
| 209 |
+
for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
|
| 210 |
+
# expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
|
| 211 |
+
latent_model_input = torch.cat([latents] * 2)
|
| 212 |
+
sigma = scheduler.sigmas[i]
|
| 213 |
+
latent_model_input = scheduler.scale_model_input(latent_model_input, t)
|
| 214 |
+
|
| 215 |
+
# predict the noise residual
|
| 216 |
+
with torch.no_grad():
|
| 217 |
+
noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
|
| 218 |
+
|
| 219 |
+
# perform CFG
|
| 220 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 221 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 222 |
+
|
| 223 |
+
#### ADDITIONAL GUIDANCE ###
|
| 224 |
+
if i%5 == 0:
|
| 225 |
+
# Requires grad on the latents
|
| 226 |
+
latents = latents.detach().requires_grad_()
|
| 227 |
+
|
| 228 |
+
# Get the predicted x0:
|
| 229 |
+
latents_x0 = latents - sigma * noise_pred
|
| 230 |
+
# latents_x0 = scheduler.step(noise_pred, t, latents).pred_original_sample
|
| 231 |
+
|
| 232 |
+
# Decode to image space
|
| 233 |
+
denoised_images = vae.decode((1 / 0.18215) * latents_x0).sample / 2 + 0.5 # range (0, 1)
|
| 234 |
+
|
| 235 |
+
# Calculate loss
|
| 236 |
+
loss = guide_loss(denoised_images, loss_type) * loss_scale
|
| 237 |
+
|
| 238 |
+
# Occasionally print it out
|
| 239 |
+
if i%10==0:
|
| 240 |
+
print(i, 'loss:', loss.item())
|
| 241 |
+
|
| 242 |
+
# Get gradient
|
| 243 |
+
cond_grad = torch.autograd.grad(loss, latents)[0]
|
| 244 |
+
|
| 245 |
+
# Modify the latents based on this gradient
|
| 246 |
+
latents = latents.detach() - cond_grad * sigma**2
|
| 247 |
+
|
| 248 |
+
# Now step with scheduler
|
| 249 |
+
latents = scheduler.step(noise_pred, t, latents).prev_sample
|
| 250 |
+
|
| 251 |
+
return latents_to_pil(latents)[0]
|
| 252 |
+
|
| 253 |
+
def inference(text, style, inference_step, guidance_scale, seed, guidance_method, loss_scale):
|
| 254 |
prompt = text + " the style of " + style_token_dict[style]
|
| 255 |
|
| 256 |
# Tokenize
|
|
|
|
| 267 |
modified_output_embeddings = get_output_embeds(input_embeddings)
|
| 268 |
|
| 269 |
# And generate an image with this:
|
| 270 |
+
image_embs = generate_with_embs(inference_step, guidance_scale, seed, text_input, modified_output_embeddings)
|
| 271 |
+
|
| 272 |
+
# Generate an image with guidance
|
| 273 |
+
image_guide = generate_with_guide_loss(inference_step, guidance_scale, seed, text_input,
|
| 274 |
+
modified_output_embeddings, guidance_method, loss_scale)
|
| 275 |
|
| 276 |
+
return image_embs, image_guide
|
| 277 |
|
| 278 |
title = "Stable Diffusion with Textual Inversion"
|
| 279 |
description = "A simple Gradio interface to infer Stable Diffusion and generate images with different art style"
|
| 280 |
+
examples = [["A sweet potato farm", 'Concept', 10, 1.5, 1, 'Grayscale', 100],
|
| 281 |
+
["Sky full of cotton candy", 'Realistic', 10, 3.5, 2, 'Bright', 200],
|
| 282 |
+
["Kittens in the bathtub", 'Line', 10, 5.5, 3, 'Contrast', 300],
|
| 283 |
+
["Water skiing on a lake", 'Ricky', 10, 7.5, 4, 'Symmetry', 400],
|
| 284 |
+
["Miniature pet elephant", 'Plane Scape', 10, 9.5, 5, 'Saturation', 500]]
|
| 285 |
|
| 286 |
demo = gr.Interface(inference,
|
| 287 |
inputs = [gr.Textbox(label="Prompt", type="text"),
|
| 288 |
gr.Dropdown(label="Style", choices=['Concept', 'Realistic', 'Line',
|
| 289 |
'Ricky', 'Plane Scape'], value="Concept"),
|
| 290 |
+
gr.Slider(10, 30, 10, step = 5, label="Inference steps"),
|
| 291 |
gr.Slider(1, 10, 7.5, step = 0.1, label="Guidance scale"),
|
| 292 |
+
gr.Slider(0, 10000, 1, step = 1, label="Seed"),
|
| 293 |
+
gr.Dropdown(label="Guidance method", choices=['Grayscale', 'Bright', 'Contrast',
|
| 294 |
+
'Symmetry', 'Saturation'], value="Concept"),
|
| 295 |
+
gr.Slider(100, 10000, 100, step = 1, label="Loss scale")],
|
| 296 |
+
outputs= [gr.Image(width=320, height=320, label="Generated art"),
|
| 297 |
+
gr.Image(width=320, height=320, label="Generated art with guidance")],
|
| 298 |
title=title,
|
| 299 |
description=description,
|
| 300 |
examples=examples)
|