forked from multimodalart/mindseye
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hypertron_streamlit_run.py
2721 lines (2405 loc) · 112 KB
/
hypertron_streamlit_run.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
# Hypertron v2 (modified by @softology to work on Visions of Chaos and further modified by @multimodalart to run on MindsEye)
# Original file is located at https://colab.research.google.com/drive/1N4UNSbtNMd31N_gAT9rAm8ZzPh62Y5ud
"""
More info on flavors [here](https://i.ibb.co/hCdm3W4/flavors.png).
More info on prompt experiments [here](https://i.ibb.co/0FF7vNn/prompt-experiments.png).
The styles of made-up, not real, artists can be found [here](https://docs.google.com/spreadsheets/d/1nMq-TjBj3t6us-npLRoLFq0VtgpVwdXCKTcQgnxKgTQ/edit?usp=sharing).
Keywords cheatsheet can be found [here](https://imgur.com/a/SnSIQRu) (made by kingdomakrillic).
A short guide to prompt engineering can be found [here](https://docs.google.com/document/d/1qy5fdeThu7pIikulQuWpmKvYBiv9wMshIHcrBr-VldA/edit?usp=sharing).
"""
"""
Main_Libraries = True #@param {type:"boolean"}
Import_Libraries = True
Download_Video = False #@param {type:"boolean"}
Download_Super_Res = False #@param {type:"boolean"}
Download_Super_Slomo = False #@param {type:"boolean"}
if Main_Libraries == True:
print('GPU:')
!nvidia-smi --query-gpu=name,memory.total --format=cs
print("\nDownloading CLIP...")
!git clone https://github.com/openai/CLIP &> /dev/null
print("Installing AI Python libraries...")
!git clone https://github.com/CompVis/taming-transformers &> /dev/null
!pip install ftfy regex tqdm omegaconf pytorch-lightning &> /dev/null
!pip install kornia &> /dev/null
!pip install einops &> /dev/null
!pip install transformers &> /dev/null
!pip install torch_optimizer &> /dev/null
!pip install noise &> /dev/null
!pip install gputil &> /dev/null
!pip install taming-transformers &> /dev/null
#!git clone https://github.com/lessw2020/Ranger21.git &> /dev/null
#!cd Ranger21 &> /dev/null
#!pip install -e . &> /dev/null
#!cd .. &> /dev/null
!mkdir steps
# %mkdir Init_Img
print("Installing libraries for handling metadata...")
!pip install stegano &> /dev/null
!apt install exempi &> /dev/null
!pip install python-xmp-toolkit &> /dev/null
!pip install imgtag &> /dev/null
if Download_Video:
print("Installing Python libraries for video creation...")
!pip install imageio-ffmpeg &> /dev/null
!pip install timm &> /dev/null
if Download_Super_Res:
print("Installing Python libraries for super resolution...")
# %cd /content/
!git clone https://github.com/sberbank-ai/Real-ESRGAN /content/RealESRGAN &> /dev/null
# %cd RealESRGAN
!pip install -r requirements.txt &> /dev/null
# download model weights
# x2
#!gdown https://drive.google.com/uc?id=1pG2S3sYvSaO0V0B8QPOl1RapPHpUGOaV -O weights/RealESRGAN_x2.pth
# x4
!gdown https://drive.google.com/uc?id=1SGHdZAln4en65_NQeQY9UjchtkEF9f5F -O weights/RealESRGAN_x4.pth &> /dev/null
# x8
#!gdown https://drive.google.com/uc?id=1mT9ewx86PSrc43b-ax47l1E2UzR7Ln4j -O weights/RealESRGAN_x8.pth
# %cd /content/
if Download_Super_Slomo:
!git clone -q --depth 1 https://github.com/avinashpaliwal/Super-SloMo.git &> /dev/null
from os.path import exists
def download_from_google_drive(file_id, file_name):
# download a file from the Google Drive link
!rm -f ./cookie
!curl -c ./cookie -s -L "https://drive.google.com/uc?export=download&id={file_id}" > /dev/null
confirm_text = !awk '/download/ {print $NF}' ./cookie
confirm_text = confirm_text[0]
!curl -Lb ./cookie "https://drive.google.com/uc?export=download&confirm={confirm_text}&id={file_id}" -o {file_name} &> /dev/null
pretrained_model = 'SuperSloMo.ckpt'
if not exists(pretrained_model):
download_from_google_drive('1IvobLDbRiBgZr3ryCRrWL8xDbMZ-KnpF', pretrained_model)
# %mkdir png_processing
# %mkdir templates
!curl https://i.ibb.co/3kn9Qrv/flag.png -o templates/flag.png &> /dev/null
!curl https://i.ibb.co/0BHqVyg/14135136623-3973d3f03c-z.jpg -o templates/planet.png &> /dev/null
!curl https://i.ibb.co/52WMK2M/j7oocvu80qe11.png -o templates/map.png &> /dev/null
!curl https://i.ibb.co/3fg9Zkx/creature.png -o templates/creature.png &> /dev/null
!curl https://i.ibb.co/X3Mh2pP/human.jpg -o templates/human.png &> /dev/null
"""
import sys
import streamlit as st
import argparse
import math
from pathlib import Path
import sys
import pandas as pd
from IPython import display
from base64 import b64encode
from omegaconf import OmegaConf
from PIL import Image
from taming.models import cond_transformer, vqgan
import torch
from os.path import exists as path_exists
torch.cuda.empty_cache()
from torch import nn
import torch.optim as optim
from torch import optim
from torch.nn import functional as F
from torchvision import transforms
from torchvision.transforms import functional as TF
import torchvision.transforms as T
#from stqdm import stqdm
# from tqdm.notebook import tqdm
from CLIP import clip
import kornia.augmentation as K
import numpy as np
import subprocess
import imageio
from PIL import ImageFile, Image
import time
# ImageFile.LOAD_TRUNCATED_IMAGES = True
import hashlib
from PIL.PngImagePlugin import PngImageFile, PngInfo
import json
import IPython
from IPython.display import Markdown, display, Image, clear_output
import urllib.request
import random
from random import randint
from pathvalidate import sanitize_filename
sys.stdout.write("Imports ...\n")
sys.stdout.flush()
sys.path.append("./CLIP")
sys.path.append("./taming-transformers")
sys.stdout.write("Parsing arguments ...\n")
sys.stdout.flush()
torch.cuda.empty_cache()
def run_model(args2, status, stoutput, DefaultPaths):
global model, last_model
try:
last_model
except:
last_model = ''
if args2.seed is not None:
import torch
sys.stdout.write(f"Setting seed to {args2.seed} ...\n")
sys.stdout.flush()
status.write(f"Setting seed to {args2.seed} ...\n")
import numpy as np
np.random.seed(args2.seed)
import random
random.seed(args2.seed)
# next line forces deterministic random values, but causes other issues with resampling (uncomment to see)
torch.manual_seed(args2.seed)
torch.cuda.manual_seed(args2.seed)
torch.cuda.manual_seed_all(args2.seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
"""
from imgtag import ImgTag # metadata
from libxmp import * # metadata
import libxmp # metadata
from stegano import lsb
import gc
import GPUtil as GPU
"""
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print("Using device:", device)
def noise_gen(shape, octaves=5):
n, c, h, w = shape
noise = torch.zeros([n, c, 1, 1])
max_octaves = min(octaves, math.log(h) / math.log(2), math.log(w) / math.log(2))
for i in reversed(range(max_octaves)):
h_cur, w_cur = h // 2**i, w // 2**i
noise = F.interpolate(
noise, (h_cur, w_cur), mode="bicubic", align_corners=False
)
noise += torch.randn([n, c, h_cur, w_cur]) / 5
return noise
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.view([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.view([n, c, h, w])
return F.interpolate(input, size, mode="bicubic", align_corners=align_corners)
def lerp(a, b, f):
return (a * (1.0 - f)) + (b * f)
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
class ClampWithGrad(torch.autograd.Function):
@staticmethod
def forward(ctx, input, min, max):
ctx.min = min
ctx.max = max
ctx.save_for_backward(input)
return input.clamp(min, max)
@staticmethod
def backward(ctx, grad_in):
(input,) = ctx.saved_tensors
return (
grad_in * (grad_in * (input - input.clamp(ctx.min, ctx.max)) >= 0),
None,
None,
)
clamp_with_grad = ClampWithGrad.apply
def vector_quantize(x, codebook):
d = (
x.pow(2).sum(dim=-1, keepdim=True)
+ codebook.pow(2).sum(dim=1)
- 2 * x @ codebook.T
)
indices = d.argmin(-1)
x_q = F.one_hot(indices, codebook.shape[0]).to(d.dtype) @ codebook
return replace_grad(x_q, x)
class Prompt(nn.Module):
def __init__(self, embed, weight=1.0, 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):]
# return vals[0], float(vals[1]), float(vals[2])
def parse_prompt(prompt):
if prompt.startswith("http://") or prompt.startswith("https://"):
vals = prompt.rsplit(":", 1)
vals = [vals[0] + ":" + vals[1], *vals[2:]]
else:
vals = prompt.rsplit(":", 1)
vals = vals + ["", "1", "-inf"][len(vals) :]
return vals[0], float(vals[1]), float(vals[2])
def one_sided_clip_loss(input, target, labels=None, logit_scale=100):
input_normed = F.normalize(input, dim=-1)
target_normed = F.normalize(target, dim=-1)
logits = input_normed @ target_normed.T * logit_scale
if labels is None:
labels = torch.arange(len(input), device=logits.device)
return F.cross_entropy(logits, labels)
class EMATensor(nn.Module):
"""implmeneted by Katherine Crowson"""
def __init__(self, tensor, decay):
super().__init__()
self.tensor = nn.Parameter(tensor)
self.register_buffer("biased", torch.zeros_like(tensor))
self.register_buffer("average", torch.zeros_like(tensor))
self.decay = decay
self.register_buffer("accum", torch.tensor(1.0))
self.update()
@torch.no_grad()
def update(self):
if not self.training:
raise RuntimeError("update() should only be called during training")
self.accum *= self.decay
self.biased.mul_(self.decay)
self.biased.add_((1 - self.decay) * self.tensor)
self.average.copy_(self.biased)
self.average.div_(1 - self.accum)
def forward(self):
if self.training:
return self.tensor
return self.average
############################################################################################
############################################################################################
class MakeCutoutsCustom(nn.Module):
def __init__(self, cut_size, cutn, cut_pow, augs):
super().__init__()
self.cut_size = cut_size
# tqdm.write(f"cut size: {self.cut_size}")
self.cutn = cutn
self.cut_pow = cut_pow
self.noise_fac = 0.1
self.av_pool = nn.AdaptiveAvgPool2d((self.cut_size, self.cut_size))
self.max_pool = nn.AdaptiveMaxPool2d((self.cut_size, self.cut_size))
self.augs = nn.Sequential(
K.RandomHorizontalFlip(p=Random_Horizontal_Flip),
K.RandomSharpness(Random_Sharpness, p=Random_Sharpness_P),
K.RandomGaussianBlur(
(Random_Gaussian_Blur),
(Random_Gaussian_Blur_W, Random_Gaussian_Blur_W),
p=Random_Gaussian_Blur_P,
),
K.RandomGaussianNoise(p=Random_Gaussian_Noise_P),
K.RandomElasticTransform(
kernel_size=(
Random_Elastic_Transform_Kernel_Size_W,
Random_Elastic_Transform_Kernel_Size_H,
),
sigma=(Random_Elastic_Transform_Sigma),
p=Random_Elastic_Transform_P,
),
K.RandomAffine(
degrees=Random_Affine_Degrees,
translate=Random_Affine_Translate,
p=Random_Affine_P,
padding_mode="border",
),
K.RandomPerspective(Random_Perspective, p=Random_Perspective_P),
K.ColorJitter(
hue=Color_Jitter_Hue,
saturation=Color_Jitter_Saturation,
p=Color_Jitter_P,
),
)
# K.RandomErasing((0.1, 0.7), (0.3, 1/0.4), same_on_batch=True, p=0.2),)
def set_cut_pow(self, cut_pow):
self.cut_pow = cut_pow
def forward(self, input):
sideY, sideX = input.shape[2:4]
max_size = min(sideX, sideY)
min_size = min(sideX, sideY, self.cut_size)
cutouts = []
cutouts_full = []
noise_fac = 0.1
min_size_width = min(sideX, sideY)
lower_bound = float(self.cut_size / min_size_width)
for ii in range(self.cutn):
# size = int(torch.rand([])**self.cut_pow * (max_size - min_size) + min_size)
randsize = (
torch.zeros(
1,
)
.normal_(mean=0.8, std=0.3)
.clip(lower_bound, 1.0)
)
size_mult = randsize**self.cut_pow
size = int(
min_size_width * (size_mult.clip(lower_bound, 1.0))
) # replace .5 with a result for 224 the default large size is .95
# size = int(min_size_width*torch.zeros(1,).normal_(mean=.9, std=.3).clip(lower_bound, .95)) # replace .5 with a result for 224 the default large size is .95
offsetx = torch.randint(0, sideX - size + 1, ())
offsety = torch.randint(0, sideY - size + 1, ())
cutout = input[:, :, offsety : offsety + size, offsetx : offsetx + size]
cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))
cutouts = torch.cat(cutouts, dim=0)
cutouts = clamp_with_grad(cutouts, 0, 1)
# if args.use_augs:
cutouts = self.augs(cutouts)
if self.noise_fac:
facs = cutouts.new_empty([cutouts.shape[0], 1, 1, 1]).uniform_(
0, self.noise_fac
)
cutouts = cutouts + facs * torch.randn_like(cutouts)
return cutouts
class MakeCutoutsJuu(nn.Module):
def __init__(self, cut_size, cutn, cut_pow, augs):
super().__init__()
self.cut_size = cut_size
self.cutn = cutn
self.cut_pow = cut_pow
self.augs = nn.Sequential(
# K.RandomGaussianNoise(mean=0.0, std=0.5, p=0.1),
K.RandomHorizontalFlip(p=0.5),
K.RandomSharpness(0.3, p=0.4),
K.RandomAffine(degrees=30, translate=0.1, p=0.8, padding_mode="border"),
K.RandomPerspective(0.2, p=0.4),
K.ColorJitter(hue=0.01, saturation=0.01, p=0.7),
K.RandomGrayscale(p=0.1),
)
self.noise_fac = 0.1
def forward(self, input):
sideY, sideX = input.shape[2:4]
max_size = min(sideX, sideY)
min_size = min(sideX, sideY, self.cut_size)
cutouts = []
for _ in range(self.cutn):
size = int(
torch.rand([]) ** self.cut_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]
cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))
batch = self.augs(torch.cat(cutouts, dim=0))
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
class MakeCutoutsMoth(nn.Module):
def __init__(self, cut_size, cutn, cut_pow, augs, skip_augs=False):
super().__init__()
self.cut_size = cut_size
self.cutn = cutn
self.cut_pow = cut_pow
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(cutn):
if ch > cutn - cutn // 4:
cutout = input.clone()
else:
size = int(
max_size
* torch.zeros(
1,
)
.normal_(mean=0.8, std=0.3)
.clip(float(self.cut_size / max_size), 1.0)
)
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
class MakeCutoutsAaron(nn.Module):
def __init__(self, cut_size, cutn, cut_pow, augs):
super().__init__()
self.cut_size = cut_size
self.cutn = cutn
self.cut_pow = cut_pow
self.augs = augs
self.av_pool = nn.AdaptiveAvgPool2d((self.cut_size, self.cut_size))
self.max_pool = nn.AdaptiveMaxPool2d((self.cut_size, self.cut_size))
def set_cut_pow(self, cut_pow):
self.cut_pow = cut_pow
def forward(self, input):
sideY, sideX = input.shape[2:4]
max_size = min(sideX, sideY)
min_size = min(sideX, sideY, self.cut_size)
cutouts = []
cutouts_full = []
min_size_width = min(sideX, sideY)
lower_bound = float(self.cut_size / min_size_width)
for ii in range(self.cutn):
size = int(
min_size_width
* torch.zeros(
1,
)
.normal_(mean=0.8, std=0.3)
.clip(lower_bound, 1.0)
) # replace .5 with a result for 224 the default large size is .95
offsetx = torch.randint(0, sideX - size + 1, ())
offsety = torch.randint(0, sideY - size + 1, ())
cutout = input[:, :, offsety : offsety + size, offsetx : offsetx + size]
cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))
cutouts = torch.cat(cutouts, dim=0)
return clamp_with_grad(cutouts, 0, 1)
class MakeCutoutsCumin(nn.Module):
# from https://colab.research.google.com/drive/1ZAus_gn2RhTZWzOWUpPERNC0Q8OhZRTZ
def __init__(self, cut_size, cutn, cut_pow, augs):
super().__init__()
self.cut_size = cut_size
# tqdm.write(f"cut size: {self.cut_size}")
self.cutn = cutn
self.cut_pow = cut_pow
self.noise_fac = 0.1
self.av_pool = nn.AdaptiveAvgPool2d((self.cut_size, self.cut_size))
self.max_pool = nn.AdaptiveMaxPool2d((self.cut_size, self.cut_size))
self.augs = nn.Sequential(
# K.RandomHorizontalFlip(p=0.5),
# K.RandomSharpness(0.3,p=0.4),
# K.RandomGaussianBlur((3,3),(10.5,10.5),p=0.2),
# K.RandomGaussianNoise(p=0.5),
# K.RandomElasticTransform(kernel_size=(33, 33), sigma=(7,7), p=0.2),
K.RandomAffine(degrees=15, translate=0.1, p=0.7, padding_mode="border"),
K.RandomPerspective(0.7, p=0.7),
K.ColorJitter(hue=0.1, saturation=0.1, p=0.7),
K.RandomErasing((0.1, 0.4), (0.3, 1 / 0.3), same_on_batch=True, p=0.7),
)
def set_cut_pow(self, cut_pow):
self.cut_pow = cut_pow
def forward(self, input):
sideY, sideX = input.shape[2:4]
max_size = min(sideX, sideY)
min_size = min(sideX, sideY, self.cut_size)
cutouts = []
cutouts_full = []
noise_fac = 0.1
min_size_width = min(sideX, sideY)
lower_bound = float(self.cut_size / min_size_width)
for ii in range(self.cutn):
# size = int(torch.rand([])**self.cut_pow * (max_size - min_size) + min_size)
randsize = (
torch.zeros(
1,
)
.normal_(mean=0.8, std=0.3)
.clip(lower_bound, 1.0)
)
size_mult = randsize**self.cut_pow
size = int(
min_size_width * (size_mult.clip(lower_bound, 1.0))
) # replace .5 with a result for 224 the default large size is .95
# size = int(min_size_width*torch.zeros(1,).normal_(mean=.9, std=.3).clip(lower_bound, .95)) # replace .5 with a result for 224 the default large size is .95
offsetx = torch.randint(0, sideX - size + 1, ())
offsety = torch.randint(0, sideY - size + 1, ())
cutout = input[:, :, offsety : offsety + size, offsetx : offsetx + size]
cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))
cutouts = torch.cat(cutouts, dim=0)
cutouts = clamp_with_grad(cutouts, 0, 1)
# if args.use_augs:
cutouts = self.augs(cutouts)
if self.noise_fac:
facs = cutouts.new_empty([cutouts.shape[0], 1, 1, 1]).uniform_(
0, self.noise_fac
)
cutouts = cutouts + facs * torch.randn_like(cutouts)
return cutouts
class MakeCutoutsHolywater(nn.Module):
def __init__(self, cut_size, cutn, cut_pow, augs):
super().__init__()
self.cut_size = cut_size
# tqdm.write(f"cut size: {self.cut_size}")
self.cutn = cutn
self.cut_pow = cut_pow
self.noise_fac = 0.1
self.av_pool = nn.AdaptiveAvgPool2d((self.cut_size, self.cut_size))
self.max_pool = nn.AdaptiveMaxPool2d((self.cut_size, self.cut_size))
self.augs = nn.Sequential(
# K.RandomGaussianNoise(mean=0.0, std=0.5, p=0.1),
K.RandomHorizontalFlip(p=0.5),
K.RandomSharpness(0.3, p=0.4),
K.RandomAffine(degrees=30, translate=0.1, p=0.8, padding_mode="border"),
K.RandomPerspective(0.2, p=0.4),
K.ColorJitter(hue=0.01, saturation=0.01, p=0.7),
K.RandomGrayscale(p=0.1),
)
def set_cut_pow(self, cut_pow):
self.cut_pow = cut_pow
def forward(self, input):
sideY, sideX = input.shape[2:4]
max_size = min(sideX, sideY)
min_size = min(sideX, sideY, self.cut_size)
cutouts = []
cutouts_full = []
noise_fac = 0.1
min_size_width = min(sideX, sideY)
lower_bound = float(self.cut_size / min_size_width)
for ii in range(self.cutn):
size = int(
torch.rand([]) ** self.cut_pow * (max_size - min_size) + min_size
)
randsize = (
torch.zeros(
1,
)
.normal_(mean=0.8, std=0.3)
.clip(lower_bound, 1.0)
)
size_mult = randsize**self.cut_pow * ii + size
size1 = int(
(min_size_width) * (size_mult.clip(lower_bound, 1.0))
) # replace .5 with a result for 224 the default large size is .95
size2 = int(
(min_size_width)
* torch.zeros(
1,
)
.normal_(mean=0.9, std=0.3)
.clip(lower_bound, 0.95)
) # replace .5 with a result for 224 the default large size is .95
offsetx = torch.randint(0, sideX - size1 + 1, ())
offsety = torch.randint(0, sideY - size2 + 1, ())
cutout = input[
:, :, offsety : offsety + size2 + ii, offsetx : offsetx + size1 + ii
]
cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))
cutouts = torch.cat(cutouts, dim=0)
cutouts = clamp_with_grad(cutouts, 0, 1)
cutouts = self.augs(cutouts)
facs = cutouts.new_empty([cutouts.shape[0], 1, 1, 1]).uniform_(
0, self.noise_fac
)
cutouts = cutouts + facs * torch.randn_like(cutouts)
return cutouts
class MakeCutoutsOldHolywater(nn.Module):
def __init__(self, cut_size, cutn, cut_pow, augs):
super().__init__()
self.cut_size = cut_size
# tqdm.write(f"cut size: {self.cut_size}")
self.cutn = cutn
self.cut_pow = cut_pow
self.noise_fac = 0.1
self.av_pool = nn.AdaptiveAvgPool2d((self.cut_size, self.cut_size))
self.max_pool = nn.AdaptiveMaxPool2d((self.cut_size, self.cut_size))
self.augs = nn.Sequential(
# K.RandomHorizontalFlip(p=0.5),
# K.RandomSharpness(0.3,p=0.4),
# K.RandomGaussianBlur((3,3),(10.5,10.5),p=0.2),
# K.RandomGaussianNoise(p=0.5),
# K.RandomElasticTransform(kernel_size=(33, 33), sigma=(7,7), p=0.2),
K.RandomAffine(
degrees=180, translate=0.5, p=0.2, padding_mode="border"
),
K.RandomPerspective(0.6, p=0.9),
K.ColorJitter(hue=0.03, saturation=0.01, p=0.1),
K.RandomErasing((0.1, 0.7), (0.3, 1 / 0.4), same_on_batch=True, p=0.2),
)
def set_cut_pow(self, cut_pow):
self.cut_pow = cut_pow
def forward(self, input):
sideY, sideX = input.shape[2:4]
max_size = min(sideX, sideY)
min_size = min(sideX, sideY, self.cut_size)
cutouts = []
cutouts_full = []
noise_fac = 0.1
min_size_width = min(sideX, sideY)
lower_bound = float(self.cut_size / min_size_width)
for ii in range(self.cutn):
# size = int(torch.rand([])**self.cut_pow * (max_size - min_size) + min_size)
randsize = (
torch.zeros(
1,
)
.normal_(mean=0.8, std=0.3)
.clip(lower_bound, 1.0)
)
size_mult = randsize**self.cut_pow
size = int(
min_size_width * (size_mult.clip(lower_bound, 1.0))
) # replace .5 with a result for 224 the default large size is .95
# size = int(min_size_width*torch.zeros(1,).normal_(mean=.9, std=.3).clip(lower_bound, .95)) # replace .5 with a result for 224 the default large size is .95
offsetx = torch.randint(0, sideX - size + 1, ())
offsety = torch.randint(0, sideY - size + 1, ())
cutout = input[:, :, offsety : offsety + size, offsetx : offsetx + size]
cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))
cutouts = torch.cat(cutouts, dim=0)
cutouts = clamp_with_grad(cutouts, 0, 1)
# if args.use_augs:
cutouts = self.augs(cutouts)
if self.noise_fac:
facs = cutouts.new_empty([cutouts.shape[0], 1, 1, 1]).uniform_(
0, self.noise_fac
)
cutouts = cutouts + facs * torch.randn_like(cutouts)
return cutouts
class MakeCutoutsGinger(nn.Module):
def __init__(self, cut_size, cutn, cut_pow, augs):
super().__init__()
self.cut_size = cut_size
# tqdm.write(f"cut size: {self.cut_size}")
self.cutn = cutn
self.cut_pow = cut_pow
self.noise_fac = 0.1
self.av_pool = nn.AdaptiveAvgPool2d((self.cut_size, self.cut_size))
self.max_pool = nn.AdaptiveMaxPool2d((self.cut_size, self.cut_size))
self.augs = augs
"""
nn.Sequential(
K.RandomHorizontalFlip(p=0.5),
K.RandomSharpness(0.3,p=0.4),
K.RandomGaussianBlur((3,3),(10.5,10.5),p=0.2),
K.RandomGaussianNoise(p=0.5),
K.RandomElasticTransform(kernel_size=(33, 33), sigma=(7,7), p=0.2),
K.RandomAffine(degrees=30, translate=0.1, p=0.8, padding_mode='border'), # padding_mode=2
K.RandomPerspective(0.2,p=0.4, ),
K.ColorJitter(hue=0.01, saturation=0.01, p=0.7),)
"""
def set_cut_pow(self, cut_pow):
self.cut_pow = cut_pow
def forward(self, input):
sideY, sideX = input.shape[2:4]
max_size = min(sideX, sideY)
min_size = min(sideX, sideY, self.cut_size)
cutouts = []
cutouts_full = []
noise_fac = 0.1
min_size_width = min(sideX, sideY)
lower_bound = float(self.cut_size / min_size_width)
for ii in range(self.cutn):
# size = int(torch.rand([])**self.cut_pow * (max_size - min_size) + min_size)
randsize = (
torch.zeros(
1,
)
.normal_(mean=0.8, std=0.3)
.clip(lower_bound, 1.0)
)
size_mult = randsize**self.cut_pow
size = int(
min_size_width * (size_mult.clip(lower_bound, 1.0))
) # replace .5 with a result for 224 the default large size is .95
# size = int(min_size_width*torch.zeros(1,).normal_(mean=.9, std=.3).clip(lower_bound, .95)) # replace .5 with a result for 224 the default large size is .95
offsetx = torch.randint(0, sideX - size + 1, ())
offsety = torch.randint(0, sideY - size + 1, ())
cutout = input[:, :, offsety : offsety + size, offsetx : offsetx + size]
cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))
cutouts = torch.cat(cutouts, dim=0)
cutouts = clamp_with_grad(cutouts, 0, 1)
# if args.use_augs:
cutouts = self.augs(cutouts)
if self.noise_fac:
facs = cutouts.new_empty([cutouts.shape[0], 1, 1, 1]).uniform_(
0, self.noise_fac
)
cutouts = cutouts + facs * torch.randn_like(cutouts)
return cutouts
class MakeCutoutsZynth(nn.Module):
def __init__(self, cut_size, cutn, cut_pow, augs):
super().__init__()
self.cut_size = cut_size
# tqdm.write(f"cut size: {self.cut_size}")
self.cutn = cutn
self.cut_pow = cut_pow
self.noise_fac = 0.1
self.av_pool = nn.AdaptiveAvgPool2d((self.cut_size, self.cut_size))
self.max_pool = nn.AdaptiveMaxPool2d((self.cut_size, self.cut_size))
self.augs = nn.Sequential(
K.RandomHorizontalFlip(p=0.5),
# K.RandomSolarize(0.01, 0.01, p=0.7),
K.RandomSharpness(0.3, p=0.4),
K.RandomAffine(degrees=30, translate=0.1, p=0.8, padding_mode="border"),
K.RandomPerspective(0.2, p=0.4),
K.ColorJitter(hue=0.01, saturation=0.01, p=0.7),
)
def set_cut_pow(self, cut_pow):
self.cut_pow = cut_pow
def forward(self, input):
sideY, sideX = input.shape[2:4]
max_size = min(sideX, sideY)
min_size = min(sideX, sideY, self.cut_size)
cutouts = []
cutouts_full = []
noise_fac = 0.1
min_size_width = min(sideX, sideY)
lower_bound = float(self.cut_size / min_size_width)
for ii in range(self.cutn):
# size = int(torch.rand([])**self.cut_pow * (max_size - min_size) + min_size)
randsize = (
torch.zeros(
1,
)
.normal_(mean=0.8, std=0.3)
.clip(lower_bound, 1.0)
)
size_mult = randsize**self.cut_pow
size = int(
min_size_width * (size_mult.clip(lower_bound, 1.0))
) # replace .5 with a result for 224 the default large size is .95
# size = int(min_size_width*torch.zeros(1,).normal_(mean=.9, std=.3).clip(lower_bound, .95)) # replace .5 with a result for 224 the default large size is .95
offsetx = torch.randint(0, sideX - size + 1, ())
offsety = torch.randint(0, sideY - size + 1, ())
cutout = input[:, :, offsety : offsety + size, offsetx : offsetx + size]
cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))
cutouts = torch.cat(cutouts, dim=0)
cutouts = clamp_with_grad(cutouts, 0, 1)
# if args.use_augs:
cutouts = self.augs(cutouts)
if self.noise_fac:
facs = cutouts.new_empty([cutouts.shape[0], 1, 1, 1]).uniform_(
0, self.noise_fac
)
cutouts = cutouts + facs * torch.randn_like(cutouts)
return cutouts
class MakeCutoutsWyvern(nn.Module):
def __init__(self, cut_size, cutn, cut_pow, augs):
super().__init__()
self.cut_size = cut_size
# tqdm.write(f"cut size: {self.cut_size}")
self.cutn = cutn
self.cut_pow = cut_pow
self.noise_fac = 0.1
self.av_pool = nn.AdaptiveAvgPool2d((self.cut_size, self.cut_size))
self.max_pool = nn.AdaptiveMaxPool2d((self.cut_size, self.cut_size))
self.augs = augs
def forward(self, input):
sideY, sideX = input.shape[2:4]
max_size = min(sideX, sideY)
min_size = min(sideX, sideY, self.cut_size)
cutouts = []
for _ in range(self.cutn):
size = int(
torch.rand([]) ** self.cut_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]
cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))
return clamp_with_grad(torch.cat(cutouts, dim=0), 0, 1)
def load_vqgan_model(config_path, checkpoint_path):
config = OmegaConf.load(config_path)
if config.model.target == "taming.models.vqgan.VQModel":
model = vqgan.VQModel(**config.model.params)
model.eval().requires_grad_(False)
model.init_from_ckpt(checkpoint_path)
elif config.model.target == "taming.models.cond_transformer.Net2NetTransformer":
parent_model = cond_transformer.Net2NetTransformer(**config.model.params)
parent_model.eval().requires_grad_(False)
parent_model.init_from_ckpt(checkpoint_path)
model = parent_model.first_stage_model
elif config.model.target == "taming.models.vqgan.GumbelVQ":
model = vqgan.GumbelVQ(**config.model.params)
# print(config.model.params)
model.eval().requires_grad_(False)
model.init_from_ckpt(checkpoint_path)
else:
raise ValueError(f"unknown model type: {config.model.target}")
del model.loss
return model
import PIL
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, PIL.Image.LANCZOS)
class GaussianBlur2d(nn.Module):
def __init__(self, sigma, window=0, mode="reflect", value=0):
super().__init__()
self.mode = mode
self.value = value
if not window:
window = max(math.ceil((sigma * 6 + 1) / 2) * 2 - 1, 3)
if sigma:
kernel = torch.exp(
-((torch.arange(window) - window // 2) ** 2) / 2 / sigma**2
)
kernel /= kernel.sum()
else:
kernel = torch.ones([1])
self.register_buffer("kernel", kernel)
def forward(self, input):