forked from alembics/disco-diffusion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
disco.py
2623 lines (2231 loc) · 99.6 KB
/
disco.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
# %%
# !! {"metadata": {
# !! "id": "view-in-github",
# !! "colab_type": "text"
# !! }}
"""
<a href="https://colab.research.google.com/github/alembics/disco-diffusion/blob/main/Disco_Diffusion.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
"""
# %%
# !! {"metadata": {
# !! "id": "TitleTop"
# !! }}
"""
# Disco Diffusion v5.2 - Now with VR Mode
In case of confusion, Disco is the name of this notebook edit. The diffusion model in use is Katherine Crowson's fine-tuned 512x512 model
For issues, join the [Disco Diffusion Discord](https://discord.gg/msEZBy4HxA) or message us on twitter at [@somnai_dreams](https://twitter.com/somnai_dreams) or [@gandamu](https://twitter.com/gandamu_ml)
"""
# %%
# !! {"metadata": {
# !! "id": "CreditsChTop"
# !! }}
"""
### Credits & Changelog ⬇️
"""
# %%
# !! {"metadata": {
# !! "id": "Credits"
# !! }}
"""
#### Credits
Original notebook by Katherine Crowson (https://github.com/crowsonkb, https://twitter.com/RiversHaveWings). It uses either OpenAI's 256x256 unconditional ImageNet or Katherine Crowson's fine-tuned 512x512 diffusion model (https://github.com/openai/guided-diffusion), together with CLIP (https://github.com/openai/CLIP) to connect text prompts with images.
Modified by Daniel Russell (https://github.com/russelldc, https://twitter.com/danielrussruss) to include (hopefully) optimal params for quick generations in 15-100 timesteps rather than 1000, as well as more robust augmentations.
Further improvements from Dango233 and nsheppard helped improve the quality of diffusion in general, and especially so for shorter runs like this notebook aims to achieve.
Vark added code to load in multiple Clip models at once, which all prompts are evaluated against, which may greatly improve accuracy.
The latest zoom, pan, rotation, and keyframes features were taken from Chigozie Nri's VQGAN Zoom Notebook (https://github.com/chigozienri, https://twitter.com/chigozienri)
Advanced DangoCutn Cutout method is also from Dango223.
--
Disco:
Somnai (https://twitter.com/Somnai_dreams) added Diffusion Animation techniques, QoL improvements and various implementations of tech and techniques, mostly listed in the changelog below.
3D animation implementation added by Adam Letts (https://twitter.com/gandamu_ml) in collaboration with Somnai. Creation of disco.py and ongoing maintenance.
Turbo feature by Chris Allen (https://twitter.com/zippy731)
Improvements to ability to run on local systems, Windows support, and dependency installation by HostsServer (https://twitter.com/HostsServer)
VR Mode by Tom Mason (https://twitter.com/nin_artificial)
"""
# %%
# !! {"metadata": {
# !! "id": "LicenseTop"
# !! }}
"""
#### License
"""
# %%
# !! {"metadata": {
# !! "id": "License"
# !! }}
"""
Licensed under the MIT License
Copyright (c) 2021 Katherine Crowson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
--
MIT License
Copyright (c) 2019 Intel ISL (Intel Intelligent Systems Lab)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--
Licensed under the MIT License
Copyright (c) 2021 Maxwell Ingham
Copyright (c) 2022 Adam Letts
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
# %%
# !! {"metadata": {
# !! "id": "ChangelogTop"
# !! }}
"""
#### Changelog
"""
# %%
# !! {"metadata": {
# !! "cellView": "form",
# !! "id": "Changelog"
# !! }}
#@title <- View Changelog
skip_for_run_all = True #@param {type: 'boolean'}
if skip_for_run_all == False:
print(
'''
v1 Update: Oct 29th 2021 - Somnai
QoL improvements added by Somnai (@somnai_dreams), including user friendly UI, settings+prompt saving and improved google drive folder organization.
v1.1 Update: Nov 13th 2021 - Somnai
Now includes sizing options, intermediate saves and fixed image prompts and perlin inits. unexposed batch option since it doesn't work
v2 Update: Nov 22nd 2021 - Somnai
Initial addition of Katherine Crowson's Secondary Model Method (https://colab.research.google.com/drive/1mpkrhOjoyzPeSWy2r7T8EYRaU7amYOOi#scrollTo=X5gODNAMEUCR)
Noticed settings were saving with the wrong name so corrected it. Let me know if you preferred the old scheme.
v3 Update: Dec 24th 2021 - Somnai
Implemented Dango's advanced cutout method
Added SLIP models, thanks to NeuralDivergent
Fixed issue with NaNs resulting in black images, with massive help and testing from @Softology
Perlin now changes properly within batches (not sure where this perlin_regen code came from originally, but thank you)
v4 Update: Jan 2021 - Somnai
Implemented Diffusion Zooming
Added Chigozie keyframing
Made a bunch of edits to processes
v4.1 Update: Jan 14th 2021 - Somnai
Added video input mode
Added license that somehow went missing
Added improved prompt keyframing, fixed image_prompts and multiple prompts
Improved UI
Significant under the hood cleanup and improvement
Refined defaults for each mode
Added latent-diffusion SuperRes for sharpening
Added resume run mode
v4.9 Update: Feb 5th 2022 - gandamu / Adam Letts
Added 3D
Added brightness corrections to prevent animation from steadily going dark over time
v4.91 Update: Feb 19th 2022 - gandamu / Adam Letts
Cleaned up 3D implementation and made associated args accessible via Colab UI elements
v4.92 Update: Feb 20th 2022 - gandamu / Adam Letts
Separated transform code
v5.01 Update: Mar 10th 2022 - gandamu / Adam Letts
IPython magic commands replaced by Python code
v5.1 Update: Mar 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts
Integrated Turbo+Smooth features from Disco Diffusion Turbo -- just the implementation, without its defaults.
Implemented resume of turbo animations in such a way that it's now possible to resume from different batch folders and batch numbers.
3D rotation parameter units are now degrees (rather than radians)
Corrected name collision in sampling_mode (now diffusion_sampling_mode for plms/ddim, and sampling_mode for 3D transform sampling)
Added video_init_seed_continuity option to make init video animations more continuous
v5.1 Update: Apr 4th 2022 - MSFTserver aka HostsServer
Removed pytorch3d from needing to be compiled with a lite version specifically made for Disco Diffusion
Remove Super Resolution
Remove SLIP Models
Update for crossplatform support
v5.2 Update: Apr 10th 2022 - nin_artificial / Tom Mason
VR Mode
'''
)
# %%
# !! {"metadata": {
# !! "id": "TutorialTop"
# !! }}
"""
# Tutorial
"""
# %%
# !! {"metadata": {
# !! "id": "DiffusionSet"
# !! }}
"""
**Diffusion settings (Defaults are heavily outdated)**
---
Disco Diffusion is complex, and continually evolving with new features. The most current documentation on on Disco Diffusion settings can be found in the unofficial guidebook:
[Zippy's Disco Diffusion Cheatsheet](https://docs.google.com/document/d/1l8s7uS2dGqjztYSjPpzlmXLjl5PM3IGkRWI3IiCuK7g/edit)
We also encourage users to join the [Disco Diffusion User Discord](https://discord.gg/XGZrFFCRfN) to learn from the active user community.
This section below is outdated as of v2
Setting | Description | Default
--- | --- | ---
**Your vision:**
`text_prompts` | A description of what you'd like the machine to generate. Think of it like writing the caption below your image on a website. | N/A
`image_prompts` | Think of these images more as a description of their contents. | N/A
**Image quality:**
`clip_guidance_scale` | Controls how much the image should look like the prompt. | 1000
`tv_scale` | Controls the smoothness of the final output. | 150
`range_scale` | Controls how far out of range RGB values are allowed to be. | 150
`sat_scale` | Controls how much saturation is allowed. From nshepperd's JAX notebook. | 0
`cutn` | Controls how many crops to take from the image. | 16
`cutn_batches` | Accumulate CLIP gradient from multiple batches of cuts. | 2
**Init settings:**
`init_image` | URL or local path | None
`init_scale` | This enhances the effect of the init image, a good value is 1000 | 0
`skip_steps` | Controls the starting point along the diffusion timesteps | 0
`perlin_init` | Option to start with random perlin noise | False
`perlin_mode` | ('gray', 'color') | 'mixed'
**Advanced:**
`skip_augs` | Controls whether to skip torchvision augmentations | False
`randomize_class` | Controls whether the imagenet class is randomly changed each iteration | True
`clip_denoised` | Determines whether CLIP discriminates a noisy or denoised image | False
`clamp_grad` | Experimental: Using adaptive clip grad in the cond_fn | True
`seed` | Choose a random seed and print it at end of run for reproduction | random_seed
`fuzzy_prompt` | Controls whether to add multiple noisy prompts to the prompt losses | False
`rand_mag` | Controls the magnitude of the random noise | 0.1
`eta` | DDIM hyperparameter | 0.5
..
**Model settings**
---
Setting | Description | Default
--- | --- | ---
**Diffusion:**
`timestep_respacing` | Modify this value to decrease the number of timesteps. | ddim100
`diffusion_steps` || 1000
**Diffusion:**
`clip_models` | Models of CLIP to load. Typically the more, the better but they all come at a hefty VRAM cost. | ViT-B/32, ViT-B/16, RN50x4
"""
# %%
# !! {"metadata": {
# !! "id": "SetupTop"
# !! }}
"""
# 1. Set Up
"""
# %%
# !! {"metadata": {
# !! "cellView": "form",
# !! "id": "CheckGPU"
# !! }}
#@title 1.1 Check GPU Status
import subprocess
simple_nvidia_smi_display = False#@param {type:"boolean"}
if simple_nvidia_smi_display:
#!nvidia-smi
nvidiasmi_output = subprocess.run(['nvidia-smi', '-L'], stdout=subprocess.PIPE).stdout.decode('utf-8')
print(nvidiasmi_output)
else:
#!nvidia-smi -i 0 -e 0
nvidiasmi_output = subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE).stdout.decode('utf-8')
print(nvidiasmi_output)
nvidiasmi_ecc_note = subprocess.run(['nvidia-smi', '-i', '0', '-e', '0'], stdout=subprocess.PIPE).stdout.decode('utf-8')
print(nvidiasmi_ecc_note)
# %%
# !! {"metadata": {
# !! "cellView": "form",
# !! "id": "PrepFolders"
# !! }}
#@title 1.2 Prepare Folders
import subprocess, os, sys, ipykernel
def gitclone(url):
res = subprocess.run(['git', 'clone', url], stdout=subprocess.PIPE).stdout.decode('utf-8')
print(res)
def pipi(modulestr):
res = subprocess.run(['pip', 'install', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8')
print(res)
def pipie(modulestr):
res = subprocess.run(['git', 'install', '-e', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8')
print(res)
def wget(url, outputdir):
res = subprocess.run(['wget', url, '-P', f'{outputdir}'], stdout=subprocess.PIPE).stdout.decode('utf-8')
print(res)
try:
from google.colab import drive
print("Google Colab detected. Using Google Drive.")
is_colab = True
#@markdown If you connect your Google Drive, you can save the final image of each run on your drive.
google_drive = True #@param {type:"boolean"}
#@markdown Click here if you'd like to save the diffusion model checkpoint file to (and/or load from) your Google Drive:
save_models_to_google_drive = True #@param {type:"boolean"}
except:
is_colab = False
google_drive = False
save_models_to_google_drive = False
print("Google Colab not detected.")
if is_colab:
if google_drive is True:
drive.mount('/content/drive')
root_path = '/content/drive/MyDrive/AI/Disco_Diffusion'
else:
root_path = '/content'
else:
root_path = os.getcwd()
import os
def createPath(filepath):
os.makedirs(filepath, exist_ok=True)
initDirPath = f'{root_path}/init_images'
createPath(initDirPath)
outDirPath = f'{root_path}/images_out'
createPath(outDirPath)
if is_colab:
if google_drive and not save_models_to_google_drive or not google_drive:
model_path = '/content/models'
createPath(model_path)
if google_drive and save_models_to_google_drive:
model_path = f'{root_path}/models'
createPath(model_path)
else:
model_path = f'{root_path}/models'
createPath(model_path)
# libraries = f'{root_path}/libraries'
# createPath(libraries)
# %%
# !! {"metadata": {
# !! "cellView": "form",
# !! "id": "InstallDeps"
# !! }}
#@title ### 1.3 Install and import dependencies
import pathlib, shutil, os, sys
if not is_colab:
# If running locally, there's a good chance your env will need this in order to not crash upon np.matmul() or similar operations.
os.environ['KMP_DUPLICATE_LIB_OK']='TRUE'
PROJECT_DIR = os.path.abspath(os.getcwd())
USE_ADABINS = True
if is_colab:
if google_drive is not True:
root_path = f'/content'
model_path = '/content/models'
else:
root_path = os.getcwd()
model_path = f'{root_path}/models'
model_256_downloaded = False
model_512_downloaded = False
model_secondary_downloaded = False
multipip_res = subprocess.run(['pip', 'install', 'lpips', 'datetime', 'timm', 'ftfy', 'einops', 'pytorch-lightning', 'omegaconf'], stdout=subprocess.PIPE).stdout.decode('utf-8')
print(multipip_res)
if is_colab:
subprocess.run(['apt', 'install', 'imagemagick'], stdout=subprocess.PIPE).stdout.decode('utf-8')
try:
from CLIP import clip
except:
if not os.path.exists("CLIP"):
gitclone("https://github.com/openai/CLIP")
sys.path.append(f'{PROJECT_DIR}/CLIP')
try:
from guided_diffusion.script_util import create_model_and_diffusion
except:
if not os.path.exists("guided-diffusion"):
gitclone("https://github.com/crowsonkb/guided-diffusion")
sys.path.append(f'{PROJECT_DIR}/guided-diffusion')
try:
from resize_right import resize
except:
if not os.path.exists("ResizeRight"):
gitclone("https://github.com/assafshocher/ResizeRight.git")
sys.path.append(f'{PROJECT_DIR}/ResizeRight')
try:
import py3d_tools
except:
if not os.path.exists('pytorch3d-lite'):
gitclone("https://github.com/MSFTserver/pytorch3d-lite.git")
sys.path.append(f'{PROJECT_DIR}/pytorch3d-lite')
try:
from midas.dpt_depth import DPTDepthModel
except:
if not os.path.exists('MiDaS'):
gitclone("https://github.com/isl-org/MiDaS.git")
if not os.path.exists('MiDaS/midas_utils.py'):
shutil.move('MiDaS/utils.py', 'MiDaS/midas_utils.py')
if not os.path.exists(f'{model_path}/dpt_large-midas-2f21e586.pt'):
wget("https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", model_path)
sys.path.append(f'{PROJECT_DIR}/MiDaS')
try:
sys.path.append(PROJECT_DIR)
import disco_xform_utils as dxf
except:
if not os.path.exists("disco-diffusion"):
gitclone("https://github.com/alembics/disco-diffusion.git")
if os.path.exists('disco_xform_utils.py') is not True:
shutil.move('disco-diffusion/disco_xform_utils.py', 'disco_xform_utils.py')
sys.path.append(PROJECT_DIR)
import torch
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
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
from CLIP 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
from functools import partial
if is_colab:
os.chdir('/content')
from google.colab import files
else:
os.chdir(f'{PROJECT_DIR}')
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)
# AdaBins stuff
if USE_ADABINS:
try:
from infer import InferenceHelper
except:
if os.path.exists("AdaBins") is not True:
gitclone("https://github.com/shariqfarooq123/AdaBins.git")
if not os.path.exists(f'{PROJECT_DIR}/pretrained/AdaBins_nyu.pt'):
createPath(f'{PROJECT_DIR}/pretrained')
wget("https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt", f'{PROJECT_DIR}/pretrained')
sys.path.append(f'{PROJECT_DIR}/AdaBins')
from infer import InferenceHelper
MAX_ADABINS_AREA = 500000
import torch
DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print('Using device:', DEVICE)
device = DEVICE # At least one of the modules expects this name..
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
# %%
# !! {"metadata": {
# !! "cellView": "form",
# !! "id": "DefMidasFns"
# !! }}
#@title ### 1.4 Define Midas functions
from midas.dpt_depth import DPTDepthModel
from midas.midas_net import MidasNet
from midas.midas_net_custom import MidasNet_small
from midas.transforms import Resize, NormalizeImage, PrepareForNet
# Initialize MiDaS depth model.
# It remains resident in VRAM and likely takes around 2GB VRAM.
# You could instead initialize it for each frame (and free it after each frame) to save VRAM.. but initializing it is slow.
default_models = {
"midas_v21_small": f"{model_path}/midas_v21_small-70d6b9c8.pt",
"midas_v21": f"{model_path}/midas_v21-f6b98070.pt",
"dpt_large": f"{model_path}/dpt_large-midas-2f21e586.pt",
"dpt_hybrid": f"{model_path}/dpt_hybrid-midas-501f0c75.pt",
"dpt_hybrid_nyu": f"{model_path}/dpt_hybrid_nyu-2ce69ec7.pt",}
def init_midas_depth_model(midas_model_type="dpt_large", optimize=True):
midas_model = None
net_w = None
net_h = None
resize_mode = None
normalization = None
print(f"Initializing MiDaS '{midas_model_type}' depth model...")
# load network
midas_model_path = default_models[midas_model_type]
if midas_model_type == "dpt_large": # DPT-Large
midas_model = DPTDepthModel(
path=midas_model_path,
backbone="vitl16_384",
non_negative=True,
)
net_w, net_h = 384, 384
resize_mode = "minimal"
normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
elif midas_model_type == "dpt_hybrid": #DPT-Hybrid
midas_model = DPTDepthModel(
path=midas_model_path,
backbone="vitb_rn50_384",
non_negative=True,
)
net_w, net_h = 384, 384
resize_mode="minimal"
normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
elif midas_model_type == "dpt_hybrid_nyu": #DPT-Hybrid-NYU
midas_model = DPTDepthModel(
path=midas_model_path,
backbone="vitb_rn50_384",
non_negative=True,
)
net_w, net_h = 384, 384
resize_mode="minimal"
normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
elif midas_model_type == "midas_v21":
midas_model = MidasNet(midas_model_path, non_negative=True)
net_w, net_h = 384, 384
resize_mode="upper_bound"
normalization = NormalizeImage(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
)
elif midas_model_type == "midas_v21_small":
midas_model = MidasNet_small(midas_model_path, features=64, backbone="efficientnet_lite3", exportable=True, non_negative=True, blocks={'expand': True})
net_w, net_h = 256, 256
resize_mode="upper_bound"
normalization = NormalizeImage(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
)
else:
print(f"midas_model_type '{midas_model_type}' not implemented")
assert False
midas_transform = T.Compose(
[
Resize(
net_w,
net_h,
resize_target=None,
keep_aspect_ratio=True,
ensure_multiple_of=32,
resize_method=resize_mode,
image_interpolation_method=cv2.INTER_CUBIC,
),
normalization,
PrepareForNet(),
]
)
midas_model.eval()
if optimize==True:
if DEVICE == torch.device("cuda"):
midas_model = midas_model.to(memory_format=torch.channels_last)
midas_model = midas_model.half()
midas_model.to(DEVICE)
print(f"MiDaS '{midas_model_type}' depth model initialized.")
return midas_model, midas_transform, net_w, net_h, resize_mode, normalization
# %%
# !! {"metadata": {
# !! "cellView": "form",
# !! "id": "DefFns"
# !! }}
#@title 1.5 Define necessary functions
# https://gist.github.com/adefossez/0646dbe9ed4005480a2407c62aac8869
import py3d_tools as p3dT
import disco_xform_utils as dxf
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' or args.animation_mode == '3D':
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:
if is_colab:
TF.to_pil_image(cutouts[0].clamp(0, 1).squeeze(0)).save("/content/cutout_overview0.jpg",quality=99)
else:
TF.to_pil_image(cutouts[0].clamp(0, 1).squeeze(0)).save("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:
if is_colab:
TF.to_pil_image(cutouts[-1].clamp(0, 1).squeeze(0)).save("/content/cutout_InnerCrop.jpg",quality=99)
else:
TF.to_pil_image(cutouts[-1].clamp(0, 1).squeeze(0)).save("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
TRANSLATION_SCALE = 1.0/200.0
def do_3d_step(img_filepath, frame_num, midas_model, midas_transform):
if args.key_frames:
translation_x = args.translation_x_series[frame_num]
translation_y = args.translation_y_series[frame_num]
translation_z = args.translation_z_series[frame_num]
rotation_3d_x = args.rotation_3d_x_series[frame_num]
rotation_3d_y = args.rotation_3d_y_series[frame_num]
rotation_3d_z = args.rotation_3d_z_series[frame_num]
print(
f'translation_x: {translation_x}',
f'translation_y: {translation_y}',
f'translation_z: {translation_z}',
f'rotation_3d_x: {rotation_3d_x}',
f'rotation_3d_y: {rotation_3d_y}',
f'rotation_3d_z: {rotation_3d_z}',
)
translate_xyz = [-translation_x*TRANSLATION_SCALE, translation_y*TRANSLATION_SCALE, -translation_z*TRANSLATION_SCALE]