-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlore-disco
More file actions
2790 lines (2790 loc) · 134 KB
/
lore-disco
File metadata and controls
2790 lines (2790 loc) · 134 KB
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
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "Disco Diffusion v4.1 [w/ Video Inits, Recovery & DDIM Sharpen].ipynb",
"private_outputs": true,
"provenance": [],
"collapsed_sections": [
"1YwMUyt9LHG1",
"XTu6AjLyFQUq",
"CQVtY1Ixnqx4",
"CnkTNXJAPzL2",
"u1VHzHvNx5fd"
],
"machine_shape": "hm",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
},
"accelerator": "GPU"
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/jameslbarnes/lore-images/blob/main/lore-disco\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1YwMUyt9LHG1"
},
"source": [
"# Disco Diffusion v4.1 - Now with Video Inits, Recovery, DDIM Sharpen and improved UI\n",
"\n",
"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\n",
"\n",
"For issues, message [@Somnai_dreams](https://twitter.com/Somnai_dreams) or Somnai#6855\n",
"\n",
"Credits & Changelog ⬇️\n"
]
},
{
"cell_type": "markdown",
"source": [
"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.\n",
"\n",
"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.\n",
"\n",
"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.\n",
"\n",
"Vark added code to load in multiple Clip models at once, which all prompts are evaluated against, which may greatly improve accuracy.\n",
"\n",
"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)\n",
"\n",
"Advanced DangoCutn Cutout method is also from Dango223.\n",
"\n",
"--\n",
"\n",
"I, Somnai (https://twitter.com/Somnai_dreams), have added Diffusion Animation techniques, QoL improvements and various implementations of tech and techniques, mostly listed in the changelog below."
],
"metadata": {
"id": "wX5omb9C7Bjz"
}
},
{
"cell_type": "code",
"source": [
"# @title Licensed under the MIT License\n",
"\n",
"# Copyright (c) 2021 Katherine Crowson \n",
"\n",
"# Permission is hereby granted, free of charge, to any person obtaining a copy\n",
"# of this software and associated documentation files (the \"Software\"), to deal\n",
"# in the Software without restriction, including without limitation the rights\n",
"# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n",
"# copies of the Software, and to permit persons to whom the Software is\n",
"# furnished to do so, subject to the following conditions:\n",
"\n",
"# The above copyright notice and this permission notice shall be included in\n",
"# all copies or substantial portions of the Software.\n",
"\n",
"# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n",
"# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n",
"# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n",
"# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n",
"# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n",
"# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n",
"# THE SOFTWARE."
],
"metadata": {
"cellView": "form",
"id": "wDSYhyjqZQI9"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"#@title <- View Changelog\n",
"\n",
"skip_for_run_all = True #@param {type: 'boolean'}\n",
"\n",
"if skip_for_run_all == False:\n",
" print(\n",
" '''\n",
" v1 Update: Oct 29th 2021\n",
"\n",
" QoL improvements added by Somnai (@somnai_dreams), including user friendly UI, settings+prompt saving and improved google drive folder organization.\n",
"\n",
" v1.1 Update: Nov 13th 2021\n",
"\n",
" Now includes sizing options, intermediate saves and fixed image prompts and perlin inits. unexposed batch option since it doesn't work\n",
"\n",
" v2 Update: Nov 22nd 2021\n",
"\n",
" Initial addition of Katherine Crowson's Secondary Model Method (https://colab.research.google.com/drive/1mpkrhOjoyzPeSWy2r7T8EYRaU7amYOOi#scrollTo=X5gODNAMEUCR)\n",
"\n",
" Noticed settings were saving with the wrong name so corrected it. Let me know if you preferred the old scheme.\n",
"\n",
" v3 Update: Dec 24th 2021\n",
"\n",
" Implemented Dango's advanced cutout method\n",
"\n",
" Added SLIP models, thanks to NeuralDivergent\n",
"\n",
" Fixed issue with NaNs resulting in black images, with massive help and testing from @Softology\n",
"\n",
" Perlin now changes properly within batches (not sure where this perlin_regen code came from originally, but thank you)\n",
"\n",
" v4 Update: Jan 2021\n",
"\n",
" Implemented Diffusion Zooming\n",
"\n",
" Added Chigozie keyframing\n",
"\n",
" Made a bunch of edits to processes\n",
" \n",
" v4.1 Update: Jan 14th 2021\n",
"\n",
" Added video input mode\n",
"\n",
" Added license that somehow went missing\n",
"\n",
" Added improved prompt keyframing, fixed image_prompts and multiple prompts\n",
"\n",
" Improved UI\n",
"\n",
" Significant under the hood cleanup and improvement\n",
"\n",
" Refined defaults for each mode\n",
"\n",
" Added latent-diffusion SuperRes for sharpening\n",
"\n",
" Added resume run mode\n",
"\n",
" '''\n",
" )"
],
"metadata": {
"cellView": "form",
"id": "qFB3nwLSQI8X"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "XTu6AjLyFQUq"
},
"source": [
"#Tutorial"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "YR806W0wi3He"
},
"source": [
"**Diffusion settings**\n",
"---\n",
"\n",
"This section is outdated as of v2\n",
"\n",
"Setting | Description | Default\n",
"--- | --- | ---\n",
"**Your vision:**\n",
"`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\n",
"`image_prompts` | Think of these images more as a description of their contents. | N/A\n",
"**Image quality:**\n",
"`clip_guidance_scale` | Controls how much the image should look like the prompt. | 1000\n",
"`tv_scale` | Controls the smoothness of the final output. | 150\n",
"`range_scale` | Controls how far out of range RGB values are allowed to be. | 150\n",
"`sat_scale` | Controls how much saturation is allowed. From nshepperd's JAX notebook. | 0\n",
"`cutn` | Controls how many crops to take from the image. | 16\n",
"`cutn_batches` | Accumulate CLIP gradient from multiple batches of cuts | 2\n",
"**Init settings:**\n",
"`init_image` | URL or local path | None\n",
"`init_scale` | This enhances the effect of the init image, a good value is 1000 | 0\n",
"`skip_steps Controls the starting point along the diffusion timesteps | 0\n",
"`perlin_init` | Option to start with random perlin noise | False\n",
"`perlin_mode` | ('gray', 'color') | 'mixed'\n",
"**Advanced:**\n",
"`skip_augs` |Controls whether to skip torchvision augmentations | False\n",
"`randomize_class` |Controls whether the imagenet class is randomly changed each iteration | True\n",
"`clip_denoised` |Determines whether CLIP discriminates a noisy or denoised image | False\n",
"`clamp_grad` |Experimental: Using adaptive clip grad in the cond_fn | True\n",
"`seed` | Choose a random seed and print it at end of run for reproduction | random_seed\n",
"`fuzzy_prompt` | Controls whether to add multiple noisy prompts to the prompt losses | False\n",
"`rand_mag` |Controls the magnitude of the random noise | 0.1\n",
"`eta` | DDIM hyperparameter | 0.5\n",
"\n",
"..\n",
"\n",
"**Model settings**\n",
"---\n",
"\n",
"Setting | Description | Default\n",
"--- | --- | ---\n",
"**Diffusion:**\n",
"`timestep_respacing` | Modify this value to decrease the number of timesteps. | ddim100\n",
"`diffusion_steps` || 1000\n",
"**Diffusion:**\n",
"`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"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_9Eg9Kf5FlfK"
},
"source": [
"# 1. Set Up"
]
},
{
"cell_type": "code",
"metadata": {
"id": "qZ3rNuAWAewx",
"cellView": "form"
},
"source": [
"#@title 1.1 Check GPU Status\n",
"!nvidia-smi -L"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "yZsjzwS0YGo6",
"cellView": "form"
},
"source": [
"from google.colab import drive\n",
"#@title 1.2 Prepare Folders\n",
"#@markdown If you connect your Google Drive, you can save the final image of each run on your drive.\n",
"\n",
"google_drive = True #@param {type:\"boolean\"}\n",
"\n",
"#@markdown Click here if you'd like to save the diffusion model checkpoint file to (and/or load from) your Google Drive:\n",
"yes_please = True #@param {type:\"boolean\"}\n",
"\n",
"if google_drive is True:\n",
" drive.mount('/content/drive')\n",
" root_path = '/content/drive/MyDrive/AI/Disco_Diffusion'\n",
"else:\n",
" root_path = '/content'\n",
"\n",
"import os\n",
"from os import path\n",
"#Simple create paths taken with modifications from Datamosh's Batch VQGAN+CLIP notebook\n",
"def createPath(filepath):\n",
" if path.exists(filepath) == False:\n",
" os.makedirs(filepath)\n",
" print(f'Made {filepath}')\n",
" else:\n",
" print(f'filepath {filepath} exists.')\n",
"\n",
"initDirPath = f'{root_path}/init_images'\n",
"createPath(initDirPath)\n",
"outDirPath = f'{root_path}/images_out'\n",
"createPath(outDirPath)\n",
"\n",
"if google_drive and not yes_please or not google_drive:\n",
" model_path = '/content/models'\n",
" createPath(model_path)\n",
"if google_drive and yes_please:\n",
" model_path = f'{root_path}/models'\n",
" createPath(model_path)\n",
"# libraries = f'{root_path}/libraries'\n",
"# createPath(libraries)\n",
"\n"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "JmbrcrhpBPC6",
"cellView": "form"
},
"source": [
"#@title ### 1.3 Install and import dependencies\n",
"\n",
"if google_drive is not True:\n",
" root_path = f'/content'\n",
" model_path = '/content/models' \n",
"\n",
"model_256_downloaded = False\n",
"model_512_downloaded = False\n",
"model_secondary_downloaded = False\n",
"\n",
"!git clone https://github.com/openai/CLIP\n",
"# !git clone https://github.com/facebookresearch/SLIP.git\n",
"!git clone https://github.com/crowsonkb/guided-diffusion\n",
"!git clone https://github.com/assafshocher/ResizeRight.git\n",
"!pip install -e ./CLIP\n",
"!pip install -e ./guided-diffusion\n",
"!pip install lpips datetime timm\n",
"!apt install imagemagick\n",
"\n",
"\n",
"import sys\n",
"# sys.path.append('./SLIP')\n",
"sys.path.append('./ResizeRight')\n",
"from dataclasses import dataclass\n",
"from functools import partial\n",
"import cv2\n",
"import pandas as pd\n",
"import gc\n",
"import io\n",
"import math\n",
"import timm\n",
"from IPython import display\n",
"import lpips\n",
"from PIL import Image, ImageOps\n",
"import requests\n",
"from glob import glob\n",
"import json\n",
"from types import SimpleNamespace\n",
"import torch\n",
"from torch import nn\n",
"from torch.nn import functional as F\n",
"import torchvision.transforms as T\n",
"import torchvision.transforms.functional as TF\n",
"from tqdm.notebook import tqdm\n",
"sys.path.append('./CLIP')\n",
"sys.path.append('./guided-diffusion')\n",
"import clip\n",
"from resize_right import resize\n",
"# from models import SLIP_VITB16, SLIP, SLIP_VITL16\n",
"from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults\n",
"from datetime import datetime\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import random\n",
"from ipywidgets import Output\n",
"import hashlib\n",
"\n",
"#SuperRes\n",
"!git clone https://github.com/CompVis/latent-diffusion.git\n",
"!git clone https://github.com/CompVis/taming-transformers\n",
"!pip install -e ./taming-transformers\n",
"!pip install ipywidgets omegaconf>=2.0.0 pytorch-lightning>=1.0.8 torch-fidelity einops wandb\n",
"\n",
"#SuperRes\n",
"import ipywidgets as widgets\n",
"import os\n",
"sys.path.append(\".\")\n",
"sys.path.append('./taming-transformers')\n",
"from taming.models import vqgan # checking correct import from taming\n",
"from torchvision.datasets.utils import download_url\n",
"%cd '/content/latent-diffusion'\n",
"from functools import partial\n",
"from ldm.util import instantiate_from_config\n",
"from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like\n",
"# from ldm.models.diffusion.ddim import DDIMSampler\n",
"from ldm.util import ismap\n",
"%cd '/content'\n",
"from google.colab import files\n",
"from IPython.display import Image as ipyimg\n",
"from numpy import asarray\n",
"from einops import rearrange, repeat\n",
"import torch, torchvision\n",
"import time\n",
"from omegaconf import OmegaConf\n",
"import warnings\n",
"warnings.filterwarnings(\"ignore\", category=UserWarning)\n",
"\n",
"\n",
"import torch\n",
"device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n",
"print('Using device:', device)\n",
"\n",
"if torch.cuda.get_device_capability(device) == (8,0): ## A100 fix thanks to Emad\n",
" print('Disabling CUDNN for A100 gpu', file=sys.stderr)\n",
" torch.backends.cudnn.enabled = False"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "FpZczxnOnPIU",
"cellView": "form"
},
"source": [
"#@title 1.4 Define necessary functions\n",
"\n",
"# https://gist.github.com/adefossez/0646dbe9ed4005480a2407c62aac8869\n",
"\n",
"def interp(t):\n",
" return 3 * t**2 - 2 * t ** 3\n",
"\n",
"def perlin(width, height, scale=10, device=None):\n",
" gx, gy = torch.randn(2, width + 1, height + 1, 1, 1, device=device)\n",
" xs = torch.linspace(0, 1, scale + 1)[:-1, None].to(device)\n",
" ys = torch.linspace(0, 1, scale + 1)[None, :-1].to(device)\n",
" wx = 1 - interp(xs)\n",
" wy = 1 - interp(ys)\n",
" dots = 0\n",
" dots += wx * wy * (gx[:-1, :-1] * xs + gy[:-1, :-1] * ys)\n",
" dots += (1 - wx) * wy * (-gx[1:, :-1] * (1 - xs) + gy[1:, :-1] * ys)\n",
" dots += wx * (1 - wy) * (gx[:-1, 1:] * xs - gy[:-1, 1:] * (1 - ys))\n",
" dots += (1 - wx) * (1 - wy) * (-gx[1:, 1:] * (1 - xs) - gy[1:, 1:] * (1 - ys))\n",
" return dots.permute(0, 2, 1, 3).contiguous().view(width * scale, height * scale)\n",
"\n",
"def perlin_ms(octaves, width, height, grayscale, device=device):\n",
" out_array = [0.5] if grayscale else [0.5, 0.5, 0.5]\n",
" # out_array = [0.0] if grayscale else [0.0, 0.0, 0.0]\n",
" for i in range(1 if grayscale else 3):\n",
" scale = 2 ** len(octaves)\n",
" oct_width = width\n",
" oct_height = height\n",
" for oct in octaves:\n",
" p = perlin(oct_width, oct_height, scale, device)\n",
" out_array[i] += p * oct\n",
" scale //= 2\n",
" oct_width *= 2\n",
" oct_height *= 2\n",
" return torch.cat(out_array)\n",
"\n",
"def create_perlin_noise(octaves=[1, 1, 1, 1], width=2, height=2, grayscale=True):\n",
" out = perlin_ms(octaves, width, height, grayscale)\n",
" if grayscale:\n",
" out = TF.resize(size=(side_y, side_x), img=out.unsqueeze(0))\n",
" out = TF.to_pil_image(out.clamp(0, 1)).convert('RGB')\n",
" else:\n",
" out = out.reshape(-1, 3, out.shape[0]//3, out.shape[1])\n",
" out = TF.resize(size=(side_y, side_x), img=out)\n",
" out = TF.to_pil_image(out.clamp(0, 1).squeeze())\n",
"\n",
" out = ImageOps.autocontrast(out)\n",
" return out\n",
"\n",
"def regen_perlin():\n",
" if perlin_mode == 'color':\n",
" init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)\n",
" init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False)\n",
" elif perlin_mode == 'gray':\n",
" init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True)\n",
" init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)\n",
" else:\n",
" init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)\n",
" init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)\n",
"\n",
" init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1)\n",
" del init2\n",
" return init.expand(batch_size, -1, -1, -1)\n",
"\n",
"def fetch(url_or_path):\n",
" if str(url_or_path).startswith('http://') or str(url_or_path).startswith('https://'):\n",
" r = requests.get(url_or_path)\n",
" r.raise_for_status()\n",
" fd = io.BytesIO()\n",
" fd.write(r.content)\n",
" fd.seek(0)\n",
" return fd\n",
" return open(url_or_path, 'rb')\n",
"\n",
"def read_image_workaround(path):\n",
" \"\"\"OpenCV reads images as BGR, Pillow saves them as RGB. Work around\n",
" this incompatibility to avoid colour inversions.\"\"\"\n",
" im_tmp = cv2.imread(path)\n",
" return cv2.cvtColor(im_tmp, cv2.COLOR_BGR2RGB)\n",
"\n",
"def parse_prompt(prompt):\n",
" if prompt.startswith('http://') or prompt.startswith('https://'):\n",
" vals = prompt.rsplit(':', 2)\n",
" vals = [vals[0] + ':' + vals[1], *vals[2:]]\n",
" else:\n",
" vals = prompt.rsplit(':', 1)\n",
" vals = vals + ['', '1'][len(vals):]\n",
" return vals[0], float(vals[1])\n",
"\n",
"def sinc(x):\n",
" return torch.where(x != 0, torch.sin(math.pi * x) / (math.pi * x), x.new_ones([]))\n",
"\n",
"def lanczos(x, a):\n",
" cond = torch.logical_and(-a < x, x < a)\n",
" out = torch.where(cond, sinc(x) * sinc(x/a), x.new_zeros([]))\n",
" return out / out.sum()\n",
"\n",
"def ramp(ratio, width):\n",
" n = math.ceil(width / ratio + 1)\n",
" out = torch.empty([n])\n",
" cur = 0\n",
" for i in range(out.shape[0]):\n",
" out[i] = cur\n",
" cur += ratio\n",
" return torch.cat([-out[1:].flip([0]), out])[1:-1]\n",
"\n",
"def resample(input, size, align_corners=True):\n",
" n, c, h, w = input.shape\n",
" dh, dw = size\n",
"\n",
" input = input.reshape([n * c, 1, h, w])\n",
"\n",
" if dh < h:\n",
" kernel_h = lanczos(ramp(dh / h, 2), 2).to(input.device, input.dtype)\n",
" pad_h = (kernel_h.shape[0] - 1) // 2\n",
" input = F.pad(input, (0, 0, pad_h, pad_h), 'reflect')\n",
" input = F.conv2d(input, kernel_h[None, None, :, None])\n",
"\n",
" if dw < w:\n",
" kernel_w = lanczos(ramp(dw / w, 2), 2).to(input.device, input.dtype)\n",
" pad_w = (kernel_w.shape[0] - 1) // 2\n",
" input = F.pad(input, (pad_w, pad_w, 0, 0), 'reflect')\n",
" input = F.conv2d(input, kernel_w[None, None, None, :])\n",
"\n",
" input = input.reshape([n, c, h, w])\n",
" return F.interpolate(input, size, mode='bicubic', align_corners=align_corners)\n",
"\n",
"class MakeCutouts(nn.Module):\n",
" def __init__(self, cut_size, cutn, skip_augs=False):\n",
" super().__init__()\n",
" self.cut_size = cut_size\n",
" self.cutn = cutn\n",
" self.skip_augs = skip_augs\n",
" self.augs = T.Compose([\n",
" T.RandomHorizontalFlip(p=0.5),\n",
" T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
" T.RandomAffine(degrees=15, translate=(0.1, 0.1)),\n",
" T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
" T.RandomPerspective(distortion_scale=0.4, p=0.7),\n",
" T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
" T.RandomGrayscale(p=0.15),\n",
" T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
" # T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),\n",
" ])\n",
"\n",
" def forward(self, input):\n",
" input = T.Pad(input.shape[2]//4, fill=0)(input)\n",
" sideY, sideX = input.shape[2:4]\n",
" max_size = min(sideX, sideY)\n",
"\n",
" cutouts = []\n",
" for ch in range(self.cutn):\n",
" if ch > self.cutn - self.cutn//4:\n",
" cutout = input.clone()\n",
" else:\n",
" size = int(max_size * torch.zeros(1,).normal_(mean=.8, std=.3).clip(float(self.cut_size/max_size), 1.))\n",
" offsetx = torch.randint(0, abs(sideX - size + 1), ())\n",
" offsety = torch.randint(0, abs(sideY - size + 1), ())\n",
" cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]\n",
"\n",
" if not self.skip_augs:\n",
" cutout = self.augs(cutout)\n",
" cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))\n",
" del cutout\n",
"\n",
" cutouts = torch.cat(cutouts, dim=0)\n",
" return cutouts\n",
"\n",
"cutout_debug = False\n",
"padargs = {}\n",
"\n",
"class MakeCutoutsDango(nn.Module):\n",
" def __init__(self, cut_size,\n",
" Overview=4, \n",
" InnerCrop = 0, IC_Size_Pow=0.5, IC_Grey_P = 0.2\n",
" ):\n",
" super().__init__()\n",
" self.cut_size = cut_size\n",
" self.Overview = Overview\n",
" self.InnerCrop = InnerCrop\n",
" self.IC_Size_Pow = IC_Size_Pow\n",
" self.IC_Grey_P = IC_Grey_P\n",
" if args.animation_mode == 'None':\n",
" self.augs = T.Compose([\n",
" T.RandomHorizontalFlip(p=0.5),\n",
" T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
" T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR),\n",
" T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
" T.RandomGrayscale(p=0.1),\n",
" T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
" T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),\n",
" ])\n",
" elif args.animation_mode == 'Video Input':\n",
" self.augs = T.Compose([\n",
" T.RandomHorizontalFlip(p=0.5),\n",
" T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
" T.RandomAffine(degrees=15, translate=(0.1, 0.1)),\n",
" T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
" T.RandomPerspective(distortion_scale=0.4, p=0.7),\n",
" T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
" T.RandomGrayscale(p=0.15),\n",
" T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
" # T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),\n",
" ])\n",
" elif args.animation_mode == '2D':\n",
" self.augs = T.Compose([\n",
" T.RandomHorizontalFlip(p=0.4),\n",
" T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
" T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR),\n",
" T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
" T.RandomGrayscale(p=0.1),\n",
" T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
" T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.3),\n",
" ])\n",
" \n",
"\n",
" def forward(self, input):\n",
" cutouts = []\n",
" gray = T.Grayscale(3)\n",
" sideY, sideX = input.shape[2:4]\n",
" max_size = min(sideX, sideY)\n",
" min_size = min(sideX, sideY, self.cut_size)\n",
" l_size = max(sideX, sideY)\n",
" output_shape = [1,3,self.cut_size,self.cut_size] \n",
" output_shape_2 = [1,3,self.cut_size+2,self.cut_size+2]\n",
" pad_input = F.pad(input,((sideY-max_size)//2,(sideY-max_size)//2,(sideX-max_size)//2,(sideX-max_size)//2), **padargs)\n",
" cutout = resize(pad_input, out_shape=output_shape)\n",
"\n",
" if self.Overview>0:\n",
" if self.Overview<=4:\n",
" if self.Overview>=1:\n",
" cutouts.append(cutout)\n",
" if self.Overview>=2:\n",
" cutouts.append(gray(cutout))\n",
" if self.Overview>=3:\n",
" cutouts.append(TF.hflip(cutout))\n",
" if self.Overview==4:\n",
" cutouts.append(gray(TF.hflip(cutout)))\n",
" else:\n",
" cutout = resize(pad_input, out_shape=output_shape)\n",
" for _ in range(self.Overview):\n",
" cutouts.append(cutout)\n",
"\n",
" if cutout_debug:\n",
" TF.to_pil_image(cutouts[0].clamp(0, 1).squeeze(0)).save(\"/content/cutout_overview0.jpg\",quality=99)\n",
" \n",
" if self.InnerCrop >0:\n",
" for i in range(self.InnerCrop):\n",
" size = int(torch.rand([])**self.IC_Size_Pow * (max_size - min_size) + min_size)\n",
" offsetx = torch.randint(0, sideX - size + 1, ())\n",
" offsety = torch.randint(0, sideY - size + 1, ())\n",
" cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]\n",
" if i <= int(self.IC_Grey_P * self.InnerCrop):\n",
" cutout = gray(cutout)\n",
" cutout = resize(cutout, out_shape=output_shape)\n",
" cutouts.append(cutout)\n",
" if cutout_debug:\n",
" TF.to_pil_image(cutouts[-1].clamp(0, 1).squeeze(0)).save(\"/content/cutout_InnerCrop.jpg\",quality=99)\n",
" cutouts = torch.cat(cutouts)\n",
" if skip_augs is not True: cutouts=self.augs(cutouts)\n",
" return cutouts\n",
"\n",
"def spherical_dist_loss(x, y):\n",
" x = F.normalize(x, dim=-1)\n",
" y = F.normalize(y, dim=-1)\n",
" return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2) \n",
"\n",
"def tv_loss(input):\n",
" \"\"\"L2 total variation loss, as in Mahendran et al.\"\"\"\n",
" input = F.pad(input, (0, 1, 0, 1), 'replicate')\n",
" x_diff = input[..., :-1, 1:] - input[..., :-1, :-1]\n",
" y_diff = input[..., 1:, :-1] - input[..., :-1, :-1]\n",
" return (x_diff**2 + y_diff**2).mean([1, 2, 3])\n",
"\n",
"\n",
"def range_loss(input):\n",
" return (input - input.clamp(-1, 1)).pow(2).mean([1, 2, 3])\n",
"\n",
"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\n",
"\n",
"def do_run():\n",
" seed = args.seed\n",
" print(range(args.start_frame, args.max_frames))\n",
" for frame_num in range(args.start_frame, args.max_frames):\n",
" if stop_on_next_loop:\n",
" break\n",
" \n",
" display.clear_output(wait=True)\n",
"\n",
" # Print Frame progress if animation mode is on\n",
" if args.animation_mode != \"None\":\n",
" batchBar = tqdm(range(args.max_frames), desc =\"Frames\")\n",
" batchBar.n = frame_num\n",
" batchBar.refresh()\n",
"\n",
" \n",
" # Inits if not video frames\n",
" if args.animation_mode != \"Video Input\":\n",
" if args.init_image == '':\n",
" init_image = None\n",
" else:\n",
" init_image = args.init_image\n",
" init_scale = args.init_scale\n",
" skip_steps = args.skip_steps\n",
"\n",
" if args.animation_mode == \"2D\":\n",
" if args.key_frames:\n",
" angle = args.angle_series[frame_num]\n",
" zoom = args.zoom_series[frame_num]\n",
" translation_x = args.translation_x_series[frame_num]\n",
" translation_y = args.translation_y_series[frame_num]\n",
" print(\n",
" f'angle: {angle}',\n",
" f'zoom: {zoom}',\n",
" f'translation_x: {translation_x}',\n",
" f'translation_y: {translation_y}',\n",
" )\n",
" \n",
" if frame_num > 0:\n",
" seed = seed + 1 \n",
" if resume_run and frame_num == start_frame:\n",
" img_0 = cv2.imread(batchFolder+f\"/{batch_name}({batchNum})_{start_frame-1:04}.png\")\n",
" else:\n",
" img_0 = cv2.imread('prevFrame.png')\n",
" center = (1*img_0.shape[1]//2, 1*img_0.shape[0]//2)\n",
" trans_mat = np.float32(\n",
" [[1, 0, translation_x],\n",
" [0, 1, translation_y]]\n",
" )\n",
" rot_mat = cv2.getRotationMatrix2D( center, angle, zoom )\n",
" trans_mat = np.vstack([trans_mat, [0,0,1]])\n",
" rot_mat = np.vstack([rot_mat, [0,0,1]])\n",
" transformation_matrix = np.matmul(rot_mat, trans_mat)\n",
" img_0 = cv2.warpPerspective(\n",
" img_0,\n",
" transformation_matrix,\n",
" (img_0.shape[1], img_0.shape[0]),\n",
" borderMode=cv2.BORDER_WRAP\n",
" )\n",
" cv2.imwrite('prevFrameScaled.png', img_0)\n",
" init_image = 'prevFrameScaled.png'\n",
" init_scale = args.frames_scale\n",
" skip_steps = args.calc_frames_skip_steps\n",
"\n",
" if args.animation_mode == \"Video Input\":\n",
" seed = seed + 1 \n",
" init_image = f'{videoFramesFolder}/{frame_num+1:04}.jpg'\n",
" init_scale = args.frames_scale\n",
" skip_steps = args.calc_frames_skip_steps\n",
"\n",
" loss_values = []\n",
" \n",
" if seed is not None:\n",
" np.random.seed(seed)\n",
" random.seed(seed)\n",
" torch.manual_seed(seed)\n",
" torch.cuda.manual_seed_all(seed)\n",
" torch.backends.cudnn.deterministic = True\n",
" \n",
" target_embeds, weights = [], []\n",
" \n",
" if args.prompts_series is not None and frame_num >= len(args.prompts_series):\n",
" frame_prompt = args.prompts_series[-1]\n",
" elif args.prompts_series is not None:\n",
" frame_prompt = args.prompts_series[frame_num]\n",
" else:\n",
" frame_prompt = []\n",
" \n",
" print(args.image_prompts_series)\n",
" if args.image_prompts_series is not None and frame_num >= len(args.image_prompts_series):\n",
" image_prompt = args.image_prompts_series[-1]\n",
" elif args.image_prompts_series is not None:\n",
" image_prompt = args.image_prompts_series[frame_num]\n",
" else:\n",
" image_prompt = []\n",
"\n",
" print(f'Frame Prompt: {frame_prompt}')\n",
"\n",
" model_stats = []\n",
" for clip_model in clip_models:\n",
" cutn = 16\n",
" model_stat = {\"clip_model\":None,\"target_embeds\":[],\"make_cutouts\":None,\"weights\":[]}\n",
" model_stat[\"clip_model\"] = clip_model\n",
" \n",
" \n",
" for prompt in frame_prompt:\n",
" txt, weight = parse_prompt(prompt)\n",
" txt = clip_model.encode_text(clip.tokenize(prompt).to(device)).float()\n",
" \n",
" if args.fuzzy_prompt:\n",
" for i in range(25):\n",
" model_stat[\"target_embeds\"].append((txt + torch.randn(txt.shape).cuda() * args.rand_mag).clamp(0,1))\n",
" model_stat[\"weights\"].append(weight)\n",
" else:\n",
" model_stat[\"target_embeds\"].append(txt)\n",
" model_stat[\"weights\"].append(weight)\n",
" \n",
" if image_prompt:\n",
" model_stat[\"make_cutouts\"] = MakeCutouts(clip_model.visual.input_resolution, cutn, skip_augs=skip_augs) \n",
" for prompt in image_prompt:\n",
" path, weight = parse_prompt(prompt)\n",
" img = Image.open(fetch(path)).convert('RGB')\n",
" img = TF.resize(img, min(side_x, side_y, *img.size), T.InterpolationMode.LANCZOS)\n",
" batch = model_stat[\"make_cutouts\"](TF.to_tensor(img).to(device).unsqueeze(0).mul(2).sub(1))\n",
" embed = clip_model.encode_image(normalize(batch)).float()\n",
" if fuzzy_prompt:\n",
" for i in range(25):\n",
" model_stat[\"target_embeds\"].append((embed + torch.randn(embed.shape).cuda() * rand_mag).clamp(0,1))\n",
" weights.extend([weight / cutn] * cutn)\n",
" else:\n",
" model_stat[\"target_embeds\"].append(embed)\n",
" model_stat[\"weights\"].extend([weight / cutn] * cutn)\n",
" \n",
" model_stat[\"target_embeds\"] = torch.cat(model_stat[\"target_embeds\"])\n",
" model_stat[\"weights\"] = torch.tensor(model_stat[\"weights\"], device=device)\n",
" if model_stat[\"weights\"].sum().abs() < 1e-3:\n",
" raise RuntimeError('The weights must not sum to 0.')\n",
" model_stat[\"weights\"] /= model_stat[\"weights\"].sum().abs()\n",
" model_stats.append(model_stat)\n",
" \n",
" init = None\n",
" if init_image is not None:\n",
" init = Image.open(fetch(init_image)).convert('RGB')\n",
" init = init.resize((args.side_x, args.side_y), Image.LANCZOS)\n",
" init = TF.to_tensor(init).to(device).unsqueeze(0).mul(2).sub(1)\n",
" \n",
" if args.perlin_init:\n",
" if args.perlin_mode == 'color':\n",
" init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)\n",
" init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False)\n",
" elif args.perlin_mode == 'gray':\n",
" init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True)\n",
" init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)\n",
" else:\n",
" init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)\n",
" init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)\n",
" # init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device)\n",
" init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1)\n",
" del init2\n",
" \n",
" cur_t = None\n",
" \n",
" def cond_fn(x, t, y=None):\n",
" with torch.enable_grad():\n",
" x_is_NaN = False\n",
" x = x.detach().requires_grad_()\n",
" n = x.shape[0]\n",
" if use_secondary_model is True:\n",
" alpha = torch.tensor(diffusion.sqrt_alphas_cumprod[cur_t], device=device, dtype=torch.float32)\n",
" sigma = torch.tensor(diffusion.sqrt_one_minus_alphas_cumprod[cur_t], device=device, dtype=torch.float32)\n",
" cosine_t = alpha_sigma_to_t(alpha, sigma)\n",
" out = secondary_model(x, cosine_t[None].repeat([n])).pred\n",
" fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t]\n",
" x_in = out * fac + x * (1 - fac)\n",
" x_in_grad = torch.zeros_like(x_in)\n",
" else:\n",
" my_t = torch.ones([n], device=device, dtype=torch.long) * cur_t\n",
" out = diffusion.p_mean_variance(model, x, my_t, clip_denoised=False, model_kwargs={'y': y})\n",
" fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t]\n",
" x_in = out['pred_xstart'] * fac + x * (1 - fac)\n",
" x_in_grad = torch.zeros_like(x_in)\n",
" for model_stat in model_stats:\n",
" for i in range(args.cutn_batches):\n",
" t_int = int(t.item())+1 #errors on last step without +1, need to find source\n",
" #when using SLIP Base model the dimensions need to be hard coded to avoid AttributeError: 'VisionTransformer' object has no attribute 'input_resolution'\n",
" try:\n",
" input_resolution=model_stat[\"clip_model\"].visual.input_resolution\n",
" except:\n",
" input_resolution=224\n",
"\n",
" cuts = MakeCutoutsDango(input_resolution,\n",
" Overview= args.cut_overview[1000-t_int], \n",
" InnerCrop = args.cut_innercut[1000-t_int], IC_Size_Pow=args.cut_ic_pow, IC_Grey_P = args.cut_icgray_p[1000-t_int]\n",
" )\n",
" clip_in = normalize(cuts(x_in.add(1).div(2)))\n",
" image_embeds = model_stat[\"clip_model\"].encode_image(clip_in).float()\n",
" dists = spherical_dist_loss(image_embeds.unsqueeze(1), model_stat[\"target_embeds\"].unsqueeze(0))\n",
" dists = dists.view([args.cut_overview[1000-t_int]+args.cut_innercut[1000-t_int], n, -1])\n",
" losses = dists.mul(model_stat[\"weights\"]).sum(2).mean(0)\n",
" loss_values.append(losses.sum().item()) # log loss, probably shouldn't do per cutn_batch\n",
" x_in_grad += torch.autograd.grad(losses.sum() * clip_guidance_scale, x_in)[0] / cutn_batches\n",
" tv_losses = tv_loss(x_in)\n",
" if use_secondary_model is True:\n",
" range_losses = range_loss(out)\n",
" else:\n",
" range_losses = range_loss(out['pred_xstart'])\n",
" sat_losses = torch.abs(x_in - x_in.clamp(min=-1,max=1)).mean()\n",
" loss = tv_losses.sum() * tv_scale + range_losses.sum() * range_scale + sat_losses.sum() * sat_scale\n",
" if init is not None and args.init_scale:\n",
" init_losses = lpips_model(x_in, init)\n",
" loss = loss + init_losses.sum() * args.init_scale\n",
" x_in_grad += torch.autograd.grad(loss, x_in)[0]\n",
" if torch.isnan(x_in_grad).any()==False:\n",
" grad = -torch.autograd.grad(x_in, x, x_in_grad)[0]\n",
" else:\n",
" # print(\"NaN'd\")\n",
" x_is_NaN = True\n",
" grad = torch.zeros_like(x)\n",
" if args.clamp_grad and x_is_NaN == False:\n",
" magnitude = grad.square().mean().sqrt()\n",
" return grad * magnitude.clamp(max=args.clamp_max) / magnitude #min=-0.02, min=-clamp_max, \n",
" return grad\n",
" \n",
" if model_config['timestep_respacing'].startswith('ddim'):\n",
" sample_fn = diffusion.ddim_sample_loop_progressive\n",
" else:\n",
" sample_fn = diffusion.p_sample_loop_progressive\n",
" \n",
"\n",
" image_display = Output()\n",
" for i in range(args.n_batches):\n",
" if args.animation_mode == 'None':\n",
" display.clear_output(wait=True)\n",
" batchBar = tqdm(range(args.n_batches), desc =\"Batches\")\n",
" batchBar.n = i\n",
" batchBar.refresh()\n",
" print('')\n",
" display.display(image_display)\n",
" gc.collect()\n",
" torch.cuda.empty_cache()\n",
" cur_t = diffusion.num_timesteps - skip_steps - 1\n",
" total_steps = cur_t\n",
"\n",
" if perlin_init:\n",
" init = regen_perlin()\n",
"\n",
" if model_config['timestep_respacing'].startswith('ddim'):\n",
" samples = sample_fn(\n",
" model,\n",
" (batch_size, 3, args.side_y, args.side_x),\n",
" clip_denoised=clip_denoised,\n",
" model_kwargs={},\n",
" cond_fn=cond_fn,\n",
" progress=True,\n",
" skip_timesteps=skip_steps,\n",
" init_image=init,\n",
" randomize_class=randomize_class,\n",
" eta=eta,\n",
" )\n",
" else:\n",
" samples = sample_fn(\n",
" model,\n",
" (batch_size, 3, args.side_y, args.side_x),\n",
" clip_denoised=clip_denoised,\n",
" model_kwargs={},\n",
" cond_fn=cond_fn,\n",
" progress=True,\n",
" skip_timesteps=skip_steps,\n",
" init_image=init,\n",
" randomize_class=randomize_class,\n",
" )\n",
" \n",
" \n",
" # with run_display:\n",
" # display.clear_output(wait=True)\n",
" imgToSharpen = None\n",
" for j, sample in enumerate(samples): \n",
" cur_t -= 1\n",
" intermediateStep = False\n",
" if args.steps_per_checkpoint is not None:\n",
" if j % steps_per_checkpoint == 0 and j > 0:\n",
" intermediateStep = True\n",
" elif j in args.intermediate_saves:\n",
" intermediateStep = True\n",
" with image_display:\n",
" if j % args.display_rate == 0 or cur_t == -1 or intermediateStep == True:\n",
" for k, image in enumerate(sample['pred_xstart']):\n",
" # tqdm.write(f'Batch {i}, step {j}, output {k}:')\n",
" current_time = datetime.now().strftime('%y%m%d-%H%M%S_%f')\n",
" percent = math.ceil(j/total_steps*100)\n",
" if args.n_batches > 0:\n",
" #if intermediates are saved to the subfolder, don't append a step or percentage to the name\n",
" if cur_t == -1 and args.intermediates_in_subfolder is True:\n",
" save_num = f'{frame_num:04}' if animation_mode != \"None\" else i\n",
" filename = f'{args.batch_name}({args.batchNum})_{save_num}.png'\n",
" else:\n",