Spaces:
Sleeping
Sleeping
Update utils.py
Browse files
utils.py
CHANGED
@@ -1,291 +1,297 @@
|
|
1 |
-
import torch
|
2 |
-
import torchvision
|
3 |
-
from diffusers import StableDiffusionPipeline
|
4 |
-
from base64 import b64encode
|
5 |
-
from diffusers import AutoencoderKL, LMSDiscreteScheduler, UNet2DConditionModel
|
6 |
-
from transformers import CLIPTextModel, CLIPTokenizer, logging
|
7 |
-
from torchvision import transforms as tfms
|
8 |
-
from PIL import Image
|
9 |
-
from tqdm.auto import tqdm
|
10 |
-
from matplotlib import pyplot as plt
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
# Supress some unnecessary warnings when loading the CLIPTextModel
|
15 |
-
logging.set_verbosity_error()
|
16 |
-
|
17 |
-
# Set device
|
18 |
-
torch_device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
19 |
-
if "mps" == torch_device: os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = "1"
|
20 |
-
|
21 |
-
|
22 |
-
# Load the autoencoder model which will be used to decode the latents into image space.
|
23 |
-
vae = AutoencoderKL.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="vae")
|
24 |
-
|
25 |
-
# Load the tokenizer and text encoder to tokenize and encode the text.
|
26 |
-
tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")
|
27 |
-
text_encoder = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14")
|
28 |
-
|
29 |
-
# The UNet model for generating the latents.
|
30 |
-
unet = UNet2DConditionModel.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="unet")
|
31 |
-
|
32 |
-
# The noise scheduler
|
33 |
-
scheduler = LMSDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000)
|
34 |
-
|
35 |
-
# To the GPU we go!
|
36 |
-
vae = vae.to(torch_device)
|
37 |
-
text_encoder = text_encoder.to(torch_device)
|
38 |
-
unet = unet.to(torch_device);
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
def
|
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 |
-
def
|
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 |
-
|
186 |
-
)
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
)
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
#
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
#
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torchvision
|
3 |
+
from diffusers import StableDiffusionPipeline
|
4 |
+
from base64 import b64encode
|
5 |
+
from diffusers import AutoencoderKL, LMSDiscreteScheduler, UNet2DConditionModel
|
6 |
+
from transformers import CLIPTextModel, CLIPTokenizer, logging
|
7 |
+
from torchvision import transforms as tfms
|
8 |
+
from PIL import Image
|
9 |
+
from tqdm.auto import tqdm
|
10 |
+
from matplotlib import pyplot as plt
|
11 |
+
|
12 |
+
|
13 |
+
|
14 |
+
# Supress some unnecessary warnings when loading the CLIPTextModel
|
15 |
+
logging.set_verbosity_error()
|
16 |
+
|
17 |
+
# Set device
|
18 |
+
torch_device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
19 |
+
if "mps" == torch_device: os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = "1"
|
20 |
+
|
21 |
+
|
22 |
+
# Load the autoencoder model which will be used to decode the latents into image space.
|
23 |
+
vae = AutoencoderKL.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="vae")
|
24 |
+
|
25 |
+
# Load the tokenizer and text encoder to tokenize and encode the text.
|
26 |
+
tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")
|
27 |
+
text_encoder = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14")
|
28 |
+
|
29 |
+
# The UNet model for generating the latents.
|
30 |
+
unet = UNet2DConditionModel.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="unet")
|
31 |
+
|
32 |
+
# The noise scheduler
|
33 |
+
scheduler = LMSDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000)
|
34 |
+
|
35 |
+
# To the GPU we go!
|
36 |
+
vae = vae.to(torch_device)
|
37 |
+
text_encoder = text_encoder.to(torch_device)
|
38 |
+
unet = unet.to(torch_device);
|
39 |
+
|
40 |
+
def build_causal_attention_mask(bsz, seq_len, dtype):
|
41 |
+
mask = torch.empty(bsz, seq_len, seq_len, dtype=dtype)
|
42 |
+
mask.fill_(torch.tensor(torch.finfo(dtype).min)) # fill with large negative number (acts like -inf)
|
43 |
+
mask = mask.triu_(1) # zero out the lower diagonal to enforce causality
|
44 |
+
return mask.unsqueeze(1) # add a batch dimension
|
45 |
+
|
46 |
+
|
47 |
+
# Prep Scheduler
|
48 |
+
def set_timesteps(scheduler, num_inference_steps):
|
49 |
+
scheduler.set_timesteps(num_inference_steps)
|
50 |
+
scheduler.timesteps = scheduler.timesteps.to(torch.float32) # minor fix to ensure MPS compatibility, fixed in diffusers PR 3925
|
51 |
+
|
52 |
+
|
53 |
+
|
54 |
+
|
55 |
+
def pil_to_latent(input_im):
|
56 |
+
# Single image -> single latent in a batch (so size 1, 4, 64, 64)
|
57 |
+
with torch.no_grad():
|
58 |
+
latent = vae.encode(tfms.ToTensor()(input_im).unsqueeze(0).to(torch_device)*2-1) # Note scaling
|
59 |
+
return 0.18215 * latent.latent_dist.sample()
|
60 |
+
|
61 |
+
def latents_to_pil(latents):
|
62 |
+
# bath of latents -> list of images
|
63 |
+
latents = (1 / 0.18215) * latents
|
64 |
+
with torch.no_grad():
|
65 |
+
image = vae.decode(latents).sample
|
66 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
67 |
+
image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
|
68 |
+
images = (image * 255).round().astype("uint8")
|
69 |
+
pil_images = [Image.fromarray(image) for image in images]
|
70 |
+
return pil_images
|
71 |
+
|
72 |
+
def get_output_embeds(input_embeddings):
|
73 |
+
# CLIP's text model uses causal mask, so we prepare it here:
|
74 |
+
bsz, seq_len = input_embeddings.shape[:2]
|
75 |
+
causal_attention_mask = build_causal_attention_mask(bsz, seq_len, dtype=input_embeddings.dtype)
|
76 |
+
|
77 |
+
# Getting the output embeddings involves calling the model with passing output_hidden_states=True
|
78 |
+
# so that it doesn't just return the pooled final predictions:
|
79 |
+
encoder_outputs = text_encoder.text_model.encoder(
|
80 |
+
inputs_embeds=input_embeddings,
|
81 |
+
attention_mask=None, # We aren't using an attention mask so that can be None
|
82 |
+
causal_attention_mask=causal_attention_mask.to(torch_device),
|
83 |
+
output_attentions=None,
|
84 |
+
output_hidden_states=True, # We want the output embs not the final output
|
85 |
+
return_dict=None,
|
86 |
+
)
|
87 |
+
|
88 |
+
# We're interested in the output hidden state only
|
89 |
+
output = encoder_outputs[0]
|
90 |
+
|
91 |
+
# There is a final layer norm we need to pass these through
|
92 |
+
output = text_encoder.text_model.final_layer_norm(output)
|
93 |
+
|
94 |
+
# And now they're ready!
|
95 |
+
return output
|
96 |
+
|
97 |
+
|
98 |
+
|
99 |
+
#Generating an image with these modified embeddings
|
100 |
+
|
101 |
+
def generate_with_embs(text_embeddings, seed=45):
|
102 |
+
height = 512 # default height of Stable Diffusion
|
103 |
+
width = 512 # default width of Stable Diffusion
|
104 |
+
num_inference_steps = 30 # Number of denoising steps
|
105 |
+
guidance_scale = 7.5 # Scale for classifier-free guidance
|
106 |
+
generator = torch.manual_seed(seed) # Seed generator to create the inital latent noise
|
107 |
+
batch_size = 1
|
108 |
+
|
109 |
+
max_length = text_input.input_ids.shape[-1]
|
110 |
+
uncond_input = tokenizer(
|
111 |
+
[""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
|
112 |
+
)
|
113 |
+
with torch.no_grad():
|
114 |
+
uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]
|
115 |
+
text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
|
116 |
+
|
117 |
+
# Prep Scheduler
|
118 |
+
set_timesteps(scheduler, num_inference_steps)
|
119 |
+
|
120 |
+
# Prep latents
|
121 |
+
latents = torch.randn(
|
122 |
+
(batch_size, unet.in_channels, height // 8, width // 8),
|
123 |
+
generator=generator,
|
124 |
+
)
|
125 |
+
latents = latents.to(torch_device)
|
126 |
+
latents = latents * scheduler.init_noise_sigma
|
127 |
+
|
128 |
+
# Loop
|
129 |
+
for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
|
130 |
+
# expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
|
131 |
+
latent_model_input = torch.cat([latents] * 2)
|
132 |
+
sigma = scheduler.sigmas[i]
|
133 |
+
latent_model_input = scheduler.scale_model_input(latent_model_input, t)
|
134 |
+
|
135 |
+
# predict the noise residual
|
136 |
+
with torch.no_grad():
|
137 |
+
noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
|
138 |
+
|
139 |
+
# perform guidance
|
140 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
141 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
142 |
+
|
143 |
+
# compute the previous noisy sample x_t -> x_t-1
|
144 |
+
latents = scheduler.step(noise_pred, t, latents).prev_sample
|
145 |
+
|
146 |
+
return latents_to_pil(latents)[0]
|
147 |
+
|
148 |
+
|
149 |
+
|
150 |
+
def blue_loss(images):
|
151 |
+
# How far are the blue channel values to 0.9:
|
152 |
+
error = torch.abs(images[:,2] - 0.9).mean() # [:,2] -> all images in batch, only the blue channel
|
153 |
+
return error
|
154 |
+
|
155 |
+
|
156 |
+
def amber_loss(images):
|
157 |
+
"""Calculates the mean absolute error for amber color.
|
158 |
+
|
159 |
+
Args:
|
160 |
+
images: A tensor of shape (batch_size, channels, height, width).
|
161 |
+
target_red: Target red value for amber.
|
162 |
+
target_green: Target green value for amber.
|
163 |
+
target_blue: Target blue value for amber.
|
164 |
+
|
165 |
+
Returns:
|
166 |
+
The mean absolute error.
|
167 |
+
#target_red=0.8, target_green=0.6, target_blue=0.4
|
168 |
+
"""
|
169 |
+
|
170 |
+
red_error = torch.abs(images[:, 0] - 0.12).mean()
|
171 |
+
green_error = torch.abs(images[:, 1] - 0.2).mean()
|
172 |
+
blue_error = torch.abs(images[:, 2] - 0.15).mean()
|
173 |
+
|
174 |
+
# You can adjust weights for each channel if needed
|
175 |
+
amber_error = (red_error + green_error + blue_error) / 3
|
176 |
+
return amber_error
|
177 |
+
|
178 |
+
|
179 |
+
def generate_with_custom_loss(text_embeddings, text_input, generator, loss_fn):
|
180 |
+
blue_loss_scale = 60
|
181 |
+
|
182 |
+
height = 256 # default height of Stable Diffusion
|
183 |
+
width = 256 # default width of Stable Diffusion
|
184 |
+
num_inference_steps = 15 # Number of denoising steps
|
185 |
+
guidance_scale = 7.5 # Scale for classifier-free guidance
|
186 |
+
# generator = torch.manual_seed(32) # Seed generator to create the inital latent noise
|
187 |
+
batch_size = 1
|
188 |
+
|
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 guidance
|
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 % 10 == 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 = loss_fn(denoised_images) * blue_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 |
+
# compute the previous noisy sample x_t -> x_t-1
|
249 |
+
latents = scheduler.step(noise_pred, t, latents).prev_sample
|
250 |
+
|
251 |
+
return latents_to_pil(latents)[0]
|
252 |
+
def gen_image_as_per_prompt(prompt, style, seed, custom_loss=None):
|
253 |
+
# prompt = 'dog as Wolverine'
|
254 |
+
|
255 |
+
generator = torch.manual_seed(seed)
|
256 |
+
|
257 |
+
# Tokenize
|
258 |
+
text_input = tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True,
|
259 |
+
return_tensors="pt")
|
260 |
+
input_ids = text_input.input_ids.to(torch_device)
|
261 |
+
|
262 |
+
# Access the embedding layer
|
263 |
+
token_emb_layer = text_encoder.text_model.embeddings.token_embedding
|
264 |
+
|
265 |
+
# Get token embeddings
|
266 |
+
token_embeddings = token_emb_layer(input_ids)
|
267 |
+
|
268 |
+
# The new embedding - special style
|
269 |
+
if style:
|
270 |
+
style_embed = torch.load(style)
|
271 |
+
keys = list(style_embed.keys())
|
272 |
+
replacement_token_embedding = style_embed[keys[0]].to(torch_device)
|
273 |
+
|
274 |
+
# The new embedding. In this case just the input embedding of token 2368...mixing CAT
|
275 |
+
# replacement_token_embedding = text_encoder.get_input_embeddings()(torch.tensor(2368, device=torch_device))
|
276 |
+
|
277 |
+
# Insert this into the token embeddings (
|
278 |
+
token_embeddings[0, torch.where(input_ids[0] == 6829)] = replacement_token_embedding.to(torch_device)
|
279 |
+
|
280 |
+
# get pos embed
|
281 |
+
pos_emb_layer = text_encoder.text_model.embeddings.position_embedding
|
282 |
+
position_ids = text_encoder.text_model.embeddings.position_ids[:, :77]
|
283 |
+
position_embeddings = pos_emb_layer(position_ids)
|
284 |
+
|
285 |
+
# Combine with pos embs
|
286 |
+
input_embeddings = token_embeddings + position_embeddings
|
287 |
+
|
288 |
+
# Feed through to get final output embs
|
289 |
+
modified_output_embeddings = get_output_embeds(input_embeddings)
|
290 |
+
|
291 |
+
if custom_loss is not None:
|
292 |
+
image = generate_with_custom_loss(modified_output_embeddings, text_input, generator, custom_loss)
|
293 |
+
else:
|
294 |
+
image = generate_with_embs(modified_output_embeddings, text_input, generator)
|
295 |
+
|
296 |
+
return image
|
297 |
+
|