AYYasaswini commited on
Commit
92f7b71
·
verified ·
1 Parent(s): 9e1a42d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +340 -137
app.py CHANGED
@@ -1,146 +1,349 @@
1
- import gradio as gr
2
- import numpy as np
3
- import random
4
- from diffusers import DiffusionPipeline
5
  import torch
 
 
6
 
7
- device = "cuda" if torch.cuda.is_available() else "cpu"
 
 
 
 
 
 
 
 
 
8
 
9
- if torch.cuda.is_available():
10
- torch.cuda.max_memory_allocated(device=device)
11
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
12
- pipe.enable_xformers_memory_efficient_attention()
13
- pipe = pipe.to(device)
14
- else:
15
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", use_safetensors=True)
16
- pipe = pipe.to(device)
17
 
18
- MAX_SEED = np.iinfo(np.int32).max
19
- MAX_IMAGE_SIZE = 1024
20
 
21
- def infer(prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):
 
22
 
23
- if randomize_seed:
24
- seed = random.randint(0, MAX_SEED)
25
-
26
- generator = torch.Generator().manual_seed(seed)
27
-
28
- image = pipe(
29
- prompt = prompt,
30
- negative_prompt = negative_prompt,
31
- guidance_scale = guidance_scale,
32
- num_inference_steps = num_inference_steps,
33
- width = width,
34
- height = height,
35
- generator = generator
36
- ).images[0]
37
-
38
- return image
39
-
40
- examples = [
41
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
42
- "An astronaut riding a green horse",
43
- "A delicious ceviche cheesecake slice",
44
- ]
45
-
46
- css="""
47
- #col-container {
48
- margin: 0 auto;
49
- max-width: 520px;
50
- }
51
- """
52
-
53
- if torch.cuda.is_available():
54
- power_device = "GPU"
55
- else:
56
- power_device = "CPU"
57
-
58
- with gr.Blocks(css=css) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
- with gr.Column(elem_id="col-container"):
61
- gr.Markdown(f"""
62
- # Text-to-Image Gradio Template
63
- Currently running on {power_device}.
64
- """)
65
-
66
- with gr.Row():
67
-
68
- prompt = gr.Text(
69
- label="Prompt",
70
- show_label=False,
71
- max_lines=1,
72
- placeholder="Enter your prompt",
73
- container=False,
74
- )
75
-
76
- run_button = gr.Button("Run", scale=0)
77
-
78
- result = gr.Image(label="Result", show_label=False)
79
-
80
- with gr.Accordion("Advanced Settings", open=False):
81
-
82
- negative_prompt = gr.Text(
83
- label="Negative prompt",
84
- max_lines=1,
85
- placeholder="Enter a negative prompt",
86
- visible=False,
87
- )
88
-
89
- seed = gr.Slider(
90
- label="Seed",
91
- minimum=0,
92
- maximum=MAX_SEED,
93
- step=1,
94
- value=0,
95
- )
96
-
97
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
98
-
99
- with gr.Row():
100
-
101
- width = gr.Slider(
102
- label="Width",
103
- minimum=256,
104
- maximum=MAX_IMAGE_SIZE,
105
- step=32,
106
- value=512,
107
- )
108
-
109
- height = gr.Slider(
110
- label="Height",
111
- minimum=256,
112
- maximum=MAX_IMAGE_SIZE,
113
- step=32,
114
- value=512,
115
- )
116
-
117
- with gr.Row():
118
-
119
- guidance_scale = gr.Slider(
120
- label="Guidance scale",
121
- minimum=0.0,
122
- maximum=10.0,
123
- step=0.1,
124
- value=0.0,
125
- )
126
-
127
- num_inference_steps = gr.Slider(
128
- label="Number of inference steps",
129
- minimum=1,
130
- maximum=12,
131
- step=1,
132
- value=2,
133
- )
134
-
135
- gr.Examples(
136
- examples = examples,
137
- inputs = [prompt]
138
- )
139
-
140
- run_button.click(
141
- fn = infer,
142
- inputs = [prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
143
- outputs = [result]
144
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
- demo.queue().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 orange_loss(images):
183
+ """
184
+ Calculate the mean absolute error between the RGB values of the images and the target orange color.
185
+
186
+ Parameters:
187
+ - images (torch.Tensor): A batch of images with shape (batch_size, channels, height, width).
188
+ The images are assumed to be in RGB format.
189
+
190
+ Returns:
191
+ - torch.Tensor: The mean absolute error for the orange color.
192
+ """
193
+ # Define the target RGB values for the color orange
194
+ target_orange = torch.tensor([255/255, 200/255, 0/255]).view(1, 3, 1, 1).to(images.device) # (R, G, B)
195
+
196
+ # Normalize images to [0, 1] range if not already normalized
197
+ images = images / 255.0 if images.max() > 1.0 else images
198
+
199
+ # Calculate the mean absolute error between the RGB values and the target orange values
200
+ error = torch.abs(images - target_orange).mean()
201
+
202
+ return error
203
+
204
+
205
+ def generate_with_prompt_style_guidance(prompt, style, seed=42):
206
+
207
+ prompt = prompt + ' in style of s'
208
 
209
+ embed = torch.load(style)
210
+
211
+ height = 512 # default height of Stable Diffusion
212
+ width = 512 # default width of Stable Diffusion
213
+ num_inference_steps = 10 # # Number of denoising steps
214
+ guidance_scale = 8 # # Scale for classifier-free guidance
215
+ generator = torch.manual_seed(seed) # Seed generator to create the inital latent noise
216
+ batch_size = 1
217
+ orange_loss_scale = 200 #
218
+
219
+ # Prep text
220
+ text_input = tokenizer([prompt], padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
221
+ with torch.no_grad():
222
+ text_embeddings = text_encoder(text_input.input_ids.to(torch_device))[0]
223
+
224
+ input_ids = text_input.input_ids.to(torch_device)
225
+
226
+ # Get token embeddings
227
+ token_embeddings = token_emb_layer(input_ids)
228
+
229
+ # The new embedding - our special birb word
230
+ replacement_token_embedding = embed[list(embed.keys())[0]].to(torch_device)
231
+
232
+ # Insert this into the token embeddings
233
+ token_embeddings[0, torch.where(input_ids[0]==338)] = replacement_token_embedding.to(torch_device)
234
+
235
+ # Combine with pos embs
236
+ input_embeddings = token_embeddings + position_embeddings
237
+
238
+ # Feed through to get final output embs
239
+ modified_output_embeddings = get_output_embeds(input_embeddings)
240
+
241
+ # And the uncond. input as before:
242
+ max_length = text_input.input_ids.shape[-1]
243
+ uncond_input = tokenizer(
244
+ [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
245
+ )
246
+ with torch.no_grad():
247
+ uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]
248
+
249
+ text_embeddings = torch.cat([uncond_embeddings, modified_output_embeddings])
250
+
251
+ # Prep Scheduler
252
+ scheduler.set_timesteps(num_inference_steps)
253
+
254
+ # Prep latents
255
+ latents = torch.randn(
256
+ (batch_size, unet.config.in_channels, height // 8, width // 8),
257
+ generator=generator,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
258
  )
259
+ latents = latents.to(torch_device)
260
+ latents = latents * scheduler.init_noise_sigma
261
+
262
+ # Loop
263
+ for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
264
+ # expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
265
+ latent_model_input = torch.cat([latents] * 2)
266
+ sigma = scheduler.sigmas[i]
267
+ latent_model_input = scheduler.scale_model_input(latent_model_input, t)
268
+
269
+ # predict the noise residual
270
+ with torch.no_grad():
271
+ noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
272
+
273
+ # perform CFG
274
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
275
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
276
+
277
+ #### ADDITIONAL GUIDANCE ###
278
+ if i%5 == 0:
279
+ # Requires grad on the latents
280
+ latents = latents.detach().requires_grad_()
281
+
282
+ # Get the predicted x0:
283
+ latents_x0 = latents - sigma * noise_pred
284
+ # latents_x0 = scheduler.step(noise_pred, t, latents).pred_original_sample
285
+
286
+ # Decode to image space
287
+ denoised_images = vae.decode((1 / 0.18215) * latents_x0).sample / 2 + 0.5 # range (0, 1)
288
+
289
+ # Calculate loss
290
+ loss = orange_loss(denoised_images) * orange_loss_scale
291
+
292
+ # # Occasionally print it out
293
+ # if i%10==0:
294
+ # print(i, 'loss:', loss.item())
295
+
296
+ # Get gradient
297
+ cond_grad = torch.autograd.grad(loss, latents)[0]
298
+
299
+ # Modify the latents based on this gradient
300
+ latents = latents.detach() - cond_grad * sigma**2
301
+
302
+ # Now step with scheduler
303
+ latents = scheduler.step(noise_pred, t, latents).prev_sample
304
+
305
+
306
+ return latents_to_pil(latents)[0]
307
+
308
+
309
+ import gradio as gr
310
+
311
+ dict_styles = {'Arcane':'styles/learned_embeds_arcane.bin',
312
+ 'Button eyes':'styles/learned_embeds_buttoneyes.bin',
313
+ 'Dr Strange': 'styles/learned_embeds_dr_strange.bin',
314
+ 'GTA-5':'styles/learned_embeds_gta5.bin',
315
+ 'Illustration': 'styles/learned_embeds_illustration.bin',
316
+ 'Manga':'styles/learned_embeds_manga.bin',
317
+ 'Matrix':'styles/learned_embeds_matrix.bin',
318
+ 'Oil Painting':'styles/learned_embeds_oil.bin',
319
+ 'Pokemon':'styles/learned_embeds_pokemon.bin',
320
+ 'Stripes': 'styles/learned_embeds_stripe.bin'}
321
+ # dict_styles.keys()
322
+
323
+ def inference(prompt, style):
324
+
325
+ if prompt is not None and style is not None:
326
+ style = dict_styles[style]
327
+ result = generate_with_prompt_style_guidance(prompt, style)
328
+ return np.array(result)
329
+ else:
330
+ return None
331
+
332
+ title = "Stable Diffusion and Textual Inversion"
333
+ description = "A simple Gradio interface to stylize Stable Diffusion outputs"
334
+ examples = [['A man sipping wine wearing a spacesuit on the moon', 'Stripes']]
335
 
336
+ demo = gr.Interface(inference,
337
+ inputs = [gr.Textbox(label='Prompt'),
338
+ gr.Dropdown(['Arcane', 'Button eyes', 'Dr Strange', 'GTA-5', 'Illustration',
339
+ 'Manga', 'Matrix', 'Oil Painting', 'Pokemon', 'Stripes'], label='Style')
340
+ ],
341
+ outputs = [
342
+ gr.Image(label="Stable Diffusion Output"),
343
+ ],
344
+ title = title,
345
+ description = description,
346
+ # examples = examples,
347
+ # cache_examples=True
348
+ )
349
+ demo.launch()