SeemG commited on
Commit
2a51e24
·
verified ·
1 Parent(s): 4b7b668

Update utils.py

Browse files
Files changed (1) hide show
  1. utils.py +297 -291
utils.py CHANGED
@@ -1,291 +1,297 @@
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
-
 
 
 
 
 
 
 
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
+ def build_causal_attention_mask(bsz, seq_len, dtype):
41
+ mask = torch.empty(bsz, seq_len, seq_len, dtype=dtype)
42
+ mask.fill_(torch.tensor(torch.finfo(dtype).min)) # fill with large negative number (acts like -inf)
43
+ mask = mask.triu_(1) # zero out the lower diagonal to enforce causality
44
+ return mask.unsqueeze(1) # add a batch dimension
45
+
46
+
47
+ # Prep Scheduler
48
+ def set_timesteps(scheduler, num_inference_steps):
49
+ scheduler.set_timesteps(num_inference_steps)
50
+ scheduler.timesteps = scheduler.timesteps.to(torch.float32) # minor fix to ensure MPS compatibility, fixed in diffusers PR 3925
51
+
52
+
53
+
54
+
55
+ def pil_to_latent(input_im):
56
+ # Single image -> single latent in a batch (so size 1, 4, 64, 64)
57
+ with torch.no_grad():
58
+ latent = vae.encode(tfms.ToTensor()(input_im).unsqueeze(0).to(torch_device)*2-1) # Note scaling
59
+ return 0.18215 * latent.latent_dist.sample()
60
+
61
+ def latents_to_pil(latents):
62
+ # bath of latents -> list of images
63
+ latents = (1 / 0.18215) * latents
64
+ with torch.no_grad():
65
+ image = vae.decode(latents).sample
66
+ image = (image / 2 + 0.5).clamp(0, 1)
67
+ image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
68
+ images = (image * 255).round().astype("uint8")
69
+ pil_images = [Image.fromarray(image) for image in images]
70
+ return pil_images
71
+
72
+ def get_output_embeds(input_embeddings):
73
+ # CLIP's text model uses causal mask, so we prepare it here:
74
+ bsz, seq_len = input_embeddings.shape[:2]
75
+ causal_attention_mask = build_causal_attention_mask(bsz, seq_len, dtype=input_embeddings.dtype)
76
+
77
+ # Getting the output embeddings involves calling the model with passing output_hidden_states=True
78
+ # so that it doesn't just return the pooled final predictions:
79
+ encoder_outputs = text_encoder.text_model.encoder(
80
+ inputs_embeds=input_embeddings,
81
+ attention_mask=None, # We aren't using an attention mask so that can be None
82
+ causal_attention_mask=causal_attention_mask.to(torch_device),
83
+ output_attentions=None,
84
+ output_hidden_states=True, # We want the output embs not the final output
85
+ return_dict=None,
86
+ )
87
+
88
+ # We're interested in the output hidden state only
89
+ output = encoder_outputs[0]
90
+
91
+ # There is a final layer norm we need to pass these through
92
+ output = text_encoder.text_model.final_layer_norm(output)
93
+
94
+ # And now they're ready!
95
+ return output
96
+
97
+
98
+
99
+ #Generating an image with these modified embeddings
100
+
101
+ def generate_with_embs(text_embeddings, seed=45):
102
+ height = 512 # default height of Stable Diffusion
103
+ width = 512 # default width of Stable Diffusion
104
+ num_inference_steps = 30 # 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
+
150
+ def blue_loss(images):
151
+ # How far are the blue channel values to 0.9:
152
+ error = torch.abs(images[:,2] - 0.9).mean() # [:,2] -> all images in batch, only the blue channel
153
+ return error
154
+
155
+
156
+ def amber_loss(images):
157
+ """Calculates the mean absolute error for amber color.
158
+
159
+ Args:
160
+ images: A tensor of shape (batch_size, channels, height, width).
161
+ target_red: Target red value for amber.
162
+ target_green: Target green value for amber.
163
+ target_blue: Target blue value for amber.
164
+
165
+ Returns:
166
+ The mean absolute error.
167
+ #target_red=0.8, target_green=0.6, target_blue=0.4
168
+ """
169
+
170
+ red_error = torch.abs(images[:, 0] - 0.12).mean()
171
+ green_error = torch.abs(images[:, 1] - 0.2).mean()
172
+ blue_error = torch.abs(images[:, 2] - 0.15).mean()
173
+
174
+ # You can adjust weights for each channel if needed
175
+ amber_error = (red_error + green_error + blue_error) / 3
176
+ return amber_error
177
+
178
+
179
+ def generate_with_custom_loss(text_embeddings, text_input, generator, loss_fn):
180
+ blue_loss_scale = 60
181
+
182
+ height = 256 # default height of Stable Diffusion
183
+ width = 256 # default width of Stable Diffusion
184
+ num_inference_steps = 15 # Number of denoising steps
185
+ guidance_scale = 7.5 # Scale for classifier-free guidance
186
+ # generator = torch.manual_seed(32) # Seed generator to create the inital latent noise
187
+ batch_size = 1
188
+
189
+ max_length = text_input.input_ids.shape[-1]
190
+ uncond_input = tokenizer(
191
+ [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
192
+ )
193
+ with torch.no_grad():
194
+ uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]
195
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
196
+
197
+ # Prep Scheduler
198
+ set_timesteps(scheduler, num_inference_steps)
199
+
200
+ # Prep latents
201
+ latents = torch.randn(
202
+ (batch_size, unet.in_channels, height // 8, width // 8),
203
+ generator=generator,
204
+ )
205
+ latents = latents.to(torch_device)
206
+ latents = latents * scheduler.init_noise_sigma
207
+
208
+ # Loop
209
+ for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
210
+ # expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
211
+ latent_model_input = torch.cat([latents] * 2)
212
+ sigma = scheduler.sigmas[i]
213
+ latent_model_input = scheduler.scale_model_input(latent_model_input, t)
214
+
215
+ # predict the noise residual
216
+ with torch.no_grad():
217
+ noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
218
+
219
+ # perform guidance
220
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
221
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
222
+
223
+ #### ADDITIONAL GUIDANCE ###
224
+ if i % 10 == 0:
225
+ # Requires grad on the latents
226
+ latents = latents.detach().requires_grad_()
227
+
228
+ # Get the predicted x0:
229
+ latents_x0 = latents - sigma * noise_pred
230
+ # latents_x0 = scheduler.step(noise_pred, t, latents).pred_original_sample
231
+
232
+ # Decode to image space
233
+ denoised_images = vae.decode((1 / 0.18215) * latents_x0).sample / 2 + 0.5 # range (0, 1)
234
+
235
+ # Calculate loss
236
+ loss = loss_fn(denoised_images) * blue_loss_scale
237
+
238
+ # Occasionally print it out
239
+ if i % 10 == 0:
240
+ print(i, 'loss:', loss.item())
241
+
242
+ # Get gradient
243
+ cond_grad = torch.autograd.grad(loss, latents)[0]
244
+
245
+ # Modify the latents based on this gradient
246
+ latents = latents.detach() - cond_grad * sigma ** 2
247
+
248
+ # compute the previous noisy sample x_t -> x_t-1
249
+ latents = scheduler.step(noise_pred, t, latents).prev_sample
250
+
251
+ return latents_to_pil(latents)[0]
252
+ def gen_image_as_per_prompt(prompt, style, seed, custom_loss=None):
253
+ # prompt = 'dog as Wolverine'
254
+
255
+ generator = torch.manual_seed(seed)
256
+
257
+ # Tokenize
258
+ text_input = tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True,
259
+ return_tensors="pt")
260
+ input_ids = text_input.input_ids.to(torch_device)
261
+
262
+ # Access the embedding layer
263
+ token_emb_layer = text_encoder.text_model.embeddings.token_embedding
264
+
265
+ # Get token embeddings
266
+ token_embeddings = token_emb_layer(input_ids)
267
+
268
+ # The new embedding - special style
269
+ if style:
270
+ style_embed = torch.load(style)
271
+ keys = list(style_embed.keys())
272
+ replacement_token_embedding = style_embed[keys[0]].to(torch_device)
273
+
274
+ # The new embedding. In this case just the input embedding of token 2368...mixing CAT
275
+ # replacement_token_embedding = text_encoder.get_input_embeddings()(torch.tensor(2368, device=torch_device))
276
+
277
+ # Insert this into the token embeddings (
278
+ token_embeddings[0, torch.where(input_ids[0] == 6829)] = replacement_token_embedding.to(torch_device)
279
+
280
+ # get pos embed
281
+ pos_emb_layer = text_encoder.text_model.embeddings.position_embedding
282
+ position_ids = text_encoder.text_model.embeddings.position_ids[:, :77]
283
+ position_embeddings = pos_emb_layer(position_ids)
284
+
285
+ # Combine with pos embs
286
+ input_embeddings = token_embeddings + position_embeddings
287
+
288
+ # Feed through to get final output embs
289
+ modified_output_embeddings = get_output_embeds(input_embeddings)
290
+
291
+ if custom_loss is not None:
292
+ image = generate_with_custom_loss(modified_output_embeddings, text_input, generator, custom_loss)
293
+ else:
294
+ image = generate_with_embs(modified_output_embeddings, text_input, generator)
295
+
296
+ return image
297
+