-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsd.py
237 lines (196 loc) · 9.57 KB
/
sd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import jittor as jt
from jittor import init
import jittor.transform as T
from transformers import CLIPTextModel, CLIPTokenizer, logging, CLIPVisionModel, CLIPFeatureExtractor
from diffusers import PNDMScheduler, DDIMScheduler
from JDiffusion.models import AutoencoderKL, UNet2DConditionModel
from JDiffusion.pipelines.pipeline_output_jittor import StableDiffusionPipelineOutput
logging.set_verbosity_error()
from JDiffusion.utils import randn_tensor
from jittor import nn
import time
import os
from jittor import Function
import jclip as clip
def nan_to_num(
a,
nan=0.0,
posinf=None,
neginf=None,
):
assert isinstance(a, jt.Var)
if a.dtype is bool or a.dtype is int:
return a.clone()
if nan is None:
nan = 0.0
if posinf is None:
posinf = jt.misc.finfo(a.dtype).max
if neginf is None:
neginf = jt.misc.finfo(a.dtype).min
result = jt.where(jt.isnan(a), nan, a) # type: ignore[call-overload]
result = jt.where(jt.isneginf(result), neginf, result) # type: ignore[call-overload]
result = jt.where(jt.isposinf(result), posinf, result) # type: ignore[call-overload]
return result
def seed_everything(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
class _backward_fun(Function):
def execute(self, x, grad_scale):
self.grad_scale = grad_scale
return x.mean()
def grad(self, g):
grad_scale = self.grad_scale
gt_grad = g * grad_scale
return gt_grad, None
backward_fun = _backward_fun.apply
class Resize(nn.Module):
def __init__(self, size):
super().__init__()
self.size = size
def execute(self, img):
return nn.resize(img, self.size)
class Normalize(nn.Module):
def __init__(self, mean, std):
self.mean = jt.array(mean)
self.std = jt.array(std)
self.mean = self.mean.view(1, 3, 1, 1)
self.std = self.std.view(1, 3, 1, 1)
def execute(self, img):
return (img - self.mean) / self.std
# return nn.normalize(img, self.mean, self.std)
class StableDiffusion(nn.Module):
def __init__(self, device,sd_version='2.0', hf_key=None, step_range=[0.2, 0.6]):
super().__init__()
# self.device = device
self.sd_version = sd_version
if (self.sd_version == '2.0'):
model_key = './sd2'
elif (hf_key is not None):
print(f'[INFO] using hugging face custom model key: {hf_key}')
model_key = hf_key
elif (self.sd_version == '1.5'):
model_key = 'runwayml/stable-diffusion-v1-5'
else:
raise ValueError(f'Stable-diffusion version {self.sd_version} not supported.')
self.vae = AutoencoderKL.from_pretrained(model_key, subfolder='vae')
self.tokenizer = CLIPTokenizer.from_pretrained(model_key, subfolder='tokenizer')
self.text_encoder = CLIPTextModel.from_pretrained(model_key, subfolder='text_encoder')
self.mean_img = [0.48145466, 0.4578275, 0.40821073]
self.std_img = [0.26862954, 0.26130258, 0.27577711]
self.normalize = Normalize(self.mean_img, self.std_img)
self.unet = UNet2DConditionModel.from_pretrained(model_key, subfolder='unet')
self.scheduler = DDIMScheduler.from_pretrained(model_key, subfolder='scheduler')
self.num_train_timesteps = self.scheduler.config.num_train_timesteps
self.num_inference_steps = 50
self.min_step = int((self.num_train_timesteps * float(step_range[0])))
self.max_step = int((self.num_train_timesteps * float(step_range[1])))
self.alphas = self.scheduler.alphas_cumprod# .to(self.device)
self.scheduler.alphas_cumprod = self.scheduler.alphas_cumprod# .to(self.device)
self.ref_imgs = None
print(f'[INFO] loaded stable diffusion!')
def get_text_embeds(self, prompt, negative_prompt=''):
text_input = self.tokenizer(prompt, padding='max_length', max_length=self.tokenizer.model_max_length, truncation=True, return_tensors='pt')
with jt.no_grad():
text_embeddings = self.text_encoder(text_input.input_ids)[0]# .to(self.device))[0]
prompt_embeds_dtype = self.text_encoder.dtype
text_embeddings = text_embeddings.to(dtype=prompt_embeds_dtype)
# bs_embed, seq_len, _ = prompt_embeds.shape
uncond_input = self.tokenizer(negative_prompt, padding='max_length', max_length=self.tokenizer.model_max_length, return_tensors='pt')
with jt.no_grad():
uncond_embeddings = self.text_encoder(uncond_input.input_ids)[0] # .to(self.device))[0]
text_embeddings = jt.concat([uncond_embeddings, text_embeddings])
return text_embeddings
def img_clip_loss(self, clip_model, rgb1, rgb2):
rgb1 = nn.resize(rgb1, (224, 224))
rgb1 = self.normalize(rgb1)
image_z_1 = clip_model.encode_image(rgb1)
rgb2 = nn.resize(rgb2, (224, 224))
rgb2 = self.normalize(rgb2)
image_z_2 = clip_model.encode_image(rgb2)
image_z_1 = (image_z_1 / image_z_1.norm(dim=(- 1), keepdim=True))
image_z_2 = (image_z_2 / image_z_2.norm(dim=(- 1), keepdim=True))
loss = (- (image_z_1 * image_z_2).sum((- 1)).mean())
return loss
def img_text_clip_loss(self, clip_model, rgb, prompt):
rgb = nn.resize(rgb, (224, 224))
rgb = self.normalize(rgb)
image_z_1 = clip_model.encode_image(rgb)
image_z_1 = (image_z_1 / image_z_1.norm(dim=(- 1), keepdim=True))
text = clip.tokenize(prompt) # .to(self.device)
text_z = clip_model.encode_text(text)
text_z = (text_z / text_z.norm(dim=(- 1), keepdim=True))
loss = (- (image_z_1 * text_z).sum((- 1)).mean())
return loss
def train_step(self, text_embeddings, pred_rgb, ref_rgb=None, noise=None, islarge=False, ref_text=None, clip_model=None, guidance_scale=10, step=-1):
loss = 0
imgs = None
pred_rgb_512 = nn.interpolate(pred_rgb, (512, 512), mode='bilinear', align_corners=False)
t = jt.randint(self.min_step, (self.max_step + 1), [1], dtype='int32')
w_ = 1.0
latents = self.encode_imgs(pred_rgb_512)
with jt.no_grad():
# noise = randn_tensor(latents.shape, seed, dtype=latents.dtype)
noise = jt.randn_like(latents)
latents_noisy = self.scheduler.add_noise(latents, noise, t)
latent_model_input = jt.concat(([latents_noisy] * 2))
latent_model_input = latent_model_input.detach().start_grad()
noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
(noise_pred_uncond, noise_pred_text) = noise_pred.chunk(2)
noise_pred = (noise_pred_text + (guidance_scale * (noise_pred_text - noise_pred_uncond)))
if not islarge and (t / self.num_train_timesteps) <= 0.4:
self.scheduler.set_timesteps(self.num_train_timesteps)
de_latents = self.scheduler.step(noise_pred, t, latents_noisy)['prev_sample']
imgs = self.decode_latents(de_latents)
loss = 10 * self.img_clip_loss(clip_model, imgs, ref_rgb) + \
10 * self.img_text_clip_loss(clip_model, imgs, ref_text)
else:
w = (1 - self.alphas[t])
grad = ((w * (noise_pred - noise)) * w_)
imgs = None
loss = backward_fun(latents, grad)
return (loss, imgs)
def produce_latents(self, text_embeddings, height=512, width=512, num_inference_steps=50, guidance_scale=7.5, latents=None):
if (latents is None):
latents = jt.randn(((text_embeddings.shape[0] // 2), self.unet.in_channels, (height // 8), (width // 8)))
self.scheduler.set_timesteps(num_inference_steps)
for (i, t) in enumerate(self.scheduler.timesteps):
latent_model_input = jt.concat(([latents] * 2))
with jt.no_grad():
noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings)['sample']
(noise_pred_uncond, noise_pred_text) = noise_pred.chunk(2)
noise_pred = (noise_pred_text + (guidance_scale * (noise_pred_text - noise_pred_uncond)))
latents = self.scheduler.step(noise_pred, t, latents)['prev_sample']
return latents
def decode_latents(self, latents):
latents = ((1 / 0.18215) * latents)
with jt.no_grad():
imgs = self.vae.decode(latents).sample
imgs = jt.clamp(((imgs / 2) + 0.5), 0, 1)
return imgs
def encode_imgs(self, imgs):
imgs = ((2 * imgs) - 1)
if self.vae.config.force_upcast:
imgs = imgs.float()
self.vae.to(dtype=jt.float32)
posterior = self.vae.encode(imgs).latent_dist
latents = (posterior.sample() * 0.18215)
return latents
def prompt_to_img(self, prompts, negative_prompts='', height=512, width=512, num_inference_steps=50, guidance_scale=7.5, latents=None):
if isinstance(prompts, str):
prompts = [prompts]
if isinstance(negative_prompts, str):
negative_prompts = [negative_prompts]
text_embeds = self.get_text_embeds(prompts, negative_prompts)
latents = self.produce_latents(text_embeds, height=height, width=width, latents=latents, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale)
imgs = self.decode_latents(latents)
return imgs
if (__name__ == '__main__'):
x=jt.randn((6,6))
x.requires_grad=True
optim=jt.nn.Adam([x],lr=0.001)
for i in range(100):
loss=backward_fun(x)
optim.backward(loss)
print(x)
optim.clip_grad_norm(max_norm=10)
optim.step()