Vasudevakrishna commited on
Commit
3ef77b8
·
verified ·
1 Parent(s): b15e27e

Update utils.py

Browse files
Files changed (1) hide show
  1. utils.py +156 -0
utils.py CHANGED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import numpy as np
3
+ import numpy
4
+ import torch
5
+ from diffusers import AutoencoderKL, LMSDiscreteScheduler, UNet2DConditionModel
6
+
7
+ from matplotlib import pyplot as plt
8
+ from pathlib import Path
9
+ from PIL import Image
10
+ from torch import autocast
11
+ from torchvision import transforms as tfms
12
+ from tqdm.auto import tqdm
13
+ from transformers import CLIPTextModel, CLIPTokenizer, logging
14
+ import os
15
+ from diffusers import StableDiffusionPipeline, DiffusionPipeline
16
+
17
+ # large or small model
18
+
19
+ # configurations
20
+ height, width = 512, 512
21
+ guidance_scale = 8
22
+ custom_loss_scale = 200
23
+ num_inference_steps = 50
24
+ batch_size = 1
25
+ torch_device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
26
+
27
+
28
+ pretrained_model_name_or_path = "CompVis/stable-diffusion-v1-4"
29
+ pipe = DiffusionPipeline.from_pretrained(
30
+ pretrained_model_name_or_path,
31
+ torch_dtype=torch.float32
32
+ ).to(torch_device)
33
+
34
+ # Load SD concepts
35
+ sdconcepts = ['<morino-hon>', '<space-style>', '<tesla-bot>', '<midjourney-style>', ' <hanfu-anime-style>']
36
+
37
+ pipe.load_textual_inversion("sd-concepts-library/morino-hon-style")
38
+ pipe.load_textual_inversion("sd-concepts-library/space-style")
39
+ pipe.load_textual_inversion("sd-concepts-library/tesla-bot")
40
+ pipe.load_textual_inversion("sd-concepts-library/midjourney-style")
41
+ pipe.load_textual_inversion("sd-concepts-library/hanfu-anime-style")
42
+
43
+ # define seeds
44
+ seed_list = [1, 2, 3, 4, 5]
45
+
46
+
47
+ def custom_loss(images):
48
+
49
+ # Gradient loss
50
+ gradient_x = torch.abs(images[:, :, :, :-1] - images[:, :, :, 1:]).mean()
51
+ gradient_y = torch.abs(images[:, :, :-1, :] - images[:, :, 1:, :]).mean()
52
+ error = gradient_x + gradient_y
53
+ #Variational loss
54
+ # diff_x = torch.abs(images[:, :, :, :-1] - images[:, :, :, 1:])
55
+ # diff_y = torch.abs(images[:, :, :-1, :] - images[:, :, 1:, :])
56
+ # error = diff_x.mean() + diff_y.mean()
57
+
58
+ return error
59
+
60
+ def latents_to_pil(latents):
61
+ # bath of latents -> list of images
62
+ latents = (1 / 0.18215) * latents
63
+ with torch.no_grad():
64
+ image = pipe.vae.decode(latents).sample
65
+ image = (image / 2 + 0.5).clamp(0, 1) # 0 to 1
66
+ image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
67
+ images = (image * 255).round().astype("uint8")
68
+ pil_images = [Image.fromarray(image) for image in images]
69
+ return pil_images
70
+
71
+ def generate_latents(prompts, seed_nums, loss_apply=False):
72
+
73
+ generator = torch.manual_seed(seed_nums)
74
+
75
+ # scheduler
76
+ scheduler = LMSDiscreteScheduler(beta_start = 0.00085, beta_end = 0.012, beta_schedule = "scaled_linear", num_train_timesteps = 1000)
77
+ scheduler.set_timesteps(num_inference_steps)
78
+ scheduler.timesteps = scheduler.timesteps.to(torch.float32)
79
+
80
+ # text embeddings of the prompt
81
+ text_input = pipe.tokenizer(prompts, padding='max_length', max_length = pipe.tokenizer.model_max_length, truncation= True, return_tensors="pt")
82
+ input_ids = text_input.input_ids.to(torch_device)
83
+
84
+ with torch.no_grad():
85
+ text_embeddings = pipe.text_encoder(text_input.input_ids.to(torch_device))[0]
86
+
87
+ max_length = text_input.input_ids.shape[-1]
88
+ uncond_input = pipe.tokenizer(
89
+ [""] * batch_size, padding="max_length", max_length= max_length, return_tensors="pt"
90
+ )
91
+
92
+ with torch.no_grad():
93
+ uncond_embeddings = pipe.text_encoder(uncond_input.input_ids.to(torch_device))[0]
94
+
95
+ text_embeddings = torch.cat([uncond_embeddings,text_embeddings]) # 2,77,768
96
+
97
+ # random latent
98
+ latents = torch.randn(
99
+ (batch_size, pipe.unet.config.in_channels, height// 8, width //8),
100
+ generator = generator,
101
+ ) .to(torch.float16)
102
+
103
+
104
+ latents = latents.to(torch_device)
105
+ latents = latents * scheduler.init_noise_sigma
106
+
107
+ for i, t in tqdm(enumerate(scheduler.timesteps), total = len(scheduler.timesteps)):
108
+
109
+ latent_model_input = torch.cat([latents] * 2)
110
+ sigma = scheduler.sigmas[i]
111
+ latent_model_input = scheduler.scale_model_input(latent_model_input, t)
112
+
113
+ with torch.no_grad():
114
+ noise_pred = pipe.unet(latent_model_input.to(torch.float32), t, encoder_hidden_states=text_embeddings)["sample"]
115
+ #noise_pred = pipe.unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
116
+
117
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
118
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
119
+
120
+ if (loss_apply and i%5 == 0):
121
+
122
+ latents = latents.detach().requires_grad_()
123
+ #latents_x0 = scheduler.step(noise_pred,t, latents).pred_original_sample # this line does not work
124
+ latents_x0 = latents - sigma * noise_pred
125
+
126
+ # use vae to decode the image
127
+ denoised_images = pipe.vae.decode((1/ 0.18215) * latents_x0).sample / 2 + 0.5 # range(0,1)
128
+
129
+ loss = custom_loss(denoised_images) * custom_loss_scale
130
+ print(f"Custom gradient loss {loss}")
131
+
132
+ cond_grad = torch.autograd.grad(loss, latents)[0]
133
+ latents = latents.detach() - cond_grad * sigma**2
134
+
135
+ latents = scheduler.step(noise_pred,t, latents).prev_sample
136
+
137
+ return latents
138
+
139
+
140
+ # Function to convert PIL images to NumPy arrays
141
+ def pil_to_np(image):
142
+ return np.array(image)
143
+
144
+ def generate_gradio_images(prompts):
145
+ # after loss is applied
146
+ latents_list = []
147
+ loss_flag = False
148
+ for seed_no, sd in zip(seed_list, sdconcepts):
149
+ prompts = [f'{prompt} {sd}']
150
+ latents = generate_latents(prompts, seed_no, loss_apply=loss_flag)
151
+ latents_list.append(latents)
152
+ loss_flag = True
153
+ for seed_no, sd in zip(seed_list, sdconcepts):
154
+ prompts = [f'{prompt} {sd}']
155
+ latents = generate_latents(prompts, seed_no, loss_apply=loss_flag)
156
+ latents_list.append(latents)