-
Notifications
You must be signed in to change notification settings - Fork 11
/
diffuse.py
1718 lines (1431 loc) · 63.9 KB
/
diffuse.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
# # 1. Set Up
import os
from os import path
import sys
from argparse import ArgumentParser, Namespace
def run_from_ipython():
try:
__IPYTHON__
return True
except NameError:
return False
parser = ArgumentParser()
parser.add_argument("--gpu", default="0", type=str)
parser.add_argument("--text", default="", type=str)
parser.add_argument("--root_path", default="out_diffusion")
parser.add_argument("--setup", default=False, type=bool)
parser.add_argument("--out_name", default="out_image", type=str)
parser.add_argument("--sharpen_preset", default="Off", type=str, choices=['Off', 'Faster', 'Fast', 'Slow', 'Very Slow'])
parser.add_argument("--width", default=1280, type=int)
parser.add_argument("--height", default=768, type=int)
parser.add_argument("--init_image", default=None, type=str)
parser.add_argument("--steps", default=250, type=int)
parser.add_argument("--skip_steps", default=None, type=int)
parser.add_argument("--inter_saves", default=3, type=int)
if run_from_ipython():
argparse_args = parser.parse_args({})
argparse_args.setup = 1
else:
argparse_args = parser.parse_args()
# read args to determine GPU before importing torch and befor importing other files (torch is also imported in other files)
os.environ["CUDA_VISIBLE_DEVICES"] = argparse_args.gpu
if argparse_args.setup:
get_ipython().system('python3 -m pip install torch lpips datetime timm ipywidgets omegaconf>=2.0.0 pytorch-lightning>=1.0.8 torch-fidelity einops wandb')
get_ipython().system('git clone https://github.com/CompVis/latent-diffusion.git')
get_ipython().system('git clone https://github.com/openai/CLIP')
get_ipython().system('pip3 install -e ./CLIP')
get_ipython().system('git clone https://github.com/assafshocher/ResizeRight.git')
get_ipython().system('git clone https://github.com/crowsonkb/guided-diffusion')
get_ipython().system('python3 -m pip install -e ./guided-diffusion')
get_ipython().system('apt install imagemagick')
#SuperRes
get_ipython().system('git clone https://github.com/CompVis/latent-diffusion.git')
get_ipython().system('git clone https://github.com/CompVis/taming-transformers')
get_ipython().system('pip install -e ./taming-transformers')
# sys.path.append('./SLIP')
sys.path.append('./ResizeRight')
sys.path.append("latent-diffusion")
from secondary_diffusion import SecondaryDiffusionImageNet, SecondaryDiffusionImageNet2
from ddim_sampler import DDIMSampler
from augs import MakeCutouts, MakeCutoutsDango
from perlin import create_perlin_noise, regen_perlin
def alpha_sigma_to_t(alpha, sigma):
return torch.atan2(sigma, alpha) * 2 / math.pi
root_path = argparse_args.root_path
initDirPath = f'{root_path}/init_images'
os.makedirs(initDirPath, exist_ok=1)
outDirPath = f'{root_path}/images_out'
os.makedirs(outDirPath, exist_ok=1)
model_path = f'{root_path}/models'
os.makedirs(model_path, exist_ok=1)
#@title ### 2.1 Install and import dependencies
model_256_downloaded = False
model_512_downloaded = False
model_secondary_downloaded = False
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
#sys.path.append('./CLIP')
sys.path.append('./guided-diffusion')
import clip
from resize_right import resize
# from models import SLIP_VITB16, SLIP, SLIP_VITL16
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
#SuperRes
import ipywidgets as widgets
import os
sys.path.append(".")
sys.path.append('./taming-transformers')
from taming.models import vqgan # checking correct import from taming
from torchvision.datasets.utils import download_url
sys.path.append("./latent-diffusion")
if argparse_args.setup:
get_ipython().run_line_magic('cd', "latent-diffusion")
from ldm.util import instantiate_from_config
# from ldm.models.diffusion.ddim import DDIMSampler
from ldm.util import ismap
if argparse_args.setup:
get_ipython().run_line_magic('cd', '..')
#from google.colab import files
from IPython.display import Image as ipyimg
from numpy import asarray
from einops import rearrange, repeat
import torch, torchvision
import time
from omegaconf import OmegaConf
import warnings
warnings.filterwarnings("ignore", category=UserWarning)
import torch
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print('Using device:', device)
if torch.cuda.get_device_capability(device) == (8,0): ## A100 fix thanks to Emad
print('Disabling CUDNN for A100 gpu', file=sys.stderr)
torch.backends.cudnn.enabled = False
#@title 2.2 Define necessary functions
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 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 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 = []
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:
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:
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
if init is not None and args.init_scale:
lpips_model = lpips.LPIPS(net='vgg').to(device)
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],
animation_mode=args.animation_mode,
)
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:
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
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'
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'
# Or else, iIf we're working with specific steps, append those
else:
filename = f'{args.batch_name}({args.batchNum})_{i:04}-{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.jpg', subsampling=0, quality=95)
#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}')
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}')
else:
image.save(f'{batchFolder}/{filename}')
if cur_t == -1:
if frame_num == 0:
save_settings()
if args.animation_mode != "None":
image.save('prevFrame.jpg', subsampling=0, quality=95)
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 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}')
display.clear_output()
plt.plot(np.array(loss_values), 'r')
def save_settings():
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,
'RN101': RN101,
'RN50': RN50,
'RN50x4': RN50x4,
'RN50x16': RN50x16,
'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)
with open(f"{batchFolder}/{batch_name}({batchNum})_settings.txt", "w+") as f: #save settings
json.dump(setting_list, f, ensure_ascii=False, indent=4)
#@title 2.4 SuperRes Define
def download_models():
# this is the small bsr light model
url_conf = 'https://heibox.uni-heidelberg.de/f/31a76b13ea27482981b4/?dl=1'
url_ckpt = 'https://heibox.uni-heidelberg.de/f/578df07c8fc04ffbadf3/?dl=1'
path_conf = f'{model_path}/superres/'
path_ckpt = f'{model_path}/superres/'
download_url(url_conf, path_conf, 'project.yaml')
download_url(url_ckpt, path_ckpt, 'last.ckpt')
path_conf = path_conf + 'project.yaml' # fix it
path_ckpt = path_ckpt + 'last.ckpt' # fix it
return path_conf, path_ckpt
def load_model_from_config(config, ckpt):
print(f"Loading model from {ckpt}")
pl_sd = torch.load(ckpt, map_location="cpu")
global_step = pl_sd["global_step"]
sd = pl_sd["state_dict"]
model = instantiate_from_config(config.model)
m, u = model.load_state_dict(sd, strict=False)
model.cuda()
model.eval()
return {"model": model}, global_step
def get_model(mode):
path_conf, path_ckpt = download_models()
config = OmegaConf.load(path_conf)
model, step = load_model_from_config(config, path_ckpt)
return model
def get_custom_cond(mode):
dest = "data/example_conditioning"
if mode == "superresolution":
uploaded_img = files.upload()
filename = next(iter(uploaded_img))
name, filetype = filename.split(".") # todo assumes just one dot in name !
os.rename(f"{filename}", f"{dest}/{mode}/custom_{name}.{filetype}")
elif mode == "text_conditional":
w = widgets.Text(value='A cake with cream!', disabled=True)
display.display(w)
with open(f"{dest}/{mode}/custom_{w.value[:20]}.txt", 'w') as f:
f.write(w.value)
elif mode == "class_conditional":
w = widgets.IntSlider(min=0, max=1000)
display.display(w)
with open(f"{dest}/{mode}/custom.txt", 'w') as f:
f.write(w.value)
else:
raise NotImplementedError(f"cond not implemented for mode{mode}")
def get_cond_options(mode):
path = "data/example_conditioning"
path = os.path.join(path, mode)
onlyfiles = [f for f in sorted(os.listdir(path))]
return path, onlyfiles
def select_cond_path(mode):
path = "data/example_conditioning" # todo
path = os.path.join(path, mode)
onlyfiles = [f for f in sorted(os.listdir(path))]
selected = widgets.RadioButtons(
options=onlyfiles,
description='Select conditioning:',
disabled=False
)
display.display(selected)
selected_path = os.path.join(path, selected.value)
return selected_path
def get_cond(mode, img):
example = dict()
if mode == "superresolution":
up_f = 4
# visualize_cond_img(selected_path)
c = img
c = torch.unsqueeze(torchvision.transforms.ToTensor()(c), 0)
c_up = torchvision.transforms.functional.resize(c, size=[up_f * c.shape[2], up_f * c.shape[3]], antialias=True)
c_up = rearrange(c_up, '1 c h w -> 1 h w c')
c = rearrange(c, '1 c h w -> 1 h w c')
c = 2. * c - 1.
c = c.to(torch.device("cuda"))
example["LR_image"] = c
example["image"] = c_up
return example
def visualize_cond_img(path):
display.display(ipyimg(filename=path))
def sr_run(model, img, task, custom_steps, eta, resize_enabled=False, classifier_ckpt=None, global_step=None):
# global stride
example = get_cond(task, img)
save_intermediate_vid = False
n_runs = 1
masked = False
guider = None
ckwargs = None
mode = 'ddim'
ddim_use_x0_pred = False
temperature = 1.
eta = eta
make_progrow = True
custom_shape = None
height, width = example["image"].shape[1:3]
split_input = height >= 128 and width >= 128
if split_input:
ks = 128
stride = 64
vqf = 4 #
model.split_input_params = {"ks": (ks, ks), "stride": (stride, stride),
"vqf": vqf,
"patch_distributed_vq": True,
"tie_braker": False,
"clip_max_weight": 0.5,
"clip_min_weight": 0.01,
"clip_max_tie_weight": 0.5,
"clip_min_tie_weight": 0.01}
else:
if hasattr(model, "split_input_params"):
delattr(model, "split_input_params")
invert_mask = False
x_T = None
for n in range(n_runs):
if custom_shape is not None:
x_T = torch.randn(1, custom_shape[1], custom_shape[2], custom_shape[3]).to(model.device)
x_T = repeat(x_T, '1 c h w -> b c h w', b=custom_shape[0])
logs = make_convolutional_sample(example, model,
mode=mode, custom_steps=custom_steps,
eta=eta, swap_mode=False , masked=masked,
invert_mask=invert_mask, quantize_x0=False,
custom_schedule=None, decode_interval=10,
resize_enabled=resize_enabled, custom_shape=custom_shape,
temperature=temperature, noise_dropout=0.,
corrector=guider, corrector_kwargs=ckwargs, x_T=x_T, save_intermediate_vid=save_intermediate_vid,
make_progrow=make_progrow,ddim_use_x0_pred=ddim_use_x0_pred
)
return logs
@torch.no_grad()
def convsample_ddim(model, cond, steps, shape, eta=1.0, callback=None, normals_sequence=None,
mask=None, x0=None, quantize_x0=False, img_callback=None,
temperature=1., noise_dropout=0., score_corrector=None,
corrector_kwargs=None, x_T=None, log_every_t=None
):
ddim = DDIMSampler(model)
bs = shape[0] # dont know where this comes from but wayne
shape = shape[1:] # cut batch dim
# print(f"Sampling with eta = {eta}; steps: {steps}")
samples, intermediates = ddim.sample(steps, batch_size=bs, shape=shape, conditioning=cond, callback=callback,
normals_sequence=normals_sequence, quantize_x0=quantize_x0, eta=eta,
mask=mask, x0=x0, temperature=temperature, verbose=False,
score_corrector=score_corrector,
corrector_kwargs=corrector_kwargs, x_T=x_T)
return samples, intermediates
@torch.no_grad()
def make_convolutional_sample(batch, model, mode="vanilla", custom_steps=None, eta=1.0, swap_mode=False, masked=False,
invert_mask=True, quantize_x0=False, custom_schedule=None, decode_interval=1000,
resize_enabled=False, custom_shape=None, temperature=1., noise_dropout=0., corrector=None,
corrector_kwargs=None, x_T=None, save_intermediate_vid=False, make_progrow=True,ddim_use_x0_pred=False):
log = dict()
z, c, x, xrec, xc = model.get_input(batch, model.first_stage_key,
return_first_stage_outputs=True,
force_c_encode=not (hasattr(model, 'split_input_params')
and model.cond_stage_key == 'coordinates_bbox'),
return_original_cond=True)
log_every_t = 1 if save_intermediate_vid else None
if custom_shape is not None:
z = torch.randn(custom_shape)
# print(f"Generating {custom_shape[0]} samples of shape {custom_shape[1:]}")
z0 = None
log["input"] = x
log["reconstruction"] = xrec
if ismap(xc):
log["original_conditioning"] = model.to_rgb(xc)
if hasattr(model, 'cond_stage_key'):
log[model.cond_stage_key] = model.to_rgb(xc)
else:
log["original_conditioning"] = xc if xc is not None else torch.zeros_like(x)
if model.cond_stage_model:
log[model.cond_stage_key] = xc if xc is not None else torch.zeros_like(x)
if model.cond_stage_key =='class_label':
log[model.cond_stage_key] = xc[model.cond_stage_key]
with model.ema_scope("Plotting"):
t0 = time.time()
img_cb = None
sample, intermediates = convsample_ddim(model, c, steps=custom_steps, shape=z.shape,
eta=eta,
quantize_x0=quantize_x0, img_callback=img_cb, mask=None, x0=z0,
temperature=temperature, noise_dropout=noise_dropout,
score_corrector=corrector, corrector_kwargs=corrector_kwargs,
x_T=x_T, log_every_t=log_every_t)
t1 = time.time()
if ddim_use_x0_pred:
sample = intermediates['pred_x0'][-1]
x_sample = model.decode_first_stage(sample)
try:
x_sample_noquant = model.decode_first_stage(sample, force_not_quantize=True)
log["sample_noquant"] = x_sample_noquant
log["sample_diff"] = torch.abs(x_sample_noquant - x_sample)
except:
pass
log["sample"] = x_sample
log["time"] = t1 - t0
return log
sr_diffMode = 'superresolution'
sr_model = get_model('superresolution') if argparse_args.sharpen_preset != "Off" else None
def do_superres(img, filepath):
if args.sharpen_preset == 'Faster':
sr_diffusion_steps = "25"
sr_pre_downsample = '1/2'
if args.sharpen_preset == 'Fast':
sr_diffusion_steps = "100"
sr_pre_downsample = '1/2'
if args.sharpen_preset == 'Slow':
sr_diffusion_steps = "25"
sr_pre_downsample = 'None'
if args.sharpen_preset == 'Very Slow':
sr_diffusion_steps = "100"
sr_pre_downsample = 'None'
sr_post_downsample = 'Original Size'
sr_diffusion_steps = int(sr_diffusion_steps)
sr_eta = 1.0
sr_downsample_method = 'Lanczos'
gc.collect()
torch.cuda.empty_cache()
im_og = img
width_og, height_og = im_og.size
#Downsample Pre
if sr_pre_downsample == '1/2':
downsample_rate = 2
elif sr_pre_downsample == '1/4':
downsample_rate = 4
else:
downsample_rate = 1
width_downsampled_pre = width_og//downsample_rate
height_downsampled_pre = height_og//downsample_rate
if downsample_rate != 1:
# print(f'Downsampling from [{width_og}, {height_og}] to [{width_downsampled_pre}, {height_downsampled_pre}]')
im_og = im_og.resize((width_downsampled_pre, height_downsampled_pre), Image.LANCZOS)
# im_og.save('/content/temp.png')
# filepath = '/content/temp.png'
logs = sr_run(sr_model["model"], im_og, sr_diffMode, sr_diffusion_steps, sr_eta)
sample = logs["sample"]
sample = sample.detach().cpu()
sample = torch.clamp(sample, -1., 1.)
sample = (sample + 1.) / 2. * 255
sample = sample.numpy().astype(np.uint8)
sample = np.transpose(sample, (0, 2, 3, 1))
a = Image.fromarray(sample[0])
#Downsample Post
if sr_post_downsample == '1/2':
downsample_rate = 2
elif sr_post_downsample == '1/4':
downsample_rate = 4
else:
downsample_rate = 1
width, height = a.size
width_downsampled_post = width//downsample_rate
height_downsampled_post = height//downsample_rate
if sr_downsample_method == 'Lanczos':
aliasing = Image.LANCZOS
else:
aliasing = Image.NEAREST
if downsample_rate != 1:
# print(f'Downsampling from [{width}, {height}] to [{width_downsampled_post}, {height_downsampled_post}]')
a = a.resize((width_downsampled_post, height_downsampled_post), aliasing)
elif sr_post_downsample == 'Original Size':
# print(f'Downsampling from [{width}, {height}] to Original Size [{width_og}, {height_og}]')
a = a.resize((width_og, height_og), aliasing)
display.display(a)
a.save(filepath)
return
print(f'Processing finished!')
# # 3. Diffusion and CLIP model settings
#@markdown ####**Models Settings:**
diffusion_model = "512x512_diffusion_uncond_finetune_008100" #@param ["256x256_diffusion_uncond", "512x512_diffusion_uncond_finetune_008100"]
use_secondary_model = True #@param {type: 'boolean'}
timestep_respacing = '50' # param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000']
diffusion_steps = 1000 # param {type: 'number'}
use_checkpoint = True #@param {type: 'boolean'}
ViTB32 = True #@param{type:"boolean"}
ViTB16 = True #@param{type:"boolean"}
RN101 = False #@param{type:"boolean"}
RN50 = True #@param{type:"boolean"}
RN50x4 = False #@param{type:"boolean"}
RN50x16 = False #@param{type:"boolean"}
SLIPB16 = False # param{type:"boolean"}
SLIPL16 = False # param{type:"boolean"}
#@markdown If you're having issues with model downloads, check this to compare SHA's:
check_model_SHA = False #@param{type:"boolean"}
model_256_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a'
model_512_SHA = '9c111ab89e214862b76e1fa6a1b3f1d329b1a88281885943d2cdbe357ad57648'
model_secondary_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a'
model_256_link = 'https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt'
model_512_link = 'http://batbot.tv/ai/models/guided-diffusion/512x512_diffusion_uncond_finetune_008100.pt'
model_secondary_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/secondary_model_imagenet_2.pth'
model_256_path = f'{model_path}/256x256_diffusion_uncond.pt'
model_512_path = f'{model_path}/512x512_diffusion_uncond_finetune_008100.pt'
model_secondary_path = f'{model_path}/secondary_model_imagenet_2.pth'
# Download the diffusion model
if diffusion_model == '256x256_diffusion_uncond':
if os.path.exists(model_256_path) and check_model_SHA:
print('Checking 256 Diffusion File')
with open(model_256_path,"rb") as f:
bytes = f.read()
hash = hashlib.sha256(bytes).hexdigest()
if hash == model_256_SHA:
print('256 Model SHA matches')
model_256_downloaded = True
else:
print("256 Model SHA doesn't match, redownloading...")
if argparse_args.setup:
download_url(model_256_link, model_path, '256x256_diffusion_uncond.pt')
model_256_downloaded = True
elif os.path.exists(model_256_path) and not check_model_SHA or model_256_downloaded == True:
print('256 Model already downloaded, check check_model_SHA if the file is corrupt')
else:
if argparse_args.setup:
download_url(model_256_link, model_path, '256x256_diffusion_uncond.pt')
model_256_downloaded = True
elif diffusion_model == '512x512_diffusion_uncond_finetune_008100':
if os.path.exists(model_512_path) and check_model_SHA:
print('Checking 512 Diffusion File')