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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from base64 import b64encode
|
| 2 |
+
import numpy
|
| 3 |
+
import torch
|
| 4 |
+
from diffusers import AutoencoderKL, LMSDiscreteScheduler, UNet2DConditionModel
|
| 5 |
+
from huggingface_hub import notebook_login
|
| 6 |
+
import gradio as gr
|
| 7 |
+
|
| 8 |
+
# For video display:
|
| 9 |
+
from matplotlib import pyplot as plt
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from PIL import Image
|
| 12 |
+
from torch import autocast
|
| 13 |
+
from torchvision import transforms as tfms
|
| 14 |
+
from tqdm.auto import tqdm
|
| 15 |
+
from transformers import CLIPTextModel, CLIPTokenizer, logging
|
| 16 |
+
import os
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# Supress some unnecessary warnings when loading the CLIPTextModel
|
| 22 |
+
logging.set_verbosity_error()
|
| 23 |
+
|
| 24 |
+
# Set device
|
| 25 |
+
torch_device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
| 26 |
+
|
| 27 |
+
# Load the autoencoder model which will be used to decode the latents into image space.
|
| 28 |
+
vae = AutoencoderKL.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="vae")
|
| 29 |
+
|
| 30 |
+
# Load the tokenizer and text encoder to tokenize and encode the text.
|
| 31 |
+
tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")
|
| 32 |
+
text_encoder = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14")
|
| 33 |
+
|
| 34 |
+
# The UNet model for generating the latents.
|
| 35 |
+
unet = UNet2DConditionModel.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="unet")
|
| 36 |
+
|
| 37 |
+
# The noise scheduler
|
| 38 |
+
scheduler = LMSDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000)
|
| 39 |
+
|
| 40 |
+
# To the GPU we go!
|
| 41 |
+
vae = vae.to(torch_device)
|
| 42 |
+
text_encoder = text_encoder.to(torch_device)
|
| 43 |
+
unet = unet.to(torch_device)
|
| 44 |
+
token_emb_layer = text_encoder.text_model.embeddings.token_embedding
|
| 45 |
+
pos_emb_layer = text_encoder.text_model.embeddings.position_embedding
|
| 46 |
+
|
| 47 |
+
position_ids = text_encoder.text_model.embeddings.position_ids[:, :77]
|
| 48 |
+
position_embeddings = pos_emb_layer(position_ids)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def get_output_embeds(input_embeddings):
|
| 52 |
+
# CLIP's text model uses causal mask, so we prepare it here:
|
| 53 |
+
bsz, seq_len = input_embeddings.shape[:2]
|
| 54 |
+
causal_attention_mask = text_encoder.text_model._build_causal_attention_mask(bsz, seq_len, dtype=input_embeddings.dtype)
|
| 55 |
+
|
| 56 |
+
# Getting the output embeddings involves calling the model with passing output_hidden_states=True
|
| 57 |
+
# so that it doesn't just return the pooled final predictions:
|
| 58 |
+
encoder_outputs = text_encoder.text_model.encoder(
|
| 59 |
+
inputs_embeds=input_embeddings,
|
| 60 |
+
attention_mask=None, # We aren't using an attention mask so that can be None
|
| 61 |
+
causal_attention_mask=causal_attention_mask.to(torch_device),
|
| 62 |
+
output_attentions=None,
|
| 63 |
+
output_hidden_states=True, # We want the output embs not the final output
|
| 64 |
+
return_dict=None,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
# We're interested in the output hidden state only
|
| 68 |
+
output = encoder_outputs[0]
|
| 69 |
+
|
| 70 |
+
# There is a final layer norm we need to pass these through
|
| 71 |
+
output = text_encoder.text_model.final_layer_norm(output)
|
| 72 |
+
|
| 73 |
+
# And now they're ready!
|
| 74 |
+
return output
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def set_timesteps(scheduler, num_inference_steps):
|
| 78 |
+
scheduler.set_timesteps(num_inference_steps)
|
| 79 |
+
scheduler.timesteps = scheduler.timesteps.to(torch.float32)
|
| 80 |
+
|
| 81 |
+
def pil_to_latent(input_im):
|
| 82 |
+
# Single image -> single latent in a batch (so size 1, 4, 64, 64)
|
| 83 |
+
with torch.no_grad():
|
| 84 |
+
latent = vae.encode(tfms.ToTensor()(input_im).unsqueeze(0).to(torch_device)*2-1) # Note scaling
|
| 85 |
+
return 0.18215 * latent.latent_dist.sample()
|
| 86 |
+
|
| 87 |
+
def latents_to_pil(latents):
|
| 88 |
+
# bath of latents -> list of images
|
| 89 |
+
latents = (1 / 0.18215) * latents
|
| 90 |
+
with torch.no_grad():
|
| 91 |
+
image = vae.decode(latents).sample
|
| 92 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 93 |
+
image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
|
| 94 |
+
images = (image * 255).round().astype("uint8")
|
| 95 |
+
pil_images = [Image.fromarray(image) for image in images]
|
| 96 |
+
return pil_images
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def generate_with_embs(text_embeddings, text_input, seed,num_inference_steps,guidance_scale):
|
| 100 |
+
|
| 101 |
+
height = 512 # default height of Stable Diffusion
|
| 102 |
+
width = 512 # default width of Stable Diffusion
|
| 103 |
+
num_inference_steps = num_inference_steps # 10 # Number of denoising steps
|
| 104 |
+
guidance_scale = guidance_scale # 7.5 # Scale for classifier-free guidance
|
| 105 |
+
generator = torch.manual_seed(seed) # Seed generator to create the inital latent noise
|
| 106 |
+
batch_size = 1
|
| 107 |
+
|
| 108 |
+
max_length = text_input.input_ids.shape[-1]
|
| 109 |
+
uncond_input = tokenizer(
|
| 110 |
+
[""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
|
| 111 |
+
)
|
| 112 |
+
with torch.no_grad():
|
| 113 |
+
uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]
|
| 114 |
+
text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
|
| 115 |
+
|
| 116 |
+
# Prep Scheduler
|
| 117 |
+
set_timesteps(scheduler, num_inference_steps)
|
| 118 |
+
|
| 119 |
+
# Prep latents
|
| 120 |
+
latents = torch.randn(
|
| 121 |
+
(batch_size, unet.in_channels, height // 8, width // 8),
|
| 122 |
+
generator=generator,
|
| 123 |
+
)
|
| 124 |
+
latents = latents.to(torch_device)
|
| 125 |
+
latents = latents * scheduler.init_noise_sigma
|
| 126 |
+
|
| 127 |
+
# Loop
|
| 128 |
+
for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
|
| 129 |
+
# expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
|
| 130 |
+
latent_model_input = torch.cat([latents] * 2)
|
| 131 |
+
sigma = scheduler.sigmas[i]
|
| 132 |
+
latent_model_input = scheduler.scale_model_input(latent_model_input, t)
|
| 133 |
+
|
| 134 |
+
# predict the noise residual
|
| 135 |
+
with torch.no_grad():
|
| 136 |
+
noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
|
| 137 |
+
|
| 138 |
+
# perform guidance
|
| 139 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 140 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 141 |
+
|
| 142 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 143 |
+
latents = scheduler.step(noise_pred, t, latents).prev_sample
|
| 144 |
+
|
| 145 |
+
return latents_to_pil(latents)[0]
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def generate_with_prompt_style(prompt, style, seed):
|
| 149 |
+
|
| 150 |
+
prompt = prompt + ' in style of s'
|
| 151 |
+
embed = torch.load(style)
|
| 152 |
+
|
| 153 |
+
text_input = tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
|
| 154 |
+
# for t in text_input['input_ids'][0][:20]: # We'll just look at the first 7 to save you from a wall of '<|endoftext|>'
|
| 155 |
+
# print(t, tokenizer.decoder.get(int(t)))
|
| 156 |
+
input_ids = text_input.input_ids.to(torch_device)
|
| 157 |
+
|
| 158 |
+
token_embeddings = token_emb_layer(input_ids)
|
| 159 |
+
# The new embedding - our special birb word
|
| 160 |
+
replacement_token_embedding = embed[list(embed.keys())[0]].to(torch_device)
|
| 161 |
+
|
| 162 |
+
# Insert this into the token embeddings
|
| 163 |
+
token_embeddings[0, torch.where(input_ids[0]==338)] = replacement_token_embedding.to(torch_device)
|
| 164 |
+
|
| 165 |
+
# Combine with pos embs
|
| 166 |
+
input_embeddings = token_embeddings + position_embeddings
|
| 167 |
+
|
| 168 |
+
# Feed through to get final output embs
|
| 169 |
+
modified_output_embeddings = get_output_embeds(input_embeddings)
|
| 170 |
+
|
| 171 |
+
# And generate an image with this:
|
| 172 |
+
return generate_with_embs(modified_output_embeddings, text_input, seed)
|
| 173 |
+
|
| 174 |
+
def contrast_loss(images):
|
| 175 |
+
variance = torch.var(images)
|
| 176 |
+
return -variance
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def blue_loss(images):
|
| 180 |
+
"""
|
| 181 |
+
Computes the blue loss for a batch of images.
|
| 182 |
+
|
| 183 |
+
The blue loss is defined as the negative variance of the blue channel's pixel values.
|
| 184 |
+
|
| 185 |
+
Parameters:
|
| 186 |
+
images (torch.Tensor): A batch of images. Expected shape is (N, C, H, W) where
|
| 187 |
+
N is the batch size, C is the number of channels (3 for RGB),
|
| 188 |
+
H is the height, and W is the width.
|
| 189 |
+
|
| 190 |
+
Returns:
|
| 191 |
+
torch.Tensor: The blue loss, which is the negative variance of the blue channel's pixel values.
|
| 192 |
+
"""
|
| 193 |
+
# Ensure the input tensor has the correct shape
|
| 194 |
+
if images.shape[1] != 3:
|
| 195 |
+
raise ValueError("Expected images with 3 channels (RGB), but got shape {}".format(images.shape))
|
| 196 |
+
|
| 197 |
+
# Extract the blue channel (assuming the channels are in RGB order)
|
| 198 |
+
blue_channel = images[:, 2, :, :]
|
| 199 |
+
|
| 200 |
+
# Calculate the variance of the blue channel
|
| 201 |
+
variance = torch.var(blue_channel)
|
| 202 |
+
|
| 203 |
+
return -variance
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def ymca_loss(images, weights=(1.0, 1.0, 1.0, 1.0)):
|
| 207 |
+
"""
|
| 208 |
+
Computes the YMCA loss for a batch of images.
|
| 209 |
+
|
| 210 |
+
The YMCA loss is a custom loss function combining the mean value of the Y (luminance) channel,
|
| 211 |
+
the mean value of the M (magenta) channel, the variance of the C (cyan) channel, and the
|
| 212 |
+
absolute sum of the A (alpha) channel if present.
|
| 213 |
+
|
| 214 |
+
Parameters:
|
| 215 |
+
images (torch.Tensor): A batch of images. Expected shape is (N, C, H, W) where
|
| 216 |
+
N is the batch size, C is the number of channels (3 for RGB or 4 for RGBA),
|
| 217 |
+
H is the height, and W is the width.
|
| 218 |
+
weights (tuple): A tuple of four floats representing the weights for each component of the loss
|
| 219 |
+
(default is (1.0, 1.0, 1.0, 1.0)).
|
| 220 |
+
|
| 221 |
+
Returns:
|
| 222 |
+
torch.Tensor: The YMCA loss, combining the specified components.
|
| 223 |
+
"""
|
| 224 |
+
num_channels = images.shape[1]
|
| 225 |
+
|
| 226 |
+
if num_channels not in [3, 4]:
|
| 227 |
+
raise ValueError("Expected images with 3 (RGB) or 4 (RGBA) channels, but got shape {}".format(images.shape))
|
| 228 |
+
|
| 229 |
+
# Extract the RGB channels
|
| 230 |
+
R = images[:, 0, :, :]
|
| 231 |
+
G = images[:, 1, :, :]
|
| 232 |
+
B = images[:, 2, :, :]
|
| 233 |
+
|
| 234 |
+
# Convert RGB to Y (luminance) channel
|
| 235 |
+
Y = 0.299 * R + 0.587 * G + 0.114 * B
|
| 236 |
+
|
| 237 |
+
# Convert RGB to M (magenta) channel
|
| 238 |
+
M = 1 - G
|
| 239 |
+
|
| 240 |
+
# Convert RGB to C (cyan) channel
|
| 241 |
+
C = 1 - R
|
| 242 |
+
|
| 243 |
+
# Compute the mean of the Y channel
|
| 244 |
+
mean_Y = torch.mean(Y)
|
| 245 |
+
|
| 246 |
+
# Compute the mean of the M channel
|
| 247 |
+
mean_M = torch.mean(M)
|
| 248 |
+
|
| 249 |
+
# Compute the variance of the C channel
|
| 250 |
+
variance_C = torch.var(C)
|
| 251 |
+
|
| 252 |
+
loss = weights[0] * mean_Y + weights[1] * mean_M - weights[2] * variance_C
|
| 253 |
+
|
| 254 |
+
if num_channels == 4:
|
| 255 |
+
# Extract the alpha channel
|
| 256 |
+
A = images[:, 3, :, :]
|
| 257 |
+
# Compute the absolute sum of the A channel
|
| 258 |
+
abs_sum_A = torch.sum(torch.abs(A))
|
| 259 |
+
# Include the alpha component in the loss
|
| 260 |
+
loss += weights[3] * abs_sum_A
|
| 261 |
+
|
| 262 |
+
return loss
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def rgb_to_cmyk(images):
|
| 267 |
+
"""
|
| 268 |
+
Converts an RGB image tensor to CMYK.
|
| 269 |
+
|
| 270 |
+
Parameters:
|
| 271 |
+
images (torch.Tensor): A batch of images in RGB format. Expected shape is (N, 3, H, W).
|
| 272 |
+
|
| 273 |
+
Returns:
|
| 274 |
+
torch.Tensor: A tensor containing the CMYK channels.
|
| 275 |
+
"""
|
| 276 |
+
R = images[:, 0, :, :]
|
| 277 |
+
G = images[:, 1, :, :]
|
| 278 |
+
B = images[:, 2, :, :]
|
| 279 |
+
|
| 280 |
+
# Convert RGB to CMY
|
| 281 |
+
C = 1 - R
|
| 282 |
+
M = 1 - G
|
| 283 |
+
Y = 1 - B
|
| 284 |
+
|
| 285 |
+
# Convert CMY to CMYK
|
| 286 |
+
K = torch.min(torch.min(C, M), Y)
|
| 287 |
+
C = (C - K) / (1 - K + 1e-8)
|
| 288 |
+
M = (M - K) / (1 - K + 1e-8)
|
| 289 |
+
Y = (Y - K) / (1 - K + 1e-8)
|
| 290 |
+
|
| 291 |
+
CMYK = torch.stack([C, M, Y, K], dim=1)
|
| 292 |
+
return CMYK
|
| 293 |
+
|
| 294 |
+
def cymk_loss(images, weights=(1.0, 1.0, 1.0, 1.0)):
|
| 295 |
+
"""
|
| 296 |
+
Computes the CYMK loss for a batch of images.
|
| 297 |
+
|
| 298 |
+
The CYMK loss is a custom loss function combining the variance of the Cyan channel,
|
| 299 |
+
the mean value of the Yellow channel, the variance of the Magenta channel, and the
|
| 300 |
+
absolute sum of the Black channel.
|
| 301 |
+
|
| 302 |
+
Parameters:
|
| 303 |
+
images (torch.Tensor): A batch of images. Expected shape is (N, 3, H, W) for RGB input.
|
| 304 |
+
weights (tuple): A tuple of four floats representing the weights for each component of the loss
|
| 305 |
+
(default is (1.0, 1.0, 1.0, 1.0)).
|
| 306 |
+
|
| 307 |
+
Returns:
|
| 308 |
+
torch.Tensor: The CYMK loss, combining the specified components.
|
| 309 |
+
"""
|
| 310 |
+
# Ensure the input tensor has the correct shape
|
| 311 |
+
if images.shape[1] != 3:
|
| 312 |
+
raise ValueError("Expected images with 3 channels (RGB), but got shape {}".format(images.shape))
|
| 313 |
+
|
| 314 |
+
# Convert RGB to CMYK
|
| 315 |
+
cmyk_images = rgb_to_cmyk(images)
|
| 316 |
+
|
| 317 |
+
# Extract CMYK channels
|
| 318 |
+
C = cmyk_images[:, 0, :, :]
|
| 319 |
+
M = cmyk_images[:, 1, :, :]
|
| 320 |
+
Y = cmyk_images[:, 2, :, :]
|
| 321 |
+
K = cmyk_images[:, 3, :, :]
|
| 322 |
+
|
| 323 |
+
# Compute the variance of the C channel
|
| 324 |
+
variance_C = torch.var(C)
|
| 325 |
+
|
| 326 |
+
# Compute the mean of the Y channel
|
| 327 |
+
mean_Y = torch.mean(Y)
|
| 328 |
+
|
| 329 |
+
# Compute the variance of the M channel
|
| 330 |
+
variance_M = torch.var(M)
|
| 331 |
+
|
| 332 |
+
# Compute the absolute sum of the K channel
|
| 333 |
+
abs_sum_K = torch.sum(torch.abs(K))
|
| 334 |
+
|
| 335 |
+
# Combine the components with the given weights
|
| 336 |
+
loss = (weights[0] * variance_C) + (weights[1] * mean_Y) + (weights[2] * variance_M) + (weights[3] * abs_sum_K)
|
| 337 |
+
|
| 338 |
+
return loss
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def blue_loss_variant(images, use_mean=False, alpha=1.0):
|
| 342 |
+
"""
|
| 343 |
+
Computes the blue loss for a batch of images with an optional mean component.
|
| 344 |
+
|
| 345 |
+
The blue loss is defined as the negative variance of the blue channel's pixel values.
|
| 346 |
+
Optionally, it can also include the mean value of the blue channel.
|
| 347 |
+
|
| 348 |
+
Parameters:
|
| 349 |
+
images (torch.Tensor): A batch of images. Expected shape is (N, C, H, W) where
|
| 350 |
+
N is the batch size, C is the number of channels (3 for RGB),
|
| 351 |
+
H is the height, and W is the width.
|
| 352 |
+
use_mean (bool): If True, includes the mean of the blue channel in the loss calculation.
|
| 353 |
+
alpha (float): Weighting factor for the mean component when use_mean is True.
|
| 354 |
+
|
| 355 |
+
Returns:
|
| 356 |
+
torch.Tensor: The blue loss, which is the negative variance of the blue channel's pixel values,
|
| 357 |
+
optionally combined with the mean value of the blue channel.
|
| 358 |
+
"""
|
| 359 |
+
# Ensure the input tensor has the correct shape
|
| 360 |
+
if images.shape[1] != 3:
|
| 361 |
+
raise ValueError("Expected images with 3 channels (RGB), but got shape {}".format(images.shape))
|
| 362 |
+
|
| 363 |
+
# Extract the blue channel (assuming the channels are in RGB order)
|
| 364 |
+
blue_channel = images[:, 2, :, :]
|
| 365 |
+
|
| 366 |
+
# Calculate the variance of the blue channel
|
| 367 |
+
variance = torch.var(blue_channel)
|
| 368 |
+
|
| 369 |
+
if use_mean:
|
| 370 |
+
# Calculate the mean of the blue channel
|
| 371 |
+
mean = torch.mean(blue_channel)
|
| 372 |
+
# Combine variance and mean into the loss
|
| 373 |
+
loss = -variance + alpha * mean
|
| 374 |
+
else:
|
| 375 |
+
loss = -variance
|
| 376 |
+
|
| 377 |
+
return loss
|
| 378 |
+
|
| 379 |
+
def generate_with_prompt_style_guidance(prompt, style, seed,num_inference_steps,guidance_scale,loss_function):
|
| 380 |
+
|
| 381 |
+
prompt = prompt + ' in style of s'
|
| 382 |
+
|
| 383 |
+
embed = torch.load(style)
|
| 384 |
+
|
| 385 |
+
height = 512 # default height of Stable Diffusion
|
| 386 |
+
width = 512 # default width of Stable Diffusion
|
| 387 |
+
num_inference_steps = num_inference_steps # # Number of denoising steps
|
| 388 |
+
guidance_scale = guidance_scale # # Scale for classifier-free guidance
|
| 389 |
+
generator = torch.manual_seed(seed) # Seed generator to create the inital latent noise
|
| 390 |
+
batch_size = 1
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
# Prep text
|
| 394 |
+
text_input = tokenizer([prompt], padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
|
| 395 |
+
with torch.no_grad():
|
| 396 |
+
text_embeddings = text_encoder(text_input.input_ids.to(torch_device))[0]
|
| 397 |
+
|
| 398 |
+
input_ids = text_input.input_ids.to(torch_device)
|
| 399 |
+
|
| 400 |
+
# Get token embeddings
|
| 401 |
+
token_embeddings = token_emb_layer(input_ids)
|
| 402 |
+
|
| 403 |
+
# The new embedding - our special birb word
|
| 404 |
+
replacement_token_embedding = embed[list(embed.keys())[0]].to(torch_device)
|
| 405 |
+
|
| 406 |
+
# Insert this into the token embeddings
|
| 407 |
+
token_embeddings[0, torch.where(input_ids[0]==338)] = replacement_token_embedding.to(torch_device)
|
| 408 |
+
|
| 409 |
+
# Combine with pos embs
|
| 410 |
+
input_embeddings = token_embeddings + position_embeddings
|
| 411 |
+
|
| 412 |
+
# Feed through to get final output embs
|
| 413 |
+
modified_output_embeddings = get_output_embeds(input_embeddings)
|
| 414 |
+
|
| 415 |
+
# And the uncond. input as before:
|
| 416 |
+
max_length = text_input.input_ids.shape[-1]
|
| 417 |
+
uncond_input = tokenizer(
|
| 418 |
+
[""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
|
| 419 |
+
)
|
| 420 |
+
with torch.no_grad():
|
| 421 |
+
uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]
|
| 422 |
+
|
| 423 |
+
text_embeddings = torch.cat([uncond_embeddings, modified_output_embeddings])
|
| 424 |
+
|
| 425 |
+
# Prep Scheduler
|
| 426 |
+
scheduler.set_timesteps(num_inference_steps)
|
| 427 |
+
|
| 428 |
+
# Prep latents
|
| 429 |
+
latents = torch.randn(
|
| 430 |
+
(batch_size, unet.config.in_channels, height // 8, width // 8),
|
| 431 |
+
generator=generator,
|
| 432 |
+
)
|
| 433 |
+
latents = latents.to(torch_device)
|
| 434 |
+
latents = latents * scheduler.init_noise_sigma
|
| 435 |
+
|
| 436 |
+
# Loop
|
| 437 |
+
for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
|
| 438 |
+
# expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
|
| 439 |
+
latent_model_input = torch.cat([latents] * 2)
|
| 440 |
+
sigma = scheduler.sigmas[i]
|
| 441 |
+
latent_model_input = scheduler.scale_model_input(latent_model_input, t)
|
| 442 |
+
|
| 443 |
+
# predict the noise residual
|
| 444 |
+
with torch.no_grad():
|
| 445 |
+
noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
|
| 446 |
+
|
| 447 |
+
# perform CFG
|
| 448 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 449 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 450 |
+
|
| 451 |
+
#### ADDITIONAL GUIDANCE ###
|
| 452 |
+
if i%5 == 0:
|
| 453 |
+
# Requires grad on the latents
|
| 454 |
+
latents = latents.detach().requires_grad_()
|
| 455 |
+
|
| 456 |
+
# Get the predicted x0:
|
| 457 |
+
latents_x0 = latents - sigma * noise_pred
|
| 458 |
+
# latents_x0 = scheduler.step(noise_pred, t, latents).pred_original_sample
|
| 459 |
+
|
| 460 |
+
# Decode to image space
|
| 461 |
+
denoised_images = vae.decode((1 / 0.18215) * latents_x0).sample / 2 + 0.5 # range (0, 1)
|
| 462 |
+
|
| 463 |
+
# Calculate loss
|
| 464 |
+
# "contrast", "blue_original", "blue_modified","ymca_loss","cymk_loss"
|
| 465 |
+
if loss_function == "contrast":
|
| 466 |
+
loss_scale = 200 #
|
| 467 |
+
loss = contrast_loss(denoised_images) * loss_scale
|
| 468 |
+
elif loss_function == "blue_original":
|
| 469 |
+
loss_scale = 200 #
|
| 470 |
+
loss = blue_loss(denoised_images) * loss_scale
|
| 471 |
+
elif loss_function == "blue_modified":
|
| 472 |
+
loss_scale = 200 #
|
| 473 |
+
loss = blue_loss_variant(denoised_images) * loss_scale
|
| 474 |
+
elif loss_function == "ymca":
|
| 475 |
+
loss_scale = 200 #
|
| 476 |
+
loss = ymca_loss(denoised_images) * loss_scale
|
| 477 |
+
elif loss_function == "cmyk":
|
| 478 |
+
loss_scale = 1 #
|
| 479 |
+
loss = cymk_loss(denoised_images) * loss_scale
|
| 480 |
+
else :
|
| 481 |
+
loss_scale = 200
|
| 482 |
+
loss = ymca_loss(denoised_images) * loss_scale
|
| 483 |
+
|
| 484 |
+
# # Occasionally print it out
|
| 485 |
+
# if i%10==0:
|
| 486 |
+
# print(i, 'loss:', loss.item())
|
| 487 |
+
|
| 488 |
+
# Get gradient
|
| 489 |
+
cond_grad = torch.autograd.grad(loss, latents)[0]
|
| 490 |
+
|
| 491 |
+
# Modify the latents based on this gradient
|
| 492 |
+
latents = latents.detach() - cond_grad * sigma**2
|
| 493 |
+
|
| 494 |
+
# Now step with scheduler
|
| 495 |
+
latents = scheduler.step(noise_pred, t, latents).prev_sample
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
return latents_to_pil(latents)[0]
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
dict_styles = {
|
| 504 |
+
'Dr Strange': 'styles/learned_embeds_dr_strange.bin',
|
| 505 |
+
'GTA-5':'styles/learned_embeds_gta5.bin',
|
| 506 |
+
'Manga':'styles/learned_embeds_manga.bin',
|
| 507 |
+
'Pokemon':'styles/learned_embeds_pokemon.bin',
|
| 508 |
+
'Illustration': 'styles/learned_embeds_illustration.bin',
|
| 509 |
+
'Matrix':'styles/learned_embeds_matrix.bin',
|
| 510 |
+
'Oil Painting':'styles/learned_embeds_oil.bin',
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
def inference(prompt, seed, style,num_inference_steps,guidance_scale,loss_function):
|
| 514 |
+
|
| 515 |
+
if prompt is not None and style is not None and seed is not None:
|
| 516 |
+
print(loss_function)
|
| 517 |
+
style = dict_styles[style]
|
| 518 |
+
torch.manual_seed(seed)
|
| 519 |
+
result = generate_with_prompt_style_guidance(prompt, style,seed,num_inference_steps,guidance_scale,loss_function)
|
| 520 |
+
return np.array(result)
|
| 521 |
+
else:
|
| 522 |
+
return None
|
| 523 |
+
|
| 524 |
+
title = "Stable Diffusion and Textual Inversion"
|
| 525 |
+
description = "Gradio interface to apply style to Stable Diffusion outputs"
|
| 526 |
+
examples = [["Pink Ferrari Car", 24041975,"Manga"], ["A man sipping tea wearing a spacesuit on the moon",24041975, "GTA-5"]] # Added valid styles
|
| 527 |
+
|
| 528 |
+
demo = gr.Interface(inference,
|
| 529 |
+
inputs = [gr.Textbox(label='Prompt', value='Pink Ferrari Car'), gr.Textbox(label='Seed', value=24041975),
|
| 530 |
+
gr.Dropdown(['Dr Strange', 'GTA-5', 'Manga', 'Pokemon','Illustration','Matrix','Oil Painting'], label='Style', value='Dr Strange'),
|
| 531 |
+
gr.Slider(
|
| 532 |
+
minimum=5,
|
| 533 |
+
maximum=20,
|
| 534 |
+
value=10,
|
| 535 |
+
step=5,
|
| 536 |
+
label="Select Number of Steps",
|
| 537 |
+
interactive=True,
|
| 538 |
+
),
|
| 539 |
+
gr.Slider(
|
| 540 |
+
minimum=0,
|
| 541 |
+
maximum=10,
|
| 542 |
+
value=8,
|
| 543 |
+
step=8,
|
| 544 |
+
label="Select Guidance Scale",
|
| 545 |
+
interactive=True,
|
| 546 |
+
),gr.Radio(["contrast", "blue_original", "blue_modified","ymca","cmyk"], label="loss-function", info="loss-function" , value="ymca"),
|
| 547 |
+
],
|
| 548 |
+
outputs = [
|
| 549 |
+
gr.Image(label="Stable Diffusion Output"),
|
| 550 |
+
],
|
| 551 |
+
title = title,
|
| 552 |
+
description = description,
|
| 553 |
+
# examples = examples,
|
| 554 |
+
# cache_examples=True
|
| 555 |
+
)
|
| 556 |
+
demo.launch()
|
| 557 |
+
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
transformers==4.25.1
|
| 3 |
+
diffusers
|
| 4 |
+
ftfy
|
| 5 |
+
torchvision
|
| 6 |
+
tqdm
|
| 7 |
+
numpy
|
| 8 |
+
accelerate
|
| 9 |
+
scipy
|
| 10 |
+
Pillow
|