LN1996 commited on
Commit
191e987
·
1 Parent(s): 5177a7c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +329 -0
app.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from base64 import b64encode
2
+
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 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
+ torch.manual_seed(1)
20
+ # if not (Path.home()/'.cache/huggingface'/'token').exists(): notebook_login()
21
+
22
+ # Supress some unnecessary warnings when loading the CLIPTextModel
23
+ logging.set_verbosity_error()
24
+
25
+ # Set device
26
+ torch_device = "cuda:1" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
27
+
28
+
29
+
30
+ # Load the autoencoder model which will be used to decode the latents into image space.
31
+ vae = AutoencoderKL.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="vae")
32
+
33
+ # Load the tokenizer and text encoder to tokenize and encode the text.
34
+ tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")
35
+ text_encoder = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14")
36
+
37
+ # The UNet model for generating the latents.
38
+ unet = UNet2DConditionModel.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="unet")
39
+
40
+ # The noise scheduler
41
+ scheduler = LMSDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000)
42
+
43
+ # To the GPU we go!
44
+ vae = vae.to(torch_device)
45
+ text_encoder = text_encoder.to(torch_device)
46
+ unet = unet.to(torch_device)
47
+ token_emb_layer = text_encoder.text_model.embeddings.token_embedding
48
+ pos_emb_layer = text_encoder.text_model.embeddings.position_embedding
49
+
50
+ position_ids = text_encoder.text_model.embeddings.position_ids[:, :77]
51
+ position_embeddings = pos_emb_layer(position_ids)
52
+
53
+
54
+ def get_output_embeds(input_embeddings):
55
+ # CLIP's text model uses causal mask, so we prepare it here:
56
+ bsz, seq_len = input_embeddings.shape[:2]
57
+ causal_attention_mask = text_encoder.text_model._build_causal_attention_mask(bsz, seq_len, dtype=input_embeddings.dtype)
58
+
59
+ # Getting the output embeddings involves calling the model with passing output_hidden_states=True
60
+ # so that it doesn't just return the pooled final predictions:
61
+ encoder_outputs = text_encoder.text_model.encoder(
62
+ inputs_embeds=input_embeddings,
63
+ attention_mask=None, # We aren't using an attention mask so that can be None
64
+ causal_attention_mask=causal_attention_mask.to(torch_device),
65
+ output_attentions=None,
66
+ output_hidden_states=True, # We want the output embs not the final output
67
+ return_dict=None,
68
+ )
69
+
70
+ # We're interested in the output hidden state only
71
+ output = encoder_outputs[0]
72
+
73
+ # There is a final layer norm we need to pass these through
74
+ output = text_encoder.text_model.final_layer_norm(output)
75
+
76
+ # And now they're ready!
77
+ return output
78
+
79
+
80
+ def set_timesteps(scheduler, num_inference_steps):
81
+ scheduler.set_timesteps(num_inference_steps)
82
+ scheduler.timesteps = scheduler.timesteps.to(torch.float32)
83
+
84
+ def pil_to_latent(input_im):
85
+ # Single image -> single latent in a batch (so size 1, 4, 64, 64)
86
+ with torch.no_grad():
87
+ latent = vae.encode(tfms.ToTensor()(input_im).unsqueeze(0).to(torch_device)*2-1) # Note scaling
88
+ return 0.18215 * latent.latent_dist.sample()
89
+
90
+ def latents_to_pil(latents):
91
+ # bath of latents -> list of images
92
+ latents = (1 / 0.18215) * latents
93
+ with torch.no_grad():
94
+ image = vae.decode(latents).sample
95
+ image = (image / 2 + 0.5).clamp(0, 1)
96
+ image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
97
+ images = (image * 255).round().astype("uint8")
98
+ pil_images = [Image.fromarray(image) for image in images]
99
+ return pil_images
100
+
101
+
102
+ def generate_with_embs(text_embeddings, text_input, seed):
103
+
104
+ height = 512 # default height of Stable Diffusion
105
+ width = 512 # default width of Stable Diffusion
106
+ num_inference_steps = 30 # Number of denoising steps
107
+ guidance_scale = 7.5 # Scale for classifier-free guidance
108
+ generator = torch.manual_seed(seed) # Seed generator to create the inital latent noise
109
+ batch_size = 1
110
+
111
+ max_length = text_input.input_ids.shape[-1]
112
+ uncond_input = tokenizer(
113
+ [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
114
+ )
115
+ with torch.no_grad():
116
+ uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]
117
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
118
+
119
+ # Prep Scheduler
120
+ set_timesteps(scheduler, num_inference_steps)
121
+
122
+ # Prep latents
123
+ latents = torch.randn(
124
+ (batch_size, unet.in_channels, height // 8, width // 8),
125
+ generator=generator,
126
+ )
127
+ latents = latents.to(torch_device)
128
+ latents = latents * scheduler.init_noise_sigma
129
+
130
+ # Loop
131
+ for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
132
+ # expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
133
+ latent_model_input = torch.cat([latents] * 2)
134
+ sigma = scheduler.sigmas[i]
135
+ latent_model_input = scheduler.scale_model_input(latent_model_input, t)
136
+
137
+ # predict the noise residual
138
+ with torch.no_grad():
139
+ noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
140
+
141
+ # perform guidance
142
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
143
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
144
+
145
+ # compute the previous noisy sample x_t -> x_t-1
146
+ latents = scheduler.step(noise_pred, t, latents).prev_sample
147
+
148
+ return latents_to_pil(latents)[0]
149
+
150
+
151
+ def generate_with_prompt_style(prompt, style, seed = 42):
152
+
153
+ prompt = prompt + ' in style of s'
154
+ embed = torch.load(style)
155
+
156
+ text_input = tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
157
+ # 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|>'
158
+ # print(t, tokenizer.decoder.get(int(t)))
159
+ input_ids = text_input.input_ids.to(torch_device)
160
+
161
+ token_embeddings = token_emb_layer(input_ids)
162
+ # The new embedding - our special birb word
163
+ replacement_token_embedding = embed[list(embed.keys())[0]].to(torch_device)
164
+
165
+ # Insert this into the token embeddings
166
+ token_embeddings[0, torch.where(input_ids[0]==338)] = replacement_token_embedding.to(torch_device)
167
+
168
+ # Combine with pos embs
169
+ input_embeddings = token_embeddings + position_embeddings
170
+
171
+ # Feed through to get final output embs
172
+ modified_output_embeddings = get_output_embeds(input_embeddings)
173
+
174
+ # And generate an image with this:
175
+ return generate_with_embs(modified_output_embeddings, text_input, seed)
176
+
177
+
178
+ import torch
179
+
180
+ def contrast_loss(images):
181
+ variance = torch.var(images)
182
+ return -variance
183
+
184
+ def generate_with_prompt_style_guidance(prompt, style, seed=42):
185
+
186
+ prompt = prompt + ' in style of s'
187
+
188
+ embed = torch.load(style)
189
+
190
+ height = 512 # default height of Stable Diffusion
191
+ width = 512 # default width of Stable Diffusion
192
+ num_inference_steps = 50 # # Number of denoising steps
193
+ guidance_scale = 8 # # Scale for classifier-free guidance
194
+ generator = torch.manual_seed(seed) # Seed generator to create the inital latent noise
195
+ batch_size = 1
196
+ contrast_loss_scale = 200 #
197
+
198
+ # Prep text
199
+ text_input = tokenizer([prompt], padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
200
+ with torch.no_grad():
201
+ text_embeddings = text_encoder(text_input.input_ids.to(torch_device))[0]
202
+
203
+ input_ids = text_input.input_ids.to(torch_device)
204
+
205
+ # Get token embeddings
206
+ token_embeddings = token_emb_layer(input_ids)
207
+
208
+ # The new embedding - our special birb word
209
+ replacement_token_embedding = embed[list(embed.keys())[0]].to(torch_device)
210
+
211
+ # Insert this into the token embeddings
212
+ token_embeddings[0, torch.where(input_ids[0]==338)] = replacement_token_embedding.to(torch_device)
213
+
214
+ # Combine with pos embs
215
+ input_embeddings = token_embeddings + position_embeddings
216
+
217
+ # Feed through to get final output embs
218
+ modified_output_embeddings = get_output_embeds(input_embeddings)
219
+
220
+ # And the uncond. input as before:
221
+ max_length = text_input.input_ids.shape[-1]
222
+ uncond_input = tokenizer(
223
+ [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
224
+ )
225
+ with torch.no_grad():
226
+ uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]
227
+
228
+ text_embeddings = torch.cat([uncond_embeddings, modified_output_embeddings])
229
+
230
+ # Prep Scheduler
231
+ scheduler.set_timesteps(num_inference_steps)
232
+
233
+ # Prep latents
234
+ latents = torch.randn(
235
+ (batch_size, unet.in_channels, height // 8, width // 8),
236
+ generator=generator,
237
+ )
238
+ latents = latents.to(torch_device)
239
+ latents = latents * scheduler.init_noise_sigma
240
+
241
+ # Loop
242
+ for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
243
+ # expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
244
+ latent_model_input = torch.cat([latents] * 2)
245
+ sigma = scheduler.sigmas[i]
246
+ latent_model_input = scheduler.scale_model_input(latent_model_input, t)
247
+
248
+ # predict the noise residual
249
+ with torch.no_grad():
250
+ noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
251
+
252
+ # perform CFG
253
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
254
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
255
+
256
+ #### ADDITIONAL GUIDANCE ###
257
+ if i%5 == 0:
258
+ # Requires grad on the latents
259
+ latents = latents.detach().requires_grad_()
260
+
261
+ # Get the predicted x0:
262
+ latents_x0 = latents - sigma * noise_pred
263
+ # latents_x0 = scheduler.step(noise_pred, t, latents).pred_original_sample
264
+
265
+ # Decode to image space
266
+ denoised_images = vae.decode((1 / 0.18215) * latents_x0).sample / 2 + 0.5 # range (0, 1)
267
+
268
+ # Calculate loss
269
+ loss = contrast_loss(denoised_images) * contrast_loss_scale
270
+
271
+ # # Occasionally print it out
272
+ # if i%10==0:
273
+ # print(i, 'loss:', loss.item())
274
+
275
+ # Get gradient
276
+ cond_grad = torch.autograd.grad(loss, latents)[0]
277
+
278
+ # Modify the latents based on this gradient
279
+ latents = latents.detach() - cond_grad * sigma**2
280
+
281
+ # Now step with scheduler
282
+ latents = scheduler.step(noise_pred, t, latents).prev_sample
283
+
284
+
285
+ return latents_to_pil(latents)[0]
286
+
287
+
288
+ import gradio as gr
289
+
290
+ dict_styles = {'Arcane':'styles/learned_embeds_arcane.bin',
291
+ 'Button eyes':'styles/learned_embeds_buttoneyes.bin',
292
+ 'Dr Strange': 'styles/learned_embeds_dr_strange.bin',
293
+ 'GTA-5':'styles/learned_embeds_gta5.bin',
294
+ 'Illustration': 'styles/learned_embeds_illustration.bin',
295
+ 'Manga':'styles/learned_embeds_manga.bin',
296
+ 'Matrix':'styles/learned_embeds_matrix.bin',
297
+ 'Oil Painting':'styles/learned_embeds_oil.bin',
298
+ 'Pokemon':'styles/learned_embeds_pokemon.bin',
299
+ 'Stripes': 'styles/learned_embeds_stripe.bin'}
300
+ # dict_styles.keys()
301
+
302
+ def inference(prompt, style):
303
+
304
+ if prompt is not None and style is not None:
305
+ style = dict_styles[style]
306
+ result = generate_with_prompt_style_guidance(prompt, style)
307
+ return np.array(result)
308
+ else:
309
+ return None
310
+
311
+ title = "Stable Diffusion and Textual Inversion"
312
+ description = "A simple Gradio interface to stylize Stable Diffusion outputs"
313
+ examples = [[prompt, style] for style in dict_styles.keys()]
314
+
315
+ demo = gr.Interface(inference,
316
+ inputs = [gr.Textbox(label='Prompt'),
317
+ gr.Dropdown(['Arcane', 'Button eyes', 'Dr Strange', 'GTA-5', 'Illustration',
318
+ 'Manga', 'Matrix', 'Oil Painting', 'Pokemon', 'Stripes'], label='Style')
319
+ ],
320
+ outputs = [
321
+ gr.Image(label="Stable Diffusion Output"),
322
+ ],
323
+ title = title,
324
+ description = description,
325
+ examples = examples,
326
+ # cache_examples=True
327
+ )
328
+ demo.launch()
329
+