Spaces:
Sleeping
Sleeping
GunaKoppula
commited on
Commit
•
fb40f9c
1
Parent(s):
a615128
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from base64 import b64encode
|
3 |
+
|
4 |
+
import numpy
|
5 |
+
import torch
|
6 |
+
from diffusers import AutoencoderKL, LMSDiscreteScheduler, UNet2DConditionModel
|
7 |
+
from huggingface_hub import notebook_login
|
8 |
+
|
9 |
+
|
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 |
+
|
18 |
+
torch.manual_seed(1)
|
19 |
+
|
20 |
+
logging.set_verbosity_error()
|
21 |
+
|
22 |
+
|
23 |
+
torch_device = "cpu"
|
24 |
+
|
25 |
+
# Load the autoencoder model which will be used to decode the latents into image space.
|
26 |
+
vae = AutoencoderKL.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="vae")
|
27 |
+
|
28 |
+
# Load the tokenizer and text encoder to tokenize and encode the text.
|
29 |
+
tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")
|
30 |
+
text_encoder = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14")
|
31 |
+
|
32 |
+
# The UNet model for generating the latents.
|
33 |
+
unet = UNet2DConditionModel.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="unet")
|
34 |
+
|
35 |
+
# The noise scheduler
|
36 |
+
scheduler = LMSDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000)
|
37 |
+
|
38 |
+
# To the GPU we go!
|
39 |
+
vae = vae.to(torch_device)
|
40 |
+
text_encoder = text_encoder.to(torch_device)
|
41 |
+
unet = unet.to(torch_device);
|
42 |
+
|
43 |
+
token_emb_layer = text_encoder.text_model.embeddings.token_embedding
|
44 |
+
pos_emb_layer = text_encoder.text_model.embeddings.position_embedding
|
45 |
+
position_ids = text_encoder.text_model.embeddings.position_ids[:, :77]
|
46 |
+
position_embeddings = pos_emb_layer(position_ids)
|
47 |
+
|
48 |
+
def pil_to_latent(input_im):
|
49 |
+
# Single image -> single latent in a batch (so size 1, 4, 64, 64)
|
50 |
+
with torch.no_grad():
|
51 |
+
latent = vae.encode(tfms.ToTensor()(input_im).unsqueeze(0).to(torch_device)*2-1) # Note scaling
|
52 |
+
return 0.18215 * latent.latent_dist.sample()
|
53 |
+
|
54 |
+
def latents_to_pil(latents):
|
55 |
+
# bath of latents -> list of images
|
56 |
+
latents = (1 / 0.18215) * latents
|
57 |
+
with torch.no_grad():
|
58 |
+
image = vae.decode(latents).sample
|
59 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
60 |
+
image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
|
61 |
+
images = (image * 255).round().astype("uint8")
|
62 |
+
pil_images = [Image.fromarray(image) for image in images]
|
63 |
+
return pil_images
|
64 |
+
|
65 |
+
def get_output_embeds(input_embeddings):
|
66 |
+
# CLIP's text model uses causal mask, so we prepare it here:
|
67 |
+
bsz, seq_len = input_embeddings.shape[:2]
|
68 |
+
causal_attention_mask = text_encoder.text_model._build_causal_attention_mask(bsz, seq_len, dtype=input_embeddings.dtype)
|
69 |
+
|
70 |
+
# Getting the output embeddings involves calling the model with passing output_hidden_states=True
|
71 |
+
# so that it doesn't just return the pooled final predictions:
|
72 |
+
encoder_outputs = text_encoder.text_model.encoder(
|
73 |
+
inputs_embeds=input_embeddings,
|
74 |
+
attention_mask=None, # We aren't using an attention mask so that can be None
|
75 |
+
causal_attention_mask=causal_attention_mask.to(torch_device),
|
76 |
+
output_attentions=None,
|
77 |
+
output_hidden_states=True, # We want the output embs not the final output
|
78 |
+
return_dict=None,
|
79 |
+
)
|
80 |
+
|
81 |
+
# We're interested in the output hidden state only
|
82 |
+
output = encoder_outputs[0]
|
83 |
+
|
84 |
+
# There is a final layer norm we need to pass these through
|
85 |
+
output = text_encoder.text_model.final_layer_norm(output)
|
86 |
+
|
87 |
+
# And now they're ready!
|
88 |
+
return output
|
89 |
+
|
90 |
+
def generate_with_embs(text_embeddings, seed, max_length):
|
91 |
+
height = 512 # default height of Stable Diffusion
|
92 |
+
width = 512 # default width of Stable Diffusion
|
93 |
+
num_inference_steps = 30 # Number of denoising steps
|
94 |
+
guidance_scale = 7.5 # Scale for classifier-free guidance
|
95 |
+
generator = torch.manual_seed(seed) # Seed generator to create the inital latent noise
|
96 |
+
batch_size = 1
|
97 |
+
|
98 |
+
# max_length = text_input.input_ids.shape[-1]
|
99 |
+
uncond_input = tokenizer(
|
100 |
+
[""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
|
101 |
+
)
|
102 |
+
with torch.no_grad():
|
103 |
+
uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]
|
104 |
+
text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
|
105 |
+
|
106 |
+
# Prep Scheduler
|
107 |
+
set_timesteps(scheduler, num_inference_steps)
|
108 |
+
|
109 |
+
# Prep latents
|
110 |
+
latents = torch.randn(
|
111 |
+
(batch_size, unet.in_channels, height // 8, width // 8),
|
112 |
+
generator=generator,
|
113 |
+
)
|
114 |
+
latents = latents.to(torch_device)
|
115 |
+
latents = latents * scheduler.init_noise_sigma
|
116 |
+
|
117 |
+
# Loop
|
118 |
+
for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
|
119 |
+
# expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
|
120 |
+
latent_model_input = torch.cat([latents] * 2)
|
121 |
+
sigma = scheduler.sigmas[i]
|
122 |
+
latent_model_input = scheduler.scale_model_input(latent_model_input, t)
|
123 |
+
|
124 |
+
# predict the noise residual
|
125 |
+
with torch.no_grad():
|
126 |
+
noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
|
127 |
+
|
128 |
+
# perform guidance
|
129 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
130 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
131 |
+
|
132 |
+
# compute the previous noisy sample x_t -> x_t-1
|
133 |
+
latents = scheduler.step(noise_pred, t, latents).prev_sample
|
134 |
+
|
135 |
+
return latents_to_pil(latents)[0]
|
136 |
+
|
137 |
+
# Prep Scheduler
|
138 |
+
def set_timesteps(scheduler, num_inference_steps):
|
139 |
+
scheduler.set_timesteps(num_inference_steps)
|
140 |
+
scheduler.timesteps = scheduler.timesteps.to(torch.float32) # minor fix to ensure MPS compatibility, fixed in diffusers PR 3925
|
141 |
+
|
142 |
+
def embed_style(prompt, style_embed, style_seed):
|
143 |
+
# Tokenize
|
144 |
+
text_input = tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
|
145 |
+
input_ids = text_input.input_ids.to(torch_device)
|
146 |
+
|
147 |
+
# Get token embeddings
|
148 |
+
token_embeddings = token_emb_layer(input_ids)
|
149 |
+
|
150 |
+
|
151 |
+
replacement_token_embedding = style_embed.to(torch_device)
|
152 |
+
|
153 |
+
# Insert this into the token embeddings
|
154 |
+
token_embeddings[0, torch.where(input_ids[0]==6829)] = replacement_token_embedding.to(torch_device)
|
155 |
+
|
156 |
+
# Combine with pos embs
|
157 |
+
input_embeddings = token_embeddings + position_embeddings
|
158 |
+
|
159 |
+
# Feed through to get final output embs
|
160 |
+
modified_output_embeddings = get_output_embeds(input_embeddings)
|
161 |
+
|
162 |
+
# And generate an image with this:
|
163 |
+
max_length = text_input.input_ids.shape[-1]
|
164 |
+
return generate_with_embs(modified_output_embeddings, style_seed, max_length)
|
165 |
+
|
166 |
+
def generate_image_from_prompt(text_in):
|
167 |
+
print(text_in)
|
168 |
+
generated_image = []
|
169 |
+
|
170 |
+
STYLE_LIST = ['coffeemachine.bin', 'collage_style.bin', 'cube.bin', 'jerrymouse2.bin', 'zero.bin']
|
171 |
+
STYLE_SEEDS = [32, 64, 128, 16, 8]
|
172 |
+
|
173 |
+
prompt = text_in
|
174 |
+
|
175 |
+
for idx, style_file in enumerate(STYLE_LIST):
|
176 |
+
style_seed = STYLE_SEEDS[idx]
|
177 |
+
style_dict = torch.load(style_file)
|
178 |
+
style_embed = [v for v in style_dict.values()]
|
179 |
+
|
180 |
+
generated_image.append(embed_style(prompt, style_embed[0], style_seed))
|
181 |
+
|
182 |
+
return generated_image
|
183 |
+
|
184 |
+
|
185 |
+
# Define Interface
|
186 |
+
|
187 |
+
demo = gr.Interface(fn = generate_image_from_prompt,
|
188 |
+
inputs = [gr.Textbox(1, label='Prompt'),
|
189 |
+
],
|
190 |
+
outputs=[gr.Gallery(
|
191 |
+
label="Stable Diffusion", show_label=False, elem_id="gallery"
|
192 |
+
).style(grid=[2], height="auto")], enable_queue=True, title="Stable Diffusion",
|
193 |
+
)
|
194 |
+
demo.launch(debug=True)
|