AYYasaswini commited on
Commit
9334966
·
verified ·
1 Parent(s): d52e1e1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +314 -137
app.py CHANGED
@@ -1,146 +1,323 @@
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 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")
198
+ with torch.no_grad():
199
+ text_embeddings = text_encoder(text_input.input_ids.to(torch_device))[0]
200
+
201
+ input_ids = text_input.input_ids.to(torch_device)
202
+
203
+ # Get token embeddings
204
+ token_embeddings = token_emb_layer(input_ids)
205
+
206
+ # The new embedding - our special birb word
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:
219
+ max_length = text_input.input_ids.shape[-1]
220
+ uncond_input = tokenizer(
221
+ [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
  )
223
+ with torch.no_grad():
224
+ uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]
225
+
226
+ text_embeddings = torch.cat([uncond_embeddings, modified_output_embeddings])
227
+
228
+ # Prep Scheduler
229
+ scheduler.set_timesteps(num_inference_steps)
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
278
+
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
+
289
+ dict_styles = {'<gartic-phone>':'styles/learned_embeds_gartic-phone.bin',
290
+ '<hawaiian shirt>':'styles/learned_embeds_hawaiian-shirt.bin',
291
+ '<gp>': 'styles/learned_embeds_phone01.bin',
292
+ '<style-spdmn>':'styles/learned_embeds_style-spdmn.bin',
293
+ '<yvmqznrm>': 'styles/learned_embedssd_yvmqznrm.bin}
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)
301
+ return np.array(result)
302
+ else:
303
+ return None
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(['Arcane', 'Button eyes', 'Dr Strange', 'GTA-5', 'Illustration',
312
+ 'Manga', 'Matrix', 'Oil Painting', 'Pokemon', 'Stripes'], 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()
323
+