-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdiffusion_latent.py
1586 lines (1279 loc) · 78.1 KB
/
diffusion_latent.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from audioop import reverse
from genericpath import isfile
import time
from glob import glob
from models.guided_diffusion.script_util import guided_Diffusion
from models.improved_ddpm.nn import normalization
from tqdm import tqdm
import os
import numpy as np
import cv2
from PIL import Image
import torch
from torch import nn
import torchvision.utils as tvu
from torchvision import models
import torchvision.transforms as transforms
import torch.nn.functional as F
from losses.clip_loss import CLIPLoss
import random
import copy
from models.ddpm.diffusion import DDPM
from models.improved_ddpm.script_util import i_DDPM
from utils.diffusion_utils import get_beta_schedule, denoising_step
from utils.text_dic import SRC_TRG_TXT_DIC
from losses import id_loss
from datasets.data_utils import get_dataset, get_dataloader
from configs.paths_config import DATASET_PATHS, MODEL_PATHS
from datasets.imagenet_dic import IMAGENET_DIC
class Asyrp(object):
def __init__(self, args, config, device=None):
# ----------- predefined parameters -----------#
self.args = args
self.config = config
if device is None:
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
self.device = device
self.model_var_type = config.model.var_type
betas = get_beta_schedule(
beta_start=config.diffusion.beta_start,
beta_end=config.diffusion.beta_end,
num_diffusion_timesteps=config.diffusion.num_diffusion_timesteps
)
self.betas = torch.from_numpy(betas).float().to(self.device)
self.num_timesteps = betas.shape[0]
alphas = 1.0 - betas
alphas_cumprod = np.cumprod(alphas, axis=0)
alphas_cumprod_prev = np.append(1.0, alphas_cumprod[:-1])
posterior_variance = betas * \
(1.0 - alphas_cumprod_prev) / (1.0 - alphas_cumprod)
self.alphas_cumprod = alphas_cumprod
if self.model_var_type == "fixedlarge":
self.logvar = np.log(np.append(posterior_variance[1], betas[1:]))
elif self.model_var_type == 'fixedsmall':
self.logvar = np.log(np.maximum(posterior_variance, 1e-20))
self.learn_sigma = False # it will be changed in load_pretrained_model()
# ----------- Editing txt -----------#
if self.args.edit_attr is None:
self.src_txts = self.args.src_txts
self.trg_txts = self.args.trg_txts
elif self.args.edit_attr == "attribute":
pass
else:
self.src_txts = SRC_TRG_TXT_DIC[self.args.edit_attr][0]
self.trg_txts = SRC_TRG_TXT_DIC[self.args.edit_attr][1]
def load_pretrained_model(self):
# ----------- Model -----------#
if self.config.data.dataset == "LSUN":
if self.config.data.category == "bedroom":
url = "https://image-editing-test-12345.s3-us-west-2.amazonaws.com/checkpoints/bedroom.ckpt"
elif self.config.data.category == "church_outdoor":
url = "https://image-editing-test-12345.s3-us-west-2.amazonaws.com/checkpoints/church_outdoor.ckpt"
elif self.config.data.dataset in ["CelebA_HQ", "CUSTOM", "CelebA_HQ_Dialog"]:
url = "https://image-editing-test-12345.s3-us-west-2.amazonaws.com/checkpoints/celeba_hq.ckpt"
elif self.config.data.dataset in ["FFHQ", "AFHQ", "IMAGENET", "MetFACE"]:
# get the model ["FFHQ", "AFHQ", "MetFACE"] from
# https://1drv.ms/u/s!AkQjJhxDm0Fyhqp_4gkYjwVRBe8V_w?e=Et3ITH
# reference : ILVR (https://arxiv.org/abs/2108.02938), P2 weighting (https://arxiv.org/abs/2204.00227)
# reference github : https://github.com/jychoi118/ilvr_adm , https://github.com/jychoi118/P2-weighting
# get the model "IMAGENET" from
# https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt
# reference : ADM (https://arxiv.org/abs/2105.05233)
pass
else:
# if you want to use LSUN-horse, LSUN-cat -> https://github.com/openai/guided-diffusion
# if you want to use CUB, Flowers -> https://1drv.ms/u/s!AkQjJhxDm0Fyhqp_4gkYjwVRBe8V_w?e=Et3ITH
raise ValueError
if self.config.data.dataset in ["CelebA_HQ", "LSUN", "CelebA_HQ_Dialog"]:
model = DDPM(self.config)
if self.args.model_path:
init_ckpt = torch.load(self.args.model_path)
else:
init_ckpt = torch.hub.load_state_dict_from_url(url, map_location=self.device)
self.learn_sigma = False
print("Original diffusion Model loaded.")
elif self.config.data.dataset in ["FFHQ", "AFHQ", "IMAGENET"]:
model = i_DDPM(self.config.data.dataset) #Get_h(self.config, model="i_DDPM", layer_num=self.args.get_h_num) #
if self.args.model_path:
init_ckpt = torch.load(self.args.model_path)
else:
init_ckpt = torch.load(MODEL_PATHS[self.config.data.dataset])
self.learn_sigma = True
print("Improved diffusion Model loaded.")
elif self.config.data.dataset in ["MetFACE"]:
model = guided_Diffusion(self.config.data.dataset)
init_ckpt = torch.load(MODEL_PATHS[self.config.data.dataset])
self.learn_sigma = True
else:
print('Not implemented dataset')
raise ValueError
model.load_state_dict(init_ckpt, strict=False)
return model
def run_training(self):
print("Running Training...")
# ----------- Losses -----------#
# We tried to use ID loss and it works well.
# But it is not used in the paper because it is not necessary.
# We just leave the code here for future research.
if self.args.use_id_loss:
id_loss_func = id_loss.IDLoss().to(self.device)
# Set self.t_edit & self.t_addnoise & return cosine similarity of attribute
cosine, clip_loss_func = self.set_t_edit_t_addnoise(LPIPS_th=self.args.lpips_edit_th,
LPIPS_addnoise_th=self.args.lpips_addnoise_th,
return_clip_loss=True)
clip_loss_func = clip_loss_func.to(self.device)
# For memory
for p in clip_loss_func.parameters():
p.requires_grad = False
for p in clip_loss_func.model.parameters():
p.requires_grad = False
# ----------- Get seq -----------#
if self.args.n_train_step != 0:
# do not need to train T~0
seq_train = np.linspace(0, 1, self.args.n_train_step) * self.args.t_0
seq_train = seq_train[seq_train >= self.t_edit]
seq_train = [int(s+1e-6) for s in list(seq_train)] # for float to int
print('Uniform skip type')
else:
seq_train = list(range(self.t_edit, self.args.t_0))
print('No skip')
seq_train_next = [-1] + list(seq_train[:-1])
# it is for sampling
seq_test = np.linspace(0, 1, self.args.n_train_step) * self.args.t_0
seq_test = [int(s+1e-6) for s in list(seq_test)]
seq_test_next = [-1] + list(seq_test[:-1])
# ----------- Model -----------#
model = self.load_pretrained_model()
optim_param_list = []
delta_h_dict = {}
for i in seq_train:
delta_h_dict[i] = None
if self.args.train_delta_block:
model.setattr_layers(self.args.get_h_num)
print("Setattr layers")
model = model.to(self.device)
model = torch.nn.DataParallel(model)
for i in range(self.args.get_h_num):
get_h = getattr(model.module, f"layer_{i}")
optim_param_list = optim_param_list + list(get_h.parameters())
elif self.args.train_delta_h:
# h_dim is hard coded to be 512
# It can be converted to get automatically
if self.args.ignore_timesteps:
delta_h_dict[0] = torch.nn.Parameter(torch.randn((512, 8, 8))*0.2) # initialization of delta_h
else:
for i in seq_train:
delta_h_dict[i] = torch.nn.Parameter(torch.randn((512, 8, 8))*0.2) # initialization of delta_h
model = model.to(self.device)
model = torch.nn.DataParallel(model)
for key in delta_h_dict.keys():
optim_param_list = optim_param_list + [delta_h_dict[key]]
# optim_ft = torch.optim.Adam(optim_get_h_list, weight_decay=0, lr=self.args.lr_latent_clr)
optim_ft = torch.optim.SGD(optim_param_list, weight_decay=0, lr=self.args.lr_training)
scheduler_ft = torch.optim.lr_scheduler.StepLR(optim_ft, step_size=self.args.scheduler_step_size, gamma=self.args.sch_gamma)
print(f"Setting optimizer with lr={self.args.lr_training}")
# hs_coeff[0] is for original h, hs_coeff[1] is for delta_h
# if you want to train multiple delta_h at once, you have to modify this part.
hs_coeff = (1.0, 1.0)
# ----------- Pre-compute -----------#
print("Prepare identity latent...")
if self.args.load_random_noise:
# get Random noise xT
img_lat_pairs_dic = self.random_noise_pairs(model, saved_noise=self.args.saved_random_noise, save_imgs=self.args.save_precomputed_images)
else:
# get Real image xT
img_lat_pairs_dic = self.precompute_pairs(model, self.args.save_precomputed_images)
if self.args.just_precompute:
# if you just want to precompute, you can stop here.
print("Pre-computed done.")
return
# if you want to train with specific image, you can use this part.
if self.args.target_image_id:
self.args.target_image_id = self.args.target_image_id.split(" ")
self.args.target_image_id = [int(i) for i in self.args.target_image_id]
# ----------- Training -----------#
for it_out in range(self.args.start_iter_when_you_use_pretrained ,self.args.n_iter):
exp_id = os.path.split(self.args.exp)[-1]
if self.args.load_from_checkpoint:
save_name = f'checkpoint/{self.args.load_from_checkpoint}_LC_{self.config.data.category}_t{self.args.t_0}_ninv{self.args.n_inv_step}_ngen{self.args.n_train_step}_{it_out}.pth'
else:
save_name = f'checkpoint/{exp_id}_{it_out}.pth'
# train set
if self.args.do_train:
save_image_iter = 0
save_model_iter_from_noise = 0
if self.args.retrain==0 and os.path.exists(save_name):
# load checkpoint
print(f'{save_name} already exists. load checkpoint')
self.args.retrain = 0
optim_ft.load_state_dict(torch.load(save_name)["optimizer"])
scheduler_ft.load_state_dict(torch.load(save_name)["scheduler"])
scheduler_ft.step()
#print lr of now
print(f"Loaded lr={optim_ft.param_groups[0]['lr']}")
# get_h_num default is 0;
if self.args.train_delta_block:
for i in range(self.args.get_h_num):
get_h = getattr(model.module, f"layer_{i}")
get_h.load_state_dict(torch.load(save_name)[f"{i}"])
if self.args.train_delta_h:
for i in delta_h_dict.keys():
delta_h_dict[i] = torch.load(save_name)[f"{i}"]
continue
else:
# Unfortunately, ima_lat_pairs_dic does not match with batch_size
# I'm sorry but you have to get ima_lat_pairs_dic with batch_size == 1
x_lat_tensor = None
x0_tensor = None
for step, (x0, _, x_lat) in enumerate(img_lat_pairs_dic['train']):
if self.args.target_image_id:
assert self.args.bs_train == 1, "target_image_id is only supported for batch_size == 1"
if not step in self.args.target_image_id:
continue
if x_lat_tensor is None:
x_lat_tensor = x_lat
if self.args.use_x0_tensor:
x0_tensor = x0
else:
x_lat_tensor = torch.cat((x_lat_tensor, x_lat), dim=0)
if self.args.use_x0_tensor:
x0_tensor = torch.cat((x0_tensor, x0), dim=0)
if (step+1) % self.args.bs_train != 0:
continue
# LoL. now x_lat_tensor has batch_size == bs_train
# torch.cuda.empty.cache()
model.train()
# For memory
for p in model.module.parameters():
p.requires_grad = False
if self.args.train_delta_block:
for i in range(self.args.get_h_num):
get_h = getattr(model.module, f"layer_{i}")
for p in get_h.parameters():
p.requires_grad = True
time_in_start = time.time()
# original DDIM
x_origin = x_lat_tensor.to(self.device)
# editing by Asyrp
xt_next = x_lat_tensor.to(self.device)
# Finally, go into training
with tqdm(total=len(seq_train), desc=f"training iteration") as progress_bar:
for t_it, (i, j) in enumerate(zip(reversed(seq_train), reversed(seq_train_next))):
optim_ft.zero_grad()
t = (torch.ones(self.args.bs_train) * i).to(self.device)
t_next = (torch.ones(self.args.bs_train) * j).to(self.device)
# step 1: Asyrp
xt_next, x0_t, _, _ = denoising_step(xt_next.detach(), t=t, t_next=t_next, models=model,
logvars=self.logvar,
b=self.betas,
sampling_type=self.args.sample_type,
eta=0.0,
learn_sigma=self.learn_sigma,
index=0 if not (self.args.image_space_noise_optim or self.args.image_space_noise_optim_delta_block) else None,
t_edit = self.t_edit,
hs_coeff=hs_coeff,
delta_h= delta_h_dict[0] if (self.args.ignore_timesteps and self.args.train_delta_h) else delta_h_dict[t[0].item()],
ignore_timestep=self.args.ignore_timesteps,
)
# when train delta_block, delta_h is None (ignored)
# step 2: DDIM
with torch.no_grad():
x_origin, x0_t_origin, _, _ = denoising_step(x_origin.detach(), t=t, t_next=t_next, models=model,
logvars=self.logvar,
b=self.betas,
sampling_type=self.args.sample_type,
eta=0.0,
learn_sigma=self.learn_sigma,
)
progress_bar.update(1)
loss = 0
loss_id = 0
loss_l1 = 0
loss_clr = 0
loss_clip = 0
# L1 loss
loss_l1 += nn.L1Loss()(x0_t, x0_t_origin)
# Following DiffusionCLIP, we use direction clip loss as below
loss_clip = -torch.log((2 - clip_loss_func(x0, self.src_txts[0], x0_t, self.trg_txts[0])) / 2)
if self.args.use_id_loss:
# We don't use this.
loss_id += torch.mean(id_loss_func(x0_t, x0_t_origin))
loss += self.args.id_loss_w * loss_id
loss += self.args.l1_loss_w * loss_l1 * cosine
loss += self.args.clip_loss_w * loss_clip
loss.backward()
optim_ft.step()
progress_bar.set_description(f"{step}-{it_out}: loss_clr: {loss_clr:.3f} loss_l1: {loss_l1:.3f} loss_id: {loss_id:.3f} loss_clip:{loss_clip} loss: {loss:.3f} ")
# save image
if self.args.save_train_image and save_image_iter % self.args.save_train_image_step == 0 and it_out % self.args.save_train_image_iter == 0:
self.save_image(model, x_lat_tensor, seq_test, seq_test_next,
save_x0 = self.args.save_x0, save_x_origin = self.args.save_x_origin,
x0_tensor=x0_tensor, delta_h_dict=delta_h_dict,
folder_dir=self.args.training_image_folder,
file_name=f'train_{step}_{it_out}', hs_coeff=hs_coeff,
)
if self.args.save_checkpoint_during_iter and save_image_iter % self.args.save_checkpoint_step ==0:
dicts = {}
if self.args.train_delta_block:
for i in range(self.args.get_h_num):
get_h = getattr(model.module, f"layer_{i}")
dicts[f"{i}"] = get_h.state_dict()
if self.args.train_delta_h:
for key in delta_h_dict.keys():
dicts[f"{key}"] = delta_h_dict[key]
save_name_tmp = save_name.split('.pth')[0] + "_" + str(save_model_iter_from_noise) + '.pth'
torch.save(dicts, save_name_tmp)
print(f'Model {save_name_tmp} is saved.')
save_model_iter_from_noise += 1
time_in_end = time.time()
print(f"Training for 1 step {time_in_end - time_in_start:.4f}s")
if step == self.args.n_train_img - 1:
break
save_image_iter += 1
x_lat_tensor = None
x0_tensor = None
# ------------------ Save ------------------#
dicts = {}
if self.args.train_delta_block:
for i in range(self.args.get_h_num):
get_h = getattr(model.module, f"layer_{i}")
dicts[f"{i}"] = get_h.state_dict()
if self.args.train_delta_h:
for key in delta_h_dict.keys():
dicts[f"{key}"] = delta_h_dict[key]
dicts["optimizer"] = optim_ft.state_dict()
dicts["scheduler"] = scheduler_ft.state_dict()
torch.save(dicts, save_name)
print(f'Model {save_name} is saved.')
scheduler_ft.step()
if self.args.save_checkpoint_only_last_iter:
if os.path.exists(f'checkpoint/{exp_id}_{it_out - 1}.pth'):
os.remove(f'checkpoint/{exp_id}_{it_out - 1}.pth')
# ------------------ Test ------------------#
if self.args.do_test:
x_lat_tensor = None
x0_tensor = None
for step, (x0, _, x_lat) in enumerate(img_lat_pairs_dic['test']):
if x_lat_tensor is None:
x_lat_tensor = x_lat
if self.args.use_x0_tensor:
x0_tensor = x0
else:
x_lat_tensor = torch.cat((x_lat_tensor, x_lat), dim=0)
if self.args.use_x0_tensor:
x0_tensor = torch.cat((x0_tensor, x0), dim=0)
if (step+1) % self.args.bs_train != 0:
continue
self.save_image(model, x_lat_tensor, seq_test, seq_test_next,
save_x0 = self.args.save_x0, save_x_origin = self.args.save_x_origin,
x0_tensor=x0_tensor, delta_h_dict=delta_h_dict,
folder_dir=self.args.test_image_folder,
file_name=f'test_{step}_{self.args.n_iter - 1}', hs_coeff=hs_coeff,
)
if step == self.args.n_test_img - 1:
break
save_image_iter += 1
x_lat_tensor = None
x0_tensor = None
@torch.no_grad()
def save_image(self, model, x_lat_tensor, seq_inv, seq_inv_next,
save_x0 = False, save_x_origin = False,
save_process_delta_h = False, save_process_origin = False,
x0_tensor = None, delta_h_dict=None, get_delta_hs=False,
folder_dir="", file_name="", hs_coeff=(1.0,1.0),
image_space_noise_dict=None):
if save_process_origin or save_process_delta_h:
os.makedirs(os.path.join(folder_dir,file_name), exist_ok=True)
process_num = int(save_x_origin) + (len(hs_coeff) if isinstance(hs_coeff, list) else 1)
with tqdm(total=len(seq_inv)*(process_num), desc=f"Generative process") as progress_bar:
time_s = time.time()
x_list = []
if save_x0:
if x0_tensor is not None:
x_list.append(x0_tensor.to(self.device))
if save_x_origin:
# No delta h
x = x_lat_tensor.clone().to(self.device)
for it, (i, j) in enumerate(zip(reversed((seq_inv)), reversed((seq_inv_next)))):
t = (torch.ones(self.args.bs_train) * i).to(self.device)
t_next = (torch.ones(self.args.bs_train) * j).to(self.device)
x, x0_t, _, _ = denoising_step(x, t=t, t_next=t_next, models=model,
logvars=self.logvar,
sampling_type= self.args.sample_type,
b=self.betas,
learn_sigma=self.learn_sigma,
eta=1.0 if (self.args.origin_process_addnoise and t[0]<self.t_addnoise) else 0.0,
)
progress_bar.update(1)
if save_process_origin:
output = torch.cat([x, x0_t], dim=0)
output = (output + 1) * 0.5
grid = tvu.make_grid(output, nrow=self.args.bs_train, padding=1)
tvu.save_image(grid, os.path.join(folder_dir, file_name, f'origin_{int(t[0].item())}.png'), normalization=True)
x_list.append(x)
if self.args.pass_editing:
pass
else:
if not isinstance(hs_coeff, list):
hs_coeff = [hs_coeff]
for hs_coeff_tuple in hs_coeff:
x = x_lat_tensor.clone().to(self.device)
for it, (i, j) in enumerate(zip(reversed((seq_inv)), reversed((seq_inv_next)))):
t = (torch.ones(self.args.bs_train) * i).to(self.device)
t_next = (torch.ones(self.args.bs_train) * j).to(self.device)
x, x0_t, delta_h, _ = denoising_step(x, t=t, t_next=t_next, models=model,
logvars=self.logvar,
sampling_type=self.args.sample_type,
b=self.betas,
learn_sigma=self.learn_sigma,
index=self.args.get_h_num-1 if not (self.args.image_space_noise_optim or self.args.image_space_noise_optim_delta_block) else None,
eta=1.0 if t[0]<self.t_addnoise else 0.0,
t_edit= self.t_edit,
hs_coeff=hs_coeff_tuple,
delta_h=None if get_delta_hs else delta_h_dict[0] if (self.args.ignore_timesteps and self.args.train_delta_h) else delta_h_dict[int(t[0].item())] if t[0]>= self.t_edit else None,
ignore_timestep=self.args.ignore_timesteps,
dt_lambda=self.args.dt_lambda,
warigari=self.args.warigari,
)
progress_bar.update(1)
if save_process_delta_h:
output = torch.cat([x, x0_t], dim=0)
output = (output + 1) * 0.5
grid = tvu.make_grid(output, nrow=self.args.bs_train, padding=1)
tvu.save_image(grid, os.path.join(folder_dir, file_name, f'delta_h_{int(t[0].item())}.png'), normalization=True)
if get_delta_hs and t[0]>= self.t_edit:
if delta_h_dict[t[0].item()] is None:
delta_h_dict[t[0].item()] = delta_h
else:
delta_h_dict[int(t[0].item())] = delta_h_dict[int(t[0].item())] + delta_h
x_list.append(x)
x = torch.cat(x_list, dim=0)
x = (x + 1) * 0.5
grid = tvu.make_grid(x, nrow=self.args.bs_train, padding=1)
tvu.save_image(grid, os.path.join(folder_dir, f'{file_name}_ngen{self.args.n_train_step}.png'), normalization=True)
time_e = time.time()
print(f'{time_e - time_s} seconds, {file_name}_ngen{self.args.n_train_step}.png is saved')
# test
@torch.no_grad()
def run_test(self):
print("Running Test")
# Set self.t_edit & self.t_addnoise & return cosine similarity of attribute
cosine = self.set_t_edit_t_addnoise(LPIPS_th=self.args.lpips_edit_th,
LPIPS_addnoise_th=self.args.lpips_addnoise_th,
return_clip_loss=False)
# ----------- Get seq -----------#
# For editing timesteps
if self.args.n_train_step != 0:
seq_train = np.linspace(0, 1, self.args.n_train_step) * self.args.t_0
seq_train = seq_train[seq_train >= self.t_edit]
seq_train = [int(s+1e-6) for s in list(seq_train)]
print('Uniform skip type')
else:
seq_train = list(range(self.t_edit, self.args.t_0))
print('No skip')
seq_train_next = [-1] + list(seq_train[:-1])
# For sampling
seq_test = np.linspace(0, 1, self.args.n_test_step) * self.args.t_0
seq_test_edit = seq_test[seq_test >= self.t_edit]
seq_test_edit = [int(s+1e-6) for s in list(seq_test_edit)]
seq_test = [int(s+1e-6) for s in list(seq_test)]
seq_test_next = [-1] + list(seq_test[:-1])
# ----------- Model -----------#
model = self.load_pretrained_model()
# init delta_h_dict.
delta_h_dict = {}
for i in seq_train:
delta_h_dict[i] = None
if self.args.train_delta_block:
model.setattr_layers(self.args.get_h_num)
print("Setattr layers")
model = model.to(self.device)
model = torch.nn.DataParallel(model)
exp_id = os.path.split(self.args.exp)[-1]
if self.args.load_from_checkpoint:
# load_from_checkpoint is exp_id
save_name = f'checkpoint/{self.args.load_from_checkpoint}_LC_{self.config.data.category}_t{self.args.t_0}_ninv{self.args.n_inv_step}_ngen{self.args.n_train_step}_{self.args.n_iter - 1}.pth'
else:
save_name = f'checkpoint/{exp_id}_{self.args.n_iter - 1}.pth'
if self.args.manual_checkpoint_name:
# manual_checkpoint_name is full name of checkpoint
save_name = 'checkpoint/' + self.args.manual_checkpoint_name
elif self.args.choose_checkpoint_num:
# choose the iter of checkpoint
if self.args.load_from_checkpoint:
save_name = f'checkpoint/{self.args.load_from_checkpoint}_LC_{self.config.data.category}_t{self.args.t_0}_ninv{self.args.n_inv_step}_ngen{self.args.n_train_step}_{self.args.n_iter - 1}_{self.args.choose_checkpoint_num}.pth'
else:
save_name = f'checkpoint/{exp_id}_{self.args.n_iter - 1}_{self.args.choose_checkpoint_num}.pth'
# For global delta h
if self.args.num_mean_of_delta_hs:
# already exist then load
if os.path.isfile(f"checkpoint_latent/{exp_id}_{self.args.n_test_step}_{self.args.num_mean_of_delta_hs}.pth"):
save_name = f"checkpoint_latent/{exp_id}_{self.args.n_test_step}_{self.args.num_mean_of_delta_hs}.pth"
load_dict = True
delta_h_dict = {}
for i in seq_test:
delta_h_dict[i] = None
# not exist then create
else:
load_dict = False
scaling_factor = self.args.n_train_step / self.args.n_test_step * self.args.hs_coeff_delta_h
# multi attribute
# It need to be updated multiple attr cosine & t_edit & t_addnoise
if self.args.multiple_attr:
multi_attr_list = self.args.multiple_attr.split(' ')
if self.args.multiple_hs_coeff:
multi_coeff_list = self.args.multiple_hs_coeff.split(' ')
multi_coeff_list = [float(c) for c in multi_coeff_list]
multi_coeff_list = multi_coeff_list + [1.0] * (len(multi_attr_list) - len(multi_coeff_list))
else:
multi_coeff_list = [1.0] * len(multi_attr_list)
save_name_list = []
max_cosine = 0
max_attr = ""
for attribute in multi_attr_list:
save_name_list.append(save_name.replace('attribute', attribute))
self.src_txts = SRC_TRG_TXT_DIC[attribute][0]
self.trg_txts = SRC_TRG_TXT_DIC[attribute][1]
cosine = self.set_t_edit_t_addnoise(LPIPS_th=self.args.lpips_edit_th, LPIPS_addnoise_th=self.args.lpips_addnoise_th, return_clip_loss=False)
if cosine > max_cosine:
max_cosine = cosine
max_attr = attribute
print(f"Max cosine: {max_cosine}, Max attribute: {max_attr}")
self.src_txts = SRC_TRG_TXT_DIC[max_attr][0]
self.trg_txts = SRC_TRG_TXT_DIC[max_attr][1]
cosine = self.set_t_edit_t_addnoise(LPIPS_th=self.args.lpips_edit_th, LPIPS_addnoise_th=self.args.lpips_addnoise_th, return_clip_loss=False)
hs_coeff = [1.0 * self.args.hs_coeff_origin_h] + [1.0 / (len(multi_attr_list))**(0.5) * scaling_factor * coeff for coeff in multi_coeff_list]
hs_coeff = tuple(hs_coeff)
else:
save_name_list = [save_name]
hs_coeff = (1.0 * self.args.hs_coeff_origin_h, 1.0 * scaling_factor)
# Most come here
if os.path.exists(save_name_list[0]):
# load checkpoint
print(f'{save_name} exists. load checkpoint')
if self.args.train_delta_block:
# for convince of num_mean_of_delta_hs. I've forgotten right parameters a lot of times.
if self.args.num_mean_of_delta_hs and load_dict:
self.args.train_delta_h = True
self.args.train_delta_block = False
self.args.num_mean_of_delta_hs = 0
# delta_block load
else:
for i in range(self.args.get_h_num):
get_h = getattr(model.module, f"layer_{i}")
get_h.load_state_dict(torch.load(save_name_list[i])[f"{0}"])
if self.args.train_delta_h:
saved_dict = torch.load(save_name_list[0])
if self.args.ignore_timesteps: # global delta h is delta_h_dict[0]
try:
delta_h_dict[0] = saved_dict[f"{0}"]
except:
delta_h_dict[0] = saved_dict[0]
else:
for i in delta_h_dict.keys():
try:
delta_h_dict[i] = saved_dict[f"{i}"]
except:
delta_h_dict[i] = saved_dict[i]
else:
if self.args.num_mean_of_delta_hs:
print("There in no pre-computed mean of delta_hs! Now compute it...")
else:
print(f"checkpoint({save_name}) does not exist!")
exit()
# Scaling
if self.args.n_train_step != self.args.n_test_step:
if self.args.train_delta_h:
trained_idx = 0
test_delta_h_dict = {}
if self.args.ignore_timesteps:
test_delta_h_dict[0] = delta_h_dict[0]
interval_seq = (seq_train[1] - seq_train[0])
if not load_dict:
for i in seq_test_edit:
test_delta_h_dict[i] = delta_h_dict[seq_train[trained_idx]]
if i > seq_train[trained_idx] - interval_seq:
if trained_idx < len(seq_train) - 1:
trained_idx += 1
del delta_h_dict
delta_h_dict = test_delta_h_dict
else:
for i in seq_test:
delta_h_dict[i] = None
# For interpolation
if self.args.delta_interpolation:
if self.args.multiple_attr:
assert self.args.get_h_num == 2, "delta_multiple_attr_interpolation is only supported for get_h_num == 2"
interpolation_vals = np.linspace(self.args.min_delta, self.args.max_delta, self.args.num_delta)
interpolation_vals = interpolation_vals.tolist()
hs_coeff = list(hs_coeff)
hs_coeff_list = []
for val_1 in interpolation_vals:
for val_2 in interpolation_vals:
coeff_tuple = (1.0, val_1*hs_coeff[1], val_2*hs_coeff[2])
hs_coeff_list.append(coeff_tuple)
del hs_coeff
hs_coeff = hs_coeff_list
else:
interpolation_vals = np.linspace(self.args.min_delta, self.args.max_delta, self.args.num_delta)
interpolation_vals = interpolation_vals.tolist()
hs_coeff_list = []
for val in interpolation_vals:
coeff_tuple = [val*elem for elem in hs_coeff]
coeff_tuple[0] = 1.0
hs_coeff_list.append(tuple(coeff_tuple))
del hs_coeff
hs_coeff = hs_coeff_list
if self.args.num_mean_of_delta_hs:
assert self.args.bs_train == 1, "if you want to use mean, batch_size must be 1"
# ----------- Pre-compute -----------#
print("Prepare identity latent...")
# get xT
if self.args.load_random_noise:
img_lat_pairs_dic = self.random_noise_pairs(model, saved_noise=self.args.saved_random_noise, save_imgs=self.args.save_precomputed_images)
else:
img_lat_pairs_dic = self.precompute_pairs(model, self.args.save_precomputed_images)
if self.args.target_image_id:
self.args.target_image_id = self.args.target_image_id.split(" ")
self.args.target_image_id = [int(i) for i in self.args.target_image_id]
# Unfortunately, ima_lat_pairs_dic does not match with batch_size
x_lat_tensor = None
x0_tensor = None
model.eval()
# Train set
if self.args.do_train:
for step, (x0, _, x_lat) in enumerate(img_lat_pairs_dic['train']):
if self.args.target_image_id:
assert self.args.bs_train == 1, "target_image_id is only supported for batch_size == 1"
if not step in self.args.target_image_id:
continue
if self.args.start_image_id > step:
continue
if x_lat_tensor is None:
x_lat_tensor = x_lat
if self.args.use_x0_tensor:
x0_tensor = x0
else:
x_lat_tensor = torch.cat((x_lat_tensor, x_lat), dim=0)
if self.args.use_x0_tensor:
x0_tensor = torch.cat((x0_tensor, x0), dim=0)
if (step+1) % self.args.bs_train != 0:
continue
self.save_image(model, x_lat_tensor, seq_test, seq_test_next,
save_x0 = self.args.save_x0, save_x_origin = self.args.save_x_origin,
x0_tensor=x0_tensor, delta_h_dict=delta_h_dict,
folder_dir=self.args.test_image_folder, get_delta_hs=self.args.num_mean_of_delta_hs,
save_process_origin=self.args.save_process_origin, save_process_delta_h=self.args.save_process_delta_h,
file_name=f'train_{step}_{self.args.n_iter - 1}', hs_coeff=hs_coeff,
)
if step == self.args.n_train_img - 1:
break
# if mean_of_delta_hs is not exist,
if step == self.args.num_mean_of_delta_hs -1:
for keys in delta_h_dict.keys():
if delta_h_dict[keys] is None:
continue
delta_h_dict[keys] = delta_h_dict[keys]/(step+1)
sumation_delta_h = None
sumation_num = 0
for keys in delta_h_dict.keys():
if sumation_delta_h is None:
sumation_delta_h = copy.deepcopy(delta_h_dict[keys])
sumation_num = 1
else:
if delta_h_dict[keys] is None:
continue
sumation_delta_h += delta_h_dict[keys]
sumation_num += 1
# if ignore_timesteps, only use delta_h_dict[0]
delta_h_dict[0] = sumation_delta_h/sumation_num
torch.save(delta_h_dict, f'checkpoint_latent/{exp_id}_{self.args.n_test_step}_{self.args.num_mean_of_delta_hs}.pth')
print(f'Dict: checkpoint_latent/{exp_id}_{self.args.n_test_step}_{self.args.num_mean_of_delta_hs}.pth is saved.')
self.args.num_mean_of_delta_hs = 0
print("now we use mean of delta_hs")
x_lat_tensor = None
# Test set
if self.args.do_test:
x_lat_tensor = None
for step, (x0, _, x_lat) in enumerate(img_lat_pairs_dic['test']):
if self.args.target_image_id:
assert self.args.bs_train == 1, "target_image_id is only supported for batch_size == 1"
if not step in self.args.target_image_id:
continue
if self.args.start_image_id > step:
continue
if x_lat_tensor is None:
x_lat_tensor = x_lat
if self.args.use_x0_tensor:
x0_tensor = x0
else:
x_lat_tensor = torch.cat((x_lat_tensor, x_lat), dim=0)
if self.args.use_x0_tensor:
x0_tensor = torch.cat((x0_tensor, x0), dim=0)
if (step+1) % self.args.bs_train != 0:
continue
self.save_image(model, x_lat_tensor, seq_test, seq_test_next,
save_x0 = self.args.save_x0, save_x_origin = self.args.save_x_origin,
x0_tensor=x0_tensor, delta_h_dict=delta_h_dict,
folder_dir=self.args.test_image_folder, get_delta_hs=self.args.num_mean_of_delta_hs,
save_process_origin=self.args.save_process_origin, save_process_delta_h=self.args.save_process_delta_h,
file_name=f'test_{step}_{self.args.n_iter - 1}', hs_coeff=hs_coeff,
)
if step == self.args.n_test_img - 1:
break
x_lat_tensor = None
# ----------- DiffStyle -----------#
@torch.no_grad()
def diff_style(self):
print("Style transfer starts....")
# ------------ Model ------------ #
model = self.load_pretrained_model()
model = model.to(self.device)
# ----------- Pre-compute ----------- #
content_lat_pairs = []
style_lat_pairs = []
# check if content and style dir are valid
if not os.path.isdir(self.args.content_dir):
raise ValueError("content_dir is not a valid directory")
if not os.path.isdir(self.args.style_dir):
raise ValueError("style_dir is not a valid directory")
# list all file path in self.args.content_dir
content_img_paths = [os.path.join(self.args.content_dir, f) for f in os.listdir(self.args.content_dir) if os.path.isfile(os.path.join(self.args.content_dir, f)) and not os.path.isdir(os.path.join(self.args.content_dir, f))]
style_img_paths = [os.path.join(self.args.style_dir, f) for f in os.listdir(self.args.style_dir) if os.path.isfile(os.path.join(self.args.style_dir, f)) and not os.path.isdir(os.path.join(self.args.style_dir, f))]
# precompute content latent pairs
for img_path in content_img_paths:
content_lat_pairs.append(self.precompute_pairs_with_h(model, img_path))
# precompute style latent pairs
for img_path in style_img_paths:
style_lat_pairs.append(self.precompute_pairs_with_h(model, img_path))
# ----------- Get seq -----------#
seq_inv = np.linspace(0, 1, self.args.n_inv_step) * self.args.t_0
seq_inv = [int(s+1e-6) for s in list(seq_inv)]
seq_inv_next = [-1] + list(seq_inv[:-1])
seq_train = np.linspace(0, 1, self.args.n_gen_step) * self.args.t_0
# seq_train = seq_train[seq_train >= self.args.maintain]
seq_train = [int(s+1e-6) for s in list(seq_train)]
print('Uniform skip type')
seq_train_next = [-1] + list(seq_train[:-1])
if self.args.content_replace_step and self.args.content_replace_step != -1:
seq_replace = np.linspace(0,1, self.args.content_replace_step) * self.args.t_0
seq_replace = [int(s+1e-6) for s in list(seq_replace)]
print('seq_replace: ', seq_replace)
else:
seq_replace = seq_train
if self.args.user_defined_t_edit is None:
self.args.user_defined_t_edit = 400
# ----------- save__dir ----------- #
if not os.path.exists(self.args.save_dir):
os.mkdir(self.args.save_dir)
print("save_dir created")
else:
print("save_dir exists")
# ----------- Diff style ----------- #
results_list = [style_lat_pair[0].cpu() for style_lat_pair in style_lat_pairs]
results_list.insert(0,torch.zeros_like(results_list[0]))
def take_closest(input_list, value):
#return closest value among input_list
return min(input_list, key=lambda x: abs(x-value))
inv_timesteps = sorted(list(content_lat_pairs[0][3].keys()),reverse=True)
for content_i, content_lat_pair in enumerate(content_lat_pairs):
results_list.append(content_lat_pair[0].cpu())
for style_i, style_lat_pair in enumerate(style_lat_pairs):
content_path = content_img_paths[content_i]
style_path = style_img_paths[style_i]
save_path = 'content_' + content_path.split('/')[-1].split('.')[0] + '_style_' + style_path.split('/')[-1].split('.')[0] + '.png'
save_path = os.path.join(self.args.save_dir, save_path)
X_T = None
target_img_lat_pairs = []
x_origin = [style_lat_pair[0].to('cpu')]
X_T = [style_lat_pair[2].to(self.device)]
target_img_lat_pairs = [content_lat_pair[3]]
target_img_x0_pairs = [content_lat_pair[0]]
X_T = torch.cat(X_T,dim=0)
x_origin = torch.cat(x_origin,dim=0)
target_img_x0_pairs = torch.cat(target_img_x0_pairs,dim=0)
x = X_T.clone().to(self.device)
noise_lat = X_T.clone().to(self.device)
xt_original = x
with tqdm(total=len(seq_train), desc="Inversion process with DiffStyle") as progress_bar:
for t_it, (i,j) in enumerate(zip(reversed(seq_train), reversed(seq_train_next))):
progress_bar.set_description(f"step_{t_it}")
t = (torch.ones(X_T.shape[0]) * i).to(self.device)
t_next = (torch.ones(X_T.shape[0]) * j).to(self.device)
closest_t = take_closest(inv_timesteps, i)
delta_hs = []
for target_img_lat_pair in target_img_lat_pairs:
h_tmp = target_img_lat_pair[closest_t].to(self.device)
delta_hs.append(h_tmp)
delta_hs = torch.cat(delta_hs,dim=0)
if i in seq_replace:
x, _, coeff_before, xt_original = denoising_step(x, t=t, t_next=t_next, models=model,
logvars=self.logvar,