Shivdutta commited on
Commit
723c4a7
·
verified ·
1 Parent(s): e84a799

Update app.py

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