-
Notifications
You must be signed in to change notification settings - Fork 126
/
diffusion.py
2305 lines (1954 loc) · 89.1 KB
/
diffusion.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
# CLIP-guided diffusion AI image generator
# adapted from @Somnai_dreams Disco Diffusion colab notebook:
# https://colab.research.google.com/drive/1sHfRn5Y0YKYKi1k-ifUSBFRNJ8_1sa39
# based on Katherine Crowson's fine-tuned 512x512 model
import sys
sys.path.append('./ResizeRight')
sys.path.append('./CLIP')
sys.path.append('./guided-diffusion')
sys.path.append('./taming-transformers')
sys.path.append('./latent-diffusion')
import argparse
import unicodedata
import re
from datetime import date
import os
from os import path
from os.path import exists
from dataclasses import dataclass
from functools import partial
import cv2
import pandas as pd
import gc
import io
import math
import timm
from IPython import display
import lpips
from PIL import Image, ImageOps
import requests
from glob import glob
import json
from types import SimpleNamespace
import torch
from torch import nn
from torch.nn import functional as F
import torchvision.transforms as T
import torchvision.transforms.functional as TF
from tqdm.notebook import tqdm
import clip
from resize_right import resize
from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
import random
from ipywidgets import Output
import hashlib
import ipywidgets as widgets
from taming.models import vqgan
from torchvision.datasets.utils import download_url
from functools import partial
from ldm.util import instantiate_from_config
from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like
from ldm.util import ismap
from IPython.display import Image as ipyimg
from numpy import asarray
from einops import rearrange, repeat
import torchvision
import time
from omegaconf import OmegaConf
import torch.nn as nn
import warnings
# Supress warnings
warnings.filterwarnings('ignore')
parser = argparse.ArgumentParser(description='AI image generation')
parser.add_argument("-p", type=str, help="Text prompts", default=None, dest='prompts')
parser.add_argument("-i", type=int, help="Number of steps", default=250, dest='max_iterations')
parser.add_argument("-s", nargs=2, type=int, help="Image size (width height) (default: %(default)s)", default=[768,448], dest='size')
parser.add_argument("-ii", type=str, help="Initial image", default=None, dest='init_image')
parser.add_argument("-ss", type=int, help="Skip steps", default=-1, dest='skip_steps')
parser.add_argument("-cuts", type=int, help="Number of cut batches", default=4, dest='cutn')
parser.add_argument("-sd", type=int, help="Seed", default=None, dest='seed')
parser.add_argument("-o", type=str, help="Output path/filename", default="output/output.png", dest='output')
parser.add_argument("-cd", type=int, help="Cuda Device to use", default="0", dest='cuda_device')
parser.add_argument("-dvitb32", type=str, help="Use VitB32 CLIP model? yes/no", default="yes", dest='VitB32')
parser.add_argument("-dvitb16", type=str, help="Use VitB16 CLIP model? yes/no", default="yes", dest='VitB16')
parser.add_argument("-dvitl14", type=str, help="Use VitL14 CLIP model? yes/no", default="no", dest='VitL14')
parser.add_argument("-drn101", type=str, help="Use RN101 CLIP model? yes/no", default="no", dest='RN101')
parser.add_argument("-drn50", type=str, help="Use RN50 CLIP model? yes/no", default="yes", dest='RN50')
parser.add_argument("-drn50x4", type=str, help="Use RN50x4 CLIP model? yes/no", default="no", dest='RN50x4')
parser.add_argument("-drn50x16", type=str, help="Use RN50x16 CLIP model? yes/no", default="no", dest='RN50x16')
parser.add_argument("-drn50x64", type=str, help="Use RN50x64 CLIP model? yes/no", default="no", dest='RN50x64')
iargs = parser.parse_args()
device = torch.device(f'cuda:{iargs.cuda_device}' if torch.cuda.is_available() else 'cpu')
print('Using device:', device)
root_path = 'content'
model_256_downloaded = False
model_512_downloaded = False
model_secondary_downloaded = False
def createPath(filepath):
if path.exists(filepath) == False:
os.makedirs(filepath)
print(f'Made {filepath}')
#else:
# print(f'filepath {filepath} exists.')
output_path = "output"
output_filename = "output.png"
# support path conventions on both windows/*nix
if '/' in iargs.output:
output_filename = iargs.output[iargs.output.rindex('/')+1:]
output_path = iargs.output.replace(output_filename,'')[:-1]
if '\\' in iargs.output:
output_filename = iargs.output[iargs.output.rindex('\\')+1:]
output_path = iargs.output.replace(output_filename,'')[:-1]
initDirPath = f'{root_path}/init_images'
createPath(initDirPath)
#outDirPath = f'{root_path}/images_out'
outDirPath = output_path
createPath(outDirPath)
model_path = 'content/models'
createPath(model_path)
# Taken from https://github.com/django/django/blob/master/django/utils/text.py
# Using here to make filesystem-safe directory names
def slugify(value, allow_unicode=False):
value = str(value)
if allow_unicode:
value = unicodedata.normalize('NFKC', value)
else:
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
value = re.sub(r'[^\w\s-]', '', value.lower())
return re.sub(r'[-\s]+', '-', value).strip('-_')
def interp(t):
return 3 * t**2 - 2 * t ** 3
def perlin(width, height, scale=10, device=None):
gx, gy = torch.randn(2, width + 1, height + 1, 1, 1, device=device)
xs = torch.linspace(0, 1, scale + 1)[:-1, None].to(device)
ys = torch.linspace(0, 1, scale + 1)[None, :-1].to(device)
wx = 1 - interp(xs)
wy = 1 - interp(ys)
dots = 0
dots += wx * wy * (gx[:-1, :-1] * xs + gy[:-1, :-1] * ys)
dots += (1 - wx) * wy * (-gx[1:, :-1] * (1 - xs) + gy[1:, :-1] * ys)
dots += wx * (1 - wy) * (gx[:-1, 1:] * xs - gy[:-1, 1:] * (1 - ys))
dots += (1 - wx) * (1 - wy) * (-gx[1:, 1:] * (1 - xs) - gy[1:, 1:] * (1 - ys))
return dots.permute(0, 2, 1, 3).contiguous().view(width * scale, height * scale)
def perlin_ms(octaves, width, height, grayscale, device=device):
out_array = [0.5] if grayscale else [0.5, 0.5, 0.5]
# out_array = [0.0] if grayscale else [0.0, 0.0, 0.0]
for i in range(1 if grayscale else 3):
scale = 2 ** len(octaves)
oct_width = width
oct_height = height
for oct in octaves:
p = perlin(oct_width, oct_height, scale, device)
out_array[i] += p * oct
scale //= 2
oct_width *= 2
oct_height *= 2
return torch.cat(out_array)
def create_perlin_noise(octaves=[1, 1, 1, 1], width=2, height=2, grayscale=True):
out = perlin_ms(octaves, width, height, grayscale)
if grayscale:
out = TF.resize(size=(side_y, side_x), img=out.unsqueeze(0))
out = TF.to_pil_image(out.clamp(0, 1)).convert('RGB')
else:
out = out.reshape(-1, 3, out.shape[0]//3, out.shape[1])
out = TF.resize(size=(side_y, side_x), img=out)
out = TF.to_pil_image(out.clamp(0, 1).squeeze())
out = ImageOps.autocontrast(out)
return out
def regen_perlin():
if perlin_mode == 'color':
init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)
init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False)
elif perlin_mode == 'gray':
init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True)
init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)
else:
init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)
init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)
init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1)
del init2
return init.expand(batch_size, -1, -1, -1)
def fetch(url_or_path):
if str(url_or_path).startswith('http://') or str(url_or_path).startswith('https://'):
r = requests.get(url_or_path)
r.raise_for_status()
fd = io.BytesIO()
fd.write(r.content)
fd.seek(0)
return fd
return open(url_or_path, 'rb')
def read_image_workaround(path):
"""OpenCV reads images as BGR, Pillow saves them as RGB. Work around
this incompatibility to avoid colour inversions."""
im_tmp = cv2.imread(path)
return cv2.cvtColor(im_tmp, cv2.COLOR_BGR2RGB)
def parse_prompt(prompt):
if prompt.startswith('http://') or prompt.startswith('https://'):
vals = prompt.rsplit(':', 2)
vals = [vals[0] + ':' + vals[1], *vals[2:]]
else:
vals = prompt.rsplit(':', 1)
vals = vals + ['', '1'][len(vals):]
return vals[0], float(vals[1])
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]
def resample(input, size, align_corners=True):
n, c, h, w = input.shape
dh, dw = size
input = input.reshape([n * c, 1, h, w])
if dh < h:
kernel_h = lanczos(ramp(dh / h, 2), 2).to(input.device, input.dtype)
pad_h = (kernel_h.shape[0] - 1) // 2
input = F.pad(input, (0, 0, pad_h, pad_h), 'reflect')
input = F.conv2d(input, kernel_h[None, None, :, None])
if dw < w:
kernel_w = lanczos(ramp(dw / w, 2), 2).to(input.device, input.dtype)
pad_w = (kernel_w.shape[0] - 1) // 2
input = F.pad(input, (pad_w, pad_w, 0, 0), 'reflect')
input = F.conv2d(input, kernel_w[None, None, None, :])
input = input.reshape([n, c, h, w])
return F.interpolate(input, size, mode='bicubic', align_corners=align_corners)
class MakeCutouts(nn.Module):
def __init__(self, cut_size, cutn, skip_augs=False):
super().__init__()
self.cut_size = cut_size
self.cutn = cutn
self.skip_augs = skip_augs
self.augs = T.Compose([
T.RandomHorizontalFlip(p=0.5),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomAffine(degrees=15, translate=(0.1, 0.1)),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomPerspective(distortion_scale=0.4, p=0.7),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomGrayscale(p=0.15),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
# T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),
])
def forward(self, input):
input = T.Pad(input.shape[2]//4, fill=0)(input)
sideY, sideX = input.shape[2:4]
max_size = min(sideX, sideY)
cutouts = []
for ch in range(self.cutn):
if ch > self.cutn - self.cutn//4:
cutout = input.clone()
else:
size = int(max_size * torch.zeros(1,).normal_(mean=.8, std=.3).clip(float(self.cut_size/max_size), 1.))
offsetx = torch.randint(0, abs(sideX - size + 1), ())
offsety = torch.randint(0, abs(sideY - size + 1), ())
cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]
if not self.skip_augs:
cutout = self.augs(cutout)
cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))
del cutout
cutouts = torch.cat(cutouts, dim=0)
return cutouts
cutout_debug = False
padargs = {}
class MakeCutoutsDango(nn.Module):
def __init__(self, cut_size,
Overview=4,
InnerCrop = 0, IC_Size_Pow=0.5, IC_Grey_P = 0.2
):
super().__init__()
self.cut_size = cut_size
self.Overview = Overview
self.InnerCrop = InnerCrop
self.IC_Size_Pow = IC_Size_Pow
self.IC_Grey_P = IC_Grey_P
if args.animation_mode == 'None':
self.augs = T.Compose([
T.RandomHorizontalFlip(p=0.5),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomGrayscale(p=0.1),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),
])
elif args.animation_mode == 'Video Input':
self.augs = T.Compose([
T.RandomHorizontalFlip(p=0.5),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomAffine(degrees=15, translate=(0.1, 0.1)),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomPerspective(distortion_scale=0.4, p=0.7),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomGrayscale(p=0.15),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
# T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),
])
elif args.animation_mode == '2D':
self.augs = T.Compose([
T.RandomHorizontalFlip(p=0.4),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.RandomGrayscale(p=0.1),
T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),
T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.3),
])
def forward(self, input):
cutouts = []
gray = T.Grayscale(3)
sideY, sideX = input.shape[2:4]
max_size = min(sideX, sideY)
min_size = min(sideX, sideY, self.cut_size)
l_size = max(sideX, sideY)
output_shape = [1,3,self.cut_size,self.cut_size]
output_shape_2 = [1,3,self.cut_size+2,self.cut_size+2]
pad_input = F.pad(input,((sideY-max_size)//2,(sideY-max_size)//2,(sideX-max_size)//2,(sideX-max_size)//2), **padargs)
cutout = resize(pad_input, out_shape=output_shape)
if self.Overview>0:
if self.Overview<=4:
if self.Overview>=1:
cutouts.append(cutout)
if self.Overview>=2:
cutouts.append(gray(cutout))
if self.Overview>=3:
cutouts.append(TF.hflip(cutout))
if self.Overview==4:
cutouts.append(gray(TF.hflip(cutout)))
else:
cutout = resize(pad_input, out_shape=output_shape)
for _ in range(self.Overview):
cutouts.append(cutout)
if cutout_debug:
TF.to_pil_image(cutouts[0].clamp(0, 1).squeeze(0)).save("/content/cutout_overview0.jpg",quality=99)
if self.InnerCrop >0:
for i in range(self.InnerCrop):
size = int(torch.rand([])**self.IC_Size_Pow * (max_size - min_size) + min_size)
offsetx = torch.randint(0, sideX - size + 1, ())
offsety = torch.randint(0, sideY - size + 1, ())
cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]
if i <= int(self.IC_Grey_P * self.InnerCrop):
cutout = gray(cutout)
cutout = resize(cutout, out_shape=output_shape)
cutouts.append(cutout)
if cutout_debug:
TF.to_pil_image(cutouts[-1].clamp(0, 1).squeeze(0)).save("/content/cutout_InnerCrop.jpg",quality=99)
cutouts = torch.cat(cutouts)
if skip_augs is not True: cutouts=self.augs(cutouts)
return cutouts
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)
def tv_loss(input):
"""L2 total variation loss, as in Mahendran et al."""
input = F.pad(input, (0, 1, 0, 1), 'replicate')
x_diff = input[..., :-1, 1:] - input[..., :-1, :-1]
y_diff = input[..., 1:, :-1] - input[..., :-1, :-1]
return (x_diff**2 + y_diff**2).mean([1, 2, 3])
def range_loss(input):
return (input - input.clamp(-1, 1)).pow(2).mean([1, 2, 3])
stop_on_next_loop = False # Make sure GPU memory doesn't get corrupted from cancelling the run mid-way through, allow a full frame to complete
def do_run():
seed = args.seed
#print(range(args.start_frame, args.max_frames))
for frame_num in range(args.start_frame, args.max_frames):
if stop_on_next_loop:
break
display.clear_output(wait=True)
# Print Frame progress if animation mode is on
if args.animation_mode != "None":
batchBar = tqdm(range(args.max_frames), desc ="Frames")
batchBar.n = frame_num
batchBar.refresh()
# Inits if not video frames
if args.animation_mode != "Video Input":
if args.init_image == '':
init_image = None
else:
init_image = args.init_image
init_scale = args.init_scale
skip_steps = args.skip_steps
if args.animation_mode == "2D":
if args.key_frames:
angle = args.angle_series[frame_num]
zoom = args.zoom_series[frame_num]
translation_x = args.translation_x_series[frame_num]
translation_y = args.translation_y_series[frame_num]
print(
f'angle: {angle}',
f'zoom: {zoom}',
f'translation_x: {translation_x}',
f'translation_y: {translation_y}',
)
if frame_num > 0:
seed = seed + 1
if resume_run and frame_num == start_frame:
img_0 = cv2.imread(batchFolder+f"/{batch_name}({batchNum})_{start_frame-1:04}.png")
else:
img_0 = cv2.imread('prevFrame.png')
center = (1*img_0.shape[1]//2, 1*img_0.shape[0]//2)
trans_mat = np.float32(
[[1, 0, translation_x],
[0, 1, translation_y]]
)
rot_mat = cv2.getRotationMatrix2D( center, angle, zoom )
trans_mat = np.vstack([trans_mat, [0,0,1]])
rot_mat = np.vstack([rot_mat, [0,0,1]])
transformation_matrix = np.matmul(rot_mat, trans_mat)
img_0 = cv2.warpPerspective(
img_0,
transformation_matrix,
(img_0.shape[1], img_0.shape[0]),
borderMode=cv2.BORDER_WRAP
)
cv2.imwrite('prevFrameScaled.png', img_0)
init_image = 'prevFrameScaled.png'
init_scale = args.frames_scale
skip_steps = args.calc_frames_skip_steps
if args.animation_mode == "Video Input":
seed = seed + 1
init_image = f'{videoFramesFolder}/{frame_num+1:04}.jpg'
init_scale = args.frames_scale
skip_steps = args.calc_frames_skip_steps
loss_values = []
if seed is not None:
np.random.seed(seed)
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
target_embeds, weights = [], []
if args.prompts_series is not None and frame_num >= len(args.prompts_series):
frame_prompt = args.prompts_series[-1]
elif args.prompts_series is not None:
frame_prompt = args.prompts_series[frame_num]
else:
frame_prompt = []
if args.image_prompts_series is not None:
print(args.image_prompts_series)
if args.image_prompts_series is not None and frame_num >= len(args.image_prompts_series):
image_prompt = args.image_prompts_series[-1]
elif args.image_prompts_series is not None:
image_prompt = args.image_prompts_series[frame_num]
else:
image_prompt = []
print(f'Frame Prompt: {frame_prompt}')
model_stats = []
for clip_model in clip_models:
cutn = 16
model_stat = {"clip_model":None,"target_embeds":[],"make_cutouts":None,"weights":[]}
model_stat["clip_model"] = clip_model
for prompt in frame_prompt:
txt, weight = parse_prompt(prompt)
txt = clip_model.encode_text(clip.tokenize(prompt).to(device)).float()
if args.fuzzy_prompt:
for i in range(25):
model_stat["target_embeds"].append((txt + torch.randn(txt.shape).cuda() * args.rand_mag).clamp(0,1))
model_stat["weights"].append(weight)
else:
model_stat["target_embeds"].append(txt)
model_stat["weights"].append(weight)
if image_prompt:
model_stat["make_cutouts"] = MakeCutouts(clip_model.visual.input_resolution, cutn, skip_augs=skip_augs)
for prompt in image_prompt:
path, weight = parse_prompt(prompt)
img = Image.open(fetch(path)).convert('RGB')
img = TF.resize(img, min(side_x, side_y, *img.size), T.InterpolationMode.LANCZOS)
batch = model_stat["make_cutouts"](TF.to_tensor(img).to(device).unsqueeze(0).mul(2).sub(1))
embed = clip_model.encode_image(normalize(batch)).float()
if fuzzy_prompt:
for i in range(25):
model_stat["target_embeds"].append((embed + torch.randn(embed.shape).cuda() * rand_mag).clamp(0,1))
weights.extend([weight / cutn] * cutn)
else:
model_stat["target_embeds"].append(embed)
model_stat["weights"].extend([weight / cutn] * cutn)
model_stat["target_embeds"] = torch.cat(model_stat["target_embeds"])
model_stat["weights"] = torch.tensor(model_stat["weights"], device=device)
if model_stat["weights"].sum().abs() < 1e-3:
raise RuntimeError('The weights must not sum to 0.')
model_stat["weights"] /= model_stat["weights"].sum().abs()
model_stats.append(model_stat)
init = None
if init_image is not None:
#print("Using init image: " + init_image)
init = Image.open(fetch(init_image)).convert('RGB')
init = init.resize((args.side_x, args.side_y), Image.LANCZOS)
init = TF.to_tensor(init).to(device).unsqueeze(0).mul(2).sub(1)
if args.perlin_init:
print("Using perlin noise as init image")
if args.perlin_mode == 'color':
init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)
init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False)
elif args.perlin_mode == 'gray':
init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True)
init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)
else:
init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)
init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)
# init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device)
init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1)
del init2
cur_t = None
def cond_fn(x, t, y=None):
with torch.enable_grad():
x_is_NaN = False
x = x.detach().requires_grad_()
n = x.shape[0]
if use_secondary_model is True:
alpha = torch.tensor(diffusion.sqrt_alphas_cumprod[cur_t], device=device, dtype=torch.float32)
sigma = torch.tensor(diffusion.sqrt_one_minus_alphas_cumprod[cur_t], device=device, dtype=torch.float32)
cosine_t = alpha_sigma_to_t(alpha, sigma)
out = secondary_model(x, cosine_t[None].repeat([n])).pred
fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t]
x_in = out * fac + x * (1 - fac)
x_in_grad = torch.zeros_like(x_in)
else:
my_t = torch.ones([n], device=device, dtype=torch.long) * cur_t
out = diffusion.p_mean_variance(model, x, my_t, clip_denoised=False, model_kwargs={'y': y})
fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t]
x_in = out['pred_xstart'] * fac + x * (1 - fac)
x_in_grad = torch.zeros_like(x_in)
for model_stat in model_stats:
for i in range(args.cutn_batches):
t_int = int(t.item())+1 #errors on last step without +1, need to find source
#when using SLIP Base model the dimensions need to be hard coded to avoid AttributeError: 'VisionTransformer' object has no attribute 'input_resolution'
try:
input_resolution=model_stat["clip_model"].visual.input_resolution
except:
input_resolution=224
cuts = MakeCutoutsDango(input_resolution,
Overview= args.cut_overview[1000-t_int],
InnerCrop = args.cut_innercut[1000-t_int], IC_Size_Pow=args.cut_ic_pow, IC_Grey_P = args.cut_icgray_p[1000-t_int]
)
clip_in = normalize(cuts(x_in.add(1).div(2)))
image_embeds = model_stat["clip_model"].encode_image(clip_in).float()
dists = spherical_dist_loss(image_embeds.unsqueeze(1), model_stat["target_embeds"].unsqueeze(0))
dists = dists.view([args.cut_overview[1000-t_int]+args.cut_innercut[1000-t_int], n, -1])
losses = dists.mul(model_stat["weights"]).sum(2).mean(0)
loss_values.append(losses.sum().item()) # log loss, probably shouldn't do per cutn_batch
x_in_grad += torch.autograd.grad(losses.sum() * clip_guidance_scale, x_in)[0] / cutn_batches
tv_losses = tv_loss(x_in)
if use_secondary_model is True:
range_losses = range_loss(out)
else:
range_losses = range_loss(out['pred_xstart'])
sat_losses = torch.abs(x_in - x_in.clamp(min=-1,max=1)).mean()
loss = tv_losses.sum() * tv_scale + range_losses.sum() * range_scale + sat_losses.sum() * sat_scale
if init is not None and args.init_scale:
init_losses = lpips_model(x_in, init)
loss = loss + init_losses.sum() * args.init_scale
x_in_grad += torch.autograd.grad(loss, x_in)[0]
if torch.isnan(x_in_grad).any()==False:
grad = -torch.autograd.grad(x_in, x, x_in_grad)[0]
else:
# print("NaN'd")
x_is_NaN = True
grad = torch.zeros_like(x)
if args.clamp_grad and x_is_NaN == False:
magnitude = grad.square().mean().sqrt()
return grad * magnitude.clamp(max=args.clamp_max) / magnitude #min=-0.02, min=-clamp_max,
return grad
if model_config['timestep_respacing'].startswith('ddim'):
sample_fn = diffusion.ddim_sample_loop_progressive
else:
sample_fn = diffusion.p_sample_loop_progressive
image_display = Output()
for i in range(args.n_batches):
if args.animation_mode == 'None':
display.clear_output(wait=True)
batchBar = tqdm(range(args.n_batches), desc ="Batches")
batchBar.n = i
batchBar.refresh()
print('')
#display.display(image_display)
gc.collect()
torch.cuda.empty_cache()
cur_t = diffusion.num_timesteps - skip_steps - 1
total_steps = cur_t
if perlin_init:
init = regen_perlin()
if model_config['timestep_respacing'].startswith('ddim'):
samples = sample_fn(
model,
(batch_size, 3, args.side_y, args.side_x),
clip_denoised=clip_denoised,
model_kwargs={},
cond_fn=cond_fn,
progress=True,
skip_timesteps=skip_steps,
init_image=init,
randomize_class=randomize_class,
eta=eta,
)
else:
samples = sample_fn(
model,
(batch_size, 3, args.side_y, args.side_x),
clip_denoised=clip_denoised,
model_kwargs={},
cond_fn=cond_fn,
progress=True,
skip_timesteps=skip_steps,
init_image=init,
randomize_class=randomize_class,
)
# with run_display:
# display.clear_output(wait=True)
imgToSharpen = None
for j, sample in enumerate(samples):
cur_t -= 1
intermediateStep = False
if args.steps_per_checkpoint is not None:
if j % steps_per_checkpoint == 0 and j > 0:
intermediateStep = True
elif j in args.intermediate_saves:
intermediateStep = True
with image_display:
# base the final filename on the input args
final_image_path = output_path + '/' + output_filename
if j % args.display_rate == 0 or cur_t == -1 or intermediateStep == True:
for k, image in enumerate(sample['pred_xstart']):
# tqdm.write(f'Batch {i}, step {j}, output {k}:')
current_time = datetime.now().strftime('%y%m%d-%H%M%S_%f')
percent = math.ceil(j/total_steps*100)
if args.n_batches > 0:
#if intermediates are saved to the subfolder, don't append a step or percentage to the name
p_filename = output_filename.replace('.png','')
if cur_t == -1 and args.intermediates_in_subfolder is True:
save_num = f'{frame_num:04}' if animation_mode != "None" else i
#filename = f'{args.batch_name}({args.batchNum})_{save_num}.png'
filename = f'{p_filename}_{save_num}.png'
else:
#If we're working with percentages, append it
if args.steps_per_checkpoint is not None:
#filename = f'{args.batch_name}({args.batchNum})_{i:04}-{percent:02}%.png'
filename = f'{p_filename}_{percent:02}%.png'
# Or else, iIf we're working with specific steps, append those
else:
#filename = f'{args.batch_name}({args.batchNum})_{i:04}-{j:03}.png'
filename = f'{p_filename}_{j:03}.png'
image = TF.to_pil_image(image.add(1).div(2).clamp(0, 1))
#if j % args.display_rate == 0 or cur_t == -1:
#image.save('progress.png')
#display.clear_output(wait=True)
#display.display(display.Image('progress.png'))
if args.steps_per_checkpoint is not None:
if j % args.steps_per_checkpoint == 0 and j > 0:
if args.intermediates_in_subfolder is True:
#image.save(f'{partialFolder}/{filename}')
im = image.convert('RGB')
im.save((partialFolder+'/'+filename).replace('.png','.jpg'), quality=80)
else:
image.save(f'{batchFolder}/{filename}')
else:
if j in args.intermediate_saves:
if args.intermediates_in_subfolder is True:
#image.save(f'{partialFolder}/{filename}')
im = image.convert('RGB')
im.save((partialFolder+'/'+filename).replace('.png','.jpg'), quality=80)
else:
image.save(f'{batchFolder}/{filename}')
if cur_t == -1:
#if frame_num == 0:
#save_settings(final_image_path)
if args.animation_mode != "None":
image.save('prevFrame.png')
if args.sharpen_preset != "Off" and animation_mode == "None":
imgToSharpen = image
if args.keep_unsharp is True:
image.save(f'{unsharpenFolder}/{filename}')
else:
#image.save(f'{batchFolder}/{filename}')
if final_image_path != '':
image.save(final_image_path)
else:
image.save(f'{batchFolder}/{filename}')
# if frame_num != args.max_frames-1:
# display.clear_output()
with image_display:
if args.sharpen_preset != "Off" and animation_mode == "None":
print('Starting Diffusion Sharpening...')
#do_superres(imgToSharpen, f'{batchFolder}/{filename}')
if final_image_path != '':
do_superres(imgToSharpen, final_image_path)
else:
do_superres(imgToSharpen, f'{batchFolder}/{filename}')
display.clear_output()
plt.plot(np.array(loss_values), 'r')
def save_settings(final_name):
setting_list = {
'text_prompts': text_prompts,
'image_prompts': image_prompts,
'clip_guidance_scale': clip_guidance_scale,
'tv_scale': tv_scale,
'range_scale': range_scale,
'sat_scale': sat_scale,
# 'cutn': cutn,
'cutn_batches': cutn_batches,
'max_frames': max_frames,
'interp_spline': interp_spline,
# 'rotation_per_frame': rotation_per_frame,
'init_image': init_image,
'init_scale': init_scale,
'skip_steps': skip_steps,
# 'zoom_per_frame': zoom_per_frame,
'frames_scale': frames_scale,
'frames_skip_steps': frames_skip_steps,
'perlin_init': perlin_init,
'perlin_mode': perlin_mode,
'skip_augs': skip_augs,
'randomize_class': randomize_class,
'clip_denoised': clip_denoised,
'clamp_grad': clamp_grad,
'clamp_max': clamp_max,
'seed': seed,
'fuzzy_prompt': fuzzy_prompt,
'rand_mag': rand_mag,
'eta': eta,
'width': width_height[0],
'height': width_height[1],
'diffusion_model': diffusion_model,
'use_secondary_model': use_secondary_model,
'steps': steps,
'diffusion_steps': diffusion_steps,
'ViTB32': ViTB32,
'ViTB16': ViTB16,
'ViTL14': ViTL14,
'RN101': RN101,
'RN50': RN50,
'RN50x4': RN50x4,
'RN50x16': RN50x16,
'RN50x64': RN50x64,
'cut_overview': str(cut_overview),
'cut_innercut': str(cut_innercut),
'cut_ic_pow': cut_ic_pow,
'cut_icgray_p': str(cut_icgray_p),
'key_frames': key_frames,
'max_frames': max_frames,
'angle': angle,
'zoom': zoom,
'translation_x': translation_x,
'translation_y': translation_y,
'video_init_path':video_init_path,
'extract_nth_frame':extract_nth_frame,
}
# print('Settings:', setting_list)
if final_name=='':
with open(f"{batchFolder}/{batch_name}({batchNum})_settings.txt", "w+") as f: #save settings
json.dump(setting_list, f, ensure_ascii=False, indent=4)
else:
with open(final_name.replace('png','txt'), "w+") as f: #save settings
json.dump(setting_list, f, ensure_ascii=False, indent=4)
def append_dims(x, n):
return x[(Ellipsis, *(None,) * (n - x.ndim))]
def expand_to_planes(x, shape):
return append_dims(x, len(shape)).repeat([1, 1, *shape[2:]])
def alpha_sigma_to_t(alpha, sigma):
return torch.atan2(sigma, alpha) * 2 / math.pi
def t_to_alpha_sigma(t):
return torch.cos(t * math.pi / 2), torch.sin(t * math.pi / 2)
@dataclass
class DiffusionOutput:
v: torch.Tensor
pred: torch.Tensor
eps: torch.Tensor
class ConvBlock(nn.Sequential):
def __init__(self, c_in, c_out):
super().__init__(
nn.Conv2d(c_in, c_out, 3, padding=1),
nn.ReLU(inplace=True),
)
class SkipBlock(nn.Module):
def __init__(self, main, skip=None):
super().__init__()
self.main = nn.Sequential(*main)
self.skip = skip if skip else nn.Identity()
def forward(self, input):
return torch.cat([self.main(input), self.skip(input)], dim=1)
class FourierFeatures(nn.Module):
def __init__(self, in_features, out_features, std=1.):
super().__init__()
assert out_features % 2 == 0
self.weight = nn.Parameter(torch.randn([out_features // 2, in_features]) * std)
def forward(self, input):
f = 2 * math.pi * input @ self.weight.T
return torch.cat([f.cos(), f.sin()], dim=-1)
class SecondaryDiffusionImageNet(nn.Module):
def __init__(self):
super().__init__()
c = 64 # The base channel count
self.timestep_embed = FourierFeatures(1, 16)
self.net = nn.Sequential(
ConvBlock(3 + 16, c),
ConvBlock(c, c),
SkipBlock([
nn.AvgPool2d(2),
ConvBlock(c, c * 2),
ConvBlock(c * 2, c * 2),
SkipBlock([
nn.AvgPool2d(2),
ConvBlock(c * 2, c * 4),
ConvBlock(c * 4, c * 4),
SkipBlock([
nn.AvgPool2d(2),
ConvBlock(c * 4, c * 8),
ConvBlock(c * 8, c * 4),
nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
]),
ConvBlock(c * 8, c * 4),
ConvBlock(c * 4, c * 2),
nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
]),
ConvBlock(c * 4, c * 2),
ConvBlock(c * 2, c),
nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
]),
ConvBlock(c * 2, c),
nn.Conv2d(c, 3, 3, padding=1),
)
def forward(self, input, t):
timestep_embed = expand_to_planes(self.timestep_embed(t[:, None]), input.shape)
v = self.net(torch.cat([input, timestep_embed], dim=1))
alphas, sigmas = map(partial(append_dims, n=v.ndim), t_to_alpha_sigma(t))
pred = input * alphas - v * sigmas
eps = input * sigmas + v * alphas
return DiffusionOutput(v, pred, eps)
class SecondaryDiffusionImageNet2(nn.Module):
def __init__(self):
super().__init__()
c = 64 # The base channel count
cs = [c, c * 2, c * 2, c * 4, c * 4, c * 8]
self.timestep_embed = FourierFeatures(1, 16)
self.down = nn.AvgPool2d(2)
self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False)
self.net = nn.Sequential(
ConvBlock(3 + 16, cs[0]),
ConvBlock(cs[0], cs[0]),
SkipBlock([
self.down,
ConvBlock(cs[0], cs[1]),
ConvBlock(cs[1], cs[1]),
SkipBlock([
self.down,
ConvBlock(cs[1], cs[2]),
ConvBlock(cs[2], cs[2]),
SkipBlock([
self.down,
ConvBlock(cs[2], cs[3]),
ConvBlock(cs[3], cs[3]),
SkipBlock([
self.down,
ConvBlock(cs[3], cs[4]),
ConvBlock(cs[4], cs[4]),
SkipBlock([
self.down,
ConvBlock(cs[4], cs[5]),
ConvBlock(cs[5], cs[5]),
ConvBlock(cs[5], cs[5]),
ConvBlock(cs[5], cs[4]),
self.up,
]),
ConvBlock(cs[4] * 2, cs[4]),
ConvBlock(cs[4], cs[3]),
self.up,
]),
ConvBlock(cs[3] * 2, cs[3]),
ConvBlock(cs[3], cs[2]),
self.up,
]),
ConvBlock(cs[2] * 2, cs[2]),
ConvBlock(cs[2], cs[1]),
self.up,
]),
ConvBlock(cs[1] * 2, cs[1]),
ConvBlock(cs[1], cs[0]),
self.up,
]),
ConvBlock(cs[0] * 2, cs[0]),
nn.Conv2d(cs[0], 3, 3, padding=1),
)
def forward(self, input, t):
timestep_embed = expand_to_planes(self.timestep_embed(t[:, None]), input.shape)
v = self.net(torch.cat([input, timestep_embed], dim=1))