├── Disco_Diffusion_v5_2_[w_VR_Mode].ipynb
├── Disco_Diffusion_v5_2_w_VR_Mode_batch_mode.ipynb
├── Disco_Diffusion_v5_Turbo_[w_3D_animation]_local.ipynb
├── Disco_Diffusion_v5_Turbo_[w_3D_animation_experimental_brightness_correction].ipynb
├── LICENSE
├── README.md
├── examples
├── abandoned_shopping_mall.jpeg
├── purity_and_grace.png
├── retro_playroom.jpg
├── self_portrait_of_an_AI.png
└── terrarium.jpg
└── queue
├── master_settings.txt
├── queue_1.txt
└── queue_2.txt
/Disco_Diffusion_v5_Turbo_[w_3D_animation]_local.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "id": "1YwMUyt9LHG1"
7 | },
8 | "source": [
9 | "# Disco Diffusion v5 (Turbo+Smooth) - Now with 3D animation\n",
10 | "\n",
11 | "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",
12 | "\n",
13 | "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)\n",
14 | "\n",
15 | "Credits & Changelog ⬇️\n"
16 | ]
17 | },
18 | {
19 | "cell_type": "markdown",
20 | "metadata": {
21 | "id": "wX5omb9C7Bjz"
22 | },
23 | "source": [
24 | "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",
25 | "\n",
26 | "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",
27 | "\n",
28 | "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",
29 | "\n",
30 | "Vark added code to load in multiple Clip models at once, which all prompts are evaluated against, which may greatly improve accuracy.\n",
31 | "\n",
32 | "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",
33 | "\n",
34 | "Advanced DangoCutn Cutout method is also from Dango223.\n",
35 | "\n",
36 | "--\n",
37 | "\n",
38 | "Disco:\n",
39 | "\n",
40 | "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.\n",
41 | "\n",
42 | "3D animation implementation added by Adam Letts (https://twitter.com/gandamu_ml) in collaboration with Somnai.\n",
43 | "\n",
44 | "Turbo feature by Chris Allen (https://twitter.com/zippy731) "
45 | ]
46 | },
47 | {
48 | "cell_type": "code",
49 | "execution_count": null,
50 | "metadata": {
51 | "id": "wDSYhyjqZQI9"
52 | },
53 | "outputs": [],
54 | "source": [
55 | "# @title Licensed under the MIT License\n",
56 | "\n",
57 | "# Copyright (c) 2021 Katherine Crowson \n",
58 | "\n",
59 | "# Permission is hereby granted, free of charge, to any person obtaining a copy\n",
60 | "# of this software and associated documentation files (the \"Software\"), to deal\n",
61 | "# in the Software without restriction, including without limitation the rights\n",
62 | "# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n",
63 | "# copies of the Software, and to permit persons to whom the Software is\n",
64 | "# furnished to do so, subject to the following conditions:\n",
65 | "\n",
66 | "# The above copyright notice and this permission notice shall be included in\n",
67 | "# all copies or substantial portions of the Software.\n",
68 | "\n",
69 | "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n",
70 | "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n",
71 | "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n",
72 | "# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n",
73 | "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n",
74 | "# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n",
75 | "# THE SOFTWARE.\n",
76 | "\n",
77 | "# --\n",
78 | "\n",
79 | "# @title Licensed under the MIT License\n",
80 | "\n",
81 | "# Copyright (c) 2021 Maxwell Ingham \n",
82 | "# Copyright (c) 2022 Adam Letts \n",
83 | "\n",
84 | "# Permission is hereby granted, free of charge, to any person obtaining a copy\n",
85 | "# of this software and associated documentation files (the \"Software\"), to deal\n",
86 | "# in the Software without restriction, including without limitation the rights\n",
87 | "# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n",
88 | "# copies of the Software, and to permit persons to whom the Software is\n",
89 | "# furnished to do so, subject to the following conditions:\n",
90 | "\n",
91 | "# The above copyright notice and this permission notice shall be included in\n",
92 | "# all copies or substantial portions of the Software.\n",
93 | "\n",
94 | "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n",
95 | "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n",
96 | "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n",
97 | "# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n",
98 | "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n",
99 | "# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n",
100 | "# THE SOFTWARE."
101 | ]
102 | },
103 | {
104 | "cell_type": "code",
105 | "execution_count": null,
106 | "metadata": {
107 | "cellView": "form",
108 | "id": "qFB3nwLSQI8X"
109 | },
110 | "outputs": [],
111 | "source": [
112 | "#@title <- View Changelog\n",
113 | "\n",
114 | "skip_for_run_all = True #@param {type: 'boolean'}\n",
115 | "\n",
116 | "if skip_for_run_all == False:\n",
117 | " print(\n",
118 | " '''\n",
119 | " v1 Update: Oct 29th 2021 - Somnai\n",
120 | "\n",
121 | " QoL improvements added by Somnai (@somnai_dreams), including user friendly UI, settings+prompt saving and improved google drive folder organization.\n",
122 | "\n",
123 | " v1.1 Update: Nov 13th 2021 - Somnai\n",
124 | "\n",
125 | " Now includes sizing options, intermediate saves and fixed image prompts and perlin inits. unexposed batch option since it doesn't work\n",
126 | "\n",
127 | " v2 Update: Nov 22nd 2021 - Somnai\n",
128 | "\n",
129 | " Initial addition of Katherine Crowson's Secondary Model Method (https://colab.research.google.com/drive/1mpkrhOjoyzPeSWy2r7T8EYRaU7amYOOi#scrollTo=X5gODNAMEUCR)\n",
130 | "\n",
131 | " Noticed settings were saving with the wrong name so corrected it. Let me know if you preferred the old scheme.\n",
132 | "\n",
133 | " v3 Update: Dec 24th 2021 - Somnai\n",
134 | "\n",
135 | " Implemented Dango's advanced cutout method\n",
136 | "\n",
137 | " Added SLIP models, thanks to NeuralDivergent\n",
138 | "\n",
139 | " Fixed issue with NaNs resulting in black images, with massive help and testing from @Softology\n",
140 | "\n",
141 | " Perlin now changes properly within batches (not sure where this perlin_regen code came from originally, but thank you)\n",
142 | "\n",
143 | " v4 Update: Jan 2021 - Somnai\n",
144 | "\n",
145 | " Implemented Diffusion Zooming\n",
146 | "\n",
147 | " Added Chigozie keyframing\n",
148 | "\n",
149 | " Made a bunch of edits to processes\n",
150 | " \n",
151 | " v4.1 Update: Jan 14th 2021 - Somnai\n",
152 | "\n",
153 | " Added video input mode\n",
154 | "\n",
155 | " Added license that somehow went missing\n",
156 | "\n",
157 | " Added improved prompt keyframing, fixed image_prompts and multiple prompts\n",
158 | "\n",
159 | " Improved UI\n",
160 | "\n",
161 | " Significant under the hood cleanup and improvement\n",
162 | "\n",
163 | " Refined defaults for each mode\n",
164 | "\n",
165 | " Added latent-diffusion SuperRes for sharpening\n",
166 | "\n",
167 | " Added resume run mode\n",
168 | "\n",
169 | " v4.9 Update: Feb 5th 2022 - gandamu / Adam Letts\n",
170 | "\n",
171 | " Added 3D\n",
172 | "\n",
173 | " Added brightness corrections to prevent animation from steadily going dark over time\n",
174 | "\n",
175 | " v4.91 Update: Feb 19th 2022 - gandamu / Adam Letts\n",
176 | "\n",
177 | " Cleaned up 3D implementation and made associated args accessible via Colab UI elements\n",
178 | "\n",
179 | " v4.92 Update: Feb 20th 2022 - gandamu / Adam Letts\n",
180 | "\n",
181 | " Separated transform code\n",
182 | " '''\n",
183 | " )"
184 | ]
185 | },
186 | {
187 | "cell_type": "markdown",
188 | "metadata": {
189 | "id": "XTu6AjLyFQUq"
190 | },
191 | "source": [
192 | "#Tutorial"
193 | ]
194 | },
195 | {
196 | "cell_type": "markdown",
197 | "metadata": {
198 | "id": "YR806W0wi3He"
199 | },
200 | "source": [
201 | "**Diffusion settings (Defaults are heavily outdated)**\n",
202 | "---\n",
203 | "\n",
204 | "This section is outdated as of v2\n",
205 | "\n",
206 | "Setting | Description | Default\n",
207 | "--- | --- | ---\n",
208 | "**Your vision:**\n",
209 | "`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",
210 | "`image_prompts` | Think of these images more as a description of their contents. | N/A\n",
211 | "**Image quality:**\n",
212 | "`clip_guidance_scale` | Controls how much the image should look like the prompt. | 1000\n",
213 | "`tv_scale` | Controls the smoothness of the final output. | 150\n",
214 | "`range_scale` | Controls how far out of range RGB values are allowed to be. | 150\n",
215 | "`sat_scale` | Controls how much saturation is allowed. From nshepperd's JAX notebook. | 0\n",
216 | "`cutn` | Controls how many crops to take from the image. | 16\n",
217 | "`cutn_batches` | Accumulate CLIP gradient from multiple batches of cuts | 2\n",
218 | "**Init settings:**\n",
219 | "`init_image` | URL or local path | None\n",
220 | "`init_scale` | This enhances the effect of the init image, a good value is 1000 | 0\n",
221 | "`skip_steps Controls the starting point along the diffusion timesteps | 0\n",
222 | "`perlin_init` | Option to start with random perlin noise | False\n",
223 | "`perlin_mode` | ('gray', 'color') | 'mixed'\n",
224 | "**Advanced:**\n",
225 | "`skip_augs` |Controls whether to skip torchvision augmentations | False\n",
226 | "`randomize_class` |Controls whether the imagenet class is randomly changed each iteration | True\n",
227 | "`clip_denoised` |Determines whether CLIP discriminates a noisy or denoised image | False\n",
228 | "`clamp_grad` |Experimental: Using adaptive clip grad in the cond_fn | True\n",
229 | "`seed` | Choose a random seed and print it at end of run for reproduction | random_seed\n",
230 | "`fuzzy_prompt` | Controls whether to add multiple noisy prompts to the prompt losses | False\n",
231 | "`rand_mag` |Controls the magnitude of the random noise | 0.1\n",
232 | "`eta` | DDIM hyperparameter | 0.5\n",
233 | "\n",
234 | "..\n",
235 | "\n",
236 | "**Model settings**\n",
237 | "---\n",
238 | "\n",
239 | "Setting | Description | Default\n",
240 | "--- | --- | ---\n",
241 | "**Diffusion:**\n",
242 | "`timestep_respacing` | Modify this value to decrease the number of timesteps. | ddim100\n",
243 | "`diffusion_steps` || 1000\n",
244 | "**Diffusion:**\n",
245 | "`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"
246 | ]
247 | },
248 | {
249 | "cell_type": "markdown",
250 | "metadata": {
251 | "id": "_9Eg9Kf5FlfK"
252 | },
253 | "source": [
254 | "# 1. Set Up"
255 | ]
256 | },
257 | {
258 | "cell_type": "code",
259 | "execution_count": null,
260 | "metadata": {
261 | "cellView": "form",
262 | "id": "qZ3rNuAWAewx"
263 | },
264 | "outputs": [],
265 | "source": [
266 | "#@title 1.1 Check GPU Status\n",
267 | "!nvidia-smi -L"
268 | ]
269 | },
270 | {
271 | "cell_type": "code",
272 | "execution_count": null,
273 | "metadata": {
274 | "cellView": "form",
275 | "id": "yZsjzwS0YGo6"
276 | },
277 | "outputs": [],
278 | "source": [
279 | "#@title 1.2 Prepare Folders\n",
280 | "\n",
281 | "try:\n",
282 | " from google.colab import drive\n",
283 | " print(\"Google Colab detected. Using Google Drive.\")\n",
284 | " is_colab = True\n",
285 | " #@markdown If you connect your Google Drive, you can save the final image of each run on your drive.\n",
286 | " google_drive = True #@param {type:\"boolean\"}\n",
287 | " #@markdown Click here if you'd like to save the diffusion model checkpoint file to (and/or load from) your Google Drive:\n",
288 | " save_models_to_google_drive = True #@param {type:\"boolean\"}\n",
289 | "except:\n",
290 | " is_colab = False\n",
291 | " google_drive = False\n",
292 | " save_models_to_google_drive = False\n",
293 | " print(\"Google Colab not detected.\")\n",
294 | "\n",
295 | "if is_colab:\n",
296 | " if google_drive is True:\n",
297 | " drive.mount('/content/drive')\n",
298 | " root_path = '/content/drive/MyDrive/AI/Disco_Diffusion'\n",
299 | " else:\n",
300 | " root_path = '/content'\n",
301 | "else:\n",
302 | " root_path = '.'\n",
303 | "\n",
304 | "import os\n",
305 | "from os import path\n",
306 | "#Simple create paths taken with modifications from Datamosh's Batch VQGAN+CLIP notebook\n",
307 | "def createPath(filepath):\n",
308 | " if path.exists(filepath) == False:\n",
309 | " os.makedirs(filepath)\n",
310 | " print(f'Made {filepath}')\n",
311 | " else:\n",
312 | " print(f'filepath {filepath} exists.')\n",
313 | "\n",
314 | "initDirPath = f'{root_path}/init_images'\n",
315 | "createPath(initDirPath)\n",
316 | "outDirPath = f'{root_path}/images_out'\n",
317 | "createPath(outDirPath)\n",
318 | "\n",
319 | "if is_colab:\n",
320 | " if google_drive and not save_models_to_google_drive or not google_drive:\n",
321 | " model_path = '/content/model'\n",
322 | " createPath(model_path)\n",
323 | " if google_drive and save_models_to_google_drive:\n",
324 | " model_path = f'{root_path}/model'\n",
325 | " createPath(model_path)\n",
326 | "else:\n",
327 | " model_path = f'{root_path}/model'\n",
328 | " createPath(model_path)\n",
329 | "\n",
330 | "# libraries = f'{root_path}/libraries'\n",
331 | "# createPath(libraries)"
332 | ]
333 | },
334 | {
335 | "cell_type": "code",
336 | "execution_count": null,
337 | "metadata": {
338 | "cellView": "form",
339 | "id": "JmbrcrhpBPC6",
340 | "scrolled": true
341 | },
342 | "outputs": [],
343 | "source": [
344 | "#@title ### 1.3 Install and import dependencies\n",
345 | "\n",
346 | "from os.path import exists as path_exists\n",
347 | "\n",
348 | "if not is_colab:\n",
349 | " # If running locally, there's a good chance your env will need this in order to not crash upon np.matmul() or similar operations.\n",
350 | " os.environ['KMP_DUPLICATE_LIB_OK']='TRUE'\n",
351 | "\n",
352 | "PROJECT_DIR = os.path.abspath(os.getcwd())\n",
353 | "USE_ADABINS = True\n",
354 | "\n",
355 | "if is_colab:\n",
356 | " if google_drive is not True:\n",
357 | " root_path = f'/content'\n",
358 | " model_path = '/content/models' \n",
359 | "else:\n",
360 | " root_path = f'.'\n",
361 | " model_path = f'{root_path}/model'\n",
362 | "\n",
363 | "model_256_downloaded = False\n",
364 | "model_512_downloaded = False\n",
365 | "model_secondary_downloaded = False\n",
366 | "\n",
367 | "#if is_colab:\n",
368 | "if True:\n",
369 | " !git clone https://github.com/openai/CLIP\n",
370 | " # !git clone https://github.com/facebookresearch/SLIP.git\n",
371 | " !git clone https://github.com/crowsonkb/guided-diffusion\n",
372 | " !git clone https://github.com/assafshocher/ResizeRight.git\n",
373 | " !pip install -e ./CLIP\n",
374 | " !pip install -e ./guided-diffusion\n",
375 | " !pip install lpips datetime timm\n",
376 | " !apt install imagemagick\n",
377 | " !git clone https://github.com/isl-org/MiDaS.git\n",
378 | " !git clone https://github.com/alembics/disco-diffusion.git\n",
379 | " # Rename a file to avoid a name conflict..\n",
380 | " !mv MiDaS/utils.py MiDaS/midas_utils.py\n",
381 | " !cp disco-diffusion/disco_xform_utils.py disco_xform_utils.py\n",
382 | "\n",
383 | "!mkdir model\n",
384 | "if not path_exists(f'{model_path}/dpt_large-midas-2f21e586.pt'):\n",
385 | " !wget https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt -P {model_path}\n",
386 | "\n",
387 | "import sys\n",
388 | "import torch\n",
389 | "\n",
390 | "#Install pytorch3d\n",
391 | "#if is_colab:\n",
392 | "if True:\n",
393 | " pyt_version_str=torch.__version__.split(\"+\")[0].replace(\".\", \"\")\n",
394 | " version_str=\"\".join([\n",
395 | " f\"py3{sys.version_info.minor}_cu\",\n",
396 | " torch.version.cuda.replace(\".\",\"\"),\n",
397 | " f\"_pyt{pyt_version_str}\"\n",
398 | " ])\n",
399 | " !pip install fvcore iopath\n",
400 | " !pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html\n",
401 | "\n",
402 | "# sys.path.append('./SLIP')\n",
403 | "sys.path.append('ResizeRight')\n",
404 | "sys.path.append('MiDaS')\n",
405 | "from dataclasses import dataclass\n",
406 | "from functools import partial\n",
407 | "import cv2\n",
408 | "import pandas as pd\n",
409 | "import gc\n",
410 | "import io\n",
411 | "import math\n",
412 | "import timm\n",
413 | "from IPython import display\n",
414 | "import lpips\n",
415 | "from PIL import Image, ImageOps\n",
416 | "import requests\n",
417 | "from glob import glob\n",
418 | "import json\n",
419 | "from types import SimpleNamespace\n",
420 | "from torch import nn\n",
421 | "from torch.nn import functional as F\n",
422 | "import torchvision.transforms as T\n",
423 | "import torchvision.transforms.functional as TF\n",
424 | "from tqdm.notebook import tqdm\n",
425 | "sys.path.append('CLIP')\n",
426 | "sys.path.append('guided-diffusion')\n",
427 | "import clip\n",
428 | "from resize_right import resize\n",
429 | "# from models import SLIP_VITB16, SLIP, SLIP_VITL16\n",
430 | "from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults\n",
431 | "from datetime import datetime\n",
432 | "import numpy as np\n",
433 | "import matplotlib.pyplot as plt\n",
434 | "import random\n",
435 | "from ipywidgets import Output\n",
436 | "import hashlib\n",
437 | "\n",
438 | "#SuperRes\n",
439 | "#if is_colab:\n",
440 | "if True:\n",
441 | " !git clone https://github.com/CompVis/latent-diffusion.git\n",
442 | " !git clone https://github.com/CompVis/taming-transformers\n",
443 | " !pip install -e ./taming-transformers\n",
444 | " !pip install ipywidgets omegaconf>=2.0.0 pytorch-lightning>=1.0.8 torch-fidelity einops wandb\n",
445 | "\n",
446 | "#SuperRes\n",
447 | "import ipywidgets as widgets\n",
448 | "import os\n",
449 | "sys.path.append(\".\")\n",
450 | "sys.path.append('taming-transformers')\n",
451 | "from taming.models import vqgan # checking correct import from taming\n",
452 | "from torchvision.datasets.utils import download_url\n",
453 | "if is_colab:\n",
454 | " %cd '/content/latent-diffusion'\n",
455 | "else:\n",
456 | " %cd 'latent-diffusion'\n",
457 | "from functools import partial\n",
458 | "from ldm.util import instantiate_from_config\n",
459 | "from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like\n",
460 | "# from ldm.models.diffusion.ddim import DDIMSampler\n",
461 | "from ldm.util import ismap\n",
462 | "if is_colab:\n",
463 | " %cd '/content'\n",
464 | " from google.colab import files\n",
465 | "else:\n",
466 | " %cd $PROJECT_DIR\n",
467 | "from IPython.display import Image as ipyimg\n",
468 | "from numpy import asarray\n",
469 | "from einops import rearrange, repeat\n",
470 | "import torch, torchvision\n",
471 | "import time\n",
472 | "from omegaconf import OmegaConf\n",
473 | "import warnings\n",
474 | "warnings.filterwarnings(\"ignore\", category=UserWarning)\n",
475 | "\n",
476 | "# AdaBins stuff\n",
477 | "if USE_ADABINS:\n",
478 | " #if is_colab:\n",
479 | " if True:\n",
480 | " !git clone https://github.com/shariqfarooq123/AdaBins.git\n",
481 | " if not path_exists(f'{model_path}/AdaBins_nyu.pt'):\n",
482 | " !wget https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt -P {model_path}\n",
483 | " !mkdir pretrained\n",
484 | " !cp -P {model_path}/AdaBins_nyu.pt pretrained/AdaBins_nyu.pt\n",
485 | " sys.path.append('AdaBins')\n",
486 | " from infer import InferenceHelper\n",
487 | " MAX_ADABINS_AREA = 500000\n",
488 | "\n",
489 | "import torch\n",
490 | "DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n",
491 | "print('Using device:', DEVICE)\n",
492 | "device = DEVICE # At least one of the modules expects this name..\n",
493 | "\n",
494 | "if torch.cuda.get_device_capability(DEVICE) == (8,0): ## A100 fix thanks to Emad\n",
495 | " print('Disabling CUDNN for A100 gpu', file=sys.stderr)\n",
496 | " torch.backends.cudnn.enabled = False\n",
497 | " \n",
498 | "%load_ext autoreload \n",
499 | "%autoreload 2"
500 | ]
501 | },
502 | {
503 | "cell_type": "code",
504 | "execution_count": null,
505 | "metadata": {},
506 | "outputs": [],
507 | "source": [
508 | "# This should print \"True\" - if not, pytorch can't see your GPU\n",
509 | "import torch\n",
510 | "torch.cuda.is_available()"
511 | ]
512 | },
513 | {
514 | "cell_type": "code",
515 | "execution_count": null,
516 | "metadata": {
517 | "cellView": "form",
518 | "id": "BLk3J0h3MtON"
519 | },
520 | "outputs": [],
521 | "source": [
522 | "#@title ### 1.4 Define Midas functions\n",
523 | "\n",
524 | "\n",
525 | "from midas.dpt_depth import DPTDepthModel\n",
526 | "from midas.midas_net import MidasNet\n",
527 | "from midas.midas_net_custom import MidasNet_small\n",
528 | "from midas.transforms import Resize, NormalizeImage, PrepareForNet\n",
529 | "\n",
530 | "# Initialize MiDaS depth model.\n",
531 | "# It remains resident in VRAM and likely takes around 2GB VRAM.\n",
532 | "# You could instead initialize it for each frame (and free it after each frame) to save VRAM.. but initializing it is slow.\n",
533 | "default_models = {\n",
534 | " \"midas_v21_small\": f\"{model_path}/midas_v21_small-70d6b9c8.pt\",\n",
535 | " \"midas_v21\": f\"{model_path}/midas_v21-f6b98070.pt\",\n",
536 | " \"dpt_large\": f\"{model_path}/dpt_large-midas-2f21e586.pt\",\n",
537 | " \"dpt_hybrid\": f\"{model_path}/dpt_hybrid-midas-501f0c75.pt\",\n",
538 | " \"dpt_hybrid_nyu\": f\"{model_path}/dpt_hybrid_nyu-2ce69ec7.pt\",}\n",
539 | "\n",
540 | "\n",
541 | "def init_midas_depth_model(midas_model_type=\"dpt_large\", optimize=True):\n",
542 | " midas_model = None\n",
543 | " net_w = None\n",
544 | " net_h = None\n",
545 | " resize_mode = None\n",
546 | " normalization = None\n",
547 | "\n",
548 | " print(f\"Initializing MiDaS '{midas_model_type}' depth model...\")\n",
549 | " # load network\n",
550 | " midas_model_path = default_models[midas_model_type]\n",
551 | "\n",
552 | " if midas_model_type == \"dpt_large\": # DPT-Large\n",
553 | " midas_model = DPTDepthModel(\n",
554 | " path=midas_model_path,\n",
555 | " backbone=\"vitl16_384\",\n",
556 | " non_negative=True,\n",
557 | " )\n",
558 | " net_w, net_h = 384, 384\n",
559 | " resize_mode = \"minimal\"\n",
560 | " normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n",
561 | " elif midas_model_type == \"dpt_hybrid\": #DPT-Hybrid\n",
562 | " midas_model = DPTDepthModel(\n",
563 | " path=midas_model_path,\n",
564 | " backbone=\"vitb_rn50_384\",\n",
565 | " non_negative=True,\n",
566 | " )\n",
567 | " net_w, net_h = 384, 384\n",
568 | " resize_mode=\"minimal\"\n",
569 | " normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n",
570 | " elif midas_model_type == \"dpt_hybrid_nyu\": #DPT-Hybrid-NYU\n",
571 | " midas_model = DPTDepthModel(\n",
572 | " path=midas_model_path,\n",
573 | " backbone=\"vitb_rn50_384\",\n",
574 | " non_negative=True,\n",
575 | " )\n",
576 | " net_w, net_h = 384, 384\n",
577 | " resize_mode=\"minimal\"\n",
578 | " normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n",
579 | " elif midas_model_type == \"midas_v21\":\n",
580 | " midas_model = MidasNet(midas_model_path, non_negative=True)\n",
581 | " net_w, net_h = 384, 384\n",
582 | " resize_mode=\"upper_bound\"\n",
583 | " normalization = NormalizeImage(\n",
584 | " mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]\n",
585 | " )\n",
586 | " elif midas_model_type == \"midas_v21_small\":\n",
587 | " midas_model = MidasNet_small(midas_model_path, features=64, backbone=\"efficientnet_lite3\", exportable=True, non_negative=True, blocks={'expand': True})\n",
588 | " net_w, net_h = 256, 256\n",
589 | " resize_mode=\"upper_bound\"\n",
590 | " normalization = NormalizeImage(\n",
591 | " mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]\n",
592 | " )\n",
593 | " else:\n",
594 | " print(f\"midas_model_type '{midas_model_type}' not implemented\")\n",
595 | " assert False\n",
596 | "\n",
597 | " midas_transform = T.Compose(\n",
598 | " [\n",
599 | " Resize(\n",
600 | " net_w,\n",
601 | " net_h,\n",
602 | " resize_target=None,\n",
603 | " keep_aspect_ratio=True,\n",
604 | " ensure_multiple_of=32,\n",
605 | " resize_method=resize_mode,\n",
606 | " image_interpolation_method=cv2.INTER_CUBIC,\n",
607 | " ),\n",
608 | " normalization,\n",
609 | " PrepareForNet(),\n",
610 | " ]\n",
611 | " )\n",
612 | "\n",
613 | " midas_model.eval()\n",
614 | " \n",
615 | " if optimize==True:\n",
616 | " if DEVICE == torch.device(\"cuda\"):\n",
617 | " midas_model = midas_model.to(memory_format=torch.channels_last) \n",
618 | " midas_model = midas_model.half()\n",
619 | "\n",
620 | " midas_model.to(DEVICE)\n",
621 | "\n",
622 | " print(f\"MiDaS '{midas_model_type}' depth model initialized.\")\n",
623 | " return midas_model, midas_transform, net_w, net_h, resize_mode, normalization\n"
624 | ]
625 | },
626 | {
627 | "cell_type": "code",
628 | "execution_count": null,
629 | "metadata": {
630 | "cellView": "form",
631 | "id": "FpZczxnOnPIU"
632 | },
633 | "outputs": [],
634 | "source": [
635 | "#@title 1.5 Define necessary functions\n",
636 | "\n",
637 | "# https://gist.github.com/adefossez/0646dbe9ed4005480a2407c62aac8869\n",
638 | "\n",
639 | "import pytorch3d.transforms as p3dT\n",
640 | "import disco_xform_utils as dxf\n",
641 | "\n",
642 | "def interp(t):\n",
643 | " return 3 * t**2 - 2 * t ** 3\n",
644 | "\n",
645 | "def perlin(width, height, scale=10, device=None):\n",
646 | " gx, gy = torch.randn(2, width + 1, height + 1, 1, 1, device=device)\n",
647 | " xs = torch.linspace(0, 1, scale + 1)[:-1, None].to(device)\n",
648 | " ys = torch.linspace(0, 1, scale + 1)[None, :-1].to(device)\n",
649 | " wx = 1 - interp(xs)\n",
650 | " wy = 1 - interp(ys)\n",
651 | " dots = 0\n",
652 | " dots += wx * wy * (gx[:-1, :-1] * xs + gy[:-1, :-1] * ys)\n",
653 | " dots += (1 - wx) * wy * (-gx[1:, :-1] * (1 - xs) + gy[1:, :-1] * ys)\n",
654 | " dots += wx * (1 - wy) * (gx[:-1, 1:] * xs - gy[:-1, 1:] * (1 - ys))\n",
655 | " dots += (1 - wx) * (1 - wy) * (-gx[1:, 1:] * (1 - xs) - gy[1:, 1:] * (1 - ys))\n",
656 | " return dots.permute(0, 2, 1, 3).contiguous().view(width * scale, height * scale)\n",
657 | "\n",
658 | "def perlin_ms(octaves, width, height, grayscale, device=device):\n",
659 | " out_array = [0.5] if grayscale else [0.5, 0.5, 0.5]\n",
660 | " # out_array = [0.0] if grayscale else [0.0, 0.0, 0.0]\n",
661 | " for i in range(1 if grayscale else 3):\n",
662 | " scale = 2 ** len(octaves)\n",
663 | " oct_width = width\n",
664 | " oct_height = height\n",
665 | " for oct in octaves:\n",
666 | " p = perlin(oct_width, oct_height, scale, device)\n",
667 | " out_array[i] += p * oct\n",
668 | " scale //= 2\n",
669 | " oct_width *= 2\n",
670 | " oct_height *= 2\n",
671 | " return torch.cat(out_array)\n",
672 | "\n",
673 | "def create_perlin_noise(octaves=[1, 1, 1, 1], width=2, height=2, grayscale=True):\n",
674 | " out = perlin_ms(octaves, width, height, grayscale)\n",
675 | " if grayscale:\n",
676 | " out = TF.resize(size=(side_y, side_x), img=out.unsqueeze(0))\n",
677 | " out = TF.to_pil_image(out.clamp(0, 1)).convert('RGB')\n",
678 | " else:\n",
679 | " out = out.reshape(-1, 3, out.shape[0]//3, out.shape[1])\n",
680 | " out = TF.resize(size=(side_y, side_x), img=out)\n",
681 | " out = TF.to_pil_image(out.clamp(0, 1).squeeze())\n",
682 | "\n",
683 | " out = ImageOps.autocontrast(out)\n",
684 | " return out\n",
685 | "\n",
686 | "def regen_perlin():\n",
687 | " if perlin_mode == 'color':\n",
688 | " init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)\n",
689 | " init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False)\n",
690 | " elif perlin_mode == 'gray':\n",
691 | " init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True)\n",
692 | " init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)\n",
693 | " else:\n",
694 | " init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)\n",
695 | " init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)\n",
696 | "\n",
697 | " init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1)\n",
698 | " del init2\n",
699 | " return init.expand(batch_size, -1, -1, -1)\n",
700 | "\n",
701 | "def fetch(url_or_path):\n",
702 | " if str(url_or_path).startswith('http://') or str(url_or_path).startswith('https://'):\n",
703 | " r = requests.get(url_or_path)\n",
704 | " r.raise_for_status()\n",
705 | " fd = io.BytesIO()\n",
706 | " fd.write(r.content)\n",
707 | " fd.seek(0)\n",
708 | " return fd\n",
709 | " return open(url_or_path, 'rb')\n",
710 | "\n",
711 | "def read_image_workaround(path):\n",
712 | " \"\"\"OpenCV reads images as BGR, Pillow saves them as RGB. Work around\n",
713 | " this incompatibility to avoid colour inversions.\"\"\"\n",
714 | " im_tmp = cv2.imread(path)\n",
715 | " return cv2.cvtColor(im_tmp, cv2.COLOR_BGR2RGB)\n",
716 | "\n",
717 | "def parse_prompt(prompt):\n",
718 | " if prompt.startswith('http://') or prompt.startswith('https://'):\n",
719 | " vals = prompt.rsplit(':', 2)\n",
720 | " vals = [vals[0] + ':' + vals[1], *vals[2:]]\n",
721 | " else:\n",
722 | " vals = prompt.rsplit(':', 1)\n",
723 | " vals = vals + ['', '1'][len(vals):]\n",
724 | " return vals[0], float(vals[1])\n",
725 | "\n",
726 | "def sinc(x):\n",
727 | " return torch.where(x != 0, torch.sin(math.pi * x) / (math.pi * x), x.new_ones([]))\n",
728 | "\n",
729 | "def lanczos(x, a):\n",
730 | " cond = torch.logical_and(-a < x, x < a)\n",
731 | " out = torch.where(cond, sinc(x) * sinc(x/a), x.new_zeros([]))\n",
732 | " return out / out.sum()\n",
733 | "\n",
734 | "def ramp(ratio, width):\n",
735 | " n = math.ceil(width / ratio + 1)\n",
736 | " out = torch.empty([n])\n",
737 | " cur = 0\n",
738 | " for i in range(out.shape[0]):\n",
739 | " out[i] = cur\n",
740 | " cur += ratio\n",
741 | " return torch.cat([-out[1:].flip([0]), out])[1:-1]\n",
742 | "\n",
743 | "def resample(input, size, align_corners=True):\n",
744 | " n, c, h, w = input.shape\n",
745 | " dh, dw = size\n",
746 | "\n",
747 | " input = input.reshape([n * c, 1, h, w])\n",
748 | "\n",
749 | " if dh < h:\n",
750 | " kernel_h = lanczos(ramp(dh / h, 2), 2).to(input.device, input.dtype)\n",
751 | " pad_h = (kernel_h.shape[0] - 1) // 2\n",
752 | " input = F.pad(input, (0, 0, pad_h, pad_h), 'reflect')\n",
753 | " input = F.conv2d(input, kernel_h[None, None, :, None])\n",
754 | "\n",
755 | " if dw < w:\n",
756 | " kernel_w = lanczos(ramp(dw / w, 2), 2).to(input.device, input.dtype)\n",
757 | " pad_w = (kernel_w.shape[0] - 1) // 2\n",
758 | " input = F.pad(input, (pad_w, pad_w, 0, 0), 'reflect')\n",
759 | " input = F.conv2d(input, kernel_w[None, None, None, :])\n",
760 | "\n",
761 | " input = input.reshape([n, c, h, w])\n",
762 | " return F.interpolate(input, size, mode='bicubic', align_corners=align_corners)\n",
763 | "\n",
764 | "class MakeCutouts(nn.Module):\n",
765 | " def __init__(self, cut_size, cutn, skip_augs=False):\n",
766 | " super().__init__()\n",
767 | " self.cut_size = cut_size\n",
768 | " self.cutn = cutn\n",
769 | " self.skip_augs = skip_augs\n",
770 | " self.augs = T.Compose([\n",
771 | " T.RandomHorizontalFlip(p=0.5),\n",
772 | " T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
773 | " T.RandomAffine(degrees=15, translate=(0.1, 0.1)),\n",
774 | " T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
775 | " T.RandomPerspective(distortion_scale=0.4, p=0.7),\n",
776 | " T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
777 | " T.RandomGrayscale(p=0.15),\n",
778 | " T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
779 | " # T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),\n",
780 | " ])\n",
781 | "\n",
782 | " def forward(self, input):\n",
783 | " input = T.Pad(input.shape[2]//4, fill=0)(input)\n",
784 | " sideY, sideX = input.shape[2:4]\n",
785 | " max_size = min(sideX, sideY)\n",
786 | "\n",
787 | " cutouts = []\n",
788 | " for ch in range(self.cutn):\n",
789 | " if ch > self.cutn - self.cutn//4:\n",
790 | " cutout = input.clone()\n",
791 | " else:\n",
792 | " size = int(max_size * torch.zeros(1,).normal_(mean=.8, std=.3).clip(float(self.cut_size/max_size), 1.))\n",
793 | " offsetx = torch.randint(0, abs(sideX - size + 1), ())\n",
794 | " offsety = torch.randint(0, abs(sideY - size + 1), ())\n",
795 | " cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]\n",
796 | "\n",
797 | " if not self.skip_augs:\n",
798 | " cutout = self.augs(cutout)\n",
799 | " cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))\n",
800 | " del cutout\n",
801 | "\n",
802 | " cutouts = torch.cat(cutouts, dim=0)\n",
803 | " return cutouts\n",
804 | "\n",
805 | "cutout_debug = False\n",
806 | "padargs = {}\n",
807 | "\n",
808 | "class MakeCutoutsDango(nn.Module):\n",
809 | " def __init__(self, cut_size,\n",
810 | " Overview=4, \n",
811 | " InnerCrop = 0, IC_Size_Pow=0.5, IC_Grey_P = 0.2\n",
812 | " ):\n",
813 | " super().__init__()\n",
814 | " self.cut_size = cut_size\n",
815 | " self.Overview = Overview\n",
816 | " self.InnerCrop = InnerCrop\n",
817 | " self.IC_Size_Pow = IC_Size_Pow\n",
818 | " self.IC_Grey_P = IC_Grey_P\n",
819 | " if args.animation_mode == 'None':\n",
820 | " self.augs = T.Compose([\n",
821 | " T.RandomHorizontalFlip(p=0.5),\n",
822 | " T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
823 | " T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR),\n",
824 | " T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
825 | " T.RandomGrayscale(p=0.1),\n",
826 | " T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
827 | " T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),\n",
828 | " ])\n",
829 | " elif args.animation_mode == 'Video Input':\n",
830 | " self.augs = T.Compose([\n",
831 | " T.RandomHorizontalFlip(p=0.5),\n",
832 | " T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
833 | " T.RandomAffine(degrees=15, translate=(0.1, 0.1)),\n",
834 | " T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
835 | " T.RandomPerspective(distortion_scale=0.4, p=0.7),\n",
836 | " T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
837 | " T.RandomGrayscale(p=0.15),\n",
838 | " T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
839 | " # T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1),\n",
840 | " ])\n",
841 | " elif args.animation_mode == '2D' or args.animation_mode == '3D':\n",
842 | " self.augs = T.Compose([\n",
843 | " T.RandomHorizontalFlip(p=0.4),\n",
844 | " T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
845 | " T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR),\n",
846 | " T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
847 | " T.RandomGrayscale(p=0.1),\n",
848 | " T.Lambda(lambda x: x + torch.randn_like(x) * 0.01),\n",
849 | " T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.3),\n",
850 | " ])\n",
851 | " \n",
852 | "\n",
853 | " def forward(self, input):\n",
854 | " cutouts = []\n",
855 | " gray = T.Grayscale(3)\n",
856 | " sideY, sideX = input.shape[2:4]\n",
857 | " max_size = min(sideX, sideY)\n",
858 | " min_size = min(sideX, sideY, self.cut_size)\n",
859 | " l_size = max(sideX, sideY)\n",
860 | " output_shape = [1,3,self.cut_size,self.cut_size] \n",
861 | " output_shape_2 = [1,3,self.cut_size+2,self.cut_size+2]\n",
862 | " pad_input = F.pad(input,((sideY-max_size)//2,(sideY-max_size)//2,(sideX-max_size)//2,(sideX-max_size)//2), **padargs)\n",
863 | " cutout = resize(pad_input, out_shape=output_shape)\n",
864 | "\n",
865 | " if self.Overview>0:\n",
866 | " if self.Overview<=4:\n",
867 | " if self.Overview>=1:\n",
868 | " cutouts.append(cutout)\n",
869 | " if self.Overview>=2:\n",
870 | " cutouts.append(gray(cutout))\n",
871 | " if self.Overview>=3:\n",
872 | " cutouts.append(TF.hflip(cutout))\n",
873 | " if self.Overview==4:\n",
874 | " cutouts.append(gray(TF.hflip(cutout)))\n",
875 | " else:\n",
876 | " cutout = resize(pad_input, out_shape=output_shape)\n",
877 | " for _ in range(self.Overview):\n",
878 | " cutouts.append(cutout)\n",
879 | "\n",
880 | " if cutout_debug:\n",
881 | " if is_colab:\n",
882 | " TF.to_pil_image(cutouts[0].clamp(0, 1).squeeze(0)).save(\"/content/cutout_overview0.jpg\",quality=99)\n",
883 | " else:\n",
884 | " TF.to_pil_image(cutouts[0].clamp(0, 1).squeeze(0)).save(\"cutout_overview0.jpg\",quality=99)\n",
885 | "\n",
886 | " \n",
887 | " if self.InnerCrop >0:\n",
888 | " for i in range(self.InnerCrop):\n",
889 | " size = int(torch.rand([])**self.IC_Size_Pow * (max_size - min_size) + min_size)\n",
890 | " offsetx = torch.randint(0, sideX - size + 1, ())\n",
891 | " offsety = torch.randint(0, sideY - size + 1, ())\n",
892 | " cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]\n",
893 | " if i <= int(self.IC_Grey_P * self.InnerCrop):\n",
894 | " cutout = gray(cutout)\n",
895 | " cutout = resize(cutout, out_shape=output_shape)\n",
896 | " cutouts.append(cutout)\n",
897 | " if cutout_debug:\n",
898 | " if is_colab:\n",
899 | " TF.to_pil_image(cutouts[-1].clamp(0, 1).squeeze(0)).save(\"/content/cutout_InnerCrop.jpg\",quality=99)\n",
900 | " else:\n",
901 | " TF.to_pil_image(cutouts[-1].clamp(0, 1).squeeze(0)).save(\"cutout_InnerCrop.jpg\",quality=99)\n",
902 | " cutouts = torch.cat(cutouts)\n",
903 | " if skip_augs is not True: cutouts=self.augs(cutouts)\n",
904 | " return cutouts\n",
905 | "\n",
906 | "def spherical_dist_loss(x, y):\n",
907 | " x = F.normalize(x, dim=-1)\n",
908 | " y = F.normalize(y, dim=-1)\n",
909 | " return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2) \n",
910 | "\n",
911 | "def tv_loss(input):\n",
912 | " \"\"\"L2 total variation loss, as in Mahendran et al.\"\"\"\n",
913 | " input = F.pad(input, (0, 1, 0, 1), 'replicate')\n",
914 | " x_diff = input[..., :-1, 1:] - input[..., :-1, :-1]\n",
915 | " y_diff = input[..., 1:, :-1] - input[..., :-1, :-1]\n",
916 | " return (x_diff**2 + y_diff**2).mean([1, 2, 3])\n",
917 | "\n",
918 | "\n",
919 | "def range_loss(input):\n",
920 | " return (input - input.clamp(-1, 1)).pow(2).mean([1, 2, 3])\n",
921 | "\n",
922 | "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",
923 | "\n",
924 | "def do_run():\n",
925 | " seed = args.seed\n",
926 | " print(range(args.start_frame, args.max_frames))\n",
927 | "\n",
928 | " if (args.animation_mode == \"3D\") and (args.midas_weight > 0.0):\n",
929 | " midas_model, midas_transform, midas_net_w, midas_net_h, midas_resize_mode, midas_normalization = init_midas_depth_model(args.midas_depth_model)\n",
930 | " for frame_num in range(args.start_frame, args.max_frames):\n",
931 | " if stop_on_next_loop:\n",
932 | " break\n",
933 | " \n",
934 | " display.clear_output(wait=True)\n",
935 | "\n",
936 | " # Print Frame progress if animation mode is on\n",
937 | " if args.animation_mode != \"None\":\n",
938 | " batchBar = tqdm(range(args.max_frames), desc =\"Frames\")\n",
939 | " batchBar.n = frame_num\n",
940 | " batchBar.refresh()\n",
941 | "\n",
942 | " \n",
943 | " # Inits if not video frames\n",
944 | " if args.animation_mode != \"Video Input\":\n",
945 | " if args.init_image == '':\n",
946 | " init_image = None\n",
947 | " else:\n",
948 | " init_image = args.init_image\n",
949 | " init_scale = args.init_scale\n",
950 | " skip_steps = args.skip_steps\n",
951 | "\n",
952 | " if args.animation_mode == \"2D\":\n",
953 | " if args.key_frames:\n",
954 | " angle = args.angle_series[frame_num]\n",
955 | " zoom = args.zoom_series[frame_num]\n",
956 | " translation_x = args.translation_x_series[frame_num]\n",
957 | " translation_y = args.translation_y_series[frame_num]\n",
958 | " print(\n",
959 | " f'angle: {angle}',\n",
960 | " f'zoom: {zoom}',\n",
961 | " f'translation_x: {translation_x}',\n",
962 | " f'translation_y: {translation_y}',\n",
963 | " )\n",
964 | " \n",
965 | " if frame_num > 0:\n",
966 | " seed = seed + 1 \n",
967 | " if resume_run and frame_num == start_frame:\n",
968 | " img_0 = cv2.imread(batchFolder+f\"/{batch_name}({batchNum})_{start_frame-1:04}.png\")\n",
969 | " else:\n",
970 | " img_0 = cv2.imread('prevFrame.png')\n",
971 | " center = (1*img_0.shape[1]//2, 1*img_0.shape[0]//2)\n",
972 | " trans_mat = np.float32(\n",
973 | " [[1, 0, translation_x],\n",
974 | " [0, 1, translation_y]]\n",
975 | " )\n",
976 | " rot_mat = cv2.getRotationMatrix2D( center, angle, zoom )\n",
977 | " trans_mat = np.vstack([trans_mat, [0,0,1]])\n",
978 | " rot_mat = np.vstack([rot_mat, [0,0,1]])\n",
979 | " transformation_matrix = np.matmul(rot_mat, trans_mat)\n",
980 | " img_0 = cv2.warpPerspective(\n",
981 | " img_0,\n",
982 | " transformation_matrix,\n",
983 | " (img_0.shape[1], img_0.shape[0]),\n",
984 | " borderMode=cv2.BORDER_WRAP\n",
985 | " )\n",
986 | "\n",
987 | " cv2.imwrite('prevFrameScaled.png', img_0)\n",
988 | " init_image = 'prevFrameScaled.png'\n",
989 | " init_scale = args.frames_scale\n",
990 | " skip_steps = args.calc_frames_skip_steps\n",
991 | "\n",
992 | " if args.animation_mode == \"3D\":\n",
993 | " if args.key_frames:\n",
994 | " angle = args.angle_series[frame_num]\n",
995 | " #zoom = args.zoom_series[frame_num]\n",
996 | " translation_x = args.translation_x_series[frame_num]\n",
997 | " translation_y = args.translation_y_series[frame_num]\n",
998 | " translation_z = args.translation_z_series[frame_num]\n",
999 | " rotation_3d_x = args.rotation_3d_x_series[frame_num]\n",
1000 | " rotation_3d_y = args.rotation_3d_y_series[frame_num]\n",
1001 | " rotation_3d_z = args.rotation_3d_z_series[frame_num]\n",
1002 | " print(\n",
1003 | " f'angle: {angle}',\n",
1004 | " #f'zoom: {zoom}',\n",
1005 | " f'translation_x: {translation_x}',\n",
1006 | " f'translation_y: {translation_y}',\n",
1007 | " f'translation_z: {translation_z}',\n",
1008 | " f'rotation_3d_x: {rotation_3d_x}',\n",
1009 | " f'rotation_3d_y: {rotation_3d_y}',\n",
1010 | " f'rotation_3d_z: {rotation_3d_z}',\n",
1011 | " )\n",
1012 | "\n",
1013 | " if frame_num > 0:\n",
1014 | " seed = seed + 1 \n",
1015 | " ### Turbo mode prep\n",
1016 | " turbo_prevScaled_path = batchFolder+f\"/turbo/prevFrameScaled.png\" if is_colab else 'prevFrameScaled.png'\n",
1017 | " turbo_oldScaled_path = batchFolder+f\"/turbo/oldFrameScaled.png\" if is_colab else 'oldFrameScaled.png'\n",
1018 | " turbo_preroll = 10 # frames\n",
1019 | " non_turbo_prevFrm = '/content/prevFrame.png' if is_colab else 'prevFrame.png' \n",
1020 | " if resume_run and frame_num == start_frame:\n",
1021 | " img_filepath = batchFolder+f\"/{batch_name}({batchNum})_{start_frame-1:04}.png\"\n",
1022 | " if turbo_mode == True and frame_num > turbo_preroll:\n",
1023 | " img_filepath = turbo_prevScaled_path\n",
1024 | " else:\n",
1025 | " img_filepath = '/content/prevFrame.png' if is_colab else 'prevFrame.png'\n",
1026 | " \n",
1027 | " \n",
1028 | " #warp prior frame\n",
1029 | " trans_scale = 1.0/200.0\n",
1030 | " translate_xyz = [-translation_x*trans_scale, translation_y*trans_scale, -translation_z*trans_scale]\n",
1031 | " rotate_xyz = [rotation_3d_x, rotation_3d_y, rotation_3d_z]\n",
1032 | " print('translation:',translate_xyz)\n",
1033 | " print('rotation:',rotate_xyz)\n",
1034 | " rot_mat = p3dT.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), \"XYZ\").unsqueeze(0)\n",
1035 | " print(\"rot_mat: \" + str(rot_mat))\n",
1036 | " next_step_pil = dxf.transform_image_3d(img_filepath, midas_model, midas_transform, DEVICE,\n",
1037 | " rot_mat, translate_xyz, args.near_plane, args.far_plane,\n",
1038 | " args.fov, padding_mode=args.padding_mode,\n",
1039 | " sampling_mode=args.sampling_mode, midas_weight=args.midas_weight)\n",
1040 | " next_step_pil.save('prevFrameScaled.png')\n",
1041 | " if turbo_mode == True:\n",
1042 | " next_step_pil.save(turbo_prevScaled_path)#stash for turbo\n",
1043 | " turbo_blend = False # default for non-turbo frame saving\n",
1044 | " if turbo_mode == True and frame_num == turbo_preroll: #start tracking oldframe\n",
1045 | " next_step_pil.save(turbo_oldScaled_path)#stash for later blending\n",
1046 | " if turbo_mode == True and frame_num > turbo_preroll:\n",
1047 | " \n",
1048 | " #set up 2 warped image sequences, old & new, to blend toward new diff image\n",
1049 | " old_frame = dxf.transform_image_3d(turbo_oldScaled_path, midas_model, midas_transform, DEVICE,\n",
1050 | " rot_mat, translate_xyz, args.near_plane, args.far_plane,\n",
1051 | " args.fov, padding_mode=args.padding_mode,\n",
1052 | " sampling_mode=args.sampling_mode, midas_weight=args.midas_weight)\n",
1053 | " old_frame.save(turbo_oldScaled_path)\n",
1054 | " if frame_num % int(turbo_steps) != 0: \n",
1055 | " print('turbo skip this frame: skipping clip diffusion steps')\n",
1056 | " filename = f'{args.batch_name}({args.batchNum})_{frame_num:04}.png'\n",
1057 | " blend_factor = ((frame_num % int(turbo_steps))+1)/int(turbo_steps)\n",
1058 | " print('turbo skip this frame: skipping clip diffusion steps and saving blended frame')\n",
1059 | " newWarpedImg = cv2.imread(turbo_prevScaled_path)#this is already updated..\n",
1060 | " oldWarpedImg = cv2.imread(turbo_oldScaled_path)\n",
1061 | " blendedImage = cv2.addWeighted(newWarpedImg, blend_factor, oldWarpedImg,1-blend_factor, 0.0)\n",
1062 | " cv2.imwrite(f'{batchFolder}/{filename}',blendedImage)\n",
1063 | " \n",
1064 | " next_step_pil.save(f'{non_turbo_prevFrm}') # save it also as prev_frame to feed next iteration\n",
1065 | " #turbo_blend = False\n",
1066 | " continue # done. exit frame loop\n",
1067 | " else:\n",
1068 | " #if not a skip frame, will run diff and need to blend.\n",
1069 | " oldWarpedImg = cv2.imread(turbo_prevScaled_path)#swap old img\n",
1070 | " cv2.imwrite(turbo_oldScaled_path ,oldWarpedImg)#swap in for blending later \n",
1071 | " #turbo_blend = True # flag to blend frames after diff generated...\n",
1072 | " print('clip/diff this frame - generate clip diff image')\n",
1073 | " init_image = 'prevFrameScaled.png'\n",
1074 | " init_scale = args.frames_scale\n",
1075 | " skip_steps = args.calc_frames_skip_steps\n",
1076 | "\n",
1077 | " if args.animation_mode == \"Video Input\":\n",
1078 | " seed = seed + 1 \n",
1079 | " init_image = f'{videoFramesFolder}/{frame_num+1:04}.jpg'\n",
1080 | " init_scale = args.frames_scale\n",
1081 | " skip_steps = args.calc_frames_skip_steps\n",
1082 | "\n",
1083 | " loss_values = []\n",
1084 | " \n",
1085 | " if seed is not None:\n",
1086 | " np.random.seed(seed)\n",
1087 | " random.seed(seed)\n",
1088 | " torch.manual_seed(seed)\n",
1089 | " torch.cuda.manual_seed_all(seed)\n",
1090 | " torch.backends.cudnn.deterministic = True\n",
1091 | " \n",
1092 | " target_embeds, weights = [], []\n",
1093 | " \n",
1094 | " if args.prompts_series is not None and frame_num >= len(args.prompts_series):\n",
1095 | " frame_prompt = args.prompts_series[-1]\n",
1096 | " elif args.prompts_series is not None:\n",
1097 | " frame_prompt = args.prompts_series[frame_num]\n",
1098 | " else:\n",
1099 | " frame_prompt = []\n",
1100 | " \n",
1101 | " print(args.image_prompts_series)\n",
1102 | " if args.image_prompts_series is not None and frame_num >= len(args.image_prompts_series):\n",
1103 | " image_prompt = args.image_prompts_series[-1]\n",
1104 | " elif args.image_prompts_series is not None:\n",
1105 | " image_prompt = args.image_prompts_series[frame_num]\n",
1106 | " else:\n",
1107 | " image_prompt = []\n",
1108 | "\n",
1109 | " print(f'Frame Prompt: {frame_prompt}')\n",
1110 | "\n",
1111 | " model_stats = []\n",
1112 | " for clip_model in clip_models:\n",
1113 | " cutn = 16\n",
1114 | " model_stat = {\"clip_model\":None,\"target_embeds\":[],\"make_cutouts\":None,\"weights\":[]}\n",
1115 | " model_stat[\"clip_model\"] = clip_model\n",
1116 | " \n",
1117 | " \n",
1118 | " for prompt in frame_prompt:\n",
1119 | " txt, weight = parse_prompt(prompt)\n",
1120 | " txt = clip_model.encode_text(clip.tokenize(prompt).to(device)).float()\n",
1121 | " \n",
1122 | " if args.fuzzy_prompt:\n",
1123 | " for i in range(25):\n",
1124 | " model_stat[\"target_embeds\"].append((txt + torch.randn(txt.shape).cuda() * args.rand_mag).clamp(0,1))\n",
1125 | " model_stat[\"weights\"].append(weight)\n",
1126 | " else:\n",
1127 | " model_stat[\"target_embeds\"].append(txt)\n",
1128 | " model_stat[\"weights\"].append(weight)\n",
1129 | " \n",
1130 | " if image_prompt:\n",
1131 | " model_stat[\"make_cutouts\"] = MakeCutouts(clip_model.visual.input_resolution, cutn, skip_augs=skip_augs) \n",
1132 | " for prompt in image_prompt:\n",
1133 | " path, weight = parse_prompt(prompt)\n",
1134 | " img = Image.open(fetch(path)).convert('RGB')\n",
1135 | " img = TF.resize(img, min(side_x, side_y, *img.size), T.InterpolationMode.LANCZOS)\n",
1136 | " batch = model_stat[\"make_cutouts\"](TF.to_tensor(img).to(device).unsqueeze(0).mul(2).sub(1))\n",
1137 | " embed = clip_model.encode_image(normalize(batch)).float()\n",
1138 | " if fuzzy_prompt:\n",
1139 | " for i in range(25):\n",
1140 | " model_stat[\"target_embeds\"].append((embed + torch.randn(embed.shape).cuda() * rand_mag).clamp(0,1))\n",
1141 | " weights.extend([weight / cutn] * cutn)\n",
1142 | " else:\n",
1143 | " model_stat[\"target_embeds\"].append(embed)\n",
1144 | " model_stat[\"weights\"].extend([weight / cutn] * cutn)\n",
1145 | " \n",
1146 | " model_stat[\"target_embeds\"] = torch.cat(model_stat[\"target_embeds\"])\n",
1147 | " model_stat[\"weights\"] = torch.tensor(model_stat[\"weights\"], device=device)\n",
1148 | " if model_stat[\"weights\"].sum().abs() < 1e-3:\n",
1149 | " raise RuntimeError('The weights must not sum to 0.')\n",
1150 | " model_stat[\"weights\"] /= model_stat[\"weights\"].sum().abs()\n",
1151 | " model_stats.append(model_stat)\n",
1152 | " \n",
1153 | " init = None\n",
1154 | " if init_image is not None:\n",
1155 | " init = Image.open(fetch(init_image)).convert('RGB')\n",
1156 | " init = init.resize((args.side_x, args.side_y), Image.LANCZOS)\n",
1157 | " init = TF.to_tensor(init).to(device).unsqueeze(0).mul(2).sub(1)\n",
1158 | " \n",
1159 | " if args.perlin_init:\n",
1160 | " if args.perlin_mode == 'color':\n",
1161 | " init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)\n",
1162 | " init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False)\n",
1163 | " elif args.perlin_mode == 'gray':\n",
1164 | " init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True)\n",
1165 | " init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)\n",
1166 | " else:\n",
1167 | " init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False)\n",
1168 | " init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True)\n",
1169 | " # init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device)\n",
1170 | " init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1)\n",
1171 | " del init2\n",
1172 | " \n",
1173 | " cur_t = None\n",
1174 | " \n",
1175 | " def cond_fn(x, t, y=None):\n",
1176 | " with torch.enable_grad():\n",
1177 | " x_is_NaN = False\n",
1178 | " x = x.detach().requires_grad_()\n",
1179 | " n = x.shape[0]\n",
1180 | " if use_secondary_model is True:\n",
1181 | " alpha = torch.tensor(diffusion.sqrt_alphas_cumprod[cur_t], device=device, dtype=torch.float32)\n",
1182 | " sigma = torch.tensor(diffusion.sqrt_one_minus_alphas_cumprod[cur_t], device=device, dtype=torch.float32)\n",
1183 | " cosine_t = alpha_sigma_to_t(alpha, sigma)\n",
1184 | " out = secondary_model(x, cosine_t[None].repeat([n])).pred\n",
1185 | " fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t]\n",
1186 | " x_in = out * fac + x * (1 - fac)\n",
1187 | " x_in_grad = torch.zeros_like(x_in)\n",
1188 | " else:\n",
1189 | " my_t = torch.ones([n], device=device, dtype=torch.long) * cur_t\n",
1190 | " out = diffusion.p_mean_variance(model, x, my_t, clip_denoised=False, model_kwargs={'y': y})\n",
1191 | " fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t]\n",
1192 | " x_in = out['pred_xstart'] * fac + x * (1 - fac)\n",
1193 | " x_in_grad = torch.zeros_like(x_in)\n",
1194 | " for model_stat in model_stats:\n",
1195 | " for i in range(args.cutn_batches):\n",
1196 | " t_int = int(t.item())+1 #errors on last step without +1, need to find source\n",
1197 | " #when using SLIP Base model the dimensions need to be hard coded to avoid AttributeError: 'VisionTransformer' object has no attribute 'input_resolution'\n",
1198 | " try:\n",
1199 | " input_resolution=model_stat[\"clip_model\"].visual.input_resolution\n",
1200 | " except:\n",
1201 | " input_resolution=224\n",
1202 | "\n",
1203 | " cuts = MakeCutoutsDango(input_resolution,\n",
1204 | " Overview= args.cut_overview[1000-t_int], \n",
1205 | " 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",
1206 | " )\n",
1207 | " clip_in = normalize(cuts(x_in.add(1).div(2)))\n",
1208 | " image_embeds = model_stat[\"clip_model\"].encode_image(clip_in).float()\n",
1209 | " dists = spherical_dist_loss(image_embeds.unsqueeze(1), model_stat[\"target_embeds\"].unsqueeze(0))\n",
1210 | " dists = dists.view([args.cut_overview[1000-t_int]+args.cut_innercut[1000-t_int], n, -1])\n",
1211 | " losses = dists.mul(model_stat[\"weights\"]).sum(2).mean(0)\n",
1212 | " loss_values.append(losses.sum().item()) # log loss, probably shouldn't do per cutn_batch\n",
1213 | " x_in_grad += torch.autograd.grad(losses.sum() * clip_guidance_scale, x_in)[0] / cutn_batches\n",
1214 | " tv_losses = tv_loss(x_in)\n",
1215 | " if use_secondary_model is True:\n",
1216 | " range_losses = range_loss(out)\n",
1217 | " else:\n",
1218 | " range_losses = range_loss(out['pred_xstart'])\n",
1219 | " sat_losses = torch.abs(x_in - x_in.clamp(min=-1,max=1)).mean()\n",
1220 | " loss = tv_losses.sum() * tv_scale + range_losses.sum() * range_scale + sat_losses.sum() * sat_scale\n",
1221 | " if init is not None and args.init_scale:\n",
1222 | " init_losses = lpips_model(x_in, init)\n",
1223 | " loss = loss + init_losses.sum() * args.init_scale\n",
1224 | " x_in_grad += torch.autograd.grad(loss, x_in)[0]\n",
1225 | " if torch.isnan(x_in_grad).any()==False:\n",
1226 | " grad = -torch.autograd.grad(x_in, x, x_in_grad)[0]\n",
1227 | " else:\n",
1228 | " # print(\"NaN'd\")\n",
1229 | " x_is_NaN = True\n",
1230 | " grad = torch.zeros_like(x)\n",
1231 | " if args.clamp_grad and x_is_NaN == False:\n",
1232 | " magnitude = grad.square().mean().sqrt()\n",
1233 | " return grad * magnitude.clamp(max=args.clamp_max) / magnitude #min=-0.02, min=-clamp_max, \n",
1234 | " return grad\n",
1235 | " \n",
1236 | " if model_config['timestep_respacing'].startswith('ddim'):\n",
1237 | " sample_fn = diffusion.ddim_sample_loop_progressive\n",
1238 | " else:\n",
1239 | " sample_fn = diffusion.p_sample_loop_progressive\n",
1240 | " \n",
1241 | "\n",
1242 | " image_display = Output()\n",
1243 | " for i in range(args.n_batches):\n",
1244 | " if args.animation_mode == 'None':\n",
1245 | " display.clear_output(wait=True)\n",
1246 | " batchBar = tqdm(range(args.n_batches), desc =\"Batches\")\n",
1247 | " batchBar.n = i\n",
1248 | " batchBar.refresh()\n",
1249 | " print('')\n",
1250 | " display.display(image_display)\n",
1251 | " gc.collect()\n",
1252 | " torch.cuda.empty_cache()\n",
1253 | " cur_t = diffusion.num_timesteps - skip_steps - 1\n",
1254 | " total_steps = cur_t\n",
1255 | "\n",
1256 | " if perlin_init:\n",
1257 | " init = regen_perlin()\n",
1258 | "\n",
1259 | " if model_config['timestep_respacing'].startswith('ddim'):\n",
1260 | " samples = sample_fn(\n",
1261 | " model,\n",
1262 | " (batch_size, 3, args.side_y, args.side_x),\n",
1263 | " clip_denoised=clip_denoised,\n",
1264 | " model_kwargs={},\n",
1265 | " cond_fn=cond_fn,\n",
1266 | " progress=True,\n",
1267 | " skip_timesteps=skip_steps,\n",
1268 | " init_image=init,\n",
1269 | " randomize_class=randomize_class,\n",
1270 | " eta=eta,\n",
1271 | " )\n",
1272 | " else:\n",
1273 | " samples = sample_fn(\n",
1274 | " model,\n",
1275 | " (batch_size, 3, args.side_y, args.side_x),\n",
1276 | " clip_denoised=clip_denoised,\n",
1277 | " model_kwargs={},\n",
1278 | " cond_fn=cond_fn,\n",
1279 | " progress=True,\n",
1280 | " skip_timesteps=skip_steps,\n",
1281 | " init_image=init,\n",
1282 | " randomize_class=randomize_class,\n",
1283 | " )\n",
1284 | " \n",
1285 | " \n",
1286 | " # with run_display:\n",
1287 | " # display.clear_output(wait=True)\n",
1288 | " imgToSharpen = None\n",
1289 | " for j, sample in enumerate(samples): \n",
1290 | " cur_t -= 1\n",
1291 | " intermediateStep = False\n",
1292 | " if args.steps_per_checkpoint is not None:\n",
1293 | " if j % steps_per_checkpoint == 0 and j > 0:\n",
1294 | " intermediateStep = True\n",
1295 | " elif j in args.intermediate_saves:\n",
1296 | " intermediateStep = True\n",
1297 | " with image_display:\n",
1298 | " if j % args.display_rate == 0 or cur_t == -1 or intermediateStep == True:\n",
1299 | " for k, image in enumerate(sample['pred_xstart']):\n",
1300 | " # tqdm.write(f'Batch {i}, step {j}, output {k}:')\n",
1301 | " current_time = datetime.now().strftime('%y%m%d-%H%M%S_%f')\n",
1302 | " percent = math.ceil(j/total_steps*100)\n",
1303 | " if args.n_batches > 0:\n",
1304 | " #if intermediates are saved to the subfolder, don't append a step or percentage to the name\n",
1305 | " if cur_t == -1 and args.intermediates_in_subfolder is True:\n",
1306 | " save_num = f'{frame_num:04}' if animation_mode != \"None\" else i\n",
1307 | " filename = f'{args.batch_name}({args.batchNum})_{save_num}.png'\n",
1308 | " else:\n",
1309 | " #If we're working with percentages, append it\n",
1310 | " if args.steps_per_checkpoint is not None:\n",
1311 | " filename = f'{args.batch_name}({args.batchNum})_{i:04}-{percent:02}%.png'\n",
1312 | " # Or else, iIf we're working with specific steps, append those\n",
1313 | " else:\n",
1314 | " filename = f'{args.batch_name}({args.batchNum})_{i:04}-{j:03}.png'\n",
1315 | " image = TF.to_pil_image(image.add(1).div(2).clamp(0, 1))\n",
1316 | " if j % args.display_rate == 0 or cur_t == -1:\n",
1317 | " image.save('progress.png')\n",
1318 | " display.clear_output(wait=True)\n",
1319 | " display.display(display.Image('progress.png'))\n",
1320 | " if args.steps_per_checkpoint is not None:\n",
1321 | " if j % args.steps_per_checkpoint == 0 and j > 0:\n",
1322 | " if args.intermediates_in_subfolder is True:\n",
1323 | " image.save(f'{partialFolder}/{filename}')\n",
1324 | " else:\n",
1325 | " image.save(f'{batchFolder}/{filename}')\n",
1326 | " else:\n",
1327 | " if j in args.intermediate_saves:\n",
1328 | " if args.intermediates_in_subfolder is True:\n",
1329 | " image.save(f'{partialFolder}/{filename}')\n",
1330 | " else:\n",
1331 | " image.save(f'{batchFolder}/{filename}')\n",
1332 | " if cur_t == -1:\n",
1333 | " if frame_num == 0:\n",
1334 | " save_settings()\n",
1335 | " if args.animation_mode != \"None\":\n",
1336 | " image.save('prevFrame.png')\n",
1337 | " if args.sharpen_preset != \"Off\" and animation_mode == \"None\":\n",
1338 | " imgToSharpen = image\n",
1339 | " if args.keep_unsharp is True:\n",
1340 | " image.save(f'{unsharpenFolder}/{filename}')\n",
1341 | " else:\n",
1342 | " #if turbo_mode, save a blended image \n",
1343 | " if turbo_mode == True:\n",
1344 | " #mix new image with prevFrameScaled\n",
1345 | " blend_factor = (1)/int(turbo_steps)\n",
1346 | " newFrame = cv2.imread('prevFrame.png')#this got updated just above..\n",
1347 | " prev_frame_warped = cv2.imread(turbo_prevScaled_path)\n",
1348 | " blendedImage = cv2.addWeighted(newFrame, blend_factor, prev_frame_warped, (1-blend_factor), 0.0)\n",
1349 | " cv2.imwrite(f'{batchFolder}/{filename}',blendedImage)\n",
1350 | " #turbo_blend = False # reset to false\n",
1351 | " else:\n",
1352 | " #non-turbo, just save normally\n",
1353 | " image.save(f'{batchFolder}/{filename}')\n",
1354 | " # if frame_num != args.max_frames-1:\n",
1355 | " # display.clear_output()\n",
1356 | "\n",
1357 | " with image_display: \n",
1358 | " if args.sharpen_preset != \"Off\" and animation_mode == \"None\":\n",
1359 | " print('Starting Diffusion Sharpening...')\n",
1360 | " do_superres(imgToSharpen, f'{batchFolder}/{filename}')\n",
1361 | " display.clear_output()\n",
1362 | " \n",
1363 | " plt.plot(np.array(loss_values), 'r')\n",
1364 | "\n",
1365 | "def save_settings():\n",
1366 | " setting_list = {\n",
1367 | " 'text_prompts': text_prompts,\n",
1368 | " 'image_prompts': image_prompts,\n",
1369 | " 'clip_guidance_scale': clip_guidance_scale,\n",
1370 | " 'tv_scale': tv_scale,\n",
1371 | " 'range_scale': range_scale,\n",
1372 | " 'sat_scale': sat_scale,\n",
1373 | " # 'cutn': cutn,\n",
1374 | " 'cutn_batches': cutn_batches,\n",
1375 | " 'max_frames': max_frames,\n",
1376 | " 'interp_spline': interp_spline,\n",
1377 | " # 'rotation_per_frame': rotation_per_frame,\n",
1378 | " 'init_image': init_image,\n",
1379 | " 'init_scale': init_scale,\n",
1380 | " 'skip_steps': skip_steps,\n",
1381 | " # 'zoom_per_frame': zoom_per_frame,\n",
1382 | " 'frames_scale': frames_scale,\n",
1383 | " 'frames_skip_steps': frames_skip_steps,\n",
1384 | " 'perlin_init': perlin_init,\n",
1385 | " 'perlin_mode': perlin_mode,\n",
1386 | " 'skip_augs': skip_augs,\n",
1387 | " 'randomize_class': randomize_class,\n",
1388 | " 'clip_denoised': clip_denoised,\n",
1389 | " 'clamp_grad': clamp_grad,\n",
1390 | " 'clamp_max': clamp_max,\n",
1391 | " 'seed': seed,\n",
1392 | " 'fuzzy_prompt': fuzzy_prompt,\n",
1393 | " 'rand_mag': rand_mag,\n",
1394 | " 'eta': eta,\n",
1395 | " 'width': width_height[0],\n",
1396 | " 'height': width_height[1],\n",
1397 | " 'diffusion_model': diffusion_model,\n",
1398 | " 'use_secondary_model': use_secondary_model,\n",
1399 | " 'steps': steps,\n",
1400 | " 'diffusion_steps': diffusion_steps,\n",
1401 | " 'ViTB32': ViTB32,\n",
1402 | " 'ViTB16': ViTB16,\n",
1403 | " 'ViTL14': ViTL14,\n",
1404 | " 'RN101': RN101,\n",
1405 | " 'RN50': RN50,\n",
1406 | " 'RN50x4': RN50x4,\n",
1407 | " 'RN50x16': RN50x16,\n",
1408 | " 'RN50x64': RN50x64,\n",
1409 | " 'cut_overview': str(cut_overview),\n",
1410 | " 'cut_innercut': str(cut_innercut),\n",
1411 | " 'cut_ic_pow': cut_ic_pow,\n",
1412 | " 'cut_icgray_p': str(cut_icgray_p),\n",
1413 | " 'key_frames': key_frames,\n",
1414 | " 'max_frames': max_frames,\n",
1415 | " 'angle': angle,\n",
1416 | " 'zoom': zoom,\n",
1417 | " 'translation_x': translation_x,\n",
1418 | " 'translation_y': translation_y,\n",
1419 | " 'translation_z': translation_z,\n",
1420 | " 'rotation_3d_x': rotation_3d_x,\n",
1421 | " 'rotation_3d_y': rotation_3d_y,\n",
1422 | " 'rotation_3d_z': rotation_3d_z,\n",
1423 | " 'midas_depth_model': midas_depth_model,\n",
1424 | " 'midas_weight': midas_weight,\n",
1425 | " 'near_plane': near_plane,\n",
1426 | " 'far_plane': far_plane,\n",
1427 | " 'fov': fov,\n",
1428 | " 'padding_mode': padding_mode,\n",
1429 | " 'sampling_mode': sampling_mode,\n",
1430 | " 'video_init_path':video_init_path,\n",
1431 | " 'extract_nth_frame':extract_nth_frame,\n",
1432 | " 'turbo_mode':turbo_mode,\n",
1433 | " 'turbo_steps':turbo_steps,\n",
1434 | " }\n",
1435 | " # print('Settings:', setting_list)\n",
1436 | " with open(f\"{batchFolder}/{batch_name}({batchNum})_settings.txt\", \"w+\") as f: #save settings\n",
1437 | " json.dump(setting_list, f, ensure_ascii=False, indent=4)\n",
1438 | " "
1439 | ]
1440 | },
1441 | {
1442 | "cell_type": "code",
1443 | "execution_count": null,
1444 | "metadata": {
1445 | "cellView": "form",
1446 | "id": "TI4oAu0N4ksZ"
1447 | },
1448 | "outputs": [],
1449 | "source": [
1450 | "#@title 1.6 Define the secondary diffusion model\n",
1451 | "\n",
1452 | "def append_dims(x, n):\n",
1453 | " return x[(Ellipsis, *(None,) * (n - x.ndim))]\n",
1454 | "\n",
1455 | "\n",
1456 | "def expand_to_planes(x, shape):\n",
1457 | " return append_dims(x, len(shape)).repeat([1, 1, *shape[2:]])\n",
1458 | "\n",
1459 | "\n",
1460 | "def alpha_sigma_to_t(alpha, sigma):\n",
1461 | " return torch.atan2(sigma, alpha) * 2 / math.pi\n",
1462 | "\n",
1463 | "\n",
1464 | "def t_to_alpha_sigma(t):\n",
1465 | " return torch.cos(t * math.pi / 2), torch.sin(t * math.pi / 2)\n",
1466 | "\n",
1467 | "\n",
1468 | "@dataclass\n",
1469 | "class DiffusionOutput:\n",
1470 | " v: torch.Tensor\n",
1471 | " pred: torch.Tensor\n",
1472 | " eps: torch.Tensor\n",
1473 | "\n",
1474 | "\n",
1475 | "class ConvBlock(nn.Sequential):\n",
1476 | " def __init__(self, c_in, c_out):\n",
1477 | " super().__init__(\n",
1478 | " nn.Conv2d(c_in, c_out, 3, padding=1),\n",
1479 | " nn.ReLU(inplace=True),\n",
1480 | " )\n",
1481 | "\n",
1482 | "\n",
1483 | "class SkipBlock(nn.Module):\n",
1484 | " def __init__(self, main, skip=None):\n",
1485 | " super().__init__()\n",
1486 | " self.main = nn.Sequential(*main)\n",
1487 | " self.skip = skip if skip else nn.Identity()\n",
1488 | "\n",
1489 | " def forward(self, input):\n",
1490 | " return torch.cat([self.main(input), self.skip(input)], dim=1)\n",
1491 | "\n",
1492 | "\n",
1493 | "class FourierFeatures(nn.Module):\n",
1494 | " def __init__(self, in_features, out_features, std=1.):\n",
1495 | " super().__init__()\n",
1496 | " assert out_features % 2 == 0\n",
1497 | " self.weight = nn.Parameter(torch.randn([out_features // 2, in_features]) * std)\n",
1498 | "\n",
1499 | " def forward(self, input):\n",
1500 | " f = 2 * math.pi * input @ self.weight.T\n",
1501 | " return torch.cat([f.cos(), f.sin()], dim=-1)\n",
1502 | "\n",
1503 | "\n",
1504 | "class SecondaryDiffusionImageNet(nn.Module):\n",
1505 | " def __init__(self):\n",
1506 | " super().__init__()\n",
1507 | " c = 64 # The base channel count\n",
1508 | "\n",
1509 | " self.timestep_embed = FourierFeatures(1, 16)\n",
1510 | "\n",
1511 | " self.net = nn.Sequential(\n",
1512 | " ConvBlock(3 + 16, c),\n",
1513 | " ConvBlock(c, c),\n",
1514 | " SkipBlock([\n",
1515 | " nn.AvgPool2d(2),\n",
1516 | " ConvBlock(c, c * 2),\n",
1517 | " ConvBlock(c * 2, c * 2),\n",
1518 | " SkipBlock([\n",
1519 | " nn.AvgPool2d(2),\n",
1520 | " ConvBlock(c * 2, c * 4),\n",
1521 | " ConvBlock(c * 4, c * 4),\n",
1522 | " SkipBlock([\n",
1523 | " nn.AvgPool2d(2),\n",
1524 | " ConvBlock(c * 4, c * 8),\n",
1525 | " ConvBlock(c * 8, c * 4),\n",
1526 | " nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),\n",
1527 | " ]),\n",
1528 | " ConvBlock(c * 8, c * 4),\n",
1529 | " ConvBlock(c * 4, c * 2),\n",
1530 | " nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),\n",
1531 | " ]),\n",
1532 | " ConvBlock(c * 4, c * 2),\n",
1533 | " ConvBlock(c * 2, c),\n",
1534 | " nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),\n",
1535 | " ]),\n",
1536 | " ConvBlock(c * 2, c),\n",
1537 | " nn.Conv2d(c, 3, 3, padding=1),\n",
1538 | " )\n",
1539 | "\n",
1540 | " def forward(self, input, t):\n",
1541 | " timestep_embed = expand_to_planes(self.timestep_embed(t[:, None]), input.shape)\n",
1542 | " v = self.net(torch.cat([input, timestep_embed], dim=1))\n",
1543 | " alphas, sigmas = map(partial(append_dims, n=v.ndim), t_to_alpha_sigma(t))\n",
1544 | " pred = input * alphas - v * sigmas\n",
1545 | " eps = input * sigmas + v * alphas\n",
1546 | " return DiffusionOutput(v, pred, eps)\n",
1547 | "\n",
1548 | "\n",
1549 | "class SecondaryDiffusionImageNet2(nn.Module):\n",
1550 | " def __init__(self):\n",
1551 | " super().__init__()\n",
1552 | " c = 64 # The base channel count\n",
1553 | " cs = [c, c * 2, c * 2, c * 4, c * 4, c * 8]\n",
1554 | "\n",
1555 | " self.timestep_embed = FourierFeatures(1, 16)\n",
1556 | " self.down = nn.AvgPool2d(2)\n",
1557 | " self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False)\n",
1558 | "\n",
1559 | " self.net = nn.Sequential(\n",
1560 | " ConvBlock(3 + 16, cs[0]),\n",
1561 | " ConvBlock(cs[0], cs[0]),\n",
1562 | " SkipBlock([\n",
1563 | " self.down,\n",
1564 | " ConvBlock(cs[0], cs[1]),\n",
1565 | " ConvBlock(cs[1], cs[1]),\n",
1566 | " SkipBlock([\n",
1567 | " self.down,\n",
1568 | " ConvBlock(cs[1], cs[2]),\n",
1569 | " ConvBlock(cs[2], cs[2]),\n",
1570 | " SkipBlock([\n",
1571 | " self.down,\n",
1572 | " ConvBlock(cs[2], cs[3]),\n",
1573 | " ConvBlock(cs[3], cs[3]),\n",
1574 | " SkipBlock([\n",
1575 | " self.down,\n",
1576 | " ConvBlock(cs[3], cs[4]),\n",
1577 | " ConvBlock(cs[4], cs[4]),\n",
1578 | " SkipBlock([\n",
1579 | " self.down,\n",
1580 | " ConvBlock(cs[4], cs[5]),\n",
1581 | " ConvBlock(cs[5], cs[5]),\n",
1582 | " ConvBlock(cs[5], cs[5]),\n",
1583 | " ConvBlock(cs[5], cs[4]),\n",
1584 | " self.up,\n",
1585 | " ]),\n",
1586 | " ConvBlock(cs[4] * 2, cs[4]),\n",
1587 | " ConvBlock(cs[4], cs[3]),\n",
1588 | " self.up,\n",
1589 | " ]),\n",
1590 | " ConvBlock(cs[3] * 2, cs[3]),\n",
1591 | " ConvBlock(cs[3], cs[2]),\n",
1592 | " self.up,\n",
1593 | " ]),\n",
1594 | " ConvBlock(cs[2] * 2, cs[2]),\n",
1595 | " ConvBlock(cs[2], cs[1]),\n",
1596 | " self.up,\n",
1597 | " ]),\n",
1598 | " ConvBlock(cs[1] * 2, cs[1]),\n",
1599 | " ConvBlock(cs[1], cs[0]),\n",
1600 | " self.up,\n",
1601 | " ]),\n",
1602 | " ConvBlock(cs[0] * 2, cs[0]),\n",
1603 | " nn.Conv2d(cs[0], 3, 3, padding=1),\n",
1604 | " )\n",
1605 | "\n",
1606 | " def forward(self, input, t):\n",
1607 | " timestep_embed = expand_to_planes(self.timestep_embed(t[:, None]), input.shape)\n",
1608 | " v = self.net(torch.cat([input, timestep_embed], dim=1))\n",
1609 | " alphas, sigmas = map(partial(append_dims, n=v.ndim), t_to_alpha_sigma(t))\n",
1610 | " pred = input * alphas - v * sigmas\n",
1611 | " eps = input * sigmas + v * alphas\n",
1612 | " return DiffusionOutput(v, pred, eps)\n"
1613 | ]
1614 | },
1615 | {
1616 | "cell_type": "code",
1617 | "execution_count": null,
1618 | "metadata": {
1619 | "cellView": "form",
1620 | "id": "NJS2AUAnvn-D",
1621 | "scrolled": true
1622 | },
1623 | "outputs": [],
1624 | "source": [
1625 | "#@title 1.7 SuperRes Define\n",
1626 | "class DDIMSampler(object):\n",
1627 | " def __init__(self, model, schedule=\"linear\", **kwargs):\n",
1628 | " super().__init__()\n",
1629 | " self.model = model\n",
1630 | " self.ddpm_num_timesteps = model.num_timesteps\n",
1631 | " self.schedule = schedule\n",
1632 | "\n",
1633 | " def register_buffer(self, name, attr):\n",
1634 | " if type(attr) == torch.Tensor:\n",
1635 | " if attr.device != torch.device(\"cuda\"):\n",
1636 | " attr = attr.to(torch.device(\"cuda\"))\n",
1637 | " setattr(self, name, attr)\n",
1638 | "\n",
1639 | " def make_schedule(self, ddim_num_steps, ddim_discretize=\"uniform\", ddim_eta=0., verbose=True):\n",
1640 | " self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,\n",
1641 | " num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)\n",
1642 | " alphas_cumprod = self.model.alphas_cumprod\n",
1643 | " assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'\n",
1644 | " to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)\n",
1645 | "\n",
1646 | " self.register_buffer('betas', to_torch(self.model.betas))\n",
1647 | " self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))\n",
1648 | " self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))\n",
1649 | "\n",
1650 | " # calculations for diffusion q(x_t | x_{t-1}) and others\n",
1651 | " self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))\n",
1652 | " self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))\n",
1653 | " self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))\n",
1654 | " self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))\n",
1655 | " self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))\n",
1656 | "\n",
1657 | " # ddim sampling parameters\n",
1658 | " ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),\n",
1659 | " ddim_timesteps=self.ddim_timesteps,\n",
1660 | " eta=ddim_eta,verbose=verbose)\n",
1661 | " self.register_buffer('ddim_sigmas', ddim_sigmas)\n",
1662 | " self.register_buffer('ddim_alphas', ddim_alphas)\n",
1663 | " self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)\n",
1664 | " self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))\n",
1665 | " sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(\n",
1666 | " (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (\n",
1667 | " 1 - self.alphas_cumprod / self.alphas_cumprod_prev))\n",
1668 | " self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)\n",
1669 | "\n",
1670 | " @torch.no_grad()\n",
1671 | " def sample(self,\n",
1672 | " S,\n",
1673 | " batch_size,\n",
1674 | " shape,\n",
1675 | " conditioning=None,\n",
1676 | " callback=None,\n",
1677 | " normals_sequence=None,\n",
1678 | " img_callback=None,\n",
1679 | " quantize_x0=False,\n",
1680 | " eta=0.,\n",
1681 | " mask=None,\n",
1682 | " x0=None,\n",
1683 | " temperature=1.,\n",
1684 | " noise_dropout=0.,\n",
1685 | " score_corrector=None,\n",
1686 | " corrector_kwargs=None,\n",
1687 | " verbose=True,\n",
1688 | " x_T=None,\n",
1689 | " log_every_t=100,\n",
1690 | " **kwargs\n",
1691 | " ):\n",
1692 | " if conditioning is not None:\n",
1693 | " if isinstance(conditioning, dict):\n",
1694 | " cbs = conditioning[list(conditioning.keys())[0]].shape[0]\n",
1695 | " if cbs != batch_size:\n",
1696 | " print(f\"Warning: Got {cbs} conditionings but batch-size is {batch_size}\")\n",
1697 | " else:\n",
1698 | " if conditioning.shape[0] != batch_size:\n",
1699 | " print(f\"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}\")\n",
1700 | "\n",
1701 | " self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)\n",
1702 | " # sampling\n",
1703 | " C, H, W = shape\n",
1704 | " size = (batch_size, C, H, W)\n",
1705 | " # print(f'Data shape for DDIM sampling is {size}, eta {eta}')\n",
1706 | "\n",
1707 | " samples, intermediates = self.ddim_sampling(conditioning, size,\n",
1708 | " callback=callback,\n",
1709 | " img_callback=img_callback,\n",
1710 | " quantize_denoised=quantize_x0,\n",
1711 | " mask=mask, x0=x0,\n",
1712 | " ddim_use_original_steps=False,\n",
1713 | " noise_dropout=noise_dropout,\n",
1714 | " temperature=temperature,\n",
1715 | " score_corrector=score_corrector,\n",
1716 | " corrector_kwargs=corrector_kwargs,\n",
1717 | " x_T=x_T,\n",
1718 | " log_every_t=log_every_t\n",
1719 | " )\n",
1720 | " return samples, intermediates\n",
1721 | "\n",
1722 | " @torch.no_grad()\n",
1723 | " def ddim_sampling(self, cond, shape,\n",
1724 | " x_T=None, ddim_use_original_steps=False,\n",
1725 | " callback=None, timesteps=None, quantize_denoised=False,\n",
1726 | " mask=None, x0=None, img_callback=None, log_every_t=100,\n",
1727 | " temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):\n",
1728 | " device = self.model.betas.device\n",
1729 | " b = shape[0]\n",
1730 | " if x_T is None:\n",
1731 | " img = torch.randn(shape, device=device)\n",
1732 | " else:\n",
1733 | " img = x_T\n",
1734 | "\n",
1735 | " if timesteps is None:\n",
1736 | " timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps\n",
1737 | " elif timesteps is not None and not ddim_use_original_steps:\n",
1738 | " subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1\n",
1739 | " timesteps = self.ddim_timesteps[:subset_end]\n",
1740 | "\n",
1741 | " intermediates = {'x_inter': [img], 'pred_x0': [img]}\n",
1742 | " time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)\n",
1743 | " total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]\n",
1744 | " print(f\"Running DDIM Sharpening with {total_steps} timesteps\")\n",
1745 | "\n",
1746 | " iterator = tqdm(time_range, desc='DDIM Sharpening', total=total_steps)\n",
1747 | "\n",
1748 | " for i, step in enumerate(iterator):\n",
1749 | " index = total_steps - i - 1\n",
1750 | " ts = torch.full((b,), step, device=device, dtype=torch.long)\n",
1751 | "\n",
1752 | " if mask is not None:\n",
1753 | " assert x0 is not None\n",
1754 | " img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?\n",
1755 | " img = img_orig * mask + (1. - mask) * img\n",
1756 | "\n",
1757 | " outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,\n",
1758 | " quantize_denoised=quantize_denoised, temperature=temperature,\n",
1759 | " noise_dropout=noise_dropout, score_corrector=score_corrector,\n",
1760 | " corrector_kwargs=corrector_kwargs)\n",
1761 | " img, pred_x0 = outs\n",
1762 | " if callback: callback(i)\n",
1763 | " if img_callback: img_callback(pred_x0, i)\n",
1764 | "\n",
1765 | " if index % log_every_t == 0 or index == total_steps - 1:\n",
1766 | " intermediates['x_inter'].append(img)\n",
1767 | " intermediates['pred_x0'].append(pred_x0)\n",
1768 | "\n",
1769 | " return img, intermediates\n",
1770 | "\n",
1771 | " @torch.no_grad()\n",
1772 | " def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,\n",
1773 | " temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):\n",
1774 | " b, *_, device = *x.shape, x.device\n",
1775 | " e_t = self.model.apply_model(x, t, c)\n",
1776 | " if score_corrector is not None:\n",
1777 | " assert self.model.parameterization == \"eps\"\n",
1778 | " e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)\n",
1779 | "\n",
1780 | " alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n",
1781 | " alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev\n",
1782 | " sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n",
1783 | " sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas\n",
1784 | " # select parameters corresponding to the currently considered timestep\n",
1785 | " a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n",
1786 | " a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)\n",
1787 | " sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)\n",
1788 | " sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)\n",
1789 | "\n",
1790 | " # current prediction for x_0\n",
1791 | " pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()\n",
1792 | " if quantize_denoised:\n",
1793 | " pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)\n",
1794 | " # direction pointing to x_t\n",
1795 | " dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t\n",
1796 | " noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature\n",
1797 | " if noise_dropout > 0.:\n",
1798 | " noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n",
1799 | " x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise\n",
1800 | " return x_prev, pred_x0\n",
1801 | "\n",
1802 | "\n",
1803 | "def download_models(mode):\n",
1804 | "\n",
1805 | " if mode == \"superresolution\":\n",
1806 | " # this is the small bsr light model\n",
1807 | " url_conf = 'https://heibox.uni-heidelberg.de/f/31a76b13ea27482981b4/?dl=1'\n",
1808 | " url_ckpt = 'https://heibox.uni-heidelberg.de/f/578df07c8fc04ffbadf3/?dl=1'\n",
1809 | "\n",
1810 | " path_conf = f'{model_path}/superres/project.yaml'\n",
1811 | " path_ckpt = f'{model_path}/superres/last.ckpt'\n",
1812 | "\n",
1813 | " download_url(url_conf, path_conf)\n",
1814 | " download_url(url_ckpt, path_ckpt)\n",
1815 | "\n",
1816 | " path_conf = path_conf + '/?dl=1' # fix it\n",
1817 | " path_ckpt = path_ckpt + '/?dl=1' # fix it\n",
1818 | " return path_conf, path_ckpt\n",
1819 | "\n",
1820 | " else:\n",
1821 | " raise NotImplementedError\n",
1822 | "\n",
1823 | "\n",
1824 | "def load_model_from_config(config, ckpt):\n",
1825 | " print(f\"Loading model from {ckpt}\")\n",
1826 | " pl_sd = torch.load(ckpt, map_location=\"cpu\")\n",
1827 | " global_step = pl_sd[\"global_step\"]\n",
1828 | " sd = pl_sd[\"state_dict\"]\n",
1829 | " model = instantiate_from_config(config.model)\n",
1830 | " m, u = model.load_state_dict(sd, strict=False)\n",
1831 | " model.cuda()\n",
1832 | " model.eval()\n",
1833 | " return {\"model\": model}, global_step\n",
1834 | "\n",
1835 | "\n",
1836 | "def get_model(mode):\n",
1837 | " path_conf, path_ckpt = download_models(mode)\n",
1838 | " config = OmegaConf.load(path_conf)\n",
1839 | " model, step = load_model_from_config(config, path_ckpt)\n",
1840 | " return model\n",
1841 | "\n",
1842 | "\n",
1843 | "def get_custom_cond(mode):\n",
1844 | " dest = \"data/example_conditioning\"\n",
1845 | "\n",
1846 | " if mode == \"superresolution\":\n",
1847 | " uploaded_img = files.upload()\n",
1848 | " filename = next(iter(uploaded_img))\n",
1849 | " name, filetype = filename.split(\".\") # todo assumes just one dot in name !\n",
1850 | " os.rename(f\"{filename}\", f\"{dest}/{mode}/custom_{name}.{filetype}\")\n",
1851 | "\n",
1852 | " elif mode == \"text_conditional\":\n",
1853 | " w = widgets.Text(value='A cake with cream!', disabled=True)\n",
1854 | " display.display(w)\n",
1855 | "\n",
1856 | " with open(f\"{dest}/{mode}/custom_{w.value[:20]}.txt\", 'w') as f:\n",
1857 | " f.write(w.value)\n",
1858 | "\n",
1859 | " elif mode == \"class_conditional\":\n",
1860 | " w = widgets.IntSlider(min=0, max=1000)\n",
1861 | " display.display(w)\n",
1862 | " with open(f\"{dest}/{mode}/custom.txt\", 'w') as f:\n",
1863 | " f.write(w.value)\n",
1864 | "\n",
1865 | " else:\n",
1866 | " raise NotImplementedError(f\"cond not implemented for mode{mode}\")\n",
1867 | "\n",
1868 | "\n",
1869 | "def get_cond_options(mode):\n",
1870 | " path = \"data/example_conditioning\"\n",
1871 | " path = os.path.join(path, mode)\n",
1872 | " onlyfiles = [f for f in sorted(os.listdir(path))]\n",
1873 | " return path, onlyfiles\n",
1874 | "\n",
1875 | "\n",
1876 | "def select_cond_path(mode):\n",
1877 | " path = \"data/example_conditioning\" # todo\n",
1878 | " path = os.path.join(path, mode)\n",
1879 | " onlyfiles = [f for f in sorted(os.listdir(path))]\n",
1880 | "\n",
1881 | " selected = widgets.RadioButtons(\n",
1882 | " options=onlyfiles,\n",
1883 | " description='Select conditioning:',\n",
1884 | " disabled=False\n",
1885 | " )\n",
1886 | " display.display(selected)\n",
1887 | " selected_path = os.path.join(path, selected.value)\n",
1888 | " return selected_path\n",
1889 | "\n",
1890 | "\n",
1891 | "def get_cond(mode, img):\n",
1892 | " example = dict()\n",
1893 | " if mode == \"superresolution\":\n",
1894 | " up_f = 4\n",
1895 | " # visualize_cond_img(selected_path)\n",
1896 | "\n",
1897 | " c = img\n",
1898 | " c = torch.unsqueeze(torchvision.transforms.ToTensor()(c), 0)\n",
1899 | " c_up = torchvision.transforms.functional.resize(c, size=[up_f * c.shape[2], up_f * c.shape[3]], antialias=True)\n",
1900 | " c_up = rearrange(c_up, '1 c h w -> 1 h w c')\n",
1901 | " c = rearrange(c, '1 c h w -> 1 h w c')\n",
1902 | " c = 2. * c - 1.\n",
1903 | "\n",
1904 | " c = c.to(torch.device(\"cuda\"))\n",
1905 | " example[\"LR_image\"] = c\n",
1906 | " example[\"image\"] = c_up\n",
1907 | "\n",
1908 | " return example\n",
1909 | "\n",
1910 | "\n",
1911 | "def visualize_cond_img(path):\n",
1912 | " display.display(ipyimg(filename=path))\n",
1913 | "\n",
1914 | "\n",
1915 | "def sr_run(model, img, task, custom_steps, eta, resize_enabled=False, classifier_ckpt=None, global_step=None):\n",
1916 | " # global stride\n",
1917 | "\n",
1918 | " example = get_cond(task, img)\n",
1919 | "\n",
1920 | " save_intermediate_vid = False\n",
1921 | " n_runs = 1\n",
1922 | " masked = False\n",
1923 | " guider = None\n",
1924 | " ckwargs = None\n",
1925 | " mode = 'ddim'\n",
1926 | " ddim_use_x0_pred = False\n",
1927 | " temperature = 1.\n",
1928 | " eta = eta\n",
1929 | " make_progrow = True\n",
1930 | " custom_shape = None\n",
1931 | "\n",
1932 | " height, width = example[\"image\"].shape[1:3]\n",
1933 | " split_input = height >= 128 and width >= 128\n",
1934 | "\n",
1935 | " if split_input:\n",
1936 | " ks = 128\n",
1937 | " stride = 64\n",
1938 | " vqf = 4 #\n",
1939 | " model.split_input_params = {\"ks\": (ks, ks), \"stride\": (stride, stride),\n",
1940 | " \"vqf\": vqf,\n",
1941 | " \"patch_distributed_vq\": True,\n",
1942 | " \"tie_braker\": False,\n",
1943 | " \"clip_max_weight\": 0.5,\n",
1944 | " \"clip_min_weight\": 0.01,\n",
1945 | " \"clip_max_tie_weight\": 0.5,\n",
1946 | " \"clip_min_tie_weight\": 0.01}\n",
1947 | " else:\n",
1948 | " if hasattr(model, \"split_input_params\"):\n",
1949 | " delattr(model, \"split_input_params\")\n",
1950 | "\n",
1951 | " invert_mask = False\n",
1952 | "\n",
1953 | " x_T = None\n",
1954 | " for n in range(n_runs):\n",
1955 | " if custom_shape is not None:\n",
1956 | " x_T = torch.randn(1, custom_shape[1], custom_shape[2], custom_shape[3]).to(model.device)\n",
1957 | " x_T = repeat(x_T, '1 c h w -> b c h w', b=custom_shape[0])\n",
1958 | "\n",
1959 | " logs = make_convolutional_sample(example, model,\n",
1960 | " mode=mode, custom_steps=custom_steps,\n",
1961 | " eta=eta, swap_mode=False , masked=masked,\n",
1962 | " invert_mask=invert_mask, quantize_x0=False,\n",
1963 | " custom_schedule=None, decode_interval=10,\n",
1964 | " resize_enabled=resize_enabled, custom_shape=custom_shape,\n",
1965 | " temperature=temperature, noise_dropout=0.,\n",
1966 | " corrector=guider, corrector_kwargs=ckwargs, x_T=x_T, save_intermediate_vid=save_intermediate_vid,\n",
1967 | " make_progrow=make_progrow,ddim_use_x0_pred=ddim_use_x0_pred\n",
1968 | " )\n",
1969 | " return logs\n",
1970 | "\n",
1971 | "\n",
1972 | "@torch.no_grad()\n",
1973 | "def convsample_ddim(model, cond, steps, shape, eta=1.0, callback=None, normals_sequence=None,\n",
1974 | " mask=None, x0=None, quantize_x0=False, img_callback=None,\n",
1975 | " temperature=1., noise_dropout=0., score_corrector=None,\n",
1976 | " corrector_kwargs=None, x_T=None, log_every_t=None\n",
1977 | " ):\n",
1978 | "\n",
1979 | " ddim = DDIMSampler(model)\n",
1980 | " bs = shape[0] # dont know where this comes from but wayne\n",
1981 | " shape = shape[1:] # cut batch dim\n",
1982 | " # print(f\"Sampling with eta = {eta}; steps: {steps}\")\n",
1983 | " samples, intermediates = ddim.sample(steps, batch_size=bs, shape=shape, conditioning=cond, callback=callback,\n",
1984 | " normals_sequence=normals_sequence, quantize_x0=quantize_x0, eta=eta,\n",
1985 | " mask=mask, x0=x0, temperature=temperature, verbose=False,\n",
1986 | " score_corrector=score_corrector,\n",
1987 | " corrector_kwargs=corrector_kwargs, x_T=x_T)\n",
1988 | "\n",
1989 | " return samples, intermediates\n",
1990 | "\n",
1991 | "\n",
1992 | "@torch.no_grad()\n",
1993 | "def make_convolutional_sample(batch, model, mode=\"vanilla\", custom_steps=None, eta=1.0, swap_mode=False, masked=False,\n",
1994 | " invert_mask=True, quantize_x0=False, custom_schedule=None, decode_interval=1000,\n",
1995 | " resize_enabled=False, custom_shape=None, temperature=1., noise_dropout=0., corrector=None,\n",
1996 | " corrector_kwargs=None, x_T=None, save_intermediate_vid=False, make_progrow=True,ddim_use_x0_pred=False):\n",
1997 | " log = dict()\n",
1998 | "\n",
1999 | " z, c, x, xrec, xc = model.get_input(batch, model.first_stage_key,\n",
2000 | " return_first_stage_outputs=True,\n",
2001 | " force_c_encode=not (hasattr(model, 'split_input_params')\n",
2002 | " and model.cond_stage_key == 'coordinates_bbox'),\n",
2003 | " return_original_cond=True)\n",
2004 | "\n",
2005 | " log_every_t = 1 if save_intermediate_vid else None\n",
2006 | "\n",
2007 | " if custom_shape is not None:\n",
2008 | " z = torch.randn(custom_shape)\n",
2009 | " # print(f\"Generating {custom_shape[0]} samples of shape {custom_shape[1:]}\")\n",
2010 | "\n",
2011 | " z0 = None\n",
2012 | "\n",
2013 | " log[\"input\"] = x\n",
2014 | " log[\"reconstruction\"] = xrec\n",
2015 | "\n",
2016 | " if ismap(xc):\n",
2017 | " log[\"original_conditioning\"] = model.to_rgb(xc)\n",
2018 | " if hasattr(model, 'cond_stage_key'):\n",
2019 | " log[model.cond_stage_key] = model.to_rgb(xc)\n",
2020 | "\n",
2021 | " else:\n",
2022 | " log[\"original_conditioning\"] = xc if xc is not None else torch.zeros_like(x)\n",
2023 | " if model.cond_stage_model:\n",
2024 | " log[model.cond_stage_key] = xc if xc is not None else torch.zeros_like(x)\n",
2025 | " if model.cond_stage_key =='class_label':\n",
2026 | " log[model.cond_stage_key] = xc[model.cond_stage_key]\n",
2027 | "\n",
2028 | " with model.ema_scope(\"Plotting\"):\n",
2029 | " t0 = time.time()\n",
2030 | " img_cb = None\n",
2031 | "\n",
2032 | " sample, intermediates = convsample_ddim(model, c, steps=custom_steps, shape=z.shape,\n",
2033 | " eta=eta,\n",
2034 | " quantize_x0=quantize_x0, img_callback=img_cb, mask=None, x0=z0,\n",
2035 | " temperature=temperature, noise_dropout=noise_dropout,\n",
2036 | " score_corrector=corrector, corrector_kwargs=corrector_kwargs,\n",
2037 | " x_T=x_T, log_every_t=log_every_t)\n",
2038 | " t1 = time.time()\n",
2039 | "\n",
2040 | " if ddim_use_x0_pred:\n",
2041 | " sample = intermediates['pred_x0'][-1]\n",
2042 | "\n",
2043 | " x_sample = model.decode_first_stage(sample)\n",
2044 | "\n",
2045 | " try:\n",
2046 | " x_sample_noquant = model.decode_first_stage(sample, force_not_quantize=True)\n",
2047 | " log[\"sample_noquant\"] = x_sample_noquant\n",
2048 | " log[\"sample_diff\"] = torch.abs(x_sample_noquant - x_sample)\n",
2049 | " except:\n",
2050 | " pass\n",
2051 | "\n",
2052 | " log[\"sample\"] = x_sample\n",
2053 | " log[\"time\"] = t1 - t0\n",
2054 | "\n",
2055 | " return log\n",
2056 | "\n",
2057 | "sr_diffMode = 'superresolution'\n",
2058 | "sr_model = get_model('superresolution')\n",
2059 | "\n",
2060 | "def do_superres(img, filepath):\n",
2061 | "\n",
2062 | " if args.sharpen_preset == 'Faster':\n",
2063 | " sr_diffusion_steps = \"25\" \n",
2064 | " sr_pre_downsample = '1/2' \n",
2065 | " if args.sharpen_preset == 'Fast':\n",
2066 | " sr_diffusion_steps = \"100\" \n",
2067 | " sr_pre_downsample = '1/2' \n",
2068 | " if args.sharpen_preset == 'Slow':\n",
2069 | " sr_diffusion_steps = \"25\" \n",
2070 | " sr_pre_downsample = 'None' \n",
2071 | " if args.sharpen_preset == 'Very Slow':\n",
2072 | " sr_diffusion_steps = \"100\" \n",
2073 | " sr_pre_downsample = 'None' \n",
2074 | "\n",
2075 | "\n",
2076 | " sr_post_downsample = 'Original Size'\n",
2077 | " sr_diffusion_steps = int(sr_diffusion_steps)\n",
2078 | " sr_eta = 1.0 \n",
2079 | " sr_downsample_method = 'Lanczos' \n",
2080 | "\n",
2081 | " gc.collect()\n",
2082 | " torch.cuda.empty_cache()\n",
2083 | "\n",
2084 | " im_og = img\n",
2085 | " width_og, height_og = im_og.size\n",
2086 | "\n",
2087 | " #Downsample Pre\n",
2088 | " if sr_pre_downsample == '1/2':\n",
2089 | " downsample_rate = 2\n",
2090 | " elif sr_pre_downsample == '1/4':\n",
2091 | " downsample_rate = 4\n",
2092 | " else:\n",
2093 | " downsample_rate = 1\n",
2094 | "\n",
2095 | " width_downsampled_pre = width_og//downsample_rate\n",
2096 | " height_downsampled_pre = height_og//downsample_rate\n",
2097 | "\n",
2098 | " if downsample_rate != 1:\n",
2099 | " # print(f'Downsampling from [{width_og}, {height_og}] to [{width_downsampled_pre}, {height_downsampled_pre}]')\n",
2100 | " im_og = im_og.resize((width_downsampled_pre, height_downsampled_pre), Image.LANCZOS)\n",
2101 | " # im_og.save('/content/temp.png')\n",
2102 | " # filepath = '/content/temp.png'\n",
2103 | "\n",
2104 | " logs = sr_run(sr_model[\"model\"], im_og, sr_diffMode, sr_diffusion_steps, sr_eta)\n",
2105 | "\n",
2106 | " sample = logs[\"sample\"]\n",
2107 | " sample = sample.detach().cpu()\n",
2108 | " sample = torch.clamp(sample, -1., 1.)\n",
2109 | " sample = (sample + 1.) / 2. * 255\n",
2110 | " sample = sample.numpy().astype(np.uint8)\n",
2111 | " sample = np.transpose(sample, (0, 2, 3, 1))\n",
2112 | " a = Image.fromarray(sample[0])\n",
2113 | "\n",
2114 | " #Downsample Post\n",
2115 | " if sr_post_downsample == '1/2':\n",
2116 | " downsample_rate = 2\n",
2117 | " elif sr_post_downsample == '1/4':\n",
2118 | " downsample_rate = 4\n",
2119 | " else:\n",
2120 | " downsample_rate = 1\n",
2121 | "\n",
2122 | " width, height = a.size\n",
2123 | " width_downsampled_post = width//downsample_rate\n",
2124 | " height_downsampled_post = height//downsample_rate\n",
2125 | "\n",
2126 | " if sr_downsample_method == 'Lanczos':\n",
2127 | " aliasing = Image.LANCZOS\n",
2128 | " else:\n",
2129 | " aliasing = Image.NEAREST\n",
2130 | "\n",
2131 | " if downsample_rate != 1:\n",
2132 | " # print(f'Downsampling from [{width}, {height}] to [{width_downsampled_post}, {height_downsampled_post}]')\n",
2133 | " a = a.resize((width_downsampled_post, height_downsampled_post), aliasing)\n",
2134 | " elif sr_post_downsample == 'Original Size':\n",
2135 | " # print(f'Downsampling from [{width}, {height}] to Original Size [{width_og}, {height_og}]')\n",
2136 | " a = a.resize((width_og, height_og), aliasing)\n",
2137 | "\n",
2138 | " display.display(a)\n",
2139 | " a.save(filepath)\n",
2140 | " return\n",
2141 | " print(f'Processing finished!')\n"
2142 | ]
2143 | },
2144 | {
2145 | "cell_type": "markdown",
2146 | "metadata": {
2147 | "id": "CQVtY1Ixnqx4"
2148 | },
2149 | "source": [
2150 | "# 2. Diffusion and CLIP model settings"
2151 | ]
2152 | },
2153 | {
2154 | "cell_type": "code",
2155 | "execution_count": null,
2156 | "metadata": {
2157 | "cellView": "form",
2158 | "id": "Fpbody2NCR7w",
2159 | "scrolled": true
2160 | },
2161 | "outputs": [],
2162 | "source": [
2163 | "#@markdown ####**Models Settings:**\n",
2164 | "diffusion_model = \"512x512_diffusion_uncond_finetune_008100\" #@param [\"256x256_diffusion_uncond\", \"512x512_diffusion_uncond_finetune_008100\"]\n",
2165 | "use_secondary_model = True #@param {type: 'boolean'}\n",
2166 | "\n",
2167 | "timestep_respacing = '50' # param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000'] \n",
2168 | "diffusion_steps = 1000 # param {type: 'number'}\n",
2169 | "use_checkpoint = True #@param {type: 'boolean'}\n",
2170 | "ViTB32 = True #@param{type:\"boolean\"}\n",
2171 | "ViTB16 = True #@param{type:\"boolean\"}\n",
2172 | "ViTL14 = False #@param{type:\"boolean\"} # Default False\n",
2173 | "RN101 = True #@param{type:\"boolean\"} # Default False\n",
2174 | "RN50 = True #@param{type:\"boolean\"} # Default True\n",
2175 | "RN50x4 = True #@param{type:\"boolean\"} # Default False\n",
2176 | "RN50x16 = False #@param{type:\"boolean\"}\n",
2177 | "RN50x64 = False #@param{type:\"boolean\"}\n",
2178 | "SLIPB16 = False # param{type:\"boolean\"} # Default False. Looks broken, likely related to commented import of SLIP_VITB16\n",
2179 | "SLIPL16 = False # param{type:\"boolean\"}\n",
2180 | "\n",
2181 | "\n",
2182 | "#@markdown If you're having issues with model downloads, check this to compare SHA's:\n",
2183 | "check_model_SHA = False #@param{type:\"boolean\"}\n",
2184 | "\n",
2185 | "model_256_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a'\n",
2186 | "model_512_SHA = '9c111ab89e214862b76e1fa6a1b3f1d329b1a88281885943d2cdbe357ad57648'\n",
2187 | "model_secondary_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a'\n",
2188 | "\n",
2189 | "model_256_link = 'https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt'\n",
2190 | "model_512_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/512x512_diffusion_uncond_finetune_008100.pt'\n",
2191 | "model_secondary_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/secondary_model_imagenet_2.pth'\n",
2192 | "\n",
2193 | "model_256_path = f'{model_path}/256x256_diffusion_uncond.pt'\n",
2194 | "model_512_path = f'{model_path}/512x512_diffusion_uncond_finetune_008100.pt'\n",
2195 | "model_secondary_path = f'{model_path}/secondary_model_imagenet_2.pth'\n",
2196 | "\n",
2197 | "# Download the diffusion model\n",
2198 | "if diffusion_model == '256x256_diffusion_uncond':\n",
2199 | " if os.path.exists(model_256_path) and check_model_SHA:\n",
2200 | " print('Checking 256 Diffusion File')\n",
2201 | " with open(model_256_path,\"rb\") as f:\n",
2202 | " bytes = f.read() \n",
2203 | " hash = hashlib.sha256(bytes).hexdigest();\n",
2204 | " if hash == model_256_SHA:\n",
2205 | " print('256 Model SHA matches')\n",
2206 | " model_256_downloaded = True\n",
2207 | " else: \n",
2208 | " print(\"256 Model SHA doesn't match, redownloading...\")\n",
2209 | " !wget --continue {model_256_link} -P {model_path}\n",
2210 | " model_256_downloaded = True\n",
2211 | " elif os.path.exists(model_256_path) and not check_model_SHA or model_256_downloaded == True:\n",
2212 | " print('256 Model already downloaded, check check_model_SHA if the file is corrupt')\n",
2213 | " else: \n",
2214 | " !wget --continue {model_256_link} -P {model_path}\n",
2215 | " model_256_downloaded = True\n",
2216 | "elif diffusion_model == '512x512_diffusion_uncond_finetune_008100':\n",
2217 | " if os.path.exists(model_512_path) and check_model_SHA:\n",
2218 | " print('Checking 512 Diffusion File')\n",
2219 | " with open(model_512_path,\"rb\") as f:\n",
2220 | " bytes = f.read() \n",
2221 | " hash = hashlib.sha256(bytes).hexdigest();\n",
2222 | " if hash == model_512_SHA:\n",
2223 | " print('512 Model SHA matches')\n",
2224 | " model_512_downloaded = True\n",
2225 | " else: \n",
2226 | " print(\"512 Model SHA doesn't match, redownloading...\")\n",
2227 | " !wget --continue {model_512_link} -P {model_path}\n",
2228 | " model_512_downloaded = True\n",
2229 | " elif os.path.exists(model_512_path) and not check_model_SHA or model_512_downloaded == True:\n",
2230 | " print('512 Model already downloaded, check check_model_SHA if the file is corrupt')\n",
2231 | " else: \n",
2232 | " !wget --continue {model_512_link} -P {model_path}\n",
2233 | " model_512_downloaded = True\n",
2234 | "\n",
2235 | "\n",
2236 | "# Download the secondary diffusion model v2\n",
2237 | "if use_secondary_model == True:\n",
2238 | " if os.path.exists(model_secondary_path) and check_model_SHA:\n",
2239 | " print('Checking Secondary Diffusion File')\n",
2240 | " with open(model_secondary_path,\"rb\") as f:\n",
2241 | " bytes = f.read() \n",
2242 | " hash = hashlib.sha256(bytes).hexdigest();\n",
2243 | " if hash == model_secondary_SHA:\n",
2244 | " print('Secondary Model SHA matches')\n",
2245 | " model_secondary_downloaded = True\n",
2246 | " else: \n",
2247 | " print(\"Secondary Model SHA doesn't match, redownloading...\")\n",
2248 | " !wget --continue {model_secondary_link} -P {model_path}\n",
2249 | " model_secondary_downloaded = True\n",
2250 | " elif os.path.exists(model_secondary_path) and not check_model_SHA or model_secondary_downloaded == True:\n",
2251 | " print('Secondary Model already downloaded, check check_model_SHA if the file is corrupt')\n",
2252 | " else: \n",
2253 | " !wget --continue {model_secondary_link} -P {model_path}\n",
2254 | " model_secondary_downloaded = True\n",
2255 | "\n",
2256 | "model_config = model_and_diffusion_defaults()\n",
2257 | "if diffusion_model == '512x512_diffusion_uncond_finetune_008100':\n",
2258 | " model_config.update({\n",
2259 | " 'attention_resolutions': '32, 16, 8',\n",
2260 | " 'class_cond': False,\n",
2261 | " 'diffusion_steps': diffusion_steps,\n",
2262 | " 'rescale_timesteps': True,\n",
2263 | " 'timestep_respacing': timestep_respacing,\n",
2264 | " 'image_size': 512,\n",
2265 | " 'learn_sigma': True,\n",
2266 | " 'noise_schedule': 'linear',\n",
2267 | " 'num_channels': 256,\n",
2268 | " 'num_head_channels': 64,\n",
2269 | " 'num_res_blocks': 2,\n",
2270 | " 'resblock_updown': True,\n",
2271 | " 'use_checkpoint': use_checkpoint,\n",
2272 | " 'use_fp16': True,\n",
2273 | " 'use_scale_shift_norm': True,\n",
2274 | " })\n",
2275 | "elif diffusion_model == '256x256_diffusion_uncond':\n",
2276 | " model_config.update({\n",
2277 | " 'attention_resolutions': '32, 16, 8',\n",
2278 | " 'class_cond': False,\n",
2279 | " 'diffusion_steps': diffusion_steps,\n",
2280 | " 'rescale_timesteps': True,\n",
2281 | " 'timestep_respacing': timestep_respacing,\n",
2282 | " 'image_size': 256,\n",
2283 | " 'learn_sigma': True,\n",
2284 | " 'noise_schedule': 'linear',\n",
2285 | " 'num_channels': 256,\n",
2286 | " 'num_head_channels': 64,\n",
2287 | " 'num_res_blocks': 2,\n",
2288 | " 'resblock_updown': True,\n",
2289 | " 'use_checkpoint': use_checkpoint,\n",
2290 | " 'use_fp16': True,\n",
2291 | " 'use_scale_shift_norm': True,\n",
2292 | " })\n",
2293 | "\n",
2294 | "secondary_model_ver = 2\n",
2295 | "model_default = model_config['image_size']\n",
2296 | "\n",
2297 | "\n",
2298 | "\n",
2299 | "if secondary_model_ver == 2:\n",
2300 | " secondary_model = SecondaryDiffusionImageNet2()\n",
2301 | " secondary_model.load_state_dict(torch.load(f'{model_path}/secondary_model_imagenet_2.pth', map_location='cpu'))\n",
2302 | "secondary_model.eval().requires_grad_(False).to(device)\n",
2303 | "\n",
2304 | "clip_models = []\n",
2305 | "if ViTB32 is True: clip_models.append(clip.load('ViT-B/32', jit=False)[0].eval().requires_grad_(False).to(device)) \n",
2306 | "if ViTB16 is True: clip_models.append(clip.load('ViT-B/16', jit=False)[0].eval().requires_grad_(False).to(device) ) \n",
2307 | "if ViTL14 is True: clip_models.append(clip.load('ViT-L/14', jit=False)[0].eval().requires_grad_(False).to(device) ) \n",
2308 | "if RN50 is True: clip_models.append(clip.load('RN50', jit=False)[0].eval().requires_grad_(False).to(device))\n",
2309 | "if RN50x4 is True: clip_models.append(clip.load('RN50x4', jit=False)[0].eval().requires_grad_(False).to(device)) \n",
2310 | "if RN50x16 is True: clip_models.append(clip.load('RN50x16', jit=False)[0].eval().requires_grad_(False).to(device)) \n",
2311 | "if RN50x64 is True: clip_models.append(clip.load('RN50x64', jit=False)[0].eval().requires_grad_(False).to(device)) \n",
2312 | "if RN101 is True: clip_models.append(clip.load('RN101', jit=False)[0].eval().requires_grad_(False).to(device)) \n",
2313 | "\n",
2314 | "if SLIPB16:\n",
2315 | " SLIPB16model = SLIP_VITB16(ssl_mlp_dim=4096, ssl_emb_dim=256)\n",
2316 | " if not os.path.exists(f'{model_path}/slip_base_100ep.pt'):\n",
2317 | " !wget https://dl.fbaipublicfiles.com/slip/slip_base_100ep.pt -P {model_path}\n",
2318 | " sd = torch.load(f'{model_path}/slip_base_100ep.pt')\n",
2319 | " real_sd = {}\n",
2320 | " for k, v in sd['state_dict'].items():\n",
2321 | " real_sd['.'.join(k.split('.')[1:])] = v\n",
2322 | " del sd\n",
2323 | " SLIPB16model.load_state_dict(real_sd)\n",
2324 | " SLIPB16model.requires_grad_(False).eval().to(device)\n",
2325 | "\n",
2326 | " clip_models.append(SLIPB16model)\n",
2327 | "\n",
2328 | "if SLIPL16:\n",
2329 | " SLIPL16model = SLIP_VITL16(ssl_mlp_dim=4096, ssl_emb_dim=256)\n",
2330 | " if not os.path.exists(f'{model_path}/slip_large_100ep.pt'):\n",
2331 | " !wget https://dl.fbaipublicfiles.com/slip/slip_large_100ep.pt -P {model_path}\n",
2332 | " sd = torch.load(f'{model_path}/slip_large_100ep.pt')\n",
2333 | " real_sd = {}\n",
2334 | " for k, v in sd['state_dict'].items():\n",
2335 | " real_sd['.'.join(k.split('.')[1:])] = v\n",
2336 | " del sd\n",
2337 | " SLIPL16model.load_state_dict(real_sd)\n",
2338 | " SLIPL16model.requires_grad_(False).eval().to(device)\n",
2339 | "\n",
2340 | " clip_models.append(SLIPL16model)\n",
2341 | "\n",
2342 | "normalize = T.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711])\n",
2343 | "lpips_model = lpips.LPIPS(net='vgg').to(device)"
2344 | ]
2345 | },
2346 | {
2347 | "cell_type": "markdown",
2348 | "metadata": {
2349 | "id": "kjtsXaszn-bB"
2350 | },
2351 | "source": [
2352 | "# 3. Settings"
2353 | ]
2354 | },
2355 | {
2356 | "cell_type": "code",
2357 | "execution_count": null,
2358 | "metadata": {
2359 | "cellView": "form",
2360 | "id": "U0PwzFZbLfcy"
2361 | },
2362 | "outputs": [],
2363 | "source": [
2364 | "#@markdown ####**Basic Settings:**\n",
2365 | "batch_name = 'TimeToDiscoTurbo3' #@param{type: 'string'}\n",
2366 | "steps = 500 #@param [25,50,100,150,250,500,1000]{type: 'raw', allow-input: true}\n",
2367 | "width_height = [800, 450]#[1280, 720]# [800, 450] #[1600, 900] #@param{type: 'raw'}\n",
2368 | "clip_guidance_scale = 35000 #@param{type: 'number'}\n",
2369 | "tv_scale = 1#@param{type: 'number'}\n",
2370 | "range_scale = 450#@param{type: 'number'}\n",
2371 | "sat_scale = 10000#@param{type: 'number'}\n",
2372 | "cutn_batches = 1 #@param{type: 'number'}\n",
2373 | "skip_augs = False#@param{type: 'boolean'}\n",
2374 | "\n",
2375 | "#@markdown ---\n",
2376 | "\n",
2377 | "#@markdown ####**Init Settings:**\n",
2378 | "init_image = None #@param{type: 'string'}\n",
2379 | "init_scale = 1000 #@param{type: 'integer'} default 1000\n",
2380 | "skip_steps = int(steps * 0.5) if init_image else steps // 5 #@param{type: 'integer'}\n",
2381 | "#@markdown *Make sure you set skip_steps to ~50% of your steps if you want to use an init image.*\n",
2382 | "\n",
2383 | "#Get corrected sizes\n",
2384 | "side_x = (width_height[0]//64)*64;\n",
2385 | "side_y = (width_height[1]//64)*64;\n",
2386 | "if side_x != width_height[0] or side_y != width_height[1]:\n",
2387 | " print(f'Changing output size to {side_x}x{side_y}. Dimensions must by multiples of 64.')\n",
2388 | "\n",
2389 | "#Update Model Settings\n",
2390 | "timestep_respacing = f'ddim{steps}'\n",
2391 | "diffusion_steps = (1000//steps)*steps if steps < 1000 else steps\n",
2392 | "model_config.update({\n",
2393 | " 'timestep_respacing': timestep_respacing,\n",
2394 | " 'diffusion_steps': diffusion_steps,\n",
2395 | "})\n",
2396 | "\n",
2397 | "#Make folder for batch\n",
2398 | "batchFolder = f'{outDirPath}/{batch_name}'\n",
2399 | "createPath(batchFolder)\n"
2400 | ]
2401 | },
2402 | {
2403 | "cell_type": "markdown",
2404 | "metadata": {
2405 | "id": "CnkTNXJAPzL2"
2406 | },
2407 | "source": [
2408 | "###Animation Settings"
2409 | ]
2410 | },
2411 | {
2412 | "cell_type": "code",
2413 | "execution_count": null,
2414 | "metadata": {
2415 | "cellView": "form",
2416 | "id": "djPY2_4kHgV2"
2417 | },
2418 | "outputs": [],
2419 | "source": [
2420 | "#@markdown ####**Animation Mode:**\n",
2421 | "animation_mode = '3D' #@param ['None', '2D', '3D', 'Video Input'] {type:'string'}\n",
2422 | "#@markdown *For animation, you probably want to turn `cutn_batches` to 1 to make it quicker.*\n",
2423 | "\n",
2424 | "\n",
2425 | "#@markdown ---\n",
2426 | "\n",
2427 | "#@markdown ####**Video Input Settings:**\n",
2428 | "if is_colab:\n",
2429 | " video_init_path = \"/content/training.mp4\" #@param {type: 'string'}\n",
2430 | "else:\n",
2431 | " video_init_path = \"training.mp4\" #@param {type: 'string'}\n",
2432 | "extract_nth_frame = 2 #@param {type:\"number\"} \n",
2433 | "\n",
2434 | "if animation_mode == \"Video Input\":\n",
2435 | " if is_colab:\n",
2436 | " videoFramesFolder = f'/content/videoFrames'\n",
2437 | " else:\n",
2438 | " videoFramesFolder = f'videoFrames'\n",
2439 | " createPath(videoFramesFolder)\n",
2440 | " print(f\"Exporting Video Frames (1 every {extract_nth_frame})...\")\n",
2441 | " try:\n",
2442 | " !rm {videoFramesFolder}/*.jpg\n",
2443 | " except:\n",
2444 | " print('')\n",
2445 | " vf = f'\"select=not(mod(n\\,{extract_nth_frame}))\"'\n",
2446 | " !ffmpeg -i {video_init_path} -vf {vf} -vsync vfr -q:v 2 -loglevel error -stats {videoFramesFolder}/%04d.jpg\n",
2447 | "\n",
2448 | "\n",
2449 | "#@markdown ---\n",
2450 | "\n",
2451 | "#@markdown ####**2D/3D Animation Settings:**\n",
2452 | "#@markdown `zoom` is a multiplier of dimensions, 1 is no zoom.\n",
2453 | "\n",
2454 | "key_frames = True #@param {type:\"boolean\"}\n",
2455 | "max_frames = 100000#@param {type:\"number\"}\n",
2456 | "\n",
2457 | "if animation_mode == \"Video Input\":\n",
2458 | " max_frames = len(glob(f'{videoFramesFolder}/*.jpg'))\n",
2459 | "\n",
2460 | "interp_spline = 'Linear' #Do not change, currently will not look good. param ['Linear','Quadratic','Cubic']{type:\"string\"}\n",
2461 | "angle = \"0:(0)\"#@param {type:\"string\"}\n",
2462 | "zoom = \"0: (1)\"#@param {type:\"string\"}\n",
2463 | "translation_x = \"0:(0.1111)\"#\"0:(0),22:(4.465),41:(0.355),61:(1.163),69:(-1.358),85:(0.079),107:(-0.843),116:(-4.123),136:(1.029),157:(1.074),166:(-3.439),187:(-0.214),209:(0.357),219:(-4.708),239:(0.49)\"#@param {type:\"string\"}\n",
2464 | "translation_y = \"0:(0)\"#\"0:(0.35), 2000:(1.4)\"#\"0:(0),22:(2.42),41:(-0.019),61:(0.24),69:(-2.381),85:(-0.358),107:(0.097),116:(1.479),136:(0.425),157:(-0.401),166:(-2.366),187:(-0.508),209:(-0.525),219:(0.683),239:(0.351)\"#@param {type:\"string\"}\n",
2465 | "translation_z = \"0:(1)\"#\"0:(2.5), 2000:(10)\"#@param {type:\"string\"}\n",
2466 | "rotation_3d_x = \"0:(0)\"#\"0:(0),22:(0.013),41:(-0.004),61:(-0.001),69:(-0.022),85:(0.005),107:(-0.002),116:(0.026),136:(0.004),157:(0.001),166:(0.027),187:(0.002),209:(-0.005),219:(-0.01),239:(-0.004)\"#@param {type:\"string\"}\n",
2467 | "rotation_3d_y = \"0:(-0.0003)\"#\"0:(0),21:(0.02),38:(0.001),53:(0.001),62:(0.016),82:(-0.004),102:(0.005),113:(0.012),130:(0.006),149:(0.002),159:(0.006),179:(0.005),200:(0.001),210:(-0.002),231:(0.005)\"#@param {type:\"string\"}\n",
2468 | "rotation_3d_z = \"0:(0)\"#\"0:(0),22:(0.007),41:(0.001),61:(0.005),69:(0.014),85:(-0.0),107:(-0.002),116:(0.028),136:(0.0),157:(0.003),166:(0.02),187:(-0.001),209:(-0.004),219:(-0.001),239:(-0.001)\"#@param {type:\"string\"}\n",
2469 | "midas_depth_model = \"dpt_large\"#@param {type:\"string\"}\n",
2470 | "midas_weight = 0.3#@param {type:\"number\"}\n",
2471 | "near_plane = 200#@param {type:\"number\"}\n",
2472 | "far_plane = 10000#@param {type:\"number\"}\n",
2473 | "fov = 40#120#@param {type:\"number\"}\n",
2474 | "padding_mode = 'border'#@param {type:\"string\"}\n",
2475 | "sampling_mode = 'bicubic'#@param {type:\"string\"}\n",
2476 | "#======= TURBO MODE\n",
2477 | "#@markdown ---\n",
2478 | "#@markdown ####**Turbo Mode (3D anim only):**\n",
2479 | "#@markdown (Starts after frame 10,) skips diffusion steps and just uses depth map to warp images for skipped frames.\n",
2480 | "#@markdown Speeds up rendering by 2x-4x, and may improve frame coherence.\n",
2481 | "\n",
2482 | "turbo_mode = True #@param {type:\"boolean\"}\n",
2483 | "turbo_steps = \"3\" #@param [\"2\",\"3\",\"4\",\"5\",\"6\"] {type:'string'}\n",
2484 | "if turbo_mode == True:\n",
2485 | " try:\n",
2486 | " #Make folder for turbo\n",
2487 | " turboFolder = f'{outDirPath}/{batch_name}/turbo'\n",
2488 | " createPath(turboFolder)\n",
2489 | " except OSError:\n",
2490 | " pass # already exists\n",
2491 | "#@markdown ---\n",
2492 | "\n",
2493 | "#@markdown ####**Coherency Settings:**\n",
2494 | "#@markdown `frame_scale` tries to guide the new frame to looking like the old one. A good default is 1500.\n",
2495 | "frames_scale = 1500 #@param{type: 'integer'} Default was 35000\n",
2496 | "#@markdown `frame_skip_steps` will blur the previous frame - higher values will flicker less but struggle to add enough new detail to zoom into.\n",
2497 | "frames_skip_steps = '70%' #@param ['40%', '50%', '60%', '70%', '80%'] {type: 'string'}\n",
2498 | "\n",
2499 | "\n",
2500 | "def parse_key_frames(string, prompt_parser=None):\n",
2501 | " \"\"\"Given a string representing frame numbers paired with parameter values at that frame,\n",
2502 | " return a dictionary with the frame numbers as keys and the parameter values as the values.\n",
2503 | "\n",
2504 | " Parameters\n",
2505 | " ----------\n",
2506 | " string: string\n",
2507 | " Frame numbers paired with parameter values at that frame number, in the format\n",
2508 | " 'framenumber1: (parametervalues1), framenumber2: (parametervalues2), ...'\n",
2509 | " prompt_parser: function or None, optional\n",
2510 | " If provided, prompt_parser will be applied to each string of parameter values.\n",
2511 | " \n",
2512 | " Returns\n",
2513 | " -------\n",
2514 | " dict\n",
2515 | " Frame numbers as keys, parameter values at that frame number as values\n",
2516 | "\n",
2517 | " Raises\n",
2518 | " ------\n",
2519 | " RuntimeError\n",
2520 | " If the input string does not match the expected format.\n",
2521 | " \n",
2522 | " Examples\n",
2523 | " --------\n",
2524 | " >>> parse_key_frames(\"10:(Apple: 1| Orange: 0), 20: (Apple: 0| Orange: 1| Peach: 1)\")\n",
2525 | " {10: 'Apple: 1| Orange: 0', 20: 'Apple: 0| Orange: 1| Peach: 1'}\n",
2526 | "\n",
2527 | " >>> parse_key_frames(\"10:(Apple: 1| Orange: 0), 20: (Apple: 0| Orange: 1| Peach: 1)\", prompt_parser=lambda x: x.lower()))\n",
2528 | " {10: 'apple: 1| orange: 0', 20: 'apple: 0| orange: 1| peach: 1'}\n",
2529 | " \"\"\"\n",
2530 | " import re\n",
2531 | " pattern = r'((?P[0-9]+):[\\s]*[\\(](?P[\\S\\s]*?)[\\)])'\n",
2532 | " frames = dict()\n",
2533 | " for match_object in re.finditer(pattern, string):\n",
2534 | " frame = int(match_object.groupdict()['frame'])\n",
2535 | " param = match_object.groupdict()['param']\n",
2536 | " if prompt_parser:\n",
2537 | " frames[frame] = prompt_parser(param)\n",
2538 | " else:\n",
2539 | " frames[frame] = param\n",
2540 | "\n",
2541 | " if frames == {} and len(string) != 0:\n",
2542 | " raise RuntimeError('Key Frame string not correctly formatted')\n",
2543 | " return frames\n",
2544 | "\n",
2545 | "def get_inbetweens(key_frames, integer=False):\n",
2546 | " \"\"\"Given a dict with frame numbers as keys and a parameter value as values,\n",
2547 | " return a pandas Series containing the value of the parameter at every frame from 0 to max_frames.\n",
2548 | " Any values not provided in the input dict are calculated by linear interpolation between\n",
2549 | " the values of the previous and next provided frames. If there is no previous provided frame, then\n",
2550 | " the value is equal to the value of the next provided frame, or if there is no next provided frame,\n",
2551 | " then the value is equal to the value of the previous provided frame. If no frames are provided,\n",
2552 | " all frame values are NaN.\n",
2553 | "\n",
2554 | " Parameters\n",
2555 | " ----------\n",
2556 | " key_frames: dict\n",
2557 | " A dict with integer frame numbers as keys and numerical values of a particular parameter as values.\n",
2558 | " integer: Bool, optional\n",
2559 | " If True, the values of the output series are converted to integers.\n",
2560 | " Otherwise, the values are floats.\n",
2561 | " \n",
2562 | " Returns\n",
2563 | " -------\n",
2564 | " pd.Series\n",
2565 | " A Series with length max_frames representing the parameter values for each frame.\n",
2566 | " \n",
2567 | " Examples\n",
2568 | " --------\n",
2569 | " >>> max_frames = 5\n",
2570 | " >>> get_inbetweens({1: 5, 3: 6})\n",
2571 | " 0 5.0\n",
2572 | " 1 5.0\n",
2573 | " 2 5.5\n",
2574 | " 3 6.0\n",
2575 | " 4 6.0\n",
2576 | " dtype: float64\n",
2577 | "\n",
2578 | " >>> get_inbetweens({1: 5, 3: 6}, integer=True)\n",
2579 | " 0 5\n",
2580 | " 1 5\n",
2581 | " 2 5\n",
2582 | " 3 6\n",
2583 | " 4 6\n",
2584 | " dtype: int64\n",
2585 | " \"\"\"\n",
2586 | " key_frame_series = pd.Series([np.nan for a in range(max_frames)])\n",
2587 | "\n",
2588 | " for i, value in key_frames.items():\n",
2589 | " key_frame_series[i] = value\n",
2590 | " key_frame_series = key_frame_series.astype(float)\n",
2591 | " \n",
2592 | " interp_method = interp_spline\n",
2593 | "\n",
2594 | " if interp_method == 'Cubic' and len(key_frames.items()) <=3:\n",
2595 | " interp_method = 'Quadratic'\n",
2596 | " \n",
2597 | " if interp_method == 'Quadratic' and len(key_frames.items()) <= 2:\n",
2598 | " interp_method = 'Linear'\n",
2599 | " \n",
2600 | " \n",
2601 | " key_frame_series[0] = key_frame_series[key_frame_series.first_valid_index()]\n",
2602 | " key_frame_series[max_frames-1] = key_frame_series[key_frame_series.last_valid_index()]\n",
2603 | " # key_frame_series = key_frame_series.interpolate(method=intrp_method,order=1, limit_direction='both')\n",
2604 | " key_frame_series = key_frame_series.interpolate(method=interp_method.lower(),limit_direction='both')\n",
2605 | " if integer:\n",
2606 | " return key_frame_series.astype(int)\n",
2607 | " return key_frame_series\n",
2608 | "\n",
2609 | "def split_prompts(prompts):\n",
2610 | " prompt_series = pd.Series([np.nan for a in range(max_frames)])\n",
2611 | " for i, prompt in prompts.items():\n",
2612 | " prompt_series[i] = prompt\n",
2613 | " # prompt_series = prompt_series.astype(str)\n",
2614 | " prompt_series = prompt_series.ffill().bfill()\n",
2615 | " return prompt_series\n",
2616 | "\n",
2617 | "if key_frames:\n",
2618 | " try:\n",
2619 | " angle_series = get_inbetweens(parse_key_frames(angle))\n",
2620 | " except RuntimeError as e:\n",
2621 | " print(\n",
2622 | " \"WARNING: You have selected to use key frames, but you have not \"\n",
2623 | " \"formatted `angle` correctly for key frames.\\n\"\n",
2624 | " \"Attempting to interpret `angle` as \"\n",
2625 | " f'\"0: ({angle})\"\\n'\n",
2626 | " \"Please read the instructions to find out how to use key frames \"\n",
2627 | " \"correctly.\\n\"\n",
2628 | " )\n",
2629 | " angle = f\"0: ({angle})\"\n",
2630 | " angle_series = get_inbetweens(parse_key_frames(angle))\n",
2631 | "\n",
2632 | " try:\n",
2633 | " zoom_series = get_inbetweens(parse_key_frames(zoom))\n",
2634 | " except RuntimeError as e:\n",
2635 | " print(\n",
2636 | " \"WARNING: You have selected to use key frames, but you have not \"\n",
2637 | " \"formatted `zoom` correctly for key frames.\\n\"\n",
2638 | " \"Attempting to interpret `zoom` as \"\n",
2639 | " f'\"0: ({zoom})\"\\n'\n",
2640 | " \"Please read the instructions to find out how to use key frames \"\n",
2641 | " \"correctly.\\n\"\n",
2642 | " )\n",
2643 | " zoom = f\"0: ({zoom})\"\n",
2644 | " zoom_series = get_inbetweens(parse_key_frames(zoom))\n",
2645 | "\n",
2646 | " try:\n",
2647 | " translation_x_series = get_inbetweens(parse_key_frames(translation_x))\n",
2648 | " except RuntimeError as e:\n",
2649 | " print(\n",
2650 | " \"WARNING: You have selected to use key frames, but you have not \"\n",
2651 | " \"formatted `translation_x` correctly for key frames.\\n\"\n",
2652 | " \"Attempting to interpret `translation_x` as \"\n",
2653 | " f'\"0: ({translation_x})\"\\n'\n",
2654 | " \"Please read the instructions to find out how to use key frames \"\n",
2655 | " \"correctly.\\n\"\n",
2656 | " )\n",
2657 | " translation_x = f\"0: ({translation_x})\"\n",
2658 | " translation_x_series = get_inbetweens(parse_key_frames(translation_x))\n",
2659 | "\n",
2660 | " try:\n",
2661 | " translation_y_series = get_inbetweens(parse_key_frames(translation_y))\n",
2662 | " except RuntimeError as e:\n",
2663 | " print(\n",
2664 | " \"WARNING: You have selected to use key frames, but you have not \"\n",
2665 | " \"formatted `translation_y` correctly for key frames.\\n\"\n",
2666 | " \"Attempting to interpret `translation_y` as \"\n",
2667 | " f'\"0: ({translation_y})\"\\n'\n",
2668 | " \"Please read the instructions to find out how to use key frames \"\n",
2669 | " \"correctly.\\n\"\n",
2670 | " )\n",
2671 | " translation_y = f\"0: ({translation_y})\"\n",
2672 | " translation_y_series = get_inbetweens(parse_key_frames(translation_y))\n",
2673 | "\n",
2674 | " try:\n",
2675 | " translation_z_series = get_inbetweens(parse_key_frames(translation_z))\n",
2676 | " except RuntimeError as e:\n",
2677 | " print(\n",
2678 | " \"WARNING: You have selected to use key frames, but you have not \"\n",
2679 | " \"formatted `translation_z` correctly for key frames.\\n\"\n",
2680 | " \"Attempting to interpret `translation_z` as \"\n",
2681 | " f'\"0: ({translation_z})\"\\n'\n",
2682 | " \"Please read the instructions to find out how to use key frames \"\n",
2683 | " \"correctly.\\n\"\n",
2684 | " )\n",
2685 | " translation_z = f\"0: ({translation_z})\"\n",
2686 | " translation_z_series = get_inbetweens(parse_key_frames(translation_z))\n",
2687 | "\n",
2688 | " try:\n",
2689 | " rotation_3d_x_series = get_inbetweens(parse_key_frames(rotation_3d_x))\n",
2690 | " except RuntimeError as e:\n",
2691 | " print(\n",
2692 | " \"WARNING: You have selected to use key frames, but you have not \"\n",
2693 | " \"formatted `rotation_3d_x` correctly for key frames.\\n\"\n",
2694 | " \"Attempting to interpret `rotation_3d_x` as \"\n",
2695 | " f'\"0: ({rotation_3d_x})\"\\n'\n",
2696 | " \"Please read the instructions to find out how to use key frames \"\n",
2697 | " \"correctly.\\n\"\n",
2698 | " )\n",
2699 | " rotation_3d_x = f\"0: ({rotation_3d_x})\"\n",
2700 | " rotation_3d_x_series = get_inbetweens(parse_key_frames(rotation_3d_x))\n",
2701 | "\n",
2702 | " try:\n",
2703 | " rotation_3d_y_series = get_inbetweens(parse_key_frames(rotation_3d_y))\n",
2704 | " except RuntimeError as e:\n",
2705 | " print(\n",
2706 | " \"WARNING: You have selected to use key frames, but you have not \"\n",
2707 | " \"formatted `rotation_3d_y` correctly for key frames.\\n\"\n",
2708 | " \"Attempting to interpret `rotation_3d_y` as \"\n",
2709 | " f'\"0: ({rotation_3d_y})\"\\n'\n",
2710 | " \"Please read the instructions to find out how to use key frames \"\n",
2711 | " \"correctly.\\n\"\n",
2712 | " )\n",
2713 | " rotation_3d_y = f\"0: ({rotation_3d_y})\"\n",
2714 | " rotation_3d_y_series = get_inbetweens(parse_key_frames(rotation_3d_y))\n",
2715 | "\n",
2716 | " try:\n",
2717 | " rotation_3d_z_series = get_inbetweens(parse_key_frames(rotation_3d_z))\n",
2718 | " except RuntimeError as e:\n",
2719 | " print(\n",
2720 | " \"WARNING: You have selected to use key frames, but you have not \"\n",
2721 | " \"formatted `rotation_3d_z` correctly for key frames.\\n\"\n",
2722 | " \"Attempting to interpret `rotation_3d_z` as \"\n",
2723 | " f'\"0: ({rotation_3d_z})\"\\n'\n",
2724 | " \"Please read the instructions to find out how to use key frames \"\n",
2725 | " \"correctly.\\n\"\n",
2726 | " )\n",
2727 | " rotation_3d_z = f\"0: ({rotation_3d_z})\"\n",
2728 | " rotation_3d_z_series = get_inbetweens(parse_key_frames(rotation_3d_z))\n",
2729 | "\n",
2730 | "else:\n",
2731 | " angle = float(angle)\n",
2732 | " zoom = float(zoom)\n",
2733 | " translation_x = float(translation_x)\n",
2734 | " translation_y = float(translation_y)\n",
2735 | " translation_z = float(translation_z)\n",
2736 | " rotation_3d_x = float(rotation_3d_x)\n",
2737 | " rotation_3d_y = float(rotation_3d_y)\n",
2738 | " rotation_3d_z = float(rotation_3d_z)"
2739 | ]
2740 | },
2741 | {
2742 | "cell_type": "markdown",
2743 | "metadata": {
2744 | "id": "u1VHzHvNx5fd"
2745 | },
2746 | "source": [
2747 | "### Extra Settings\n",
2748 | " Partial Saves, Diffusion Sharpening, Advanced Settings, Cutn Scheduling"
2749 | ]
2750 | },
2751 | {
2752 | "cell_type": "code",
2753 | "execution_count": null,
2754 | "metadata": {
2755 | "cellView": "form",
2756 | "id": "lCLMxtILyAHA"
2757 | },
2758 | "outputs": [],
2759 | "source": [
2760 | "#@markdown ####**Saving:**\n",
2761 | "\n",
2762 | "intermediate_saves = 0#@param{type: 'raw'}\n",
2763 | "intermediates_in_subfolder = True #@param{type: 'boolean'}\n",
2764 | "#@markdown Intermediate steps will save a copy at your specified intervals. You can either format it as a single integer or a list of specific steps \n",
2765 | "\n",
2766 | "#@markdown A value of `2` will save a copy at 33% and 66%. 0 will save none.\n",
2767 | "\n",
2768 | "#@markdown A value of `[5, 9, 34, 45]` will save at steps 5, 9, 34, and 45. (Make sure to include the brackets)\n",
2769 | "\n",
2770 | "\n",
2771 | "if type(intermediate_saves) is not list:\n",
2772 | " if intermediate_saves:\n",
2773 | " steps_per_checkpoint = math.floor((steps - skip_steps - 1) // (intermediate_saves+1))\n",
2774 | " steps_per_checkpoint = steps_per_checkpoint if steps_per_checkpoint > 0 else 1\n",
2775 | " print(f'Will save every {steps_per_checkpoint} steps')\n",
2776 | " else:\n",
2777 | " steps_per_checkpoint = steps+10\n",
2778 | "else:\n",
2779 | " steps_per_checkpoint = None\n",
2780 | "\n",
2781 | "if intermediate_saves and intermediates_in_subfolder is True:\n",
2782 | " partialFolder = f'{batchFolder}/partials'\n",
2783 | " createPath(partialFolder)\n",
2784 | "\n",
2785 | " #@markdown ---\n",
2786 | "\n",
2787 | "#@markdown ####**SuperRes Sharpening:**\n",
2788 | "#@markdown *Sharpen each image using latent-diffusion. Does not run in animation mode. `keep_unsharp` will save both versions.*\n",
2789 | "sharpen_preset = 'Off' #@param ['Off', 'Faster', 'Fast', 'Slow', 'Very Slow']\n",
2790 | "keep_unsharp = True #@param{type: 'boolean'}\n",
2791 | "\n",
2792 | "if sharpen_preset != 'Off' and keep_unsharp is True:\n",
2793 | " unsharpenFolder = f'{batchFolder}/unsharpened'\n",
2794 | " createPath(unsharpenFolder)\n",
2795 | "\n",
2796 | "\n",
2797 | " #@markdown ---\n",
2798 | "\n",
2799 | "#@markdown ####**Advanced Settings:**\n",
2800 | "#@markdown *There are a few extra advanced settings available if you double click this cell.*\n",
2801 | "\n",
2802 | "#@markdown *Perlin init will replace your init, so uncheck if using one.*\n",
2803 | "\n",
2804 | "perlin_init = False #@param{type: 'boolean'}\n",
2805 | "perlin_mode = 'mixed' #@param ['mixed', 'color', 'gray']\n",
2806 | "set_seed = 'random_seed' #@param{type: 'string'}\n",
2807 | "eta = 0.2#@param{type: 'number'}\n",
2808 | "clamp_grad = True #@param{type: 'boolean'}\n",
2809 | "clamp_max = 0.25 #@param{type: 'number'}\n",
2810 | "\n",
2811 | "\n",
2812 | "### EXTRA ADVANCED SETTINGS:\n",
2813 | "randomize_class = True\n",
2814 | "clip_denoised = False\n",
2815 | "fuzzy_prompt = False\n",
2816 | "rand_mag = 0.1\n",
2817 | "\n",
2818 | "\n",
2819 | " #@markdown ---\n",
2820 | "\n",
2821 | "#@markdown ####**Cutn Scheduling:**\n",
2822 | "#@markdown Format: `[40]*400+[20]*600` = 40 cuts for the first 400 /1000 steps, then 20 for the last 600/1000\n",
2823 | "\n",
2824 | "#@markdown cut_overview and cut_innercut are cumulative for total cutn on any given step. Overview cuts see the entire image and are good for early structure, innercuts are your standard cutn.\n",
2825 | "# default overview = \"[8]*30+[0]*297000, innercut = \"[8]*30+[32]*297000\"\n",
2826 | "cut_overview = \"[16]*30+[8]*297000\" #@param {type: 'string'} #\"[8]*30+[0]*2970\" #@param {type: 'string'} \n",
2827 | "cut_innercut = \"[8]*30+[24]*297000\"#@param {type: 'string'} #\"[8]*30+[32]*2970\"#@param {type: 'string'} \n",
2828 | "cut_ic_pow = 1#@param {type: 'number'} \n",
2829 | "cut_icgray_p = \"[0.2]*30+[0]*2970\"#@param {type: 'string'} \n",
2830 | "\n"
2831 | ]
2832 | },
2833 | {
2834 | "cell_type": "markdown",
2835 | "metadata": {
2836 | "id": "XIwh5RvNpk4K"
2837 | },
2838 | "source": [
2839 | "###Prompts\n",
2840 | "`animation_mode: None` will only use the first set. `animation_mode: 2D / Video` will run through them per the set frames and hold on the last one."
2841 | ]
2842 | },
2843 | {
2844 | "cell_type": "code",
2845 | "execution_count": null,
2846 | "metadata": {
2847 | "id": "BGBzhk3dpcGO"
2848 | },
2849 | "outputs": [],
2850 | "source": [
2851 | "text_prompts = {\n",
2852 | " \n",
2853 | " 0: [\"The most majestic being ever spotted in the wild\", \"trending on artstation\"],\n",
2854 | " #100: [\"This set of prompts start at frame 100\",\"This prompt has weight five:5\"],\n",
2855 | "}\n",
2856 | "\n",
2857 | "image_prompts = {\n",
2858 | " # 0:['ImagePromptsWorkButArentVeryGood.png:2',],\n",
2859 | "}"
2860 | ]
2861 | },
2862 | {
2863 | "cell_type": "markdown",
2864 | "metadata": {
2865 | "id": "Nf9hTc8YLoLx"
2866 | },
2867 | "source": [
2868 | "# 4. Diffuse!"
2869 | ]
2870 | },
2871 | {
2872 | "cell_type": "code",
2873 | "execution_count": null,
2874 | "metadata": {
2875 | "cellView": "form",
2876 | "id": "LHLiO56OfwgD",
2877 | "scrolled": false
2878 | },
2879 | "outputs": [],
2880 | "source": [
2881 | "#@title Do the Run!\n",
2882 | "#@markdown `n_batches` ignored with animation modes.\n",
2883 | "display_rate = 40 #@param{type: 'number'}\n",
2884 | "n_batches = 1 #@param{type: 'number'}\n",
2885 | "\n",
2886 | "batch_size = 1\n",
2887 | "\n",
2888 | "def move_files(start_num, end_num, old_folder, new_folder):\n",
2889 | " for i in range(start_num, end_num):\n",
2890 | " old_file = old_folder + f'/{batch_name}({batchNum})_{i:04}.png'\n",
2891 | " new_file = new_folder + f'/{batch_name}({batchNum})_{i:04}.png'\n",
2892 | " os.rename(old_file, new_file)\n",
2893 | "\n",
2894 | "#@markdown ---\n",
2895 | "\n",
2896 | "\n",
2897 | "resume_run = False #@param{type: 'boolean'}\n",
2898 | "run_to_resume = 'latest' #@param{type: 'string'}\n",
2899 | "resume_from_frame = 'latest' #@param{type: 'string'}\n",
2900 | "retain_overwritten_frames = False #@param{type: 'boolean'}\n",
2901 | "if retain_overwritten_frames is True:\n",
2902 | " retainFolder = f'{batchFolder}/retained'\n",
2903 | " createPath(retainFolder)\n",
2904 | "\n",
2905 | "\n",
2906 | "skip_step_ratio = int(frames_skip_steps.rstrip(\"%\")) / 100\n",
2907 | "calc_frames_skip_steps = math.floor(steps * skip_step_ratio)\n",
2908 | "\n",
2909 | "\n",
2910 | "if steps <= calc_frames_skip_steps:\n",
2911 | " sys.exit(\"ERROR: You can't skip more steps than your total steps\")\n",
2912 | "\n",
2913 | "if resume_run:\n",
2914 | " if run_to_resume == 'latest':\n",
2915 | " try:\n",
2916 | " batchNum\n",
2917 | " except:\n",
2918 | " batchNum = len(glob(f\"{batchFolder}/{batch_name}(*)_settings.txt\"))-1\n",
2919 | " else:\n",
2920 | " batchNum = int(run_to_resume)\n",
2921 | " if resume_from_frame == 'latest':\n",
2922 | " start_frame = len(glob(batchFolder+f\"/{batch_name}({batchNum})_*.png\"))\n",
2923 | " else:\n",
2924 | " start_frame = int(resume_from_frame)+1\n",
2925 | " if retain_overwritten_frames is True:\n",
2926 | " existing_frames = len(glob(batchFolder+f\"/{batch_name}({batchNum})_*.png\"))\n",
2927 | " frames_to_save = existing_frames - start_frame\n",
2928 | " print(f'Moving {frames_to_save} frames to the Retained folder')\n",
2929 | " move_files(start_frame, existing_frames, batchFolder, retainFolder)\n",
2930 | "else:\n",
2931 | " start_frame = 0\n",
2932 | " batchNum = len(glob(batchFolder+\"/*.txt\"))\n",
2933 | " while path.isfile(f\"{batchFolder}/{batch_name}({batchNum})_settings.txt\") is True or path.isfile(f\"{batchFolder}/{batch_name}-{batchNum}_settings.txt\") is True:\n",
2934 | " batchNum += 1\n",
2935 | "\n",
2936 | "print(f'Starting Run: {batch_name}({batchNum}) at frame {start_frame}')\n",
2937 | "\n",
2938 | "if set_seed == 'random_seed':\n",
2939 | " random.seed()\n",
2940 | " seed = random.randint(0, 2**32)\n",
2941 | " # print(f'Using seed: {seed}')\n",
2942 | "else:\n",
2943 | " seed = int(set_seed)\n",
2944 | "\n",
2945 | "args = {\n",
2946 | " 'batchNum': batchNum,\n",
2947 | " 'prompts_series':split_prompts(text_prompts) if text_prompts else None,\n",
2948 | " 'image_prompts_series':split_prompts(image_prompts) if image_prompts else None,\n",
2949 | " 'seed': seed,\n",
2950 | " 'display_rate':display_rate,\n",
2951 | " 'n_batches':n_batches if animation_mode == 'None' else 1,\n",
2952 | " 'batch_size':batch_size,\n",
2953 | " 'batch_name': batch_name,\n",
2954 | " 'steps': steps,\n",
2955 | " 'width_height': width_height,\n",
2956 | " 'clip_guidance_scale': clip_guidance_scale,\n",
2957 | " 'tv_scale': tv_scale,\n",
2958 | " 'range_scale': range_scale,\n",
2959 | " 'sat_scale': sat_scale,\n",
2960 | " 'cutn_batches': cutn_batches,\n",
2961 | " 'init_image': init_image,\n",
2962 | " 'init_scale': init_scale,\n",
2963 | " 'skip_steps': skip_steps,\n",
2964 | " 'sharpen_preset': sharpen_preset,\n",
2965 | " 'keep_unsharp': keep_unsharp,\n",
2966 | " 'side_x': side_x,\n",
2967 | " 'side_y': side_y,\n",
2968 | " 'timestep_respacing': timestep_respacing,\n",
2969 | " 'diffusion_steps': diffusion_steps,\n",
2970 | " 'animation_mode': animation_mode,\n",
2971 | " 'video_init_path': video_init_path,\n",
2972 | " 'extract_nth_frame': extract_nth_frame,\n",
2973 | " 'key_frames': key_frames,\n",
2974 | " 'max_frames': max_frames if animation_mode != \"None\" else 1,\n",
2975 | " 'interp_spline': interp_spline,\n",
2976 | " 'start_frame': start_frame,\n",
2977 | " 'angle': angle,\n",
2978 | " 'zoom': zoom,\n",
2979 | " 'translation_x': translation_x,\n",
2980 | " 'translation_y': translation_y,\n",
2981 | " 'translation_z': translation_z,\n",
2982 | " 'rotation_3d_x': rotation_3d_x,\n",
2983 | " 'rotation_3d_y': rotation_3d_y,\n",
2984 | " 'rotation_3d_z': rotation_3d_z,\n",
2985 | " 'midas_depth_model': midas_depth_model,\n",
2986 | " 'midas_weight': midas_weight,\n",
2987 | " 'near_plane': near_plane,\n",
2988 | " 'far_plane': far_plane,\n",
2989 | " 'fov': fov,\n",
2990 | " 'padding_mode': padding_mode,\n",
2991 | " 'sampling_mode': sampling_mode,\n",
2992 | " 'angle_series':angle_series,\n",
2993 | " 'zoom_series':zoom_series,\n",
2994 | " 'translation_x_series':translation_x_series,\n",
2995 | " 'translation_y_series':translation_y_series,\n",
2996 | " 'translation_z_series':translation_z_series,\n",
2997 | " 'rotation_3d_x_series':rotation_3d_x_series,\n",
2998 | " 'rotation_3d_y_series':rotation_3d_y_series,\n",
2999 | " 'rotation_3d_z_series':rotation_3d_z_series,\n",
3000 | " 'frames_scale': frames_scale,\n",
3001 | " 'calc_frames_skip_steps': calc_frames_skip_steps,\n",
3002 | " 'skip_step_ratio': skip_step_ratio,\n",
3003 | " 'calc_frames_skip_steps': calc_frames_skip_steps,\n",
3004 | " 'text_prompts': text_prompts,\n",
3005 | " 'image_prompts': image_prompts,\n",
3006 | " 'cut_overview': eval(cut_overview),\n",
3007 | " 'cut_innercut': eval(cut_innercut),\n",
3008 | " 'cut_ic_pow': cut_ic_pow,\n",
3009 | " 'cut_icgray_p': eval(cut_icgray_p),\n",
3010 | " 'intermediate_saves': intermediate_saves,\n",
3011 | " 'intermediates_in_subfolder': intermediates_in_subfolder,\n",
3012 | " 'steps_per_checkpoint': steps_per_checkpoint,\n",
3013 | " 'perlin_init': perlin_init,\n",
3014 | " 'perlin_mode': perlin_mode,\n",
3015 | " 'set_seed': set_seed,\n",
3016 | " 'eta': eta,\n",
3017 | " 'clamp_grad': clamp_grad,\n",
3018 | " 'clamp_max': clamp_max,\n",
3019 | " 'skip_augs': skip_augs,\n",
3020 | " 'randomize_class': randomize_class,\n",
3021 | " 'clip_denoised': clip_denoised,\n",
3022 | " 'fuzzy_prompt': fuzzy_prompt,\n",
3023 | " 'rand_mag': rand_mag,\n",
3024 | "}\n",
3025 | "\n",
3026 | "args = SimpleNamespace(**args)\n",
3027 | "\n",
3028 | "print('Prepping model...')\n",
3029 | "model, diffusion = create_model_and_diffusion(**model_config)\n",
3030 | "diffusion_model_path = f'{model_path}/{diffusion_model}.pt'\n",
3031 | "print(diffusion_model_path)\n",
3032 | "model.load_state_dict(torch.load(diffusion_model_path, map_location='cpu'))\n",
3033 | "model.requires_grad_(False).eval().to(device)\n",
3034 | "for name, param in model.named_parameters():\n",
3035 | " if 'qkv' in name or 'norm' in name or 'proj' in name:\n",
3036 | " param.requires_grad_()\n",
3037 | "if model_config['use_fp16']:\n",
3038 | " model.convert_to_fp16()\n",
3039 | "\n",
3040 | "gc.collect()\n",
3041 | "torch.cuda.empty_cache()\n",
3042 | "try:\n",
3043 | " do_run()\n",
3044 | "except KeyboardInterrupt:\n",
3045 | " pass\n",
3046 | "finally:\n",
3047 | " print('Seed used:', seed)\n",
3048 | " gc.collect()\n",
3049 | " torch.cuda.empty_cache()"
3050 | ]
3051 | },
3052 | {
3053 | "cell_type": "markdown",
3054 | "metadata": {
3055 | "id": "EZUg3bfzazgW"
3056 | },
3057 | "source": [
3058 | "# 5. Create the video (CURRENTLY NOT WORKING)"
3059 | ]
3060 | },
3061 | {
3062 | "cell_type": "code",
3063 | "execution_count": null,
3064 | "metadata": {
3065 | "cellView": "form",
3066 | "id": "HV54fuU3pMzJ"
3067 | },
3068 | "outputs": [],
3069 | "source": [
3070 | "# @title ### **Create video**\n",
3071 | "#@markdown Video file will save in the same folder as your images.\n",
3072 | "\n",
3073 | "skip_video_for_run_all = False #@param {type: 'boolean'}\n",
3074 | "\n",
3075 | "if skip_video_for_run_all == True:\n",
3076 | " print('Skipping video creation, uncheck skip_video_for_run_all if you want to run it')\n",
3077 | "\n",
3078 | "else:\n",
3079 | " # import subprocess in case this cell is run without the above cells\n",
3080 | " import subprocess\n",
3081 | " from base64 import b64encode\n",
3082 | "\n",
3083 | " latest_run = batchNum\n",
3084 | "\n",
3085 | " folder = batch_name #@param\n",
3086 | " run = latest_run #@param\n",
3087 | " final_frame = 'final_frame'\n",
3088 | "\n",
3089 | "\n",
3090 | " init_frame = 1#@param {type:\"number\"} This is the frame where the video will start\n",
3091 | " last_frame = final_frame#@param {type:\"number\"} You can change i to the number of the last frame you want to generate. It will raise an error if that number of frames does not exist.\n",
3092 | " fps = 12#@param {type:\"number\"}\n",
3093 | " # view_video_in_cell = True #@param {type: 'boolean'}\n",
3094 | "\n",
3095 | " frames = []\n",
3096 | " # tqdm.write('Generating video...')\n",
3097 | "\n",
3098 | " if last_frame == 'final_frame':\n",
3099 | " last_frame = len(glob(batchFolder+f\"/{folder}({run})_*.png\"))\n",
3100 | " print(f'Total frames: {last_frame}')\n",
3101 | "\n",
3102 | " image_path = f\"{outDirPath}/{folder}/{folder}({run})_%04d.png\"\n",
3103 | " filepath = f\"{outDirPath}/{folder}/{folder}({run}).mp4\"\n",
3104 | "\n",
3105 | "\n",
3106 | " cmd = [\n",
3107 | " 'ffmpeg',\n",
3108 | " '-y',\n",
3109 | " '-vcodec',\n",
3110 | " 'png',\n",
3111 | " '-r',\n",
3112 | " str(fps),\n",
3113 | " '-start_number',\n",
3114 | " str(init_frame),\n",
3115 | " #'\"' + str(init_frame) + '\"',\n",
3116 | " '-i',\n",
3117 | " '\"' + image_path + '\"',\n",
3118 | " '-frames:v',\n",
3119 | " str(last_frame+1),\n",
3120 | " '-c:v',\n",
3121 | " 'libx264',\n",
3122 | " '-vf',\n",
3123 | " f'fps={fps}',\n",
3124 | " '-pix_fmt',\n",
3125 | " 'yuv420p',\n",
3126 | " '-crf',\n",
3127 | " '17',\n",
3128 | " '-preset',\n",
3129 | " 'veryslow',\n",
3130 | " '\"' + filepath + '\"'\n",
3131 | " ]\n",
3132 | "\n",
3133 | " print(\"Going to run this command:\")\n",
3134 | " print(\" \".join(cmd))\n",
3135 | "\n",
3136 | " process = subprocess.Popen(cmd, cwd=f'{batchFolder}', stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n",
3137 | " stdout, stderr = process.communicate()\n",
3138 | " if process.returncode != 0:\n",
3139 | " print(stderr)\n",
3140 | " raise RuntimeError(stderr)\n",
3141 | " else:\n",
3142 | " print(\"The video is ready and saved to the images folder\")\n",
3143 | "\n",
3144 | " # if view_video_in_cell:\n",
3145 | " # mp4 = open(filepath,'rb').read()\n",
3146 | " # data_url = \"data:video/mp4;base64,\" + b64encode(mp4).decode()\n",
3147 | " # display.HTML(f'')"
3148 | ]
3149 | }
3150 | ],
3151 | "metadata": {
3152 | "accelerator": "GPU",
3153 | "colab": {
3154 | "collapsed_sections": [
3155 | "1YwMUyt9LHG1",
3156 | "XTu6AjLyFQUq",
3157 | "CQVtY1Ixnqx4",
3158 | "XIwh5RvNpk4K",
3159 | "EZUg3bfzazgW"
3160 | ],
3161 | "machine_shape": "hm",
3162 | "name": "Disco Diffusion v5 Turbo [w/ 3D animation]",
3163 | "private_outputs": true,
3164 | "provenance": []
3165 | },
3166 | "kernelspec": {
3167 | "display_name": "Python 3 (ipykernel)",
3168 | "language": "python",
3169 | "name": "python3"
3170 | },
3171 | "language_info": {
3172 | "codemirror_mode": {
3173 | "name": "ipython",
3174 | "version": 3
3175 | },
3176 | "file_extension": ".py",
3177 | "mimetype": "text/x-python",
3178 | "name": "python",
3179 | "nbconvert_exporter": "python",
3180 | "pygments_lexer": "ipython3",
3181 | "version": "3.9.10"
3182 | }
3183 | },
3184 | "nbformat": 4,
3185 | "nbformat_minor": 1
3186 | }
3187 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 Mohamad Zeina
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Disco Diffusion v5 Turbo, with 3D animation, running locally.
2 | Getting the latest versions of Disco Diffusion ([at time of writing this is v5 with Turbo and 3D Animation](https://colab.research.google.com/github/zippy731/disco-diffusion-turbo/blob/main/Disco_Diffusion_v5_Turbo_%5Bw_3D_animation%5D.ipynb)) to work locally, instead of colab. Including how I run this on Windows, despite some Linux only dependencies ;). Now includes an experimental batch mode to create as many videos as you want with different prompts, with only 1 run.
3 |
4 | If you run into any issues, feel free to open an issue and I’ll do my best to help troubleshoot. Be as specific as possible. For example, if you get an error message at any point you need to include this in the issue, alongside operating system and computer specs.
5 |
6 | ## Examples
7 |
8 |
9 | 
10 |
11 | 
12 |
13 | ## How to run this on Windows
14 | The same steps should work on Linux, starting from step 3.
15 |
16 | Requirements:
17 | * Nvidia GPU with at least 8GB VRAM. >12GB is recommended.
18 | * Windows 10 or 11
19 | ### Step 1: Update windows
20 |
21 | Windows 11: Windows 11 should work but it doesn't hurt to update to the latest version before continuing :) (note though that I've created and tested this on Windows 10)
22 | Windows 10: You must be running at least feature update 21H2 for your GPU to work. To check which version you're running, open cmd and type:
23 |
24 | winver
25 | If you’re on 21H2 or later, you’re good to go. If not, try updating Windows by typing “check for updates” in the start menu and using the built in tool. For me personally, the required update was not showing, but I was able to install it by using the [Windows 10 Update Assistant](https://support.microsoft.com/en-us/topic/windows-10-update-assistant-3550dfb2-a015-7765-12ea-fba2ac36fb3f).
26 |
27 | ### Step 2: install WSL2
28 | The way we’ll use Linux only dependencies is by installing the latest version of the Windows Subsystem for Linux (WSL2). This will run a virtual machine–like Ubuntu installation on Windows. However, Microsoft have implemented this at a very low level, meaning almost no performance hit and GPU support!
29 |
30 | For the latest instructions on this, follow the [official Microsoft guide](https://docs.microsoft.com/en-us/windows/wsl/install).
31 |
32 | Briefly, just open a Windows Powershell as administrator, and type:
33 |
34 | wsl —-install
35 |
36 | It might request a restart, and when you restart your computer you’ll have an app in the start menu or task bar called “Ubuntu”!
37 |
38 | ### Step 3: install Anaconda on Ubuntu
39 | We’ll need to install Anaconda inside our Ubuntu environment to manage packages easily. Open your new Ubuntu app (and fix any errors that come up on first launch. I had a few, but they were either self explanatory or fixed easily with some quick Googling).
40 | Now you want to download, then run, the Linux Anaconda installer as follows. If you’re following this much later than March 2022 you can replace the url below with the latest version from [the Anaconda website](https://www.anaconda.com/products/individual?modal=nucleus).
41 |
42 | mkdir Downloads
43 | cd Downloads
44 | wget https://repo.anaconda.com/archive/Anaconda3-2021.11-Linux-x86_64.sh
45 | bash Anaconda3-2021.11-Linux-x86_64.sh
46 |
47 | Follow the on-screen instructions. Ie type yes when it asks you to, and ask it to run conda init for you when prompted.
48 |
49 | Close your Ubuntu terminal and open it again.
50 |
51 | Now type and run
52 |
53 | conda —-help
54 | If it gives you a long list of conda options, that means it’s successfully installed Anaconda within Ubuntu!
55 |
56 | ### Step 4: creating our environment
57 |
58 | We’ll now create and activate a conda environment (inside Ubuntu) with all the appropriate dependencies.
59 |
60 | conda create -n pytorch_110
61 | conda activate pytorch_110
62 |
63 | Whenever you restart your computer, or close and open Ubuntu again, you will have to run that second command (conda activate pytorch). Now install the correct version of pytorch:
64 |
65 | conda install pytorch==1.10 torchvision torchaudio cudatoolkit==11.1 -c pytorch -c conda-forge
66 |
67 | Type y whenever prompted.
68 |
69 | Finding the above took a lot of trial and error. The difficulty was finding a pytorch and cudatoolkit combination which works with pytorch3d (required later). The above worked for me.
70 |
71 | Now install some other dependencies:
72 |
73 | conda install jupyter pandas requests matplotlib
74 | conda install opencv -c conda-forge
75 |
76 | ### Step 5, Option 1: Similar to Colab, Easy
77 | Option 1 for how to actually run the code and get images / video. Option 1 involves downloading a .ipynb, that is lightly modified from the colab notebook, editing cells and editing them inside the notebook environment.
78 | #### To use Option 1:
79 | We’ll be working within a jupyter notebook version of the colab notebook. (I’m currently working on a cleaner interface, make sure to star and watch the repo to see when this goes live).
80 |
81 | Download the jupyter notebook in this repo. If you know how, clone the repo directly into your Ubuntu distribution. To make this guide as easy to follow as possible, I’ll also show an easier way.
82 |
83 | In your Ubuntu terminal, type:
84 |
85 | explorer.exe .
86 |
87 | This will open your Ubuntu directory in Windows Explorer! Find a location you want to download the notebook to, maybe create a new folder for it.
88 |
89 | On my github repository, click “code” then download zip. Extract the zip, and copy the .ipynb file to the desired folder **in Ubuntu**. If typed explorer.exe earlier, you’ll have an Ubuntu folder open in Explorer, so you can drag and drop into this folder.
90 |
91 | In your Ubuntu terminal, run:
92 |
93 | jupyter notebook
94 |
95 | You might notice that this doesn’t automatically open jupyter in your browser. That’s okay! Just look for the URL starting with localhost, copy this, and paste it into your browser on Windows.
96 |
97 | This should open jupyter in your browser! Now navigate to the folder where you have placed your jupyter notebook, and open it. Run the cells, one by one. They should install further required dependencies and download all the models for you. Along the way, you can change any settings you would like. One of the last cells asks for “text_prompts”, which you can specify to create whatever you wish!
98 |
99 | ### Step 5, Option 2. Batch mode command line, create multiple videos in 1 run, more advanced, still experimental
100 | Option 2 for how to actually run the code and get images / video. This involves setting up a folder with settings files, which the notebook will work through 1 by 1. This will allow you to specify prompts for as many different videos as you would like, and create them all with a single run of a notebook.
101 |
102 | Some options must be specified once, and will be used for all items in the queue. Set these in "queue/master_settings.txt":
103 | * diffusion_model
104 | * use_secondary_model
105 | * ViTB32
106 | * ViTB16
107 | * ViTL14
108 | * RN101
109 | * RN50
110 | * RN50x4
111 | * RN50x16
112 | * RN50x64
113 | * width
114 | * height
115 | * init_image
116 | * translation_x
117 | * translation_y
118 | * translation_z
119 | * rotation_3d_x
120 | * rotation_3d_y
121 | * rotation_3d_z
122 | * turbo_mode
123 |
124 | Options that can be specified for each video are as follows. Must be specified in "queue/queue_1.txt", "queue/queue_2.txt" etc. Files can be created while the script is running, without interruption!
125 | * text_prompts
126 | * image_prompts
127 | * max_frames
128 | * steps
129 |
130 | Note that this is currently experimental, and intended for creating a series of videos (not images). You are welcome to submit issues for bugs / feature requests, or even your own pull requests if you want to improve this ;)
131 |
132 | Also, for my uses, fixing all those features works fine. If there are features you would like to be able to change between runs in the queue that you can't currently, feel free to start an issue or pull request.
133 | #### To use Option 2:
134 | clone the repo into your Ubuntu installation. If you don't know how to do this, click "code" and "download zip" on this repo. Copy the entire repo into a folder in your Ubuntu environment. This is usually somewhere like "\\wsl$\Ubuntu\home\USERNAME\". You can access it easily by typing explorer.exe . in your Ubuntu window.
135 |
136 | One of the folders you copied should be called "queue". Open this, and specify what settings you want in "master_settings". Then specify what prompts you want in each video, in separate files in this same folder. They should ve named "queue_1.txt" onwards, without any gaps.
137 |
138 | You can synthesize the queue files from the command line, simply navigate to the cloned repository and type:
139 |
140 | jupyter nbconvert --execute --to notebook --inplace Disco_Diffusion_v5_2_w_VR_Mode_batch_mode.ipynb
141 |
142 | The above will run all cells in the jupyter notebook from the command line. You can also run them in jupyter if you prefer. See option 1 for instructions on how to run the jupyter notebook if you'd like.
143 |
144 | That should be it! This should start creating images in your queue, 1 by 1.
145 |
146 | # FAQ
147 |
148 | 1. I'm getting CUDA errors.
149 |
150 | RuntimeError: CUDA error: unknown error
151 | CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace below might be incorrect.
152 | For debugging consider passing CUDA_LAUNCH_BLOCKING=1.
153 |
154 | If you're getting an error like the above, I've only ever known this to happen if you're using up too much VRAM.
155 | Reducing by doing 1 or all of the following:
156 | * In 2. Diffusion and CLIP model settings, try disabling all models except for 1 (and keep “use secondary model”)
157 | * In 2. Diffusion and CLIP model settings, switch to “256x256_diffusion_uncond”.
158 | * In settings reduce the resolution drastically (to 128x128) and see if that helps.
159 |
160 | If this works, slowly add back models and increase resolution until you find out where the limit is for your GPU.
161 |
--------------------------------------------------------------------------------
/examples/abandoned_shopping_mall.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MohamadZeina/Disco_Diffusion_Local/38ca9d66c344f1351d07638fbab3ad7069267263/examples/abandoned_shopping_mall.jpeg
--------------------------------------------------------------------------------
/examples/purity_and_grace.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MohamadZeina/Disco_Diffusion_Local/38ca9d66c344f1351d07638fbab3ad7069267263/examples/purity_and_grace.png
--------------------------------------------------------------------------------
/examples/retro_playroom.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MohamadZeina/Disco_Diffusion_Local/38ca9d66c344f1351d07638fbab3ad7069267263/examples/retro_playroom.jpg
--------------------------------------------------------------------------------
/examples/self_portrait_of_an_AI.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MohamadZeina/Disco_Diffusion_Local/38ca9d66c344f1351d07638fbab3ad7069267263/examples/self_portrait_of_an_AI.png
--------------------------------------------------------------------------------
/examples/terrarium.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MohamadZeina/Disco_Diffusion_Local/38ca9d66c344f1351d07638fbab3ad7069267263/examples/terrarium.jpg
--------------------------------------------------------------------------------
/queue/master_settings.txt:
--------------------------------------------------------------------------------
1 | {
2 | "width": 800,
3 | "height": 450,
4 | "init_image": null,
5 | "diffusion_model": "512x512_diffusion_uncond_finetune_008100",
6 | "use_secondary_model": true,
7 | "ViTB32": true,
8 | "ViTB16": false,
9 | "ViTL14": false,
10 | "RN101": false,
11 | "RN50": false,
12 | "RN50x4": false,
13 | "RN50x16": false,
14 | "RN50x64": false,
15 | "translation_x": "0:(0.333333333)",
16 | "translation_y": "0:(0)",
17 | "translation_z": "0:(2)",
18 | "rotation_3d_x": "0:(0)",
19 | "rotation_3d_y": "0:(-0.0009)",
20 | "rotation_3d_z": "0:(0)",
21 | "turbo_mode": true
22 | }
--------------------------------------------------------------------------------
/queue/queue_1.txt:
--------------------------------------------------------------------------------
1 | {
2 | "text_prompts": {
3 | "0": [
4 | "Painting of a serene house"
5 | ]
6 | },
7 | "image_prompts": {},
8 | "max_frames": 12,
9 | "steps": 100
10 | }
--------------------------------------------------------------------------------
/queue/queue_2.txt:
--------------------------------------------------------------------------------
1 | {
2 | "text_prompts": {
3 | "0": [
4 | "POV DMT trip"
5 | ]
6 | },
7 | "image_prompts": {},
8 | "max_frames": 12,
9 | "steps": 100
10 | }
--------------------------------------------------------------------------------