Spaces:
Runtime error
Runtime error
744/C/B0228844//Rohit_Jain
commited on
Commit
·
5b47935
1
Parent(s):
222f6f5
app
Browse files- birb-style +1 -0
- herge-style +1 -0
- indian-watercolor-portraits +1 -0
- midjourney-style +1 -0
- qr_code1.png +0 -0
- sd_utils.py +224 -0
- style-of-marc-allante +1 -0
birb-style
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
Subproject commit 421b470c1c55d204152be94d590aa4e5a2dcd715
|
herge-style
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
Subproject commit 6ddab2d3191715a679b9e6bbc38aa05baff1ffa0
|
indian-watercolor-portraits
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
Subproject commit 89ff0bc8ae9b4cb0731796be374c3f9efe2b54dc
|
midjourney-style
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
Subproject commit 4a3668469aedc8f883a88d11192156d0374bcce2
|
qr_code1.png
ADDED
sd_utils.py
ADDED
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import numpy
|
3 |
+
import torch
|
4 |
+
from torch import autocast
|
5 |
+
from torchvision import transforms as tfms
|
6 |
+
import torch.nn.functional as F
|
7 |
+
|
8 |
+
import PIL
|
9 |
+
from PIL import Image
|
10 |
+
|
11 |
+
from diffusers import StableDiffusionPipeline
|
12 |
+
from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer, logging
|
13 |
+
from diffusers import AutoencoderKL, LMSDiscreteScheduler, UNet2DConditionModel, KDPM2DiscreteScheduler
|
14 |
+
|
15 |
+
# For video display:
|
16 |
+
from IPython.display import HTML
|
17 |
+
from matplotlib import pyplot as plt
|
18 |
+
from pathlib import Path
|
19 |
+
from tqdm.auto import tqdm
|
20 |
+
import cv2
|
21 |
+
|
22 |
+
bb = cv2.imread("./qr_code1.png")
|
23 |
+
bb = cv2.cvtColor(bb, cv2.COLOR_BGR2RGB)
|
24 |
+
tfm2 = tfms.Compose([
|
25 |
+
tfms.ToTensor(),
|
26 |
+
tfms.Resize([512, 512]),
|
27 |
+
tfms.CenterCrop(512),
|
28 |
+
#tfms.Normalize((0.6813,0.6813, 0.6813), (0.4549, 0.4549, 0.4549))
|
29 |
+
])
|
30 |
+
img2 = tfm2(bb)
|
31 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
32 |
+
pretrained_model_name_or_path = "CompVis/stable-diffusion-v1-4"
|
33 |
+
# Load the autoencoder model which will be used to decode the latents into image space.
|
34 |
+
vae = AutoencoderKL.from_pretrained(pretrained_model_name_or_path, subfolder="vae")
|
35 |
+
|
36 |
+
# Load the tokenizer and text encoder to tokenize and encode the text.
|
37 |
+
tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")
|
38 |
+
text_encoder = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14")
|
39 |
+
|
40 |
+
# The UNet model for generating the latents.
|
41 |
+
unet = UNet2DConditionModel.from_pretrained(pretrained_model_name_or_path, subfolder="unet")
|
42 |
+
|
43 |
+
# The noise scheduler
|
44 |
+
scheduler = LMSDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000)
|
45 |
+
#scheduler = KDPM2DiscreteScheduler(num_train_timesteps=1000, beta_start=)
|
46 |
+
|
47 |
+
# To the GPU we go!
|
48 |
+
vae = vae.to(device)
|
49 |
+
text_encoder = text_encoder.to(device)
|
50 |
+
unet = unet.to(device)
|
51 |
+
|
52 |
+
pipe = StableDiffusionPipeline.from_pretrained(pretrained_model_name_or_path,torch_dtype=torch.float16).to(device)
|
53 |
+
|
54 |
+
|
55 |
+
|
56 |
+
# birb_embed = pipe.load_textual_inversion("sd-concepts-library/birb-style")
|
57 |
+
# herge_embed = pipe.load_textual_inversion("sd-concepts-library/herge-style")
|
58 |
+
# indian_water_color_embed = pipe.load_textual_inversion("sd-concepts-library/indian-watercolor-portraits")
|
59 |
+
# midjourney_embed = pipe.load_textual_inversion("sd-concepts-library/midjourney-style")
|
60 |
+
# marc_allante_embed = pipe.load_textual_inversion("sd-concepts-library/style-of-marc-allante")
|
61 |
+
|
62 |
+
birb_embed = torch.load('./birb-style/learned_embeds.bin')
|
63 |
+
herge_embed = torch.load('./herge-style/learned_embeds.bin')
|
64 |
+
indian_water_color_embed = torch.load('./indian-watercolor-portraits/learned_embeds.bin')
|
65 |
+
midjourney_embed = torch.load('./midjourney-style/learned_embeds.bin')
|
66 |
+
marc_allante_embed = torch.load('./style-of-marc-allante/learned_embeds.bin')
|
67 |
+
|
68 |
+
style_seeds = {
|
69 |
+
'birb': 321,
|
70 |
+
'herge': 1,
|
71 |
+
'indian_watercolor': 42,
|
72 |
+
'midjourney': 8081,
|
73 |
+
'marc_allante': 100
|
74 |
+
}
|
75 |
+
|
76 |
+
|
77 |
+
|
78 |
+
def qr_loss(images, qr_img):
|
79 |
+
|
80 |
+
#qr_img = 0.5 * qr_img
|
81 |
+
qr_img = qr_img.unsqueeze(0).to(device)
|
82 |
+
#error = F.mse_loss(images, qr_img, reduction='mean')
|
83 |
+
error = F.l1_loss(images, qr_img, reduction='mean')
|
84 |
+
|
85 |
+
return error
|
86 |
+
|
87 |
+
def set_timesteps(scheduler, num_inference_steps):
|
88 |
+
scheduler.set_timesteps(num_inference_steps)
|
89 |
+
scheduler.timesteps = scheduler.timesteps.to(torch.float32) # minor fix to ensure MPS compatibility, fixed in diffusers PR 3925
|
90 |
+
|
91 |
+
def pil_to_latent(input_im):
|
92 |
+
# Single image -> single latent in a batch (so size 1, 4, 64, 64)
|
93 |
+
with torch.no_grad():
|
94 |
+
latent = vae.encode(tfms.ToTensor()(input_im).unsqueeze(0).to(torch_device)*2-1) # Note scaling
|
95 |
+
return 0.18215 * latent.latent_dist.sample()
|
96 |
+
|
97 |
+
def latents_to_pil(latents):
|
98 |
+
# bath of latents -> list of images
|
99 |
+
latents = (1 / 0.18215) * latents
|
100 |
+
with torch.no_grad():
|
101 |
+
image = vae.decode(latents).sample
|
102 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
103 |
+
image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
|
104 |
+
images = (image * 255).round().astype("uint8")
|
105 |
+
pil_images = [Image.fromarray(image) for image in images]
|
106 |
+
return pil_images
|
107 |
+
|
108 |
+
def get_output_embeds(input_embeddings):
|
109 |
+
# CLIP's text model uses causal mask, so we prepare it here:
|
110 |
+
bsz, seq_len = input_embeddings.shape[:2]
|
111 |
+
#causal_attention_mask = text_encoder.text_model._build_causal_attention_mask(bsz, seq_len, dtype=input_embeddings.dtype)
|
112 |
+
causal_attention_mask = build_causal_attention_mask(bsz, seq_len, dtype=input_embeddings.dtype)
|
113 |
+
|
114 |
+
# Getting the output embeddings involves calling the model with passing output_hidden_states=True
|
115 |
+
# so that it doesn't just return the pooled final predictions:
|
116 |
+
encoder_outputs = text_encoder.text_model.encoder(
|
117 |
+
inputs_embeds=input_embeddings,
|
118 |
+
attention_mask=None, # We aren't using an attention mask so that can be None
|
119 |
+
causal_attention_mask=causal_attention_mask.to(device),
|
120 |
+
output_attentions=None,
|
121 |
+
output_hidden_states=True, # We want the output embs not the final output
|
122 |
+
return_dict=None,
|
123 |
+
)
|
124 |
+
|
125 |
+
# We're interested in the output hidden state only
|
126 |
+
output = encoder_outputs[0]
|
127 |
+
|
128 |
+
# There is a final layer norm we need to pass these through
|
129 |
+
output = text_encoder.text_model.final_layer_norm(output)
|
130 |
+
|
131 |
+
# And now they're ready
|
132 |
+
return output
|
133 |
+
|
134 |
+
def build_causal_attention_mask(bsz, seq_len, dtype):
|
135 |
+
# lazily create causal attention mask, with full attention between the vision tokens
|
136 |
+
# pytorch uses additive attention mask; fill with -inf
|
137 |
+
mask = torch.empty(bsz, seq_len, seq_len, dtype=dtype)
|
138 |
+
mask.fill_(torch.tensor(torch.finfo(dtype).min))
|
139 |
+
mask.triu_(1) # zero out the lower diagonal
|
140 |
+
mask = mask.unsqueeze(1) # expand mask
|
141 |
+
return mask
|
142 |
+
|
143 |
+
def generate_with_embs_custom_loss(prompt, text_embeddings, seed):
|
144 |
+
#prompt = "A labrador dog in a car" #@param
|
145 |
+
height = 512 # default height of Stable Diffusion
|
146 |
+
width = 512 # default width of Stable Diffusion
|
147 |
+
num_inference_steps = 50 #@param # Number of denoising steps
|
148 |
+
guidance_scale = 11 #@param # Scale for classifier-free guidance
|
149 |
+
generator = torch.manual_seed(seed) # Seed generator to create the inital latent noise
|
150 |
+
batch_size = 1
|
151 |
+
blue_loss_scale = 100 #@param
|
152 |
+
|
153 |
+
# Prep text
|
154 |
+
text_input = tokenizer([prompt], padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
|
155 |
+
with torch.no_grad():
|
156 |
+
text_embeddings = text_encoder(text_input.input_ids.to(device))[0]
|
157 |
+
|
158 |
+
# And the uncond. input as before:
|
159 |
+
max_length = text_input.input_ids.shape[-1]
|
160 |
+
uncond_input = tokenizer(
|
161 |
+
[""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
|
162 |
+
)
|
163 |
+
with torch.no_grad():
|
164 |
+
uncond_embeddings = text_encoder(uncond_input.input_ids.to(device))[0]
|
165 |
+
text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
|
166 |
+
|
167 |
+
# Prep Scheduler
|
168 |
+
set_timesteps(scheduler, num_inference_steps)
|
169 |
+
|
170 |
+
# Prep latents
|
171 |
+
latents = torch.randn(
|
172 |
+
(batch_size, unet.in_channels, height // 8, width // 8),
|
173 |
+
generator=generator,
|
174 |
+
)
|
175 |
+
latents = latents.to(device)
|
176 |
+
latents = latents * scheduler.init_noise_sigma
|
177 |
+
|
178 |
+
# Loop
|
179 |
+
for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
|
180 |
+
# expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
|
181 |
+
latent_model_input = torch.cat([latents] * 2)
|
182 |
+
sigma = scheduler.sigmas[i]
|
183 |
+
latent_model_input = scheduler.scale_model_input(latent_model_input, t)
|
184 |
+
|
185 |
+
# predict the noise residual
|
186 |
+
with torch.no_grad():
|
187 |
+
noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
|
188 |
+
|
189 |
+
# perform CFG guidance
|
190 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
191 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
192 |
+
|
193 |
+
#### ADDITIONAL GUIDANCE ###
|
194 |
+
if i%2 == 0:
|
195 |
+
# Requires grad on the latents
|
196 |
+
latents = latents.detach().requires_grad_()
|
197 |
+
|
198 |
+
# Get the predicted x0:
|
199 |
+
latents_x0 = latents - sigma * noise_pred
|
200 |
+
#latents_x0 = scheduler.step(noise_pred, t, latents).pred_original_sample
|
201 |
+
|
202 |
+
# Decode to image space
|
203 |
+
denoised_images = vae.decode((1 / 0.18215) * latents_x0).sample / 2 + 0.5 # range (0, 1)
|
204 |
+
|
205 |
+
# Calculate loss
|
206 |
+
#loss = blue_loss(denoised_images) * blue_loss_scale
|
207 |
+
#loss = purple_loss(denoised_images) * blue_loss_scale
|
208 |
+
loss = qr_loss(denoised_images, img2) * blue_loss_scale
|
209 |
+
|
210 |
+
# Occasionally print it out
|
211 |
+
if i%10==0:
|
212 |
+
print(i, 'loss:', loss.item())
|
213 |
+
|
214 |
+
# Get gradient
|
215 |
+
cond_grad = torch.autograd.grad(loss, latents)[0]
|
216 |
+
|
217 |
+
# Modify the latents based on this gradient
|
218 |
+
latents = latents.detach() - cond_grad * sigma**2
|
219 |
+
|
220 |
+
# Now step with scheduler
|
221 |
+
latents = scheduler.step(noise_pred, t, latents).prev_sample
|
222 |
+
|
223 |
+
return latents_to_pil(latents)[0]
|
224 |
+
|
style-of-marc-allante
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
Subproject commit 6de4ce4972ae09f61d6e4caf377b9ca00898b8b4
|