-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathclipit.py
executable file
·1411 lines (1199 loc) · 56.8 KB
/
clipit.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
import argparse
import math
from urllib.request import urlopen
import sys
import os
import json
import subprocess
import glob
from braceexpand import braceexpand
from types import SimpleNamespace
import os.path
from omegaconf import OmegaConf
import torch
from torch import nn, optim
from torch.nn import functional as F
from torchvision import transforms
from torchvision.transforms import functional as TF
torch.backends.cudnn.benchmark = False # NR: True is a bit faster, but can lead to OOM. False is more deterministic.
#torch.use_deterministic_algorithms(True) # NR: grid_sampler_2d_backward_cuda does not have a deterministic implementation
from torch_optimizer import DiffGrad, AdamP, RAdam
from perlin_numpy import generate_fractal_noise_2d
from CLIP import clip
import kornia
import kornia.augmentation as K
import numpy as np
import imageio
from PIL import ImageFile, Image, PngImagePlugin
ImageFile.LOAD_TRUNCATED_IMAGES = True
# or 'border'
global_padding_mode = 'reflection'
global_aspect_width = 1
global_spot_file = None
from vqgan import VqganDrawer
try:
from clipdrawer import ClipDrawer
except ImportError:
pass
# print('clipdrawer not imported')
try:
from pixeldrawer import PixelDrawer
except ImportError:
pass
# print('pixeldrawer not imported')
try:
import matplotlib.colors
except ImportError:
# only needed for palette stuff
pass
# print("warning: running unreleased future version")
# https://stackoverflow.com/a/39662359
def isnotebook():
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
elif shell == 'Shell':
return True # Seems to be what co-lab does
elif shell == 'TerminalInteractiveShell':
return False # Terminal running IPython
else:
return False # Other type (?)
except NameError:
return False # Probably standard Python interpreter
IS_NOTEBOOK = isnotebook()
if IS_NOTEBOOK:
from IPython import display
from tqdm.notebook import tqdm
from IPython.display import clear_output
else:
from tqdm import tqdm
# file helpers
def real_glob(rglob):
glob_list = braceexpand(rglob)
files = []
for g in glob_list:
files = files + glob.glob(g)
return sorted(files)
# Functions and classes
def sinc(x):
return torch.where(x != 0, torch.sin(math.pi * x) / (math.pi * x), x.new_ones([]))
def lanczos(x, a):
cond = torch.logical_and(-a < x, x < a)
out = torch.where(cond, sinc(x) * sinc(x/a), x.new_zeros([]))
return out / out.sum()
def ramp(ratio, width):
n = math.ceil(width / ratio + 1)
out = torch.empty([n])
cur = 0
for i in range(out.shape[0]):
out[i] = cur
cur += ratio
return torch.cat([-out[1:].flip([0]), out])[1:-1]
# NR: Testing with different intital images
def old_random_noise_image(w,h):
random_image = Image.fromarray(np.random.randint(0,255,(w,h,3),dtype=np.dtype('uint8')))
return random_image
def NormalizeData(data):
return (data - np.min(data)) / (np.max(data) - np.min(data))
# https://stats.stackexchange.com/a/289477
def contrast_noise(n):
n = 0.9998 * n + 0.0001
n1 = (n / (1-n))
n2 = np.power(n1, -2)
n3 = 1 / (1 + n2)
return n3
def random_noise_image(w,h):
# scale up roughly as power of 2
if (w>1024 or h>1024):
side, octp = 2048, 7
elif (w>512 or h>512):
side, octp = 1024, 6
elif (w>256 or h>256):
side, octp = 512, 5
else:
side, octp = 256, 4
nr = NormalizeData(generate_fractal_noise_2d((side, side), (32, 32), octp))
ng = NormalizeData(generate_fractal_noise_2d((side, side), (32, 32), octp))
nb = NormalizeData(generate_fractal_noise_2d((side, side), (32, 32), octp))
stack = np.dstack((contrast_noise(nr),contrast_noise(ng),contrast_noise(nb)))
substack = stack[:h, :w, :]
im = Image.fromarray((255.9 * stack).astype('uint8'))
return im
# testing
def gradient_2d(start, stop, width, height, is_horizontal):
if is_horizontal:
return np.tile(np.linspace(start, stop, width), (height, 1))
else:
return np.tile(np.linspace(start, stop, height), (width, 1)).T
def gradient_3d(width, height, start_list, stop_list, is_horizontal_list):
result = np.zeros((height, width, len(start_list)), dtype=float)
for i, (start, stop, is_horizontal) in enumerate(zip(start_list, stop_list, is_horizontal_list)):
result[:, :, i] = gradient_2d(start, stop, width, height, is_horizontal)
return result
def random_gradient_image(w,h):
array = gradient_3d(w, h, (0, 0, np.random.randint(0,255)), (np.random.randint(1,255), np.random.randint(2,255), np.random.randint(3,128)), (True, False, False))
random_image = Image.fromarray(np.uint8(array))
return random_image
class ReplaceGrad(torch.autograd.Function):
@staticmethod
def forward(ctx, x_forward, x_backward):
ctx.shape = x_backward.shape
return x_forward
@staticmethod
def backward(ctx, grad_in):
return None, grad_in.sum_to_size(ctx.shape)
replace_grad = ReplaceGrad.apply
def spherical_dist_loss(x, y):
x = F.normalize(x, dim=-1)
y = F.normalize(y, dim=-1)
return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)
class Prompt(nn.Module):
def __init__(self, embed, weight=1., stop=float('-inf')):
super().__init__()
self.register_buffer('embed', embed)
self.register_buffer('weight', torch.as_tensor(weight))
self.register_buffer('stop', torch.as_tensor(stop))
def forward(self, input):
input_normed = F.normalize(input.unsqueeze(1), dim=2)
embed_normed = F.normalize(self.embed.unsqueeze(0), dim=2)
dists = input_normed.sub(embed_normed).norm(dim=2).div(2).arcsin().pow(2).mul(2)
dists = dists * self.weight.sign()
return self.weight.abs() * replace_grad(dists, torch.maximum(dists, self.stop)).mean()
def parse_prompt(prompt):
vals = prompt.rsplit(':', 2)
vals = vals + ['', '1', '-inf'][len(vals):]
# print(f"parsed vals is {vals}")
return vals[0], float(vals[1]), float(vals[2])
from typing import cast, Dict, List, Optional, Tuple, Union
# override class to get padding_mode
class MyRandomPerspective(K.RandomPerspective):
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
_, _, height, width = input.shape
transform = cast(torch.Tensor, transform)
return kornia.geometry.warp_perspective(
input, transform, (height, width),
mode=self.resample.name.lower(), align_corners=self.align_corners, padding_mode=global_padding_mode
)
cached_spot_indexes = {}
def fetch_spot_indexes(sideX, sideY):
global global_spot_file
# make sure image is loaded if we need it
cache_key = (sideX, sideY)
if cache_key not in cached_spot_indexes:
if global_spot_file is not None:
mask_image = Image.open(global_spot_file)
elif global_aspect_width != 1:
mask_image = Image.open("inputs/spot_wide.png")
else:
mask_image = Image.open("inputs/spot_square.png")
# this is a one channel mask
mask_image = mask_image.convert('RGB')
mask_image = mask_image.resize((sideX, sideY), Image.LANCZOS)
mask_image_tensor = TF.to_tensor(mask_image)
# print("ONE CHANNEL ", mask_image_tensor.shape)
mask_indexes = mask_image_tensor.ge(0.5).to(device)
# print("GE ", mask_indexes.shape)
# sys.exit(0)
mask_indexes_off = mask_image_tensor.lt(0.5).to(device)
cached_spot_indexes[cache_key] = [mask_indexes, mask_indexes_off]
return cached_spot_indexes[cache_key]
# n = torch.ones((3,5,5))
# f = generate.fetch_spot_indexes(5, 5)
# f[0].shape = [60,3]
class MakeCutouts(nn.Module):
def __init__(self, cut_size, cutn, cut_pow=1.):
global global_aspect_width
super().__init__()
self.cut_size = cut_size
self.cutn = cutn
self.cutn_zoom = int(2*cutn/3)
self.cut_pow = cut_pow
self.transforms = None
augmentations = []
if global_aspect_width != 1:
augmentations.append(K.RandomCrop(size=(self.cut_size,self.cut_size), p=1.0, cropping_mode="resample", return_transform=True))
augmentations.append(MyRandomPerspective(distortion_scale=0.40, p=0.7, return_transform=True))
augmentations.append(K.RandomResizedCrop(size=(self.cut_size,self.cut_size), scale=(0.1,0.75), ratio=(0.85,1.2), cropping_mode='resample', p=0.7, return_transform=True))
augmentations.append(K.ColorJitter(hue=0.1, saturation=0.1, p=0.8, return_transform=True))
self.augs_zoom = nn.Sequential(*augmentations)
augmentations = []
if global_aspect_width == 1:
n_s = 0.95
n_t = (1-n_s)/2
augmentations.append(K.RandomAffine(degrees=0, translate=(n_t, n_t), scale=(n_s, n_s), p=1.0, return_transform=True))
elif global_aspect_width > 1:
n_s = 1/global_aspect_width
n_t = (1-n_s)/2
augmentations.append(K.RandomAffine(degrees=0, translate=(0, n_t), scale=(0.9*n_s, n_s), p=1.0, return_transform=True))
else:
n_s = global_aspect_width
n_t = (1-n_s)/2
augmentations.append(K.RandomAffine(degrees=0, translate=(n_t, 0), scale=(0.9*n_s, n_s), p=1.0, return_transform=True))
# augmentations.append(K.CenterCrop(size=(self.cut_size,self.cut_size), p=1.0, cropping_mode="resample", return_transform=True))
augmentations.append(K.CenterCrop(size=self.cut_size, cropping_mode='resample', p=1.0, return_transform=True))
augmentations.append(K.RandomPerspective(distortion_scale=0.20, p=0.7, return_transform=True))
augmentations.append(K.ColorJitter(hue=0.1, saturation=0.1, p=0.8, return_transform=True))
self.augs_wide = nn.Sequential(*augmentations)
self.noise_fac = 0.1
# Pooling
self.av_pool = nn.AdaptiveAvgPool2d((self.cut_size, self.cut_size))
self.max_pool = nn.AdaptiveMaxPool2d((self.cut_size, self.cut_size))
def forward(self, input, spot=None):
global global_aspect_width, cur_iteration
sideY, sideX = input.shape[2:4]
max_size = min(sideX, sideY)
min_size = min(sideX, sideY, self.cut_size)
cutouts = []
mask_indexes = None
if spot is not None:
spot_indexes = fetch_spot_indexes(self.cut_size, self.cut_size)
if spot == 0:
mask_indexes = spot_indexes[1]
else:
mask_indexes = spot_indexes[0]
# print("Mask indexes ", mask_indexes)
for _ in range(self.cutn):
# Pooling
cutout = (self.av_pool(input) + self.max_pool(input))/2
if mask_indexes is not None:
cutout[0][mask_indexes] = 0.5
if global_aspect_width != 1:
if global_aspect_width > 1:
cutout = kornia.geometry.transform.rescale(cutout, (1, global_aspect_width))
else:
cutout = kornia.geometry.transform.rescale(cutout, (1/global_aspect_width, 1))
# if cur_iteration % 50 == 0 and _ == 0:
# print(cutout.shape)
# TF.to_pil_image(cutout[0].cpu()).save(f"cutout_im_{cur_iteration:02d}_{spot}.png")
cutouts.append(cutout)
if self.transforms is not None:
# print("Cached transforms available")
batch1 = kornia.geometry.transform.warp_perspective(torch.cat(cutouts[:self.cutn_zoom], dim=0), self.transforms[:self.cutn_zoom],
(self.cut_size, self.cut_size), padding_mode=global_padding_mode)
batch2 = kornia.geometry.transform.warp_perspective(torch.cat(cutouts[self.cutn_zoom:], dim=0), self.transforms[self.cutn_zoom:],
(self.cut_size, self.cut_size), padding_mode='zeros')
batch = torch.cat([batch1, batch2])
# if cur_iteration < 2:
# for j in range(4):
# TF.to_pil_image(batch[j].cpu()).save(f"cached_im_{cur_iteration:02d}_{j:02d}_{spot}.png")
# j_wide = j + self.cutn_zoom
# TF.to_pil_image(batch[j_wide].cpu()).save(f"cached_im_{cur_iteration:02d}_{j_wide:02d}_{spot}.png")
else:
batch1, transforms1 = self.augs_zoom(torch.cat(cutouts[:self.cutn_zoom], dim=0))
batch2, transforms2 = self.augs_wide(torch.cat(cutouts[self.cutn_zoom:], dim=0))
# print(batch1.shape, batch2.shape)
batch = torch.cat([batch1, batch2])
# print(batch.shape)
self.transforms = torch.cat([transforms1, transforms2])
## batch, self.transforms = self.augs(torch.cat(cutouts, dim=0))
# if cur_iteration < 2:
# for j in range(4):
# TF.to_pil_image(batch[j].cpu()).save(f"live_im_{cur_iteration:02d}_{j:02d}_{spot}.png")
# j_wide = j + self.cutn_zoom
# TF.to_pil_image(batch[j_wide].cpu()).save(f"live_im_{cur_iteration:02d}_{j_wide:02d}_{spot}.png")
# print(batch.shape, self.transforms.shape)
if self.noise_fac:
facs = batch.new_empty([self.cutn, 1, 1, 1]).uniform_(0, self.noise_fac)
batch = batch + facs * torch.randn_like(batch)
return batch
def resize_image(image, out_size):
ratio = image.size[0] / image.size[1]
area = min(image.size[0] * image.size[1], out_size[0] * out_size[1])
size = round((area * ratio)**0.5), round((area / ratio)**0.5)
return image.resize(size, Image.LANCZOS)
def do_init(args):
global opts, perceptors, normalize, cutoutsTable, cutoutSizeTable
global z_orig, z_targets, z_labels, init_image_tensor, target_image_tensor
global gside_X, gside_Y, overlay_image_rgba
global pmsTable, pmsImageTable, pImages, device, spotPmsTable, spotOffPmsTable
global drawer
# Do it (init that is)
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
if args.use_clipdraw:
drawer = ClipDrawer(args.size[0], args.size[1], args.strokes)
elif args.use_pixeldraw:
if args.pixel_size is not None:
drawer = PixelDrawer(args.size[0], args.size[1], args.do_mono, args.pixel_size, scale=args.pixel_scale)
elif global_aspect_width == 1:
drawer = PixelDrawer(args.size[0], args.size[1], args.do_mono, [40, 40], scale=args.pixel_scale)
else:
drawer = PixelDrawer(args.size[0], args.size[1], args.do_mono, scale=args.pixel_scale)
else:
drawer = VqganDrawer(args.vqgan_model)
drawer.load_model(args.vqgan_config, args.vqgan_checkpoint, device)
num_resolutions = drawer.get_num_resolutions()
# print("-----------> NUMR ", num_resolutions)
jit = True if float(torch.__version__[:3]) < 1.8 else False
f = 2**(num_resolutions - 1)
toksX, toksY = args.size[0] // f, args.size[1] // f
sideX, sideY = toksX * f, toksY * f
# save sideX, sideY in globals (need if using overlay)
gside_X = sideX
gside_Y = sideY
for clip_model in args.clip_models:
perceptor = clip.load(clip_model, jit=jit)[0].eval().requires_grad_(False).to(device)
perceptors[clip_model] = perceptor
cut_size = perceptor.visual.input_resolution
cutoutSizeTable[clip_model] = cut_size
if not cut_size in cutoutsTable:
make_cutouts = MakeCutouts(cut_size, args.num_cuts, cut_pow=args.cut_pow)
cutoutsTable[cut_size] = make_cutouts
init_image_tensor = None
target_image_tensor = None
# Image initialisation
if args.init_image or args.init_noise:
# setup init image wih pil
# first - always start with noise or blank
if args.init_noise == 'pixels':
img = random_noise_image(args.size[0], args.size[1])
elif args.init_noise == 'gradient':
img = random_gradient_image(args.size[0], args.size[1])
elif args.init_noise == 'snow':
img = old_random_noise_image(args.size[0], args.size[1])
else:
img = Image.new(mode="RGB", size=(args.size[0], args.size[1]), color=(255, 255, 255))
starting_image = img.convert('RGB')
starting_image = starting_image.resize((sideX, sideY), Image.LANCZOS)
if args.init_image:
# now we might overlay an init image (init_image also can be recycled as overlay)
if 'http' in args.init_image:
init_image = Image.open(urlopen(args.init_image))
else:
init_image = Image.open(args.init_image)
# this version is needed potentially for the loss function
init_image_rgb = init_image.convert('RGB')
init_image_rgb = init_image_rgb.resize((sideX, sideY), Image.LANCZOS)
init_image_tensor = TF.to_tensor(init_image_rgb)
init_image_tensor = init_image_tensor.to(device).unsqueeze(0)
# this version gets overlaid on the background (noise)
init_image_rgba = init_image.convert('RGBA')
init_image_rgba = init_image_rgba.resize((sideX, sideY), Image.LANCZOS)
top_image = init_image_rgba.copy()
if args.init_image_alpha and args.init_image_alpha >= 0:
top_image.putalpha(args.init_image_alpha)
starting_image.paste(top_image, (0, 0), top_image)
starting_image.save("starting_image.png")
starting_tensor = TF.to_tensor(starting_image)
init_tensor = starting_tensor.to(device).unsqueeze(0) * 2 - 1
drawer.init_from_tensor(init_tensor)
else:
# untested
drawer.rand_init(toksX, toksY)
if args.overlay_every:
if args.overlay_image:
if 'http' in args.overlay_image:
overlay_image = Image.open(urlopen(args.overlay_image))
else:
overlay_image = Image.open(args.overlay_image)
overlay_image_rgba = overlay_image.convert('RGBA')
overlay_image_rgba = overlay_image_rgba.resize((sideX, sideY), Image.LANCZOS)
else:
overlay_image_rgba = init_image_rgba
if args.overlay_alpha:
overlay_image_rgba.putalpha(args.overlay_alpha)
overlay_image_rgba.save('overlay_image.png')
if args.target_images is not None:
z_targets = []
filelist = real_glob(args.target_images)
for target_image in filelist:
target_image = Image.open(target_image)
target_image_rgb = target_image.convert('RGB')
target_image_rgb = target_image_rgb.resize((sideX, sideY), Image.LANCZOS)
target_image_tensor_local = TF.to_tensor(target_image_rgb)
target_image_tensor = target_image_tensor_local.to(device).unsqueeze(0) * 2 - 1
z_target = drawer.get_z_from_tensor(target_image_tensor)
z_targets.append(z_target)
if args.image_labels is not None:
z_labels = []
filelist = real_glob(args.image_labels)
cur_labels = []
for image_label in filelist:
image_label = Image.open(image_label)
image_label_rgb = image_label.convert('RGB')
image_label_rgb = image_label_rgb.resize((sideX, sideY), Image.LANCZOS)
image_label_rgb_tensor = TF.to_tensor(image_label_rgb)
image_label_rgb_tensor = image_label_rgb_tensor.to(device).unsqueeze(0) * 2 - 1
z_label = drawer.get_z_from_tensor(image_label_rgb_tensor)
cur_labels.append(z_label)
image_embeddings = torch.stack(cur_labels)
print("Processing labels: ", image_embeddings.shape)
image_embeddings /= image_embeddings.norm(dim=-1, keepdim=True)
image_embeddings = image_embeddings.mean(dim=0)
image_embeddings /= image_embeddings.norm()
z_labels.append(image_embeddings.unsqueeze(0))
z_orig = drawer.get_z_copy()
pmsTable = {}
pmsImageTable = {}
spotPmsTable = {}
spotOffPmsTable = {}
for clip_model in args.clip_models:
pmsTable[clip_model] = []
pmsImageTable[clip_model] = []
spotPmsTable[clip_model] = []
spotOffPmsTable[clip_model] = []
normalize = transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073],
std=[0.26862954, 0.26130258, 0.27577711])
# CLIP tokenize/encode
# NR: Weights / blending
for prompt in args.prompts:
for clip_model in args.clip_models:
pMs = pmsTable[clip_model]
perceptor = perceptors[clip_model]
txt, weight, stop = parse_prompt(prompt)
embed = perceptor.encode_text(clip.tokenize(txt).to(device)).float()
pMs.append(Prompt(embed, weight, stop).to(device))
for prompt in args.spot_prompts:
for clip_model in args.clip_models:
pMs = spotPmsTable[clip_model]
perceptor = perceptors[clip_model]
txt, weight, stop = parse_prompt(prompt)
embed = perceptor.encode_text(clip.tokenize(txt).to(device)).float()
pMs.append(Prompt(embed, weight, stop).to(device))
for prompt in args.spot_prompts_off:
for clip_model in args.clip_models:
pMs = spotOffPmsTable[clip_model]
perceptor = perceptors[clip_model]
txt, weight, stop = parse_prompt(prompt)
embed = perceptor.encode_text(clip.tokenize(txt).to(device)).float()
pMs.append(Prompt(embed, weight, stop).to(device))
for label in args.labels:
for clip_model in args.clip_models:
pMs = pmsTable[clip_model]
perceptor = perceptors[clip_model]
txt, weight, stop = parse_prompt(label)
texts = [template.format(txt) for template in imagenet_templates] #format with class
print(f"Tokenizing all of {texts}")
texts = clip.tokenize(texts).to(device) #tokenize
class_embeddings = perceptor.encode_text(texts) #embed with text encoder
class_embeddings /= class_embeddings.norm(dim=-1, keepdim=True)
class_embedding = class_embeddings.mean(dim=0)
class_embedding /= class_embedding.norm()
pMs.append(Prompt(class_embedding.unsqueeze(0), weight, stop).to(device))
for clip_model in args.clip_models:
pImages = pmsImageTable[clip_model]
for prompt in args.image_prompts:
path, weight, stop = parse_prompt(prompt)
img = Image.open(path)
pil_image = img.convert('RGB')
img = resize_image(pil_image, (sideX, sideY))
pImages.append(TF.to_tensor(img).unsqueeze(0).to(device))
for seed, weight in zip(args.noise_prompt_seeds, args.noise_prompt_weights):
gen = torch.Generator().manual_seed(seed)
embed = torch.empty([1, perceptor.visual.output_dim]).normal_(generator=gen)
pMs.append(Prompt(embed, weight).to(device))
opts = drawer.get_opts()
if opts == None:
# legacy
# Set the optimiser
z = drawer.get_z();
if args.optimiser == "Adam":
opt = optim.Adam([z], lr=args.learning_rate) # LR=0.1
elif args.optimiser == "AdamW":
opt = optim.AdamW([z], lr=args.learning_rate) # LR=0.2
elif args.optimiser == "Adagrad":
opt = optim.Adagrad([z], lr=args.learning_rate) # LR=0.5+
elif args.optimiser == "Adamax":
opt = optim.Adamax([z], lr=args.learning_rate) # LR=0.5+?
elif args.optimiser == "DiffGrad":
opt = DiffGrad([z], lr=args.learning_rate) # LR=2+?
elif args.optimiser == "AdamP":
opt = AdamP([z], lr=args.learning_rate) # LR=2+?
elif args.optimiser == "RAdam":
opt = RAdam([z], lr=args.learning_rate) # LR=2+?
opts = [opt]
# Output for the user
print('Using device:', device)
print('Optimising using:', args.optimiser)
if args.prompts:
print('Using text prompts:', args.prompts)
if args.spot_prompts:
print('Using spot prompts:', args.spot_prompts)
if args.spot_prompts_off:
print('Using spot off prompts:', args.spot_prompts_off)
if args.image_prompts:
print('Using image prompts:', args.image_prompts)
if args.init_image:
print('Using initial image:', args.init_image)
if args.noise_prompt_weights:
print('Noise prompt weights:', args.noise_prompt_weights)
if args.seed is None:
seed = torch.seed()
else:
seed = args.seed
torch.manual_seed(seed)
print('Using seed:', seed)
# dreaded globals (for now)
z_orig = None
z_targets = None
z_labels = None
opts = None
drawer = None
perceptors = {}
normalize = None
cutoutsTable = {}
cutoutSizeTable = {}
init_image_tensor = None
target_image_tensor = None
pmsTable = None
spotPmsTable = None
spotOffPmsTable = None
pmsImageTable = None
gside_X=None
gside_Y=None
overlay_image_rgba=None
device=None
cur_iteration=None
cur_anim_index=None
anim_output_files=[]
anim_cur_zs=[]
anim_next_zs=[]
def make_gif(args, iter):
gif_output = os.path.join(args.animation_dir, "anim.gif")
if os.path.exists(gif_output):
os.remove(gif_output)
cmd = ['ffmpeg', '-framerate', '10', '-pattern_type', 'glob',
'-i', f"{args.animation_dir}/*.png", '-loop', '0', gif_output]
try:
output = subprocess.check_output(cmd)
except subprocess.CalledProcessError as cpe:
output = cpe.output
print("Ignoring non-zero exit: ", output)
return gif_output
# !ffmpeg \
# -framerate 10 -pattern_type glob \
# -i '{animation_output}/*_*.png' \
# -loop 0 {animation_output}/final.gif
@torch.no_grad()
def checkin(args, iter, losses):
global drawer
losses_str = ', '.join(f'{loss.item():g}' for loss in losses)
writestr = f'iter: {iter}, loss: {sum(losses).item():g}, losses: {losses_str}'
if args.animation_dir is not None:
writestr = f'anim: {cur_anim_index}/{len(anim_output_files)} {writestr}'
tqdm.write(writestr)
info = PngImagePlugin.PngInfo()
info.add_text('comment', f'{args.prompts}')
img = drawer.to_image()
if cur_anim_index is None:
outfile = args.output
else:
outfile = anim_output_files[cur_anim_index]
img.save(outfile, pnginfo=info)
if cur_anim_index == len(anim_output_files) - 1:
# save gif
gif_output = make_gif(args, iter)
if IS_NOTEBOOK and iter % args.display_every == 0:
clear_output()
display.display(display.Image(open(gif_output,'rb').read()))
if IS_NOTEBOOK and iter % args.display_every == 0:
if cur_anim_index is None or iter == 0:
display.display(display.Image(outfile))
def ascend_txt(args):
global cur_iteration, cur_anim_index, perceptors, normalize, cutoutsTable, cutoutSizeTable
global z_orig, z_targets, z_labels, init_image_tensor, target_image_tensor, drawer
global pmsTable, pmsImageTable, spotPmsTable, spotOffPmsTable, global_padding_mode
out = drawer.synth(cur_iteration);
result = []
if (cur_iteration%2 == 0):
global_padding_mode = 'reflection'
else:
global_padding_mode = 'border'
cur_cutouts = {}
cur_spot_cutouts = {}
cur_spot_off_cutouts = {}
for cutoutSize in cutoutsTable:
make_cutouts = cutoutsTable[cutoutSize]
cur_cutouts[cutoutSize] = make_cutouts(out)
if args.spot_prompts:
for cutoutSize in cutoutsTable:
cur_spot_cutouts[cutoutSize] = make_cutouts(out, spot=1)
if args.spot_prompts_off:
for cutoutSize in cutoutsTable:
cur_spot_off_cutouts[cutoutSize] = make_cutouts(out, spot=0)
for clip_model in args.clip_models:
perceptor = perceptors[clip_model]
cutoutSize = cutoutSizeTable[clip_model]
transient_pMs = []
if args.spot_prompts:
iii_s = perceptor.encode_image(normalize( cur_spot_cutouts[cutoutSize] )).float()
spotPms = spotPmsTable[clip_model]
for prompt in spotPms:
result.append(prompt(iii_s))
if args.spot_prompts_off:
iii_so = perceptor.encode_image(normalize( cur_spot_off_cutouts[cutoutSize] )).float()
spotOffPms = spotOffPmsTable[clip_model]
for prompt in spotOffPms:
result.append(prompt(iii_so))
pMs = pmsTable[clip_model]
iii = perceptor.encode_image(normalize( cur_cutouts[cutoutSize] )).float()
for prompt in pMs:
result.append(prompt(iii))
# If there are image prompts we make cutouts for those each time
# so that they line up with the current cutouts from augmentation
make_cutouts = cutoutsTable[cutoutSize]
pImages = pmsImageTable[clip_model]
for timg in pImages:
# note: this caches and reuses the transforms - a bit of a hack but it works
if args.image_prompt_shuffle:
# print("Disabling cached transforms")
make_cutouts.transforms = None
# print("Building throwaway image prompts")
# new way builds throwaway Prompts
batch = make_cutouts(timg)
embed = perceptor.encode_image(normalize(batch)).float()
if args.image_prompt_weight is not None:
transient_pMs.append(Prompt(embed, args.image_prompt_weight).to(device))
else:
transient_pMs.append(Prompt(embed).to(device))
for prompt in transient_pMs:
result.append(prompt(iii))
if args.enforce_palette_annealing and args.target_palette:
target_palette = torch.FloatTensor(args.target_palette).requires_grad_(False).to(device)
_pixels = cur_cutouts[cutoutSize].permute(0,2,3,1).reshape(-1,3)
palette_dists = torch.cdist(target_palette, _pixels, p=2)
best_guesses = palette_dists.argmin(axis=0)
diffs = _pixels - target_palette[best_guesses]
palette_loss = torch.mean( torch.norm( diffs, 2, dim=1 ) )*cur_cutouts[cutoutSize].shape[0]
result.append( palette_loss*cur_iteration/args.enforce_palette_annealing )
if args.enforce_smoothness and args.enforce_smoothness_type:
_pixels = cur_cutouts[cutoutSize].permute(0,2,3,1).reshape(-1,cur_cutouts[cutoutSize].shape[2],3)
gyr, gxr = torch.gradient(_pixels[:,:,0])
gyg, gxg = torch.gradient(_pixels[:,:,1])
gyb, gxb = torch.gradient(_pixels[:,:,2])
sharpness = torch.sqrt(gyr**2 + gxr**2+ gyg**2 + gxg**2 + gyb**2 + gxb**2)
if args.enforce_smoothness_type=='clipped':
sharpness = torch.clamp( sharpness, max=0.5 )
elif args.enforce_smoothness_type=='log':
sharpness = torch.log( torch.ones_like(sharpness)+sharpness )
sharpness = torch.mean( sharpness )
result.append( sharpness*cur_iteration/args.enforce_smoothness )
if args.enforce_saturation:
# based on the old "percepted colourfulness" heuristic from Hasler and Süsstrunk’s 2003 paper
# https://www.researchgate.net/publication/243135534_Measuring_Colourfulness_in_Natural_Images
_pixels = cur_cutouts[cutoutSize].permute(0,2,3,1).reshape(-1,3)
rg = _pixels[:,0]-_pixels[:,1]
yb = 0.5*(_pixels[:,0]+_pixels[:,1])-_pixels[:,2]
rg_std, rg_mean = torch.std_mean(rg)
yb_std, yb_mean = torch.std_mean(yb)
std_rggb = torch.sqrt(rg_std**2 + yb_std**2)
mean_rggb = torch.sqrt(rg_mean**2 + yb_mean**2)
colorfullness = std_rggb+.3*mean_rggb
result.append( -colorfullness*cur_iteration/args.enforce_saturation )
for cutoutSize in cutoutsTable:
# clear the transform "cache"
make_cutouts = cutoutsTable[cutoutSize]
make_cutouts.transforms = None
# main init_weight uses spherical loss
if args.target_images is not None and args.target_image_weight > 0:
if cur_anim_index is None:
cur_z_targets = z_targets
else:
cur_z_targets = [ z_targets[cur_anim_index] ]
for z_target in cur_z_targets:
f = drawer.get_z().reshape(1,-1)
f2 = z_target.reshape(1,-1)
cur_loss = spherical_dist_loss(f, f2) * args.target_image_weight
result.append(cur_loss)
if args.target_weight_pix:
if target_image_tensor is None:
print("OOPS TIT is 0")
else:
cur_loss = F.l1_loss(out, target_image_tensor) * args.target_weight_pix
result.append(cur_loss)
if args.image_labels is not None:
for z_label in z_labels:
f = drawer.get_z().reshape(1,-1)
f2 = z_label.reshape(1,-1)
cur_loss = spherical_dist_loss(f, f2) * args.image_label_weight
result.append(cur_loss)
# main init_weight uses spherical loss
if args.init_weight:
f = drawer.get_z().reshape(1,-1)
f2 = z_orig.reshape(1,-1)
cur_loss = spherical_dist_loss(f, f2) * args.init_weight
result.append(cur_loss)
# these three init_weight variants offer mse_loss, mse_loss in pixel space, and cos loss
if args.init_weight_dist:
cur_loss = F.mse_loss(z, z_orig) * args.init_weight_dist / 2
result.append(cur_loss)
if args.init_weight_pix:
if init_image_tensor is None:
print("OOPS IIT is 0")
else:
cur_loss = F.l1_loss(out, init_image_tensor) * args.init_weight_pix / 2
result.append(cur_loss)
if args.init_weight_cos:
f = drawer.get_z().reshape(1,-1)
f2 = z_orig.reshape(1,-1)
y = torch.ones_like(f[0])
cur_loss = F.cosine_embedding_loss(f, f2, y) * args.init_weight_cos
result.append(cur_loss)
if args.make_video:
img = np.array(out.mul(255).clamp(0, 255)[0].cpu().detach().numpy().astype(np.uint8))[:,:,:]
img = np.transpose(img, (1, 2, 0))
imageio.imwrite(f'./steps/frame_{cur_iteration:04d}.png', np.array(img))
return result
def re_average_z(args):
global gside_X, gside_Y
global device, drawer
# old_z = z.clone()
cur_z_image = drawer.to_image()
cur_z_image = cur_z_image.convert('RGB')
if overlay_image_rgba:
# print("applying overlay image")
cur_z_image.paste(overlay_image_rgba, (0, 0), overlay_image_rgba)
cur_z_image.save("overlaid.png")
cur_z_image = cur_z_image.resize((gside_X, gside_Y), Image.LANCZOS)
drawer.reapply_from_tensor(TF.to_tensor(cur_z_image).to(device).unsqueeze(0) * 2 - 1)
# torch.autograd.set_detect_anomaly(True)
def train(args, cur_it):
global drawer;
for opt in opts:
# opt.zero_grad(set_to_none=True)
opt.zero_grad()
for i in range(args.batches):
lossAll = ascend_txt(args)
if i == 0 and cur_it % args.save_every == 0:
checkin(args, cur_it, lossAll)
loss = sum(lossAll)
loss.backward()
for opt in opts:
opt.step()
if args.overlay_every and cur_it != 0 and \
(cur_it % (args.overlay_every + args.overlay_offset)) == 0:
re_average_z(args)
drawer.clip_z()
imagenet_templates = [
"itap of a {}.",
"a bad photo of the {}.",
"a origami {}.",
"a photo of the large {}.",
"a {} in a video game.",
"art of the {}.",
"a photo of the small {}.",
]
def do_run(args):
global cur_iteration, cur_anim_index
global anim_cur_zs, anim_next_zs, anim_output_files
cur_iteration = 0
if args.animation_dir is not None:
# we already have z_targets. setup some sort of global ring
# we need something like
# copies of all the current z's (they can all start off all as copies)
# a list of all the output filenames
#
if not os.path.exists(args.animation_dir):
os.mkdir(args.animation_dir)
filelist = real_glob(args.target_images)
num_anim_frames = len(filelist)
for target_image in filelist:
basename = os.path.basename(target_image)
target_output = os.path.join(args.animation_dir, basename)
anim_output_files.append(target_output)
for i in range(num_anim_frames):
cur_z = drawer.get_z_copy()
anim_cur_zs.append(cur_z)
anim_next_zs.append(None)
step_iteration = 0
with tqdm() as pbar:
while True:
cur_images = []
for i in range(num_anim_frames):
# do merge frames here from cur->next when we are ready to be fancy
cur_anim_index = i
# anim_cur_zs[cur_anim_index] = anim_next_zs[cur_anim_index]
cur_iteration = step_iteration
drawer.set_z(anim_cur_zs[cur_anim_index])
for j in range(args.save_every):
train(args, cur_iteration)
cur_iteration += 1
pbar.update()
# anim_next_zs[cur_anim_index] = drawer.get_z_copy()
cur_images.append(drawer.to_image())
step_iteration = step_iteration + args.save_every
if step_iteration >= args.iterations:
break
# compute the next round of cur_zs here from all the next_zs
for i in range(num_anim_frames):
prev_i = (i + num_anim_frames - 1) % num_anim_frames
base_image = cur_images[i].copy()
prev_image = cur_images[prev_i].copy().convert('RGBA')
prev_image.putalpha(args.animation_alpha)
base_image.paste(prev_image, (0, 0), prev_image)
# base_image.save(f"overlaid_{i:02d}.png")
drawer.reapply_from_tensor(TF.to_tensor(base_image).to(device).unsqueeze(0) * 2 - 1)
anim_cur_zs[i] = drawer.get_z_copy()
else:
try:
with tqdm() as pbar:
while True:
try:
train(args, cur_iteration)
if cur_iteration == args.iterations:
break
cur_iteration += 1
pbar.update()
except RuntimeError as e:
print("Oops: runtime error: ", e)
print("Try reducing --num-cuts to save memory")
raise e
except KeyboardInterrupt:
pass