Spaces:
Runtime error
Runtime error
Create stablediffusion.py
Browse files- stablediffusion.py +196 -0
stablediffusion.py
ADDED
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from base64 import b64encode
|
2 |
+
from utils import *
|
3 |
+
import numpy
|
4 |
+
import torch
|
5 |
+
from diffusers import AutoencoderKL, LMSDiscreteScheduler, UNet2DConditionModel
|
6 |
+
from huggingface_hub import notebook_login
|
7 |
+
|
8 |
+
# For video display:
|
9 |
+
from IPython.display import HTML
|
10 |
+
from matplotlib import pyplot as plt
|
11 |
+
from pathlib import Path
|
12 |
+
from PIL import Image
|
13 |
+
from torch import autocast
|
14 |
+
from torchvision import transforms as tfms
|
15 |
+
from tqdm.auto import tqdm
|
16 |
+
from transformers import CLIPTextModel, CLIPTokenizer, logging
|
17 |
+
import os
|
18 |
+
import shutil
|
19 |
+
from device import torch_device,vae,text_encoder,unet,tokenizer,scheduler,token_emb_layer,pos_emb_layer,position_embeddings
|
20 |
+
torch.manual_seed(1)
|
21 |
+
if not (Path.home()/'.cache/huggingface'/'token').exists(): notebook_login()
|
22 |
+
|
23 |
+
# Supress some unnecessary warnings when loading the CLIPTextModel
|
24 |
+
logging.set_verbosity_error()
|
25 |
+
|
26 |
+
# Set device
|
27 |
+
|
28 |
+
|
29 |
+
def generate_distorted_image(pil_image,vae):
|
30 |
+
# View a noised version
|
31 |
+
encoded = pil_to_latent(pil_image)
|
32 |
+
noise = torch.randn_like(encoded) # Random noise
|
33 |
+
|
34 |
+
sampling_step = 5 # Equivalent to step 10 out of 15 in the schedule above
|
35 |
+
# encoded_and_noised = scheduler.add_noise(encoded, noise, timestep) # Diffusers 0.3 and below
|
36 |
+
encoded_and_noised = scheduler.add_noise(encoded, noise, timesteps=torch.tensor([scheduler.timesteps[sampling_step]]))
|
37 |
+
return latents_to_pil(encoded_and_noised)[0] # Display
|
38 |
+
|
39 |
+
def set_timesteps(scheduler, num_inference_steps):
|
40 |
+
scheduler.set_timesteps(num_inference_steps)
|
41 |
+
scheduler.timesteps = scheduler.timesteps.to(torch.float32)
|
42 |
+
|
43 |
+
|
44 |
+
# Some settings
|
45 |
+
def generate_image(prompt,concept_embed,num_inference_steps=50,color_postprocessing=False,noised_image=False,loss_scale=10,seed=42):
|
46 |
+
height = 512 # default height of Stable Diffusion
|
47 |
+
width = 512 # default width of Stable Diffusion
|
48 |
+
num_inference_steps = num_inference_steps # Number of denoising steps
|
49 |
+
guidance_scale = 7.5 # Scale for classifier-free guidance
|
50 |
+
generator = torch.manual_seed(seed) # Seed generator to create the inital latent noise
|
51 |
+
batch_size = 1
|
52 |
+
# Define the directory name
|
53 |
+
directory_name = "steps"
|
54 |
+
|
55 |
+
# Check if the directory exists, and if so, delete it
|
56 |
+
if os.path.exists(directory_name):
|
57 |
+
shutil.rmtree(directory_name)
|
58 |
+
|
59 |
+
#Create the directory
|
60 |
+
os.makedirs(directory_name)
|
61 |
+
# Prep text
|
62 |
+
#text_input = tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
|
63 |
+
# with torch.no_grad():
|
64 |
+
# text_embeddings = text_encoder(text_input.input_ids.to(torch_device))[0]
|
65 |
+
|
66 |
+
text_input = tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
|
67 |
+
input_ids = text_input.input_ids.to(torch_device)
|
68 |
+
custom_style_token=tokenizer.encode("cs",add_special_token=False)[0]
|
69 |
+
# Get token embeddings
|
70 |
+
token_embeddings = token_emb_layer(input_ids)
|
71 |
+
embed_key=list(concept_embed.keys())[0]
|
72 |
+
# The new embedding. In this case just the input embedding of token 2368...
|
73 |
+
replacement_token_embedding = concept_embed[embed_key]
|
74 |
+
token_embeddings[0,torch.where(input_ids[0]==custom_style_token)]=replacement_token_embedding.to(torch_device)
|
75 |
+
# Combine with pos embs
|
76 |
+
input_embeddings = token_embeddings + position_embeddings
|
77 |
+
|
78 |
+
# Feed through to get final output embs
|
79 |
+
modified_output_embeddings = get_output_embeds(input_embeddings)
|
80 |
+
|
81 |
+
max_length = text_input.input_ids.shape[-1]
|
82 |
+
uncond_input = tokenizer(
|
83 |
+
[""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
|
84 |
+
)
|
85 |
+
with torch.no_grad():
|
86 |
+
uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]
|
87 |
+
text_embeddings = torch.cat([uncond_embeddings, modified_output_embeddings])
|
88 |
+
|
89 |
+
# minor fix to ensure MPS compatibility, fixed in diffusers PR 3925
|
90 |
+
|
91 |
+
set_timesteps(scheduler,num_inference_steps)
|
92 |
+
|
93 |
+
# Prep latents
|
94 |
+
latents = torch.randn(
|
95 |
+
(batch_size, unet.in_channels, height // 8, width // 8),
|
96 |
+
generator=generator,
|
97 |
+
)
|
98 |
+
latents = latents.to(torch_device)
|
99 |
+
latents = latents * scheduler.init_noise_sigma # Scaling (previous versions did latents = latents * self.scheduler.sigmas[0]
|
100 |
+
|
101 |
+
# Loop
|
102 |
+
with autocast("cuda"): # will fallback to CPU if no CUDA; no autocast for MPS
|
103 |
+
for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
|
104 |
+
# expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
|
105 |
+
latent_model_input = torch.cat([latents] * 2)
|
106 |
+
sigma = scheduler.sigmas[i]
|
107 |
+
# Scale the latents (preconditioning):
|
108 |
+
# latent_model_input = latent_model_input / ((sigma**2 + 1) ** 0.5) # Diffusers 0.3 and below
|
109 |
+
latent_model_input = scheduler.scale_model_input(latent_model_input, t)
|
110 |
+
|
111 |
+
# predict the noise residual
|
112 |
+
with torch.no_grad():
|
113 |
+
noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
|
114 |
+
|
115 |
+
# perform guidance
|
116 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
117 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
118 |
+
|
119 |
+
# compute the previous noisy sample x_t -> x_t-1
|
120 |
+
# latents = scheduler.step(noise_pred, i, latents)["prev_sample"] # Diffusers 0.3 and below
|
121 |
+
|
122 |
+
#latents = torch.tensor(initial_latents, requires_grad=True)
|
123 |
+
### ADDITIONAL GUIDANCE ###
|
124 |
+
# Requires grad on the latents
|
125 |
+
if color_postprocessing:
|
126 |
+
latents = latents.detach().requires_grad_()
|
127 |
+
|
128 |
+
# Get the predicted x0:
|
129 |
+
latents_x0 = latents - sigma * noise_pred
|
130 |
+
|
131 |
+
# Decode to image space
|
132 |
+
denoised_images = vae.decode((1 / 0.18215) * latents_x0).sample / 2 + 0.5
|
133 |
+
#denoised_images = vae.decode((1 / 0.18215) * latents_x0) / 2 + 0.5 # (0, 1)
|
134 |
+
|
135 |
+
# Calculate loss
|
136 |
+
loss = orange_loss(denoised_images) * loss_scale
|
137 |
+
#loss = color_loss(denoised_images,postporcessing_color) * color_loss_scale
|
138 |
+
if i%10==0:
|
139 |
+
print(i, 'loss:', loss.item())
|
140 |
+
|
141 |
+
# Get gradient
|
142 |
+
cond_grad = -torch.autograd.grad(loss, latents)[0]
|
143 |
+
|
144 |
+
# Modify the latents based on this gradient
|
145 |
+
latents = latents.detach() + cond_grad * sigma**2
|
146 |
+
|
147 |
+
|
148 |
+
### And saving as before ###
|
149 |
+
# Get the predicted x0:
|
150 |
+
latents_x0 = latents - sigma * noise_pred
|
151 |
+
im_t0 = latents_to_pil(latents_x0)[0]
|
152 |
+
|
153 |
+
# And the previous noisy sample x_t -> x_t-1
|
154 |
+
latents = scheduler.step(noise_pred, t, latents)["prev_sample"]
|
155 |
+
im_next = latents_to_pil(latents)[0]
|
156 |
+
|
157 |
+
# Combine the two images and save for later viewing
|
158 |
+
im = Image.new('RGB', (1024, 512))
|
159 |
+
im.paste(im_next, (0, 0))
|
160 |
+
im.paste(im_t0, (512, 0))
|
161 |
+
im.save(f'steps/{i:04}.jpeg')
|
162 |
+
|
163 |
+
else:
|
164 |
+
latents = scheduler.step(noise_pred, t, latents).prev_sample
|
165 |
+
|
166 |
+
|
167 |
+
if noised_image:
|
168 |
+
output = generate_distorted_image(latents_to_pil(latents)[0],vae)
|
169 |
+
else:
|
170 |
+
output = latents_to_pil(latents)[0]
|
171 |
+
|
172 |
+
return output
|
173 |
+
def get_output_embeds(input_embeddings):
|
174 |
+
# CLIP's text model uses causal mask, so we prepare it here:
|
175 |
+
bsz, seq_len = input_embeddings.shape[:2]
|
176 |
+
causal_attention_mask = text_encoder.text_model._build_causal_attention_mask(bsz, seq_len, dtype=input_embeddings.dtype)
|
177 |
+
|
178 |
+
# Getting the output embeddings involves calling the model with passing output_hidden_states=True
|
179 |
+
# so that it doesn't just return the pooled final predictions:
|
180 |
+
encoder_outputs = text_encoder.text_model.encoder(
|
181 |
+
inputs_embeds=input_embeddings,
|
182 |
+
attention_mask=None, # We aren't using an attention mask so that can be None
|
183 |
+
causal_attention_mask=causal_attention_mask.to(torch_device),
|
184 |
+
output_attentions=None,
|
185 |
+
output_hidden_states=True, # We want the output embs not the final output
|
186 |
+
return_dict=None,
|
187 |
+
)
|
188 |
+
|
189 |
+
# We're interested in the output hidden state only
|
190 |
+
output = encoder_outputs[0]
|
191 |
+
|
192 |
+
# There is a final layer norm we need to pass these through
|
193 |
+
output = text_encoder.text_model.final_layer_norm(output)
|
194 |
+
|
195 |
+
# And now they're ready!
|
196 |
+
return output
|