-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerate_data.py
More file actions
860 lines (702 loc) · 34.6 KB
/
generate_data.py
File metadata and controls
860 lines (702 loc) · 34.6 KB
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
from typing import Optional, Union, Tuple, List, Dict
from tqdm import tqdm
import argparse
import os.path
import random
import abc
import os
from PIL import Image
import numpy as np
import pandas as pd
import torch
from torch.optim.adam import Adam
import torch.nn.functional as nnf
from diffusers import StableDiffusionPipeline, DDIMScheduler
from utils.imagenet_list import IMAGENET_DIC
from utils.list_subclass import sub_classes
from utils.prompts import PROMPTS
from utils import ptp_utils, seq_aligner
# /////////////// Data Loader ///////////////
IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm']
domains = ['Drawing', 'Weather', 'Color', 'Texture', 'Context']
colors = ['blue', 'cyan', 'green', 'black', 'magenta', 'red', 'white', 'yellow', 'orange']
def is_image_file(filename):
"""Checks if a file is an image.
Args:
filename (string): path to a file
Returns:
bool: True if the filename ends with a known image extension
"""
filename_lower = filename.lower()
return any(filename_lower.endswith(ext) for ext in IMG_EXTENSIONS)
def find_classes(dir, num_classes=0, sub_class=None):
if sub_class in sub_classes:
classes = sub_classes[sub_class]
elif sub_class == 'all':
num_class_per_sub_class = {'animal': 15, 'plant': 12, 'person': 3, 'vehicle': 15, 'furniture': 10,
'tool': 10, 'structure': 15, 'landscape': 10, 'food': 10}
classes = []
for sub_class, class_names in sub_classes.items():
classes.extend(random.sample(class_names, num_class_per_sub_class[sub_class]))
else:
classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]
if num_classes > 0 and num_classes < len(classes):
classes = random.sample(classes, num_classes)
output_path = f'{args.output_path}/Original'
existing_classes = [d for d in os.listdir(output_path) if os.path.isdir(os.path.join(output_path, d))]
for class_name in existing_classes:
classes.remove(class_name)
classes.sort()
class_to_idx = {classes[i]: i for i in range(len(classes))}
return classes, class_to_idx
def make_dataset(dir, class_to_idx, num_images=0):
images = []
dir = os.path.expanduser(dir)
for target in sorted(os.listdir(dir)):
d = os.path.join(dir, target)
if not os.path.isdir(d) or not target in class_to_idx.keys():
continue
target_images = []
for root, _, fnames in sorted(os.walk(d)):
for fname in sorted(fnames):
if is_image_file(fname):
path = os.path.join(root, fname)
if np.array(Image.open(path)).ndim < 3:
continue
item = (path, class_to_idx[target])
target_images.append(item)
if num_images > 0 and num_images < len(target_images):
target_images = random.sample(target_images, num_images)
images.extend(target_images)
return images
def get_subclass(class_name):
for sub_class, classes in sub_classes.items():
if class_name in classes:
return sub_class
print(f'{class_name} ({IMAGENET_DIC[class_name]}) belongs to no sub-classes!')
return 'tool'
def save_csv_log(head, value, is_create=False, file_name='test'):
if len(value.shape) < 2:
value = np.expand_dims(value, axis=0)
df = pd.DataFrame(value)
file_path = f'{args.output_path}/{file_name}.csv'
if not os.path.exists(file_path) or is_create:
df.to_csv(file_path, header=head, index=False)
else:
with open(file_path, 'a') as f:
df.to_csv(f, header=False, index=False)
def pil_loader(path):
# open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
with open(path, 'rb') as f:
img = Image.open(f)
return img.convert('RGB')
def accimage_loader(path):
import accimage
try:
return accimage.Image(path)
except IOError:
# Potentially a decoding problem, fall back to PIL.Image
return pil_loader(path)
def default_loader(path):
from torchvision import get_image_backend
if get_image_backend() == 'accimage':
return accimage_loader(path)
else:
return pil_loader(path)
class EditDataset():
def __init__(self, root, num_classes, num_images, domains, transform=None, target_transform=None,
loader=default_loader, save_original=True):
classes, class_to_idx = find_classes(root, num_classes, args.sub_class)
imgs = make_dataset(root, class_to_idx, num_images)
if len(imgs) == 0:
raise (RuntimeError("Found 0 images in subfolders of: " + root + "\n" +
"Supported image extensions are: " + ",".join(IMG_EXTENSIONS)))
self.root = root
self.domains = domains
self.imgs = imgs
self.prompts = {}
self.classes = classes
self.class_to_idx = class_to_idx
self.idx_to_class = {v: k for k, v in class_to_idx.items()}
self.transform = transform
self.target_transform = target_transform
self.loader = loader
self.save_original = save_original
def get(self, index):
path, target = self.imgs[index]
img = self.loader(path)
if self.target_transform is not None:
target = self.target_transform(target)
if self.save_original:
self.save_image(img, 'Original', target, path)
images, prompts = null_text_edit(path, domains, self.idx_to_class[target])
self.prompts[path] = prompts
for image in images:
edited_image, domain = image
self.save_image(edited_image, domain, target, path)
return 0
def __len__(self):
return len(self.imgs)
def save_image(self, image, domain, target, path):
save_path = args.output_path + '/' + domain + '/' + self.idx_to_class[target]
if not os.path.exists(save_path):
os.makedirs(save_path)
save_path += path[path.rindex('/'):]
Image.fromarray(np.uint8(image)).save(save_path, quality=85, optimize=True)
def save_log(self, domain):
head = np.array(['Class'])
for i in range(1, args.num_images + 1):
head = np.append(head, [str(i)])
images = {}
for image in self.imgs:
(path, target) = image
target = self.idx_to_class[target]
if target not in images.keys():
images[target] = []
image_name = path[path.rindex('/') + 1:]
if domain == 'Original':
images[target].append(f'{image_name}')
else:
images[target].append(f'{self.prompts[path][domain]}')
image_prompts = [images[class_name] for class_name in self.classes]
value = np.concatenate([np.array(self.classes).reshape(len(self.classes), 1), image_prompts], axis=1)
save_csv_log(head, value, is_create=True, file_name=domain)
# /////////////// Null Text Code //////////////
class LocalBlend:
def get_mask(self, maps, alpha, use_pool):
k = 1
maps = (maps * alpha).sum(-1).mean(1)
if use_pool:
maps = nnf.max_pool2d(maps, (k * 2 + 1, k * 2 +1), (1, 1), padding=(k, k))
mask = nnf.interpolate(maps, size=(x_t.shape[2:]))
mask = mask / mask.max(2, keepdims=True)[0].max(3, keepdims=True)[0]
mask = mask.gt(self.th[1-int(use_pool)])
mask = mask[:1] + mask
return mask
def __call__(self, x_t, attention_store):
self.counter += 1
if self.counter > self.start_blend:
maps = attention_store["down_cross"][2:4] + attention_store["up_cross"][:3]
maps = [item.reshape(self.alpha_layers.shape[0], -1, 1, 16, 16, MAX_NUM_WORDS) for item in maps]
maps = torch.cat(maps, dim=1)
mask = self.get_mask(maps, self.alpha_layers, True)
if self.substruct_layers is not None:
maps_sub = ~self.get_mask(maps, self.substruct_layers, False)
mask = mask * maps_sub
mask = mask.float()
x_t = x_t[:1] + mask * (x_t - x_t[:1])
return x_t
def __init__(self, prompts: List[str], words: [List[List[str]]], substruct_words=None, start_blend=0.2, th=(.3, .3)):
alpha_layers = torch.zeros(len(prompts), 1, 1, 1, 1, MAX_NUM_WORDS)
for i, (prompt, words_) in enumerate(zip(prompts, words)):
if type(words_) is str:
words_ = [words_]
for word in words_:
ind = ptp_utils.get_word_inds(prompt, word, tokenizer)
alpha_layers[i, :, :, :, :, ind] = 1
if substruct_words is not None:
substruct_layers = torch.zeros(len(prompts), 1, 1, 1, 1, MAX_NUM_WORDS)
for i, (prompt, words_) in enumerate(zip(prompts, substruct_words)):
if type(words_) is str:
words_ = [words_]
for word in words_:
ind = ptp_utils.get_word_inds(prompt, word, tokenizer)
substruct_layers[i, :, :, :, :, ind] = 1
self.substruct_layers = substruct_layers.to(device)
else:
self.substruct_layers = None
self.alpha_layers = alpha_layers.to(device)
self.start_blend = int(start_blend * NUM_DDIM_STEPS)
self.counter = 0
self.th=th
class EmptyControl:
def step_callback(self, x_t):
return x_t
def between_steps(self):
return
def __call__(self, attn, is_cross: bool, place_in_unet: str):
return attn
class AttentionControl(abc.ABC):
def step_callback(self, x_t):
return x_t
def between_steps(self):
return
@property
def num_uncond_att_layers(self):
return self.num_att_layers if LOW_RESOURCE else 0
@abc.abstractmethod
def forward (self, attn, is_cross: bool, place_in_unet: str):
raise NotImplementedError
def __call__(self, attn, is_cross: bool, place_in_unet: str):
if self.cur_att_layer >= self.num_uncond_att_layers:
if LOW_RESOURCE:
attn = self.forward(attn, is_cross, place_in_unet)
else:
h = attn.shape[0]
attn[h // 2:] = self.forward(attn[h // 2:], is_cross, place_in_unet)
self.cur_att_layer += 1
if self.cur_att_layer == self.num_att_layers + self.num_uncond_att_layers:
self.cur_att_layer = 0
self.cur_step += 1
self.between_steps()
return attn
def reset(self):
self.cur_step = 0
self.cur_att_layer = 0
def __init__(self):
self.cur_step = 0
self.num_att_layers = -1
self.cur_att_layer = 0
class SpatialReplace(EmptyControl):
def step_callback(self, x_t):
if self.cur_step < self.stop_inject:
b = x_t.shape[0]
x_t = x_t[:1].expand(b, *x_t.shape[1:])
return x_t
def __init__(self, stop_inject: float):
super(SpatialReplace, self).__init__()
self.stop_inject = int((1 - stop_inject) * NUM_DDIM_STEPS)
class AttentionStore(AttentionControl):
@staticmethod
def get_empty_store():
return {"down_cross": [], "mid_cross": [], "up_cross": [],
"down_self": [], "mid_self": [], "up_self": []}
def forward(self, attn, is_cross: bool, place_in_unet: str):
key = f"{place_in_unet}_{'cross' if is_cross else 'self'}"
if attn.shape[1] <= 32 ** 2: # avoid memory overhead
self.step_store[key].append(attn)
return attn
def between_steps(self):
if len(self.attention_store) == 0:
self.attention_store = self.step_store
else:
for key in self.attention_store:
for i in range(len(self.attention_store[key])):
self.attention_store[key][i] += self.step_store[key][i]
self.step_store = self.get_empty_store()
def get_average_attention(self):
average_attention = {key: [item / self.cur_step for item in self.attention_store[key]] for key in self.attention_store}
return average_attention
def reset(self):
super(AttentionStore, self).reset()
self.step_store = self.get_empty_store()
self.attention_store = {}
def __init__(self):
super(AttentionStore, self).__init__()
self.step_store = self.get_empty_store()
self.attention_store = {}
class AttentionControlEdit(AttentionStore, abc.ABC):
def step_callback(self, x_t):
if self.local_blend is not None:
x_t = self.local_blend(x_t, self.attention_store)
return x_t
def replace_self_attention(self, attn_base, att_replace, place_in_unet):
if att_replace.shape[2] <= 32 ** 2:
attn_base = attn_base.unsqueeze(0).expand(att_replace.shape[0], *attn_base.shape)
return attn_base
else:
return att_replace
@abc.abstractmethod
def replace_cross_attention(self, attn_base, att_replace):
raise NotImplementedError
def forward(self, attn, is_cross: bool, place_in_unet: str):
super(AttentionControlEdit, self).forward(attn, is_cross, place_in_unet)
if is_cross or (self.num_self_replace[0] <= self.cur_step < self.num_self_replace[1]):
h = attn.shape[0] // (self.batch_size)
attn = attn.reshape(self.batch_size, h, *attn.shape[1:])
attn_base, attn_repalce = attn[0], attn[1:]
if is_cross:
alpha_words = self.cross_replace_alpha[self.cur_step]
attn_repalce_new = self.replace_cross_attention(attn_base, attn_repalce) * alpha_words + (1 - alpha_words) * attn_repalce
attn[1:] = attn_repalce_new
else:
attn[1:] = self.replace_self_attention(attn_base, attn_repalce, place_in_unet)
attn = attn.reshape(self.batch_size * h, *attn.shape[2:])
return attn
def __init__(self, prompts, num_steps: int,
cross_replace_steps: Union[float, Tuple[float, float], Dict[str, Tuple[float, float]]],
self_replace_steps: Union[float, Tuple[float, float]],
local_blend: Optional[LocalBlend]):
super(AttentionControlEdit, self).__init__()
self.batch_size = len(prompts)
self.cross_replace_alpha = ptp_utils.get_time_words_attention_alpha(prompts, num_steps, cross_replace_steps, tokenizer).to(device)
if type(self_replace_steps) is float:
self_replace_steps = 0, self_replace_steps
self.num_self_replace = int(num_steps * self_replace_steps[0]), int(num_steps * self_replace_steps[1])
self.local_blend = local_blend
class AttentionReplace(AttentionControlEdit):
def replace_cross_attention(self, attn_base, att_replace):
return torch.einsum('hpw,bwn->bhpn', attn_base, self.mapper)
def __init__(self, prompts, num_steps: int, cross_replace_steps: float, self_replace_steps: float,
local_blend: Optional[LocalBlend] = None):
super(AttentionReplace, self).__init__(prompts, num_steps, cross_replace_steps, self_replace_steps, local_blend)
self.mapper = seq_aligner.get_replacement_mapper(prompts, tokenizer).to(device)
class AttentionRefine(AttentionControlEdit):
def replace_cross_attention(self, attn_base, att_replace):
attn_base_replace = attn_base[:, :, self.mapper].permute(2, 0, 1, 3)
attn_replace = attn_base_replace * self.alphas + att_replace * (1 - self.alphas)
# attn_replace = attn_replace / attn_replace.sum(-1, keepdims=True)
return attn_replace
def __init__(self, prompts, num_steps: int, cross_replace_steps: float, self_replace_steps: float,
local_blend: Optional[LocalBlend] = None):
super(AttentionRefine, self).__init__(prompts, num_steps, cross_replace_steps, self_replace_steps, local_blend)
self.mapper, alphas = seq_aligner.get_refinement_mapper(prompts, tokenizer)
self.mapper, alphas = self.mapper.to(device), alphas.to(device)
self.alphas = alphas.reshape(alphas.shape[0], 1, 1, alphas.shape[1])
class AttentionReweight(AttentionControlEdit):
def replace_cross_attention(self, attn_base, att_replace):
if self.prev_controller is not None:
attn_base = self.prev_controller.replace_cross_attention(attn_base, att_replace)
attn_replace = attn_base[None, :, :, :] * self.equalizer[:, None, None, :]
# attn_replace = attn_replace / attn_replace.sum(-1, keepdims=True)
return attn_replace
def __init__(self, prompts, num_steps: int, cross_replace_steps: float, self_replace_steps: float, equalizer,
local_blend: Optional[LocalBlend] = None, controller: Optional[AttentionControlEdit] = None):
super(AttentionReweight, self).__init__(prompts, num_steps, cross_replace_steps, self_replace_steps, local_blend)
self.equalizer = equalizer.to(device)
self.prev_controller = controller
def get_equalizer(text: str, word_select: Union[int, Tuple[int, ...]], values: Union[List[float],
Tuple[float, ...]]):
if type(word_select) is int or type(word_select) is str:
word_select = (word_select,)
equalizer = torch.ones(1, 77)
for word, val in zip(word_select, values):
inds = ptp_utils.get_word_inds(text, word, tokenizer)
equalizer[:, inds] = val
return equalizer
def aggregate_attention(attention_store: AttentionStore, res: int, from_where: List[str], is_cross: bool, select: int):
out = []
attention_maps = attention_store.get_average_attention()
num_pixels = res ** 2
for location in from_where:
for item in attention_maps[f"{location}_{'cross' if is_cross else 'self'}"]:
if item.shape[1] == num_pixels:
cross_maps = item.reshape(len(prompts), -1, res, res, item.shape[-1])[select]
out.append(cross_maps)
out = torch.cat(out, dim=0)
out = out.sum(0) / out.shape[0]
return out.cpu()
def make_controller(prompts: List[str], is_replace_controller: bool, cross_replace_steps: Dict[str, float], self_replace_steps: float, blend_words=None, equilizer_params=None) -> AttentionControlEdit:
if blend_words is None:
lb = None
else:
lb = LocalBlend(prompts, blend_word)
if is_replace_controller:
controller = AttentionReplace(prompts, NUM_DDIM_STEPS, cross_replace_steps=cross_replace_steps, self_replace_steps=self_replace_steps, local_blend=lb)
else:
controller = AttentionRefine(prompts, NUM_DDIM_STEPS, cross_replace_steps=cross_replace_steps, self_replace_steps=self_replace_steps, local_blend=lb)
if equilizer_params is not None:
eq = get_equalizer(prompts[1], equilizer_params["words"], equilizer_params["values"])
controller = AttentionReweight(prompts, NUM_DDIM_STEPS, cross_replace_steps=cross_replace_steps,
self_replace_steps=self_replace_steps, equalizer=eq, local_blend=lb, controller=controller)
return controller
def load_512(image_path, left=0, right=0, top=0, bottom=0):
if type(image_path) is str:
image = np.array(Image.open(image_path))[:, :, :3]
else:
image = image_path
h, w, c = image.shape
left = min(left, w-1)
right = min(right, w - left - 1)
top = min(top, h - left - 1)
bottom = min(bottom, h - top - 1)
image = image[top:h-bottom, left:w-right]
h, w, c = image.shape
if h < w:
offset = (w - h) // 2
image = image[:, offset:offset + h]
elif w < h:
offset = (h - w) // 2
image = image[offset:offset + w]
image = np.array(Image.fromarray(image).resize((512, 512)))
return image
class NullInversion:
def prev_step(self, model_output: Union[torch.FloatTensor, np.ndarray], timestep: int, sample: Union[torch.FloatTensor, np.ndarray]):
prev_timestep = timestep - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
alpha_prod_t = self.scheduler.alphas_cumprod[timestep]
alpha_prod_t_prev = self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod
beta_prod_t = 1 - alpha_prod_t
pred_original_sample = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
pred_sample_direction = (1 - alpha_prod_t_prev) ** 0.5 * model_output
prev_sample = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction
return prev_sample
def next_step(self, model_output: Union[torch.FloatTensor, np.ndarray], timestep: int, sample: Union[torch.FloatTensor, np.ndarray]):
timestep, next_timestep = min(timestep - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps, 999), timestep
alpha_prod_t = self.scheduler.alphas_cumprod[timestep] if timestep >= 0 else self.scheduler.final_alpha_cumprod
alpha_prod_t_next = self.scheduler.alphas_cumprod[next_timestep]
beta_prod_t = 1 - alpha_prod_t
next_original_sample = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
next_sample_direction = (1 - alpha_prod_t_next) ** 0.5 * model_output
next_sample = alpha_prod_t_next ** 0.5 * next_original_sample + next_sample_direction
return next_sample
def get_noise_pred_single(self, latents, t, context):
noise_pred = self.model.unet(latents, t, encoder_hidden_states=context)["sample"]
return noise_pred
def get_noise_pred(self, latents, t, is_forward=True, context=None):
latents_input = torch.cat([latents] * 2)
if context is None:
context = self.context
guidance_scale = 1 if is_forward else GUIDANCE_SCALE
noise_pred = self.model.unet(latents_input, t, encoder_hidden_states=context)["sample"]
noise_pred_uncond, noise_prediction_text = noise_pred.chunk(2)
noise_pred = noise_pred_uncond + guidance_scale * (noise_prediction_text - noise_pred_uncond)
if is_forward:
latents = self.next_step(noise_pred, t, latents)
else:
latents = self.prev_step(noise_pred, t, latents)
return latents
@torch.no_grad()
def latent2image(self, latents, return_type='np'):
latents = 1 / 0.18215 * latents.detach()
image = self.model.vae.decode(latents)['sample']
if return_type == 'np':
image = (image / 2 + 0.5).clamp(0, 1)
image = image.cpu().permute(0, 2, 3, 1).numpy()[0]
image = (image * 255).astype(np.uint8)
return image
@torch.no_grad()
def image2latent(self, image):
with torch.no_grad():
if type(image) is Image:
image = np.array(image)
if type(image) is torch.Tensor and image.dim() == 4:
latents = image
else:
image = torch.from_numpy(image).float() / 127.5 - 1
image = image.permute(2, 0, 1).unsqueeze(0).to(device)
latents = self.model.vae.encode(image)['latent_dist'].mean
latents = latents * 0.18215
return latents
@torch.no_grad()
def init_prompt(self, prompt: str):
uncond_input = self.model.tokenizer(
[""], padding="max_length", max_length=self.model.tokenizer.model_max_length,
return_tensors="pt"
)
uncond_embeddings = self.model.text_encoder(uncond_input.input_ids.to(self.model.device))[0]
text_input = self.model.tokenizer(
[prompt],
padding="max_length",
max_length=self.model.tokenizer.model_max_length,
truncation=True,
return_tensors="pt",
)
text_embeddings = self.model.text_encoder(text_input.input_ids.to(self.model.device))[0]
self.context = torch.cat([uncond_embeddings, text_embeddings])
self.prompt = prompt
@torch.no_grad()
def ddim_loop(self, latent):
uncond_embeddings, cond_embeddings = self.context.chunk(2)
all_latent = [latent]
latent = latent.clone().detach()
for i in range(NUM_DDIM_STEPS):
t = self.model.scheduler.timesteps[len(self.model.scheduler.timesteps) - i - 1]
noise_pred = self.get_noise_pred_single(latent, t, cond_embeddings)
latent = self.next_step(noise_pred, t, latent)
all_latent.append(latent)
return all_latent
@property
def scheduler(self):
return self.model.scheduler
@torch.no_grad()
def ddim_inversion(self, image):
latent = self.image2latent(image)
image_rec = self.latent2image(latent)
ddim_latents = self.ddim_loop(latent)
return image_rec, ddim_latents
def null_optimization(self, latents, num_inner_steps, epsilon):
uncond_embeddings, cond_embeddings = self.context.chunk(2)
uncond_embeddings_list = []
latent_cur = latents[-1]
bar = tqdm(total=num_inner_steps * NUM_DDIM_STEPS)
for i in range(NUM_DDIM_STEPS):
uncond_embeddings = uncond_embeddings.clone().detach()
uncond_embeddings.requires_grad = True
optimizer = Adam([uncond_embeddings], lr=1e-2 * (1. - i / 100.))
latent_prev = latents[len(latents) - i - 2]
t = self.model.scheduler.timesteps[i]
with torch.no_grad():
noise_pred_cond = self.get_noise_pred_single(latent_cur, t, cond_embeddings)
for j in range(num_inner_steps):
noise_pred_uncond = self.get_noise_pred_single(latent_cur, t, uncond_embeddings)
noise_pred = noise_pred_uncond + GUIDANCE_SCALE * (noise_pred_cond - noise_pred_uncond)
latents_prev_rec = self.prev_step(noise_pred, t, latent_cur)
loss = nnf.mse_loss(latents_prev_rec, latent_prev)
optimizer.zero_grad()
loss.backward()
optimizer.step()
loss_item = loss.item()
bar.update()
if loss_item < epsilon + i * 2e-5:
break
for j in range(j + 1, num_inner_steps):
bar.update()
uncond_embeddings_list.append(uncond_embeddings[:1].detach())
with torch.no_grad():
context = torch.cat([uncond_embeddings, cond_embeddings])
latent_cur = self.get_noise_pred(latent_cur, t, False, context)
bar.close()
return uncond_embeddings_list
def invert(self, image_path: str, prompt: str, offsets=(0,0,0,0), num_inner_steps=10, early_stop_epsilon=1e-5, verbose=False):
self.init_prompt(prompt)
ptp_utils.register_attention_control(self.model, None)
image_gt = load_512(image_path, *offsets)
if verbose:
print("DDIM inversion...")
image_rec, ddim_latents = self.ddim_inversion(image_gt)
if verbose:
print("Null-text optimization...")
uncond_embeddings = self.null_optimization(ddim_latents, num_inner_steps, early_stop_epsilon)
return (image_gt, image_rec), ddim_latents[-1], uncond_embeddings
def __init__(self, model):
scheduler = DDIMScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", clip_sample=False,
set_alpha_to_one=False)
self.model = model
self.tokenizer = self.model.tokenizer
self.model.scheduler.set_timesteps(NUM_DDIM_STEPS)
self.prompt = None
self.context = None
@torch.no_grad()
def text2image_ldm_stable(
model,
prompt: List[str],
controller,
num_inference_steps: int = 50,
guidance_scale: Optional[float] = 7.5,
generator: Optional[torch.Generator] = None,
latent: Optional[torch.FloatTensor] = None,
uncond_embeddings=None,
start_time=50,
return_type='image'
):
batch_size = len(prompt)
ptp_utils.register_attention_control(model, controller)
height = width = 512
text_input = model.tokenizer(
prompt,
padding="max_length",
max_length=model.tokenizer.model_max_length,
truncation=True,
return_tensors="pt",
)
text_embeddings = model.text_encoder(text_input.input_ids.to(model.device))[0]
max_length = text_input.input_ids.shape[-1]
if uncond_embeddings is None:
uncond_input = model.tokenizer(
[""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
)
uncond_embeddings_ = model.text_encoder(uncond_input.input_ids.to(model.device))[0]
else:
uncond_embeddings_ = None
latent, latents = ptp_utils.init_latent(latent, model, height, width, generator, batch_size)
model.scheduler.set_timesteps(num_inference_steps)
for i, t in enumerate(tqdm(model.scheduler.timesteps[-start_time:])):
if uncond_embeddings_ is None:
context = torch.cat([uncond_embeddings[i].expand(*text_embeddings.shape), text_embeddings])
else:
context = torch.cat([uncond_embeddings_, text_embeddings])
latents = ptp_utils.diffusion_step(model, controller, latents, context, t, guidance_scale, low_resource=False)
if return_type == 'image':
image = ptp_utils.latent2image(model.vae, latents)
else:
image = latents
return image, latent
def run_and_display(prompts, controller, latent=None, run_baseline=False, generator=None, uncond_embeddings=None, verbose=True, label=''):
if run_baseline:
print("w.o. prompt-to-prompt")
images, latent = run_and_display(prompts, EmptyControl(), latent=latent, run_baseline=False, generator=generator)
print("with prompt-to-prompt")
images, x_t = text2image_ldm_stable(ldm_stable, prompts, controller, latent=latent, num_inference_steps=NUM_DDIM_STEPS, guidance_scale=GUIDANCE_SCALE, generator=generator, uncond_embeddings=uncond_embeddings)
if verbose:
ptp_utils.view_images(images, label=f'{id}/{label}-output')
return images, x_t
# /////////////// Image Editing ///////////////
def null_text_edit(path, domains, class_name):
sub_class = get_subclass(class_name)
class_name = IMAGENET_DIC[class_name].replace("_"," ")
print(f'Editing image {path} from class {class_name} and sub-class {sub_class}')
null_inversion = NullInversion(ldm_stable)
prompt = f'A {class_name}'
_, x_t, uncond_embeddings = null_inversion.invert(path, prompt, offsets=(0,0,0,0), verbose=True)
prompts = [prompt]
controller = AttentionStore()
_, x_t = run_and_display(prompts, controller, run_baseline=False, latent=x_t, uncond_embeddings=uncond_embeddings, verbose=False)
edited_images = []
target_prompts = {}
for domain in domains:
if sub_class not in PROMPTS[domain]:
target_prompts[domain] = 'N/A'
continue
if domain == 'Color':
target_prompt = random.choice(PROMPTS[domain][sub_class]).format(random.choice(colors), class_name)
else:
target_prompt = random.choice(PROMPTS[domain][sub_class]).format(class_name)
target_prompts[domain] = target_prompt
prompts = [prompt, target_prompt]
cross_replace_steps = {'default_': .8,}
self_replace_steps = .4
blend_word = None
eq_params = None
controller = make_controller(prompts, False, cross_replace_steps, self_replace_steps, blend_word, eq_params)
images, _ = run_and_display(prompts, controller, run_baseline=False, latent=x_t, uncond_embeddings=uncond_embeddings, label=target_prompt, verbose=False)
edited_images.append((images[1], domain))
return edited_images, target_prompts
def no_edit(image, path, domains, class_name):
return image, None
# ///////////// End Image Editing /////////////
# /////////////// Further Setup ///////////////
def save_edited(dataset_path, num_classes, num_images, domains):
edited_dataset = EditDataset(
root=dataset_path,
num_classes=num_classes,
num_images=num_images,
domains=domains
)
with tqdm(enumerate(edited_dataset.imgs), total=len(edited_dataset)) as pbar:
for i, _ in pbar:
edited_dataset.get(i)
edited_dataset.save_log('Original')
for domain in edited_dataset.domains:
edited_dataset.save_log(domain)
# /////////////// End Further Setup ///////////////
# /////////////////// Main Part ///////////////////
def parse_args():
parser = argparse.ArgumentParser(description='Making edited dataset')
parser.add_argument('--dataset_path', type=str,
default='/imagenet/val', help='Path of dataset')
parser.add_argument('--output_path', type=str,
default='./data/', help='Path of the generated data')
parser.add_argument('--num_classes', type=int, default=10,
help='Number of classes to choose')
parser.add_argument('--num_images', type=int, default=10,
help='Number of images to choose in each class')
parser.add_argument('--sub_class', type=str, default=None,
help='Subclass of imagenet classes to choose')
parser.add_argument('--seed', type=int, default=1234,
help='Seed of random')
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_args()
os.makedirs(args.output_path, exist_ok=True)
random.seed(args.seed)
dataset_path = args.dataset_path
num_classes = args.num_classes
num_images = args.num_images
scheduler = DDIMScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", steps_offset=1, clip_sample=False, set_alpha_to_one=False)
# For loading the Stable Diffusion using Diffusers, follow the instructions https://huggingface.co/blog/stable_diffusion and update MY_TOKEN with your token.
MY_TOKEN = ''
LOW_RESOURCE = False
NUM_DDIM_STEPS = 50
GUIDANCE_SCALE = 7.5
MAX_NUM_WORDS = 77
device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')
print("Using device: {} {} {}".format(device, torch.cuda.device_count(), torch.cuda.get_device_name(0)))
ldm_stable = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", use_auth_token=MY_TOKEN, scheduler=scheduler, cache_dir='/home/marmof/p2p/cache/diffusers/').to(device)
try:
ldm_stable.disable_xformers_memory_efficient_attention()
except AttributeError:
print("Attribute disable_xformers_memory_efficient_attention() is missing")
tokenizer = ldm_stable.tokenizer
domains = ['Drawing', 'Weather', 'Color', 'Context', 'Texture']
save_edited(dataset_path, num_classes, num_images, domains)