SeemG commited on
Commit
85ae87b
·
verified ·
1 Parent(s): 70054b9

Upload 8 files

Browse files
learned_embeds (2).bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4865a5d2ecd012985940748023fd80e4fd299837f1dccedb85ee83be5bb1f957
3
+ size 3819
learned_embeds_cosmic-galaxy-characters-style.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d30a58e4095f2f9adb26c45459da59f5fe2354e8e62842b979c3246a21e0b7b5
3
+ size 3840
learned_embeds_depthmap.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e23ba9437d8ecc4acce4dae08118272855db108e24feaaf5d428df88661335de
3
+ size 3819
learned_embeds_moebius.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ff8da3d4cbeb09ee7e0a6ef8b0dc647b31c23580678ec2f5eee0e8d5f087c29d
3
+ size 3819
learned_embeds_sd_concept-art.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cd046d1c90c6e58769033de23adadf936e873597b11fed16a07dde7750bd348c
3
+ size 3819
learned_embeds_sd_hitokomoru-style-na.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f81a9c575e329e08a24e08f47ae73c5b50dec4bcb557974552549b45e2d1b0d4
3
+ size 3819
learned_embeds_style-of-marc-allante.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2b0496315f14f212535f9350c3dbf05787ac50a78465d4be2f39a1ba373e4968
3
+ size 3819
utils (5).py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision
3
+ from diffusers import StableDiffusionPipeline
4
+ from base64 import b64encode
5
+ from diffusers import AutoencoderKL, LMSDiscreteScheduler, UNet2DConditionModel
6
+ from transformers import CLIPTextModel, CLIPTokenizer, logging
7
+ from torchvision import transforms as tfms
8
+ from PIL import Image
9
+ from tqdm.auto import tqdm
10
+ from matplotlib import pyplot as plt
11
+
12
+
13
+
14
+ # Supress some unnecessary warnings when loading the CLIPTextModel
15
+ logging.set_verbosity_error()
16
+
17
+ # Set device
18
+ torch_device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
19
+ if "mps" == torch_device: os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = "1"
20
+
21
+
22
+ # Load the autoencoder model which will be used to decode the latents into image space.
23
+ vae = AutoencoderKL.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="vae")
24
+
25
+ # Load the tokenizer and text encoder to tokenize and encode the text.
26
+ tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")
27
+ text_encoder = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14")
28
+
29
+ # The UNet model for generating the latents.
30
+ unet = UNet2DConditionModel.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="unet")
31
+
32
+ # The noise scheduler
33
+ scheduler = LMSDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000)
34
+
35
+ # To the GPU we go!
36
+ vae = vae.to(torch_device)
37
+ text_encoder = text_encoder.to(torch_device)
38
+ unet = unet.to(torch_device);
39
+
40
+
41
+ # Prep Scheduler
42
+ def set_timesteps(scheduler, num_inference_steps):
43
+ scheduler.set_timesteps(num_inference_steps)
44
+ scheduler.timesteps = scheduler.timesteps.to(torch.float32) # minor fix to ensure MPS compatibility, fixed in diffusers PR 3925
45
+
46
+
47
+
48
+
49
+ def pil_to_latent(input_im):
50
+ # Single image -> single latent in a batch (so size 1, 4, 64, 64)
51
+ with torch.no_grad():
52
+ latent = vae.encode(tfms.ToTensor()(input_im).unsqueeze(0).to(torch_device)*2-1) # Note scaling
53
+ return 0.18215 * latent.latent_dist.sample()
54
+
55
+ def latents_to_pil(latents):
56
+ # bath of latents -> list of images
57
+ latents = (1 / 0.18215) * latents
58
+ with torch.no_grad():
59
+ image = vae.decode(latents).sample
60
+ image = (image / 2 + 0.5).clamp(0, 1)
61
+ image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
62
+ images = (image * 255).round().astype("uint8")
63
+ pil_images = [Image.fromarray(image) for image in images]
64
+ return pil_images
65
+
66
+ def get_output_embeds(input_embeddings):
67
+ # CLIP's text model uses causal mask, so we prepare it here:
68
+ bsz, seq_len = input_embeddings.shape[:2]
69
+ causal_attention_mask = text_encoder.text_model._build_causal_attention_mask(bsz, seq_len, dtype=input_embeddings.dtype)
70
+
71
+ # Getting the output embeddings involves calling the model with passing output_hidden_states=True
72
+ # so that it doesn't just return the pooled final predictions:
73
+ encoder_outputs = text_encoder.text_model.encoder(
74
+ inputs_embeds=input_embeddings,
75
+ attention_mask=None, # We aren't using an attention mask so that can be None
76
+ causal_attention_mask=causal_attention_mask.to(torch_device),
77
+ output_attentions=None,
78
+ output_hidden_states=True, # We want the output embs not the final output
79
+ return_dict=None,
80
+ )
81
+
82
+ # We're interested in the output hidden state only
83
+ output = encoder_outputs[0]
84
+
85
+ # There is a final layer norm we need to pass these through
86
+ output = text_encoder.text_model.final_layer_norm(output)
87
+
88
+ # And now they're ready!
89
+ return output
90
+
91
+
92
+
93
+ #Generating an image with these modified embeddings
94
+
95
+ def generate_with_embs(text_embeddings, seed=45):
96
+ height = 512 # default height of Stable Diffusion
97
+ width = 512 # default width of Stable Diffusion
98
+ num_inference_steps = 30 # Number of denoising steps
99
+ guidance_scale = 7.5 # Scale for classifier-free guidance
100
+ generator = torch.manual_seed(seed) # Seed generator to create the inital latent noise
101
+ batch_size = 1
102
+
103
+ max_length = text_input.input_ids.shape[-1]
104
+ uncond_input = tokenizer(
105
+ [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
106
+ )
107
+ with torch.no_grad():
108
+ uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]
109
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
110
+
111
+ # Prep Scheduler
112
+ set_timesteps(scheduler, num_inference_steps)
113
+
114
+ # Prep latents
115
+ latents = torch.randn(
116
+ (batch_size, unet.in_channels, height // 8, width // 8),
117
+ generator=generator,
118
+ )
119
+ latents = latents.to(torch_device)
120
+ latents = latents * scheduler.init_noise_sigma
121
+
122
+ # Loop
123
+ for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
124
+ # expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
125
+ latent_model_input = torch.cat([latents] * 2)
126
+ sigma = scheduler.sigmas[i]
127
+ latent_model_input = scheduler.scale_model_input(latent_model_input, t)
128
+
129
+ # predict the noise residual
130
+ with torch.no_grad():
131
+ noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
132
+
133
+ # perform guidance
134
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
135
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
136
+
137
+ # compute the previous noisy sample x_t -> x_t-1
138
+ latents = scheduler.step(noise_pred, t, latents).prev_sample
139
+
140
+ return latents_to_pil(latents)[0]
141
+
142
+
143
+
144
+ def blue_loss(images):
145
+ # How far are the blue channel values to 0.9:
146
+ error = torch.abs(images[:,2] - 0.9).mean() # [:,2] -> all images in batch, only the blue channel
147
+ return error
148
+
149
+
150
+ def amber_loss(images):
151
+ """Calculates the mean absolute error for amber color.
152
+
153
+ Args:
154
+ images: A tensor of shape (batch_size, channels, height, width).
155
+ target_red: Target red value for amber.
156
+ target_green: Target green value for amber.
157
+ target_blue: Target blue value for amber.
158
+
159
+ Returns:
160
+ The mean absolute error.
161
+ #target_red=0.8, target_green=0.6, target_blue=0.4
162
+ """
163
+
164
+ red_error = torch.abs(images[:, 0] - 0.12).mean()
165
+ green_error = torch.abs(images[:, 1] - 0.2).mean()
166
+ blue_error = torch.abs(images[:, 2] - 0.15).mean()
167
+
168
+ # You can adjust weights for each channel if needed
169
+ amber_error = (red_error + green_error + blue_error) / 3
170
+ return amber_error
171
+
172
+
173
+ def generate_with_custom_loss(text_embeddings, text_input, generator, loss_fn):
174
+ blue_loss_scale = 60
175
+
176
+ height = 256 # default height of Stable Diffusion
177
+ width = 256 # default width of Stable Diffusion
178
+ num_inference_steps = 15 # Number of denoising steps
179
+ guidance_scale = 7.5 # Scale for classifier-free guidance
180
+ # generator = torch.manual_seed(32) # Seed generator to create the inital latent noise
181
+ batch_size = 1
182
+
183
+ max_length = text_input.input_ids.shape[-1]
184
+ uncond_input = tokenizer(
185
+ [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
186
+ )
187
+ with torch.no_grad():
188
+ uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]
189
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
190
+
191
+ # Prep Scheduler
192
+ set_timesteps(scheduler, num_inference_steps)
193
+
194
+ # Prep latents
195
+ latents = torch.randn(
196
+ (batch_size, unet.in_channels, height // 8, width // 8),
197
+ generator=generator,
198
+ )
199
+ latents = latents.to(torch_device)
200
+ latents = latents * scheduler.init_noise_sigma
201
+
202
+ # Loop
203
+ for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
204
+ # expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
205
+ latent_model_input = torch.cat([latents] * 2)
206
+ sigma = scheduler.sigmas[i]
207
+ latent_model_input = scheduler.scale_model_input(latent_model_input, t)
208
+
209
+ # predict the noise residual
210
+ with torch.no_grad():
211
+ noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
212
+
213
+ # perform guidance
214
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
215
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
216
+
217
+ #### ADDITIONAL GUIDANCE ###
218
+ if i % 10 == 0:
219
+ # Requires grad on the latents
220
+ latents = latents.detach().requires_grad_()
221
+
222
+ # Get the predicted x0:
223
+ latents_x0 = latents - sigma * noise_pred
224
+ # latents_x0 = scheduler.step(noise_pred, t, latents).pred_original_sample
225
+
226
+ # Decode to image space
227
+ denoised_images = vae.decode((1 / 0.18215) * latents_x0).sample / 2 + 0.5 # range (0, 1)
228
+
229
+ # Calculate loss
230
+ loss = loss_fn(denoised_images) * blue_loss_scale
231
+
232
+ # Occasionally print it out
233
+ if i % 10 == 0:
234
+ print(i, 'loss:', loss.item())
235
+
236
+ # Get gradient
237
+ cond_grad = torch.autograd.grad(loss, latents)[0]
238
+
239
+ # Modify the latents based on this gradient
240
+ latents = latents.detach() - cond_grad * sigma ** 2
241
+
242
+ # compute the previous noisy sample x_t -> x_t-1
243
+ latents = scheduler.step(noise_pred, t, latents).prev_sample
244
+
245
+ return latents_to_pil(latents)[0]
246
+ def gen_image_as_per_prompt(prompt, style, seed, custom_loss=None):
247
+ # prompt = 'dog as Wolverine'
248
+
249
+ generator = torch.manual_seed(seed)
250
+
251
+ # Tokenize
252
+ text_input = tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True,
253
+ return_tensors="pt")
254
+ input_ids = text_input.input_ids.to(torch_device)
255
+
256
+ # Access the embedding layer
257
+ token_emb_layer = text_encoder.text_model.embeddings.token_embedding
258
+
259
+ # Get token embeddings
260
+ token_embeddings = token_emb_layer(input_ids)
261
+
262
+ # The new embedding - special style
263
+ if style:
264
+ style_embed = torch.load(style)
265
+ keys = list(style_embed.keys())
266
+ replacement_token_embedding = style_embed[keys[0]].to(torch_device)
267
+
268
+ # The new embedding. In this case just the input embedding of token 2368...mixing CAT
269
+ # replacement_token_embedding = text_encoder.get_input_embeddings()(torch.tensor(2368, device=torch_device))
270
+
271
+ # Insert this into the token embeddings (
272
+ token_embeddings[0, torch.where(input_ids[0] == 6829)] = replacement_token_embedding.to(torch_device)
273
+
274
+ # get pos embed
275
+ pos_emb_layer = text_encoder.text_model.embeddings.position_embedding
276
+ position_ids = text_encoder.text_model.embeddings.position_ids[:, :77]
277
+ position_embeddings = pos_emb_layer(position_ids)
278
+
279
+ # Combine with pos embs
280
+ input_embeddings = token_embeddings + position_embeddings
281
+
282
+ # Feed through to get final output embs
283
+ modified_output_embeddings = get_output_embeds(input_embeddings)
284
+
285
+ if custom_loss is not None:
286
+ image = generate_with_custom_loss(modified_output_embeddings, text_input, generator, custom_loss)
287
+ else:
288
+ image = generate_with_embs(modified_output_embeddings, text_input, generator)
289
+
290
+ return image
291
+