From b05dd881d6d0db9c93aa5db9373775869701fb3f Mon Sep 17 00:00:00 2001 From: Somnai Date: Fri, 4 Mar 2022 18:07:20 +1100 Subject: [PATCH 01/74] Created using Colaboratory --- Disco_Diffusion.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 5221aae6..c6f1f556 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -7,7 +7,7 @@ "colab_type": "text" }, "source": [ - "\"Open" + "\"Open" ] }, { From 4c706c98a9ca638f25263200d12eaabb0d0a4f6f Mon Sep 17 00:00:00 2001 From: Somnai Date: Sat, 5 Mar 2022 10:52:06 +1100 Subject: [PATCH 02/74] Created using Colaboratory --- Disco_Diffusion.ipynb | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index c6f1f556..739acabf 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -617,7 +617,6 @@ "cell_type": "code", "execution_count": null, "metadata": { - "cellView": "form", "id": "FpZczxnOnPIU" }, "outputs": [], @@ -1181,11 +1180,11 @@ " return grad * magnitude.clamp(max=args.clamp_max) / magnitude #min=-0.02, min=-clamp_max, \n", " return grad\n", " \n", - " if model_config['timestep_respacing'].startswith('ddim'):\n", + " if args.sampling_mode == 'ddim':\n", " sample_fn = diffusion.ddim_sample_loop_progressive\n", " else:\n", - " sample_fn = diffusion.p_sample_loop_progressive\n", - " \n", + " sample_fn = diffusion.plms_sample_loop_progressive\n", + "\n", "\n", " image_display = Output()\n", " for i in range(args.n_batches):\n", @@ -1204,7 +1203,7 @@ " if perlin_init:\n", " init = regen_perlin()\n", "\n", - " if model_config['timestep_respacing'].startswith('ddim'):\n", + " if args.sampling_mode == 'ddim':\n", " samples = sample_fn(\n", " model,\n", " (batch_size, 3, args.side_y, args.side_x),\n", @@ -1228,6 +1227,7 @@ " skip_timesteps=skip_steps,\n", " init_image=init,\n", " randomize_class=randomize_class,\n", + " order=2,\n", " )\n", " \n", " \n", @@ -1335,6 +1335,7 @@ " 'use_secondary_model': use_secondary_model,\n", " 'steps': steps,\n", " 'diffusion_steps': diffusion_steps,\n", + " 'sampling_mode': sampling_mode,\n", " 'ViTB32': ViTB32,\n", " 'ViTB16': ViTB16,\n", " 'ViTL14': ViTL14,\n", @@ -2101,8 +2102,9 @@ "#@markdown ####**Models Settings:**\n", "diffusion_model = \"512x512_diffusion_uncond_finetune_008100\" #@param [\"256x256_diffusion_uncond\", \"512x512_diffusion_uncond_finetune_008100\"]\n", "use_secondary_model = True #@param {type: 'boolean'}\n", + "sampling_mode = 'plms' #@param ['plms','ddim'] \n", "\n", - "timestep_respacing = '50' # param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000'] \n", + "timestep_respacing = '150' # param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000'] \n", "diffusion_steps = 1000 # param {type: 'number'}\n", "use_checkpoint = True #@param {type: 'boolean'}\n", "ViTB32 = True #@param{type:\"boolean\"}\n", @@ -2300,7 +2302,7 @@ "source": [ "#@markdown ####**Basic Settings:**\n", "batch_name = 'TimeToDisco' #@param{type: 'string'}\n", - "steps = 250 #@param [25,50,100,150,250,500,1000]{type: 'raw', allow-input: true}\n", + "steps = 150 #@param [25,50,100,150,250,500,1000]{type: 'raw', allow-input: true}\n", "width_height = [1280, 768]#@param{type: 'raw'}\n", "clip_guidance_scale = 5000 #@param{type: 'number'}\n", "tv_scale = 0#@param{type: 'number'}\n", @@ -2804,6 +2806,14 @@ "display_rate = 50 #@param{type: 'number'}\n", "n_batches = 50 #@param{type: 'number'}\n", "\n", + "#Update Model Settings\n", + "timestep_respacing = f'ddim{steps}'\n", + "diffusion_steps = (1000//steps)*steps if steps < 1000 else steps\n", + "model_config.update({\n", + " 'timestep_respacing': timestep_respacing,\n", + " 'diffusion_steps': diffusion_steps,\n", + "})\n", + "\n", "batch_size = 1 \n", "\n", "def move_files(start_num, end_num, old_folder, new_folder):\n", @@ -2873,6 +2883,7 @@ " 'batch_size':batch_size,\n", " 'batch_name': batch_name,\n", " 'steps': steps,\n", + " 'sampling_mode': sampling_mode,\n", " 'width_height': width_height,\n", " 'clip_guidance_scale': clip_guidance_scale,\n", " 'tv_scale': tv_scale,\n", From d9a5e6993d11196d45f94d53b53bada628c3578c Mon Sep 17 00:00:00 2001 From: Somnai Date: Tue, 8 Mar 2022 09:08:05 +1100 Subject: [PATCH 03/74] Reverted default to ddim --- Disco_Diffusion.ipynb | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 739acabf..64c61f52 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -7,7 +7,7 @@ "colab_type": "text" }, "source": [ - "\"Open" + "\"Open" ] }, { @@ -2102,9 +2102,9 @@ "#@markdown ####**Models Settings:**\n", "diffusion_model = \"512x512_diffusion_uncond_finetune_008100\" #@param [\"256x256_diffusion_uncond\", \"512x512_diffusion_uncond_finetune_008100\"]\n", "use_secondary_model = True #@param {type: 'boolean'}\n", - "sampling_mode = 'plms' #@param ['plms','ddim'] \n", + "sampling_mode = 'ddim' #@param ['plms','ddim'] \n", "\n", - "timestep_respacing = '150' # param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000'] \n", + "timestep_respacing = '250' # param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000'] \n", "diffusion_steps = 1000 # param {type: 'number'}\n", "use_checkpoint = True #@param {type: 'boolean'}\n", "ViTB32 = True #@param{type:\"boolean\"}\n", @@ -2302,7 +2302,7 @@ "source": [ "#@markdown ####**Basic Settings:**\n", "batch_name = 'TimeToDisco' #@param{type: 'string'}\n", - "steps = 150 #@param [25,50,100,150,250,500,1000]{type: 'raw', allow-input: true}\n", + "steps = 250 #@param [25,50,100,150,250,500,1000]{type: 'raw', allow-input: true}\n", "width_height = [1280, 768]#@param{type: 'raw'}\n", "clip_guidance_scale = 5000 #@param{type: 'number'}\n", "tv_scale = 0#@param{type: 'number'}\n", @@ -2316,7 +2316,7 @@ "#@markdown ####**Init Settings:**\n", "init_image = None #@param{type: 'string'}\n", "init_scale = 1000 #@param{type: 'integer'}\n", - "skip_steps = 0 #@param{type: 'integer'}\n", + "skip_steps = 10 #@param{type: 'integer'}\n", "#@markdown *Make sure you set skip_steps to ~50% of your steps if you want to use an init image.*\n", "\n", "#Get corrected sizes\n", @@ -3109,4 +3109,4 @@ }, "nbformat": 4, "nbformat_minor": 0 -} \ No newline at end of file +} From 453e814884af61d109889c14a8de73b742065f82 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Thu, 10 Mar 2022 13:25:02 -0500 Subject: [PATCH 04/74] Update LICENSE --- LICENSE | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/LICENSE b/LICENSE index f94362a4..534bcbb5 100644 --- a/LICENSE +++ b/LICENSE @@ -22,6 +22,30 @@ THE SOFTWARE. -- +MIT License + +Copyright (c) 2019 Intel ISL (Intel Intelligent Systems Lab) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +-- + Licensed under the MIT License Copyright (c) 2021 Maxwell Ingham From 12fabe67d3b0f1ce8ff8eb38a06b95232f0024e9 Mon Sep 17 00:00:00 2001 From: aletts Date: Thu, 10 Mar 2022 17:11:38 -0500 Subject: [PATCH 05/74] IPython magic commands replaced by Python code --- disco.py | 2922 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 2922 insertions(+) create mode 100644 disco.py diff --git a/disco.py b/disco.py new file mode 100644 index 00000000..43125417 --- /dev/null +++ b/disco.py @@ -0,0 +1,2922 @@ +# %% +""" +# Disco Diffusion v5 - Now with 3D animation + +In case of confusion, Disco is the name of this notebook edit. The diffusion model in use is Katherine Crowson's fine-tuned 512x512 model + +For issues, join the [Disco Diffusion Discord](https://discord.gg/msEZBy4HxA) or message us on twitter at [@somnai_dreams](https://twitter.com/somnai_dreams) or [@gandamu](https://twitter.com/gandamu_ml) +""" + +# %% +""" +### Credits & Changelog ⬇️ +""" + +# %% +""" +#### Credits + +Original notebook by Katherine Crowson (https://github.com/crowsonkb, https://twitter.com/RiversHaveWings). It uses either OpenAI's 256x256 unconditional ImageNet or Katherine Crowson's fine-tuned 512x512 diffusion model (https://github.com/openai/guided-diffusion), together with CLIP (https://github.com/openai/CLIP) to connect text prompts with images. + +Modified by Daniel Russell (https://github.com/russelldc, https://twitter.com/danielrussruss) to include (hopefully) optimal params for quick generations in 15-100 timesteps rather than 1000, as well as more robust augmentations. + +Further improvements from Dango233 and nsheppard helped improve the quality of diffusion in general, and especially so for shorter runs like this notebook aims to achieve. + +Vark added code to load in multiple Clip models at once, which all prompts are evaluated against, which may greatly improve accuracy. + +The latest zoom, pan, rotation, and keyframes features were taken from Chigozie Nri's VQGAN Zoom Notebook (https://github.com/chigozienri, https://twitter.com/chigozienri) + +Advanced DangoCutn Cutout method is also from Dango223. + +-- + +Disco: + +Somnai (https://twitter.com/Somnai_dreams) added Diffusion Animation techniques, QoL improvements and various implementations of tech and techniques, mostly listed in the changelog below. + +3D animation implementation added by Adam Letts (https://twitter.com/gandamu_ml) in collaboration with Somnai. +""" + +# %% +""" +#### License +""" + +# %% +""" +Licensed under the MIT License + +Copyright (c) 2021 Katherine Crowson + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +-- + +@title Licensed under the MIT License + +Copyright (c) 2021 Maxwell Ingham +Copyright (c) 2022 Adam Letts + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +""" + +# %% +""" +#### Changelog +""" + +# %% +#@title <- View Changelog +skip_for_run_all = True #@param {type: 'boolean'} + +if skip_for_run_all == False: + print( + ''' + v1 Update: Oct 29th 2021 - Somnai + + QoL improvements added by Somnai (@somnai_dreams), including user friendly UI, settings+prompt saving and improved google drive folder organization. + + v1.1 Update: Nov 13th 2021 - Somnai + + Now includes sizing options, intermediate saves and fixed image prompts and perlin inits. unexposed batch option since it doesn't work + + v2 Update: Nov 22nd 2021 - Somnai + + Initial addition of Katherine Crowson's Secondary Model Method (https://colab.research.google.com/drive/1mpkrhOjoyzPeSWy2r7T8EYRaU7amYOOi#scrollTo=X5gODNAMEUCR) + + Noticed settings were saving with the wrong name so corrected it. Let me know if you preferred the old scheme. + + v3 Update: Dec 24th 2021 - Somnai + + Implemented Dango's advanced cutout method + + Added SLIP models, thanks to NeuralDivergent + + Fixed issue with NaNs resulting in black images, with massive help and testing from @Softology + + Perlin now changes properly within batches (not sure where this perlin_regen code came from originally, but thank you) + + v4 Update: Jan 2021 - Somnai + + Implemented Diffusion Zooming + + Added Chigozie keyframing + + Made a bunch of edits to processes + + v4.1 Update: Jan 14th 2021 - Somnai + + Added video input mode + + Added license that somehow went missing + + Added improved prompt keyframing, fixed image_prompts and multiple prompts + + Improved UI + + Significant under the hood cleanup and improvement + + Refined defaults for each mode + + Added latent-diffusion SuperRes for sharpening + + Added resume run mode + + v4.9 Update: Feb 5th 2022 - gandamu / Adam Letts + + Added 3D + + Added brightness corrections to prevent animation from steadily going dark over time + + v4.91 Update: Feb 19th 2022 - gandamu / Adam Letts + + Cleaned up 3D implementation and made associated args accessible via Colab UI elements + + v4.92 Update: Feb 20th 2022 - gandamu / Adam Letts + + Separated transform code + ''' + ) + + +# %% +""" +# Tutorial +""" + +# %% +""" +**Diffusion settings (Defaults are heavily outdated)** +--- + +This section is outdated as of v2 + +Setting | Description | Default +--- | --- | --- +**Your vision:** +`text_prompts` | A description of what you'd like the machine to generate. Think of it like writing the caption below your image on a website. | N/A +`image_prompts` | Think of these images more as a description of their contents. | N/A +**Image quality:** +`clip_guidance_scale` | Controls how much the image should look like the prompt. | 1000 +`tv_scale` | Controls the smoothness of the final output. | 150 +`range_scale` | Controls how far out of range RGB values are allowed to be. | 150 +`sat_scale` | Controls how much saturation is allowed. From nshepperd's JAX notebook. | 0 +`cutn` | Controls how many crops to take from the image. | 16 +`cutn_batches` | Accumulate CLIP gradient from multiple batches of cuts | 2 +**Init settings:** +`init_image` | URL or local path | None +`init_scale` | This enhances the effect of the init image, a good value is 1000 | 0 +`skip_steps Controls the starting point along the diffusion timesteps | 0 +`perlin_init` | Option to start with random perlin noise | False +`perlin_mode` | ('gray', 'color') | 'mixed' +**Advanced:** +`skip_augs` |Controls whether to skip torchvision augmentations | False +`randomize_class` |Controls whether the imagenet class is randomly changed each iteration | True +`clip_denoised` |Determines whether CLIP discriminates a noisy or denoised image | False +`clamp_grad` |Experimental: Using adaptive clip grad in the cond_fn | True +`seed` | Choose a random seed and print it at end of run for reproduction | random_seed +`fuzzy_prompt` | Controls whether to add multiple noisy prompts to the prompt losses | False +`rand_mag` |Controls the magnitude of the random noise | 0.1 +`eta` | DDIM hyperparameter | 0.5 + +.. + +**Model settings** +--- + +Setting | Description | Default +--- | --- | --- +**Diffusion:** +`timestep_respacing` | Modify this value to decrease the number of timesteps. | ddim100 +`diffusion_steps` || 1000 +**Diffusion:** +`clip_models` | Models of CLIP to load. Typically the more, the better but they all come at a hefty VRAM cost. | ViT-B/32, ViT-B/16, RN50x4 + +# 1. Set Up +""" + +# %% +#@title 1.1 Check GPU Status +import subprocess +simple_nvidia_smi_display = False#@param {type:"boolean"} +if simple_nvidia_smi_display: + #!nvidia-smi + nvidiasmi_output = subprocess.run(['nvidia-smi', '-L'], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(nvidiasmi_output) +else: + #!nvidia-smi -i 0 -e 0 + nvidiasmi_output = subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(nvidiasmi_output) + nvidiasmi_ecc_note = subprocess.run(['nvidia-smi', '-i', '0', '-e', '0'], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(nvidiasmi_ecc_note) + +# %% +#@title 1.2 Prepare Folders +import subprocess +import sys +import ipykernel + +def gitclone(url): + res = subprocess.run(['git', 'clone', url], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(res) + +def pipi(modulestr): + res = subprocess.run(['pip', 'install', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(res) + +def pipie(modulestr): + res = subprocess.run(['git', 'install', '-e', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(res) + +def wget(url, outputdir): + res = subprocess.run(['wget', url, '-P', f'{outputdir}'], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(res) + +try: + from google.colab import drive + print("Google Colab detected. Using Google Drive.") + is_colab = True + #@markdown If you connect your Google Drive, you can save the final image of each run on your drive. + google_drive = True #@param {type:"boolean"} + #@markdown Click here if you'd like to save the diffusion model checkpoint file to (and/or load from) your Google Drive: + save_models_to_google_drive = True #@param {type:"boolean"} +except: + is_colab = False + google_drive = False + save_models_to_google_drive = False + print("Google Colab not detected.") + +if is_colab: + if google_drive is True: + drive.mount('/content/drive') + root_path = '/content/drive/MyDrive/AI/Disco_Diffusion' + else: + root_path = '/content' +else: + root_path = '.' + +import os +from os import path +#Simple create paths taken with modifications from Datamosh's Batch VQGAN+CLIP notebook +def createPath(filepath): + if path.exists(filepath) == False: + os.makedirs(filepath) + print(f'Made {filepath}') + else: + print(f'filepath {filepath} exists.') + +initDirPath = f'{root_path}/init_images' +createPath(initDirPath) +outDirPath = f'{root_path}/images_out' +createPath(outDirPath) + +if is_colab: + if google_drive and not save_models_to_google_drive or not google_drive: + model_path = '/content/model' + createPath(model_path) + if google_drive and save_models_to_google_drive: + model_path = f'{root_path}/model' + createPath(model_path) +else: + model_path = f'{root_path}/model' + createPath(model_path) + +# libraries = f'{root_path}/libraries' +# createPath(libraries) + +# %% +#@title ### 1.3 Install and import dependencies + +from os.path import exists as path_exists +import pathlib, shutil + +if not is_colab: + # If running locally, there's a good chance your env will need this in order to not crash upon np.matmul() or similar operations. + os.environ['KMP_DUPLICATE_LIB_OK']='TRUE' + +PROJECT_DIR = os.path.abspath(os.getcwd()) +USE_ADABINS = True + +if is_colab: + if google_drive is not True: + root_path = f'/content' + model_path = '/content/models' +else: + root_path = f'.' + model_path = f'{root_path}/model' + +model_256_downloaded = False +model_512_downloaded = False +model_secondary_downloaded = False + +if is_colab: + gitclone("https://github.com/openai/CLIP") + #gitclone("https://github.com/facebookresearch/SLIP.git") + gitclone("https://github.com/crowsonkb/guided-diffusion") + gitclone("https://github.com/assafshocher/ResizeRight.git") + pipie("./CLIP") + pipie("./guided-diffusion") + multipip_res = subprocess.run(['pip', 'install', 'lpips', 'datetime', 'timm', 'ftfy'], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(multipip_res) + subprocess.run(['apt', 'install', 'imagemagick'], stdout=subprocess.PIPE).stdout.decode('utf-8') + gitclone("https://github.com/isl-org/MiDaS.git") + gitclone("https://github.com/alembics/disco-diffusion.git") + pipi("pytorch-lightning") + pipi("omegaconf") + pipi("einops") + # Rename a file to avoid a name conflict.. + try: + os.rename("MiDaS/utils.py", "MiDaS/midas_utils.py") + shutil.copyfile("disco-diffusion/disco_xform_utils.py", "disco_xform_utils.py") + except: + pass + +if not path_exists(f'{model_path}'): + pathlib.Path(model_path).mkdir(parents=True, exist_ok=True) +if not path_exists(f'{model_path}/dpt_large-midas-2f21e586.pt'): + wget("https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", out=model_path) + +import sys +import torch + +#Install pytorch3d +if is_colab: + pyt_version_str=torch.__version__.split("+")[0].replace(".", "") + version_str="".join([ + f"py3{sys.version_info.minor}_cu", + torch.version.cuda.replace(".",""), + f"_pyt{pyt_version_str}" + ]) + multipip_res = subprocess.run(['pip', 'install', 'fvcore', 'iopath'], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(multipip_res) + subprocess.run(['pip', 'install', '--no-index', '--no-cache-dir', 'pytorch3d', '-f', f'https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html'], stdout=subprocess.PIPE).stdout.decode('utf-8') + +# sys.path.append('./SLIP') +sys.path.append('./ResizeRight') +sys.path.append('./MiDaS') +from dataclasses import dataclass +from functools import partial +import cv2 +import pandas as pd +import gc +import io +import math +import timm +from IPython import display +import lpips +from PIL import Image, ImageOps +import requests +from glob import glob +import json +from types import SimpleNamespace +from torch import nn +from torch.nn import functional as F +import torchvision.transforms as T +import torchvision.transforms.functional as TF +from tqdm.notebook import tqdm +sys.path.append('./CLIP') +sys.path.append('./guided-diffusion') +import clip +from resize_right import resize +# from models import SLIP_VITB16, SLIP, SLIP_VITL16 +from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults +from datetime import datetime +import numpy as np +import matplotlib.pyplot as plt +import random +from ipywidgets import Output +import hashlib + +#SuperRes +if is_colab: + gitclone("https://github.com/CompVis/latent-diffusion.git") + gitclone("https://github.com/CompVis/taming-transformers") + pipie("./taming-transformers") + pipi("ipywidgets omegaconf>=2.0.0 pytorch-lightning>=1.0.8 torch-fidelity einops wandb") + +#SuperRes +import ipywidgets as widgets +import os +sys.path.append(".") +sys.path.append('./taming-transformers') +from taming.models import vqgan # checking correct import from taming +from torchvision.datasets.utils import download_url + +if is_colab: + os.chdir('/content/latent-diffusion') +else: + #os.chdir('latent-diffusion') + sys.path.append('latent-diffusion') +from functools import partial +from ldm.util import instantiate_from_config +from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like +# from ldm.models.diffusion.ddim import DDIMSampler +from ldm.util import ismap +if is_colab: + os.chdir('/content') + from google.colab import files +else: + os.chdir(f'{PROJECT_DIR}') +from IPython.display import Image as ipyimg +from numpy import asarray +from einops import rearrange, repeat +import torch, torchvision +import time +from omegaconf import OmegaConf +import warnings +warnings.filterwarnings("ignore", category=UserWarning) + +# AdaBins stuff +if USE_ADABINS: + if is_colab: + gitclone("https://github.com/shariqfarooq123/AdaBins.git") + if not path_exists(f'{model_path}/AdaBins_nyu.pt'): + wget("https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt", out=model_path) + pathlib.Path("pretrained").mkdir(parents=True, exist_ok=True) + shutil.copyfile(f"{model_path}/AdaBins_nyu.pt", "pretrained/AdaBins_nyu.pt") + sys.path.append('./AdaBins') + from infer import InferenceHelper + MAX_ADABINS_AREA = 500000 + +import torch +DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') +print('Using device:', DEVICE) +device = DEVICE # At least one of the modules expects this name.. + +if torch.cuda.get_device_capability(DEVICE) == (8,0): ## A100 fix thanks to Emad + print('Disabling CUDNN for A100 gpu', file=sys.stderr) + torch.backends.cudnn.enabled = False + +# %% +#@title ### 1.4 Define Midas functions + +from midas.dpt_depth import DPTDepthModel +from midas.midas_net import MidasNet +from midas.midas_net_custom import MidasNet_small +from midas.transforms import Resize, NormalizeImage, PrepareForNet + +# Initialize MiDaS depth model. +# It remains resident in VRAM and likely takes around 2GB VRAM. +# You could instead initialize it for each frame (and free it after each frame) to save VRAM.. but initializing it is slow. +default_models = { + "midas_v21_small": f"{model_path}/midas_v21_small-70d6b9c8.pt", + "midas_v21": f"{model_path}/midas_v21-f6b98070.pt", + "dpt_large": f"{model_path}/dpt_large-midas-2f21e586.pt", + "dpt_hybrid": f"{model_path}/dpt_hybrid-midas-501f0c75.pt", + "dpt_hybrid_nyu": f"{model_path}/dpt_hybrid_nyu-2ce69ec7.pt",} + + +def init_midas_depth_model(midas_model_type="dpt_large", optimize=True): + midas_model = None + net_w = None + net_h = None + resize_mode = None + normalization = None + + print(f"Initializing MiDaS '{midas_model_type}' depth model...") + # load network + midas_model_path = default_models[midas_model_type] + + if midas_model_type == "dpt_large": # DPT-Large + midas_model = DPTDepthModel( + path=midas_model_path, + backbone="vitl16_384", + non_negative=True, + ) + net_w, net_h = 384, 384 + resize_mode = "minimal" + normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + elif midas_model_type == "dpt_hybrid": #DPT-Hybrid + midas_model = DPTDepthModel( + path=midas_model_path, + backbone="vitb_rn50_384", + non_negative=True, + ) + net_w, net_h = 384, 384 + resize_mode="minimal" + normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + elif midas_model_type == "dpt_hybrid_nyu": #DPT-Hybrid-NYU + midas_model = DPTDepthModel( + path=midas_model_path, + backbone="vitb_rn50_384", + non_negative=True, + ) + net_w, net_h = 384, 384 + resize_mode="minimal" + normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + elif midas_model_type == "midas_v21": + midas_model = MidasNet(midas_model_path, non_negative=True) + net_w, net_h = 384, 384 + resize_mode="upper_bound" + normalization = NormalizeImage( + mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] + ) + elif midas_model_type == "midas_v21_small": + midas_model = MidasNet_small(midas_model_path, features=64, backbone="efficientnet_lite3", exportable=True, non_negative=True, blocks={'expand': True}) + net_w, net_h = 256, 256 + resize_mode="upper_bound" + normalization = NormalizeImage( + mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] + ) + else: + print(f"midas_model_type '{midas_model_type}' not implemented") + assert False + + midas_transform = T.Compose( + [ + Resize( + net_w, + net_h, + resize_target=None, + keep_aspect_ratio=True, + ensure_multiple_of=32, + resize_method=resize_mode, + image_interpolation_method=cv2.INTER_CUBIC, + ), + normalization, + PrepareForNet(), + ] + ) + + midas_model.eval() + + if optimize==True: + if DEVICE == torch.device("cuda"): + midas_model = midas_model.to(memory_format=torch.channels_last) + midas_model = midas_model.half() + + midas_model.to(DEVICE) + + print(f"MiDaS '{midas_model_type}' depth model initialized.") + return midas_model, midas_transform, net_w, net_h, resize_mode, normalization + +# %% +#@title 1.5 Define necessary functions + +# https://gist.github.com/adefossez/0646dbe9ed4005480a2407c62aac8869 + +import pytorch3d.transforms as p3dT +import disco_xform_utils as dxf + +def interp(t): + return 3 * t**2 - 2 * t ** 3 + +def perlin(width, height, scale=10, device=None): + gx, gy = torch.randn(2, width + 1, height + 1, 1, 1, device=device) + xs = torch.linspace(0, 1, scale + 1)[:-1, None].to(device) + ys = torch.linspace(0, 1, scale + 1)[None, :-1].to(device) + wx = 1 - interp(xs) + wy = 1 - interp(ys) + dots = 0 + dots += wx * wy * (gx[:-1, :-1] * xs + gy[:-1, :-1] * ys) + dots += (1 - wx) * wy * (-gx[1:, :-1] * (1 - xs) + gy[1:, :-1] * ys) + dots += wx * (1 - wy) * (gx[:-1, 1:] * xs - gy[:-1, 1:] * (1 - ys)) + dots += (1 - wx) * (1 - wy) * (-gx[1:, 1:] * (1 - xs) - gy[1:, 1:] * (1 - ys)) + return dots.permute(0, 2, 1, 3).contiguous().view(width * scale, height * scale) + +def perlin_ms(octaves, width, height, grayscale, device=device): + out_array = [0.5] if grayscale else [0.5, 0.5, 0.5] + # out_array = [0.0] if grayscale else [0.0, 0.0, 0.0] + for i in range(1 if grayscale else 3): + scale = 2 ** len(octaves) + oct_width = width + oct_height = height + for oct in octaves: + p = perlin(oct_width, oct_height, scale, device) + out_array[i] += p * oct + scale //= 2 + oct_width *= 2 + oct_height *= 2 + return torch.cat(out_array) + +def create_perlin_noise(octaves=[1, 1, 1, 1], width=2, height=2, grayscale=True): + out = perlin_ms(octaves, width, height, grayscale) + if grayscale: + out = TF.resize(size=(side_y, side_x), img=out.unsqueeze(0)) + out = TF.to_pil_image(out.clamp(0, 1)).convert('RGB') + else: + out = out.reshape(-1, 3, out.shape[0]//3, out.shape[1]) + out = TF.resize(size=(side_y, side_x), img=out) + out = TF.to_pil_image(out.clamp(0, 1).squeeze()) + + out = ImageOps.autocontrast(out) + return out + +def regen_perlin(): + if perlin_mode == 'color': + init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False) + init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False) + elif perlin_mode == 'gray': + init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True) + init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True) + else: + init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False) + init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True) + + init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1) + del init2 + return init.expand(batch_size, -1, -1, -1) + +def fetch(url_or_path): + if str(url_or_path).startswith('http://') or str(url_or_path).startswith('https://'): + r = requests.get(url_or_path) + r.raise_for_status() + fd = io.BytesIO() + fd.write(r.content) + fd.seek(0) + return fd + return open(url_or_path, 'rb') + +def read_image_workaround(path): + """OpenCV reads images as BGR, Pillow saves them as RGB. Work around + this incompatibility to avoid colour inversions.""" + im_tmp = cv2.imread(path) + return cv2.cvtColor(im_tmp, cv2.COLOR_BGR2RGB) + +def parse_prompt(prompt): + if prompt.startswith('http://') or prompt.startswith('https://'): + vals = prompt.rsplit(':', 2) + vals = [vals[0] + ':' + vals[1], *vals[2:]] + else: + vals = prompt.rsplit(':', 1) + vals = vals + ['', '1'][len(vals):] + return vals[0], float(vals[1]) + +def sinc(x): + return torch.where(x != 0, torch.sin(math.pi * x) / (math.pi * x), x.new_ones([])) + +def lanczos(x, a): + cond = torch.logical_and(-a < x, x < a) + out = torch.where(cond, sinc(x) * sinc(x/a), x.new_zeros([])) + return out / out.sum() + +def ramp(ratio, width): + n = math.ceil(width / ratio + 1) + out = torch.empty([n]) + cur = 0 + for i in range(out.shape[0]): + out[i] = cur + cur += ratio + return torch.cat([-out[1:].flip([0]), out])[1:-1] + +def resample(input, size, align_corners=True): + n, c, h, w = input.shape + dh, dw = size + + input = input.reshape([n * c, 1, h, w]) + + if dh < h: + kernel_h = lanczos(ramp(dh / h, 2), 2).to(input.device, input.dtype) + pad_h = (kernel_h.shape[0] - 1) // 2 + input = F.pad(input, (0, 0, pad_h, pad_h), 'reflect') + input = F.conv2d(input, kernel_h[None, None, :, None]) + + if dw < w: + kernel_w = lanczos(ramp(dw / w, 2), 2).to(input.device, input.dtype) + pad_w = (kernel_w.shape[0] - 1) // 2 + input = F.pad(input, (pad_w, pad_w, 0, 0), 'reflect') + input = F.conv2d(input, kernel_w[None, None, None, :]) + + input = input.reshape([n, c, h, w]) + return F.interpolate(input, size, mode='bicubic', align_corners=align_corners) + +class MakeCutouts(nn.Module): + def __init__(self, cut_size, cutn, skip_augs=False): + super().__init__() + self.cut_size = cut_size + self.cutn = cutn + self.skip_augs = skip_augs + self.augs = T.Compose([ + T.RandomHorizontalFlip(p=0.5), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomAffine(degrees=15, translate=(0.1, 0.1)), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomPerspective(distortion_scale=0.4, p=0.7), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomGrayscale(p=0.15), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + # T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1), + ]) + + def forward(self, input): + input = T.Pad(input.shape[2]//4, fill=0)(input) + sideY, sideX = input.shape[2:4] + max_size = min(sideX, sideY) + + cutouts = [] + for ch in range(self.cutn): + if ch > self.cutn - self.cutn//4: + cutout = input.clone() + else: + size = int(max_size * torch.zeros(1,).normal_(mean=.8, std=.3).clip(float(self.cut_size/max_size), 1.)) + offsetx = torch.randint(0, abs(sideX - size + 1), ()) + offsety = torch.randint(0, abs(sideY - size + 1), ()) + cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size] + + if not self.skip_augs: + cutout = self.augs(cutout) + cutouts.append(resample(cutout, (self.cut_size, self.cut_size))) + del cutout + + cutouts = torch.cat(cutouts, dim=0) + return cutouts + +cutout_debug = False +padargs = {} + +class MakeCutoutsDango(nn.Module): + def __init__(self, cut_size, + Overview=4, + InnerCrop = 0, IC_Size_Pow=0.5, IC_Grey_P = 0.2 + ): + super().__init__() + self.cut_size = cut_size + self.Overview = Overview + self.InnerCrop = InnerCrop + self.IC_Size_Pow = IC_Size_Pow + self.IC_Grey_P = IC_Grey_P + if args.animation_mode == 'None': + self.augs = T.Compose([ + T.RandomHorizontalFlip(p=0.5), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomGrayscale(p=0.1), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1), + ]) + elif args.animation_mode == 'Video Input': + self.augs = T.Compose([ + T.RandomHorizontalFlip(p=0.5), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomAffine(degrees=15, translate=(0.1, 0.1)), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomPerspective(distortion_scale=0.4, p=0.7), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomGrayscale(p=0.15), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + # T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1), + ]) + elif args.animation_mode == '2D' or args.animation_mode == '3D': + self.augs = T.Compose([ + T.RandomHorizontalFlip(p=0.4), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.RandomGrayscale(p=0.1), + T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), + T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.3), + ]) + + + def forward(self, input): + cutouts = [] + gray = T.Grayscale(3) + sideY, sideX = input.shape[2:4] + max_size = min(sideX, sideY) + min_size = min(sideX, sideY, self.cut_size) + l_size = max(sideX, sideY) + output_shape = [1,3,self.cut_size,self.cut_size] + output_shape_2 = [1,3,self.cut_size+2,self.cut_size+2] + pad_input = F.pad(input,((sideY-max_size)//2,(sideY-max_size)//2,(sideX-max_size)//2,(sideX-max_size)//2), **padargs) + cutout = resize(pad_input, out_shape=output_shape) + + if self.Overview>0: + if self.Overview<=4: + if self.Overview>=1: + cutouts.append(cutout) + if self.Overview>=2: + cutouts.append(gray(cutout)) + if self.Overview>=3: + cutouts.append(TF.hflip(cutout)) + if self.Overview==4: + cutouts.append(gray(TF.hflip(cutout))) + else: + cutout = resize(pad_input, out_shape=output_shape) + for _ in range(self.Overview): + cutouts.append(cutout) + + if cutout_debug: + if is_colab: + TF.to_pil_image(cutouts[0].clamp(0, 1).squeeze(0)).save("/content/cutout_overview0.jpg",quality=99) + else: + TF.to_pil_image(cutouts[0].clamp(0, 1).squeeze(0)).save("cutout_overview0.jpg",quality=99) + + + if self.InnerCrop >0: + for i in range(self.InnerCrop): + size = int(torch.rand([])**self.IC_Size_Pow * (max_size - min_size) + min_size) + offsetx = torch.randint(0, sideX - size + 1, ()) + offsety = torch.randint(0, sideY - size + 1, ()) + cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size] + if i <= int(self.IC_Grey_P * self.InnerCrop): + cutout = gray(cutout) + cutout = resize(cutout, out_shape=output_shape) + cutouts.append(cutout) + if cutout_debug: + if is_colab: + TF.to_pil_image(cutouts[-1].clamp(0, 1).squeeze(0)).save("/content/cutout_InnerCrop.jpg",quality=99) + else: + TF.to_pil_image(cutouts[-1].clamp(0, 1).squeeze(0)).save("cutout_InnerCrop.jpg",quality=99) + cutouts = torch.cat(cutouts) + if skip_augs is not True: cutouts=self.augs(cutouts) + return cutouts + +def spherical_dist_loss(x, y): + x = F.normalize(x, dim=-1) + y = F.normalize(y, dim=-1) + return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2) + +def tv_loss(input): + """L2 total variation loss, as in Mahendran et al.""" + input = F.pad(input, (0, 1, 0, 1), 'replicate') + x_diff = input[..., :-1, 1:] - input[..., :-1, :-1] + y_diff = input[..., 1:, :-1] - input[..., :-1, :-1] + return (x_diff**2 + y_diff**2).mean([1, 2, 3]) + + +def range_loss(input): + return (input - input.clamp(-1, 1)).pow(2).mean([1, 2, 3]) + +stop_on_next_loop = False # Make sure GPU memory doesn't get corrupted from cancelling the run mid-way through, allow a full frame to complete + +def do_run(): + seed = args.seed + print(range(args.start_frame, args.max_frames)) + + if (args.animation_mode == "3D") and (args.midas_weight > 0.0): + midas_model, midas_transform, midas_net_w, midas_net_h, midas_resize_mode, midas_normalization = init_midas_depth_model(args.midas_depth_model) + for frame_num in range(args.start_frame, args.max_frames): + if stop_on_next_loop: + break + + display.clear_output(wait=True) + + # Print Frame progress if animation mode is on + if args.animation_mode != "None": + batchBar = tqdm(range(args.max_frames), desc ="Frames") + batchBar.n = frame_num + batchBar.refresh() + + + # Inits if not video frames + if args.animation_mode != "Video Input": + if args.init_image == '': + init_image = None + else: + init_image = args.init_image + init_scale = args.init_scale + skip_steps = args.skip_steps + + if args.animation_mode == "2D": + if args.key_frames: + angle = args.angle_series[frame_num] + zoom = args.zoom_series[frame_num] + translation_x = args.translation_x_series[frame_num] + translation_y = args.translation_y_series[frame_num] + print( + f'angle: {angle}', + f'zoom: {zoom}', + f'translation_x: {translation_x}', + f'translation_y: {translation_y}', + ) + + if frame_num > 0: + seed = seed + 1 + if resume_run and frame_num == start_frame: + img_0 = cv2.imread(batchFolder+f"/{batch_name}({batchNum})_{start_frame-1:04}.png") + else: + img_0 = cv2.imread('prevFrame.png') + center = (1*img_0.shape[1]//2, 1*img_0.shape[0]//2) + trans_mat = np.float32( + [[1, 0, translation_x], + [0, 1, translation_y]] + ) + rot_mat = cv2.getRotationMatrix2D( center, angle, zoom ) + trans_mat = np.vstack([trans_mat, [0,0,1]]) + rot_mat = np.vstack([rot_mat, [0,0,1]]) + transformation_matrix = np.matmul(rot_mat, trans_mat) + img_0 = cv2.warpPerspective( + img_0, + transformation_matrix, + (img_0.shape[1], img_0.shape[0]), + borderMode=cv2.BORDER_WRAP + ) + + cv2.imwrite('prevFrameScaled.png', img_0) + init_image = 'prevFrameScaled.png' + init_scale = args.frames_scale + skip_steps = args.calc_frames_skip_steps + + if args.animation_mode == "3D": + if args.key_frames: + angle = args.angle_series[frame_num] + #zoom = args.zoom_series[frame_num] + translation_x = args.translation_x_series[frame_num] + translation_y = args.translation_y_series[frame_num] + translation_z = args.translation_z_series[frame_num] + rotation_3d_x = args.rotation_3d_x_series[frame_num] + rotation_3d_y = args.rotation_3d_y_series[frame_num] + rotation_3d_z = args.rotation_3d_z_series[frame_num] + print( + f'angle: {angle}', + #f'zoom: {zoom}', + f'translation_x: {translation_x}', + f'translation_y: {translation_y}', + f'translation_z: {translation_z}', + f'rotation_3d_x: {rotation_3d_x}', + f'rotation_3d_y: {rotation_3d_y}', + f'rotation_3d_z: {rotation_3d_z}', + ) + + if frame_num > 0: + seed = seed + 1 + if resume_run and frame_num == start_frame: + img_filepath = batchFolder+f"/{batch_name}({batchNum})_{start_frame-1:04}.png" + else: + img_filepath = '/content/prevFrame.png' if is_colab else 'prevFrame.png' + trans_scale = 1.0/200.0 + translate_xyz = [-translation_x*trans_scale, translation_y*trans_scale, -translation_z*trans_scale] + rotate_xyz = [rotation_3d_x, rotation_3d_y, rotation_3d_z] + print('translation:',translate_xyz) + print('rotation:',rotate_xyz) + rot_mat = p3dT.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), "XYZ").unsqueeze(0) + print("rot_mat: " + str(rot_mat)) + next_step_pil = dxf.transform_image_3d(img_filepath, midas_model, midas_transform, DEVICE, + rot_mat, translate_xyz, args.near_plane, args.far_plane, + args.fov, padding_mode=args.padding_mode, + sampling_mode=args.sampling_mode, midas_weight=args.midas_weight) + next_step_pil.save('prevFrameScaled.png') + init_image = 'prevFrameScaled.png' + init_scale = args.frames_scale + skip_steps = args.calc_frames_skip_steps + + if args.animation_mode == "Video Input": + seed = seed + 1 + init_image = f'{videoFramesFolder}/{frame_num+1:04}.jpg' + init_scale = args.frames_scale + skip_steps = args.calc_frames_skip_steps + + loss_values = [] + + if seed is not None: + np.random.seed(seed) + random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + torch.backends.cudnn.deterministic = True + + target_embeds, weights = [], [] + + if args.prompts_series is not None and frame_num >= len(args.prompts_series): + frame_prompt = args.prompts_series[-1] + elif args.prompts_series is not None: + frame_prompt = args.prompts_series[frame_num] + else: + frame_prompt = [] + + print(args.image_prompts_series) + if args.image_prompts_series is not None and frame_num >= len(args.image_prompts_series): + image_prompt = args.image_prompts_series[-1] + elif args.image_prompts_series is not None: + image_prompt = args.image_prompts_series[frame_num] + else: + image_prompt = [] + + print(f'Frame Prompt: {frame_prompt}') + + model_stats = [] + for clip_model in clip_models: + cutn = 16 + model_stat = {"clip_model":None,"target_embeds":[],"make_cutouts":None,"weights":[]} + model_stat["clip_model"] = clip_model + + + for prompt in frame_prompt: + txt, weight = parse_prompt(prompt) + txt = clip_model.encode_text(clip.tokenize(prompt).to(device)).float() + + if args.fuzzy_prompt: + for i in range(25): + model_stat["target_embeds"].append((txt + torch.randn(txt.shape).cuda() * args.rand_mag).clamp(0,1)) + model_stat["weights"].append(weight) + else: + model_stat["target_embeds"].append(txt) + model_stat["weights"].append(weight) + + if image_prompt: + model_stat["make_cutouts"] = MakeCutouts(clip_model.visual.input_resolution, cutn, skip_augs=skip_augs) + for prompt in image_prompt: + path, weight = parse_prompt(prompt) + img = Image.open(fetch(path)).convert('RGB') + img = TF.resize(img, min(side_x, side_y, *img.size), T.InterpolationMode.LANCZOS) + batch = model_stat["make_cutouts"](TF.to_tensor(img).to(device).unsqueeze(0).mul(2).sub(1)) + embed = clip_model.encode_image(normalize(batch)).float() + if fuzzy_prompt: + for i in range(25): + model_stat["target_embeds"].append((embed + torch.randn(embed.shape).cuda() * rand_mag).clamp(0,1)) + weights.extend([weight / cutn] * cutn) + else: + model_stat["target_embeds"].append(embed) + model_stat["weights"].extend([weight / cutn] * cutn) + + model_stat["target_embeds"] = torch.cat(model_stat["target_embeds"]) + model_stat["weights"] = torch.tensor(model_stat["weights"], device=device) + if model_stat["weights"].sum().abs() < 1e-3: + raise RuntimeError('The weights must not sum to 0.') + model_stat["weights"] /= model_stat["weights"].sum().abs() + model_stats.append(model_stat) + + init = None + if init_image is not None: + init = Image.open(fetch(init_image)).convert('RGB') + init = init.resize((args.side_x, args.side_y), Image.LANCZOS) + init = TF.to_tensor(init).to(device).unsqueeze(0).mul(2).sub(1) + + if args.perlin_init: + if args.perlin_mode == 'color': + init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False) + init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False) + elif args.perlin_mode == 'gray': + init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True) + init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True) + else: + init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False) + init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True) + # init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device) + init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1) + del init2 + + cur_t = None + + def cond_fn(x, t, y=None): + with torch.enable_grad(): + x_is_NaN = False + x = x.detach().requires_grad_() + n = x.shape[0] + if use_secondary_model is True: + alpha = torch.tensor(diffusion.sqrt_alphas_cumprod[cur_t], device=device, dtype=torch.float32) + sigma = torch.tensor(diffusion.sqrt_one_minus_alphas_cumprod[cur_t], device=device, dtype=torch.float32) + cosine_t = alpha_sigma_to_t(alpha, sigma) + out = secondary_model(x, cosine_t[None].repeat([n])).pred + fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t] + x_in = out * fac + x * (1 - fac) + x_in_grad = torch.zeros_like(x_in) + else: + my_t = torch.ones([n], device=device, dtype=torch.long) * cur_t + out = diffusion.p_mean_variance(model, x, my_t, clip_denoised=False, model_kwargs={'y': y}) + fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t] + x_in = out['pred_xstart'] * fac + x * (1 - fac) + x_in_grad = torch.zeros_like(x_in) + for model_stat in model_stats: + for i in range(args.cutn_batches): + t_int = int(t.item())+1 #errors on last step without +1, need to find source + #when using SLIP Base model the dimensions need to be hard coded to avoid AttributeError: 'VisionTransformer' object has no attribute 'input_resolution' + try: + input_resolution=model_stat["clip_model"].visual.input_resolution + except: + input_resolution=224 + + cuts = MakeCutoutsDango(input_resolution, + Overview= args.cut_overview[1000-t_int], + InnerCrop = args.cut_innercut[1000-t_int], IC_Size_Pow=args.cut_ic_pow, IC_Grey_P = args.cut_icgray_p[1000-t_int] + ) + clip_in = normalize(cuts(x_in.add(1).div(2))) + image_embeds = model_stat["clip_model"].encode_image(clip_in).float() + dists = spherical_dist_loss(image_embeds.unsqueeze(1), model_stat["target_embeds"].unsqueeze(0)) + dists = dists.view([args.cut_overview[1000-t_int]+args.cut_innercut[1000-t_int], n, -1]) + losses = dists.mul(model_stat["weights"]).sum(2).mean(0) + loss_values.append(losses.sum().item()) # log loss, probably shouldn't do per cutn_batch + x_in_grad += torch.autograd.grad(losses.sum() * clip_guidance_scale, x_in)[0] / cutn_batches + tv_losses = tv_loss(x_in) + if use_secondary_model is True: + range_losses = range_loss(out) + else: + range_losses = range_loss(out['pred_xstart']) + sat_losses = torch.abs(x_in - x_in.clamp(min=-1,max=1)).mean() + loss = tv_losses.sum() * tv_scale + range_losses.sum() * range_scale + sat_losses.sum() * sat_scale + if init is not None and args.init_scale: + init_losses = lpips_model(x_in, init) + loss = loss + init_losses.sum() * args.init_scale + x_in_grad += torch.autograd.grad(loss, x_in)[0] + if torch.isnan(x_in_grad).any()==False: + grad = -torch.autograd.grad(x_in, x, x_in_grad)[0] + else: + # print("NaN'd") + x_is_NaN = True + grad = torch.zeros_like(x) + if args.clamp_grad and x_is_NaN == False: + magnitude = grad.square().mean().sqrt() + return grad * magnitude.clamp(max=args.clamp_max) / magnitude #min=-0.02, min=-clamp_max, + return grad + + if model_config['timestep_respacing'].startswith('ddim'): + sample_fn = diffusion.ddim_sample_loop_progressive + else: + sample_fn = diffusion.p_sample_loop_progressive + + + image_display = Output() + for i in range(args.n_batches): + if args.animation_mode == 'None': + display.clear_output(wait=True) + batchBar = tqdm(range(args.n_batches), desc ="Batches") + batchBar.n = i + batchBar.refresh() + print('') + display.display(image_display) + gc.collect() + torch.cuda.empty_cache() + cur_t = diffusion.num_timesteps - skip_steps - 1 + total_steps = cur_t + + if perlin_init: + init = regen_perlin() + + if model_config['timestep_respacing'].startswith('ddim'): + samples = sample_fn( + model, + (batch_size, 3, args.side_y, args.side_x), + clip_denoised=clip_denoised, + model_kwargs={}, + cond_fn=cond_fn, + progress=True, + skip_timesteps=skip_steps, + init_image=init, + randomize_class=randomize_class, + eta=eta, + ) + else: + samples = sample_fn( + model, + (batch_size, 3, args.side_y, args.side_x), + clip_denoised=clip_denoised, + model_kwargs={}, + cond_fn=cond_fn, + progress=True, + skip_timesteps=skip_steps, + init_image=init, + randomize_class=randomize_class, + ) + + + # with run_display: + # display.clear_output(wait=True) + imgToSharpen = None + for j, sample in enumerate(samples): + cur_t -= 1 + intermediateStep = False + if args.steps_per_checkpoint is not None: + if j % steps_per_checkpoint == 0 and j > 0: + intermediateStep = True + elif j in args.intermediate_saves: + intermediateStep = True + with image_display: + if j % args.display_rate == 0 or cur_t == -1 or intermediateStep == True: + for k, image in enumerate(sample['pred_xstart']): + # tqdm.write(f'Batch {i}, step {j}, output {k}:') + current_time = datetime.now().strftime('%y%m%d-%H%M%S_%f') + percent = math.ceil(j/total_steps*100) + if args.n_batches > 0: + #if intermediates are saved to the subfolder, don't append a step or percentage to the name + if cur_t == -1 and args.intermediates_in_subfolder is True: + save_num = f'{frame_num:04}' if animation_mode != "None" else i + filename = f'{args.batch_name}({args.batchNum})_{save_num}.png' + else: + #If we're working with percentages, append it + if args.steps_per_checkpoint is not None: + filename = f'{args.batch_name}({args.batchNum})_{i:04}-{percent:02}%.png' + # Or else, iIf we're working with specific steps, append those + else: + filename = f'{args.batch_name}({args.batchNum})_{i:04}-{j:03}.png' + image = TF.to_pil_image(image.add(1).div(2).clamp(0, 1)) + if j % args.display_rate == 0 or cur_t == -1: + image.save('progress.png') + display.clear_output(wait=True) + display.display(display.Image('progress.png')) + if args.steps_per_checkpoint is not None: + if j % args.steps_per_checkpoint == 0 and j > 0: + if args.intermediates_in_subfolder is True: + image.save(f'{partialFolder}/{filename}') + else: + image.save(f'{batchFolder}/{filename}') + else: + if j in args.intermediate_saves: + if args.intermediates_in_subfolder is True: + image.save(f'{partialFolder}/{filename}') + else: + image.save(f'{batchFolder}/{filename}') + if cur_t == -1: + if frame_num == 0: + save_settings() + if args.animation_mode != "None": + image.save('prevFrame.png') + if args.sharpen_preset != "Off" and animation_mode == "None": + imgToSharpen = image + if args.keep_unsharp is True: + image.save(f'{unsharpenFolder}/{filename}') + else: + image.save(f'{batchFolder}/{filename}') + # if frame_num != args.max_frames-1: + # display.clear_output() + + with image_display: + if args.sharpen_preset != "Off" and animation_mode == "None": + print('Starting Diffusion Sharpening...') + do_superres(imgToSharpen, f'{batchFolder}/{filename}') + display.clear_output() + + plt.plot(np.array(loss_values), 'r') + +def save_settings(): + setting_list = { + 'text_prompts': text_prompts, + 'image_prompts': image_prompts, + 'clip_guidance_scale': clip_guidance_scale, + 'tv_scale': tv_scale, + 'range_scale': range_scale, + 'sat_scale': sat_scale, + # 'cutn': cutn, + 'cutn_batches': cutn_batches, + 'max_frames': max_frames, + 'interp_spline': interp_spline, + # 'rotation_per_frame': rotation_per_frame, + 'init_image': init_image, + 'init_scale': init_scale, + 'skip_steps': skip_steps, + # 'zoom_per_frame': zoom_per_frame, + 'frames_scale': frames_scale, + 'frames_skip_steps': frames_skip_steps, + 'perlin_init': perlin_init, + 'perlin_mode': perlin_mode, + 'skip_augs': skip_augs, + 'randomize_class': randomize_class, + 'clip_denoised': clip_denoised, + 'clamp_grad': clamp_grad, + 'clamp_max': clamp_max, + 'seed': seed, + 'fuzzy_prompt': fuzzy_prompt, + 'rand_mag': rand_mag, + 'eta': eta, + 'width': width_height[0], + 'height': width_height[1], + 'diffusion_model': diffusion_model, + 'use_secondary_model': use_secondary_model, + 'steps': steps, + 'diffusion_steps': diffusion_steps, + 'ViTB32': ViTB32, + 'ViTB16': ViTB16, + 'ViTL14': ViTL14, + 'RN101': RN101, + 'RN50': RN50, + 'RN50x4': RN50x4, + 'RN50x16': RN50x16, + 'RN50x64': RN50x64, + 'cut_overview': str(cut_overview), + 'cut_innercut': str(cut_innercut), + 'cut_ic_pow': cut_ic_pow, + 'cut_icgray_p': str(cut_icgray_p), + 'key_frames': key_frames, + 'max_frames': max_frames, + 'angle': angle, + 'zoom': zoom, + 'translation_x': translation_x, + 'translation_y': translation_y, + 'translation_z': translation_z, + 'rotation_3d_x': rotation_3d_x, + 'rotation_3d_y': rotation_3d_y, + 'rotation_3d_z': rotation_3d_z, + 'midas_depth_model': midas_depth_model, + 'midas_weight': midas_weight, + 'near_plane': near_plane, + 'far_plane': far_plane, + 'fov': fov, + 'padding_mode': padding_mode, + 'sampling_mode': sampling_mode, + 'video_init_path':video_init_path, + 'extract_nth_frame':extract_nth_frame, + } + # print('Settings:', setting_list) + with open(f"{batchFolder}/{batch_name}({batchNum})_settings.txt", "w+") as f: #save settings + json.dump(setting_list, f, ensure_ascii=False, indent=4) + +# %% +#@title 1.6 Define the secondary diffusion model + +def append_dims(x, n): + return x[(Ellipsis, *(None,) * (n - x.ndim))] + + +def expand_to_planes(x, shape): + return append_dims(x, len(shape)).repeat([1, 1, *shape[2:]]) + + +def alpha_sigma_to_t(alpha, sigma): + return torch.atan2(sigma, alpha) * 2 / math.pi + + +def t_to_alpha_sigma(t): + return torch.cos(t * math.pi / 2), torch.sin(t * math.pi / 2) + + +@dataclass +class DiffusionOutput: + v: torch.Tensor + pred: torch.Tensor + eps: torch.Tensor + + +class ConvBlock(nn.Sequential): + def __init__(self, c_in, c_out): + super().__init__( + nn.Conv2d(c_in, c_out, 3, padding=1), + nn.ReLU(inplace=True), + ) + + +class SkipBlock(nn.Module): + def __init__(self, main, skip=None): + super().__init__() + self.main = nn.Sequential(*main) + self.skip = skip if skip else nn.Identity() + + def forward(self, input): + return torch.cat([self.main(input), self.skip(input)], dim=1) + + +class FourierFeatures(nn.Module): + def __init__(self, in_features, out_features, std=1.): + super().__init__() + assert out_features % 2 == 0 + self.weight = nn.Parameter(torch.randn([out_features // 2, in_features]) * std) + + def forward(self, input): + f = 2 * math.pi * input @ self.weight.T + return torch.cat([f.cos(), f.sin()], dim=-1) + + +class SecondaryDiffusionImageNet(nn.Module): + def __init__(self): + super().__init__() + c = 64 # The base channel count + + self.timestep_embed = FourierFeatures(1, 16) + + self.net = nn.Sequential( + ConvBlock(3 + 16, c), + ConvBlock(c, c), + SkipBlock([ + nn.AvgPool2d(2), + ConvBlock(c, c * 2), + ConvBlock(c * 2, c * 2), + SkipBlock([ + nn.AvgPool2d(2), + ConvBlock(c * 2, c * 4), + ConvBlock(c * 4, c * 4), + SkipBlock([ + nn.AvgPool2d(2), + ConvBlock(c * 4, c * 8), + ConvBlock(c * 8, c * 4), + nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False), + ]), + ConvBlock(c * 8, c * 4), + ConvBlock(c * 4, c * 2), + nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False), + ]), + ConvBlock(c * 4, c * 2), + ConvBlock(c * 2, c), + nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False), + ]), + ConvBlock(c * 2, c), + nn.Conv2d(c, 3, 3, padding=1), + ) + + def forward(self, input, t): + timestep_embed = expand_to_planes(self.timestep_embed(t[:, None]), input.shape) + v = self.net(torch.cat([input, timestep_embed], dim=1)) + alphas, sigmas = map(partial(append_dims, n=v.ndim), t_to_alpha_sigma(t)) + pred = input * alphas - v * sigmas + eps = input * sigmas + v * alphas + return DiffusionOutput(v, pred, eps) + + +class SecondaryDiffusionImageNet2(nn.Module): + def __init__(self): + super().__init__() + c = 64 # The base channel count + cs = [c, c * 2, c * 2, c * 4, c * 4, c * 8] + + self.timestep_embed = FourierFeatures(1, 16) + self.down = nn.AvgPool2d(2) + self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False) + + self.net = nn.Sequential( + ConvBlock(3 + 16, cs[0]), + ConvBlock(cs[0], cs[0]), + SkipBlock([ + self.down, + ConvBlock(cs[0], cs[1]), + ConvBlock(cs[1], cs[1]), + SkipBlock([ + self.down, + ConvBlock(cs[1], cs[2]), + ConvBlock(cs[2], cs[2]), + SkipBlock([ + self.down, + ConvBlock(cs[2], cs[3]), + ConvBlock(cs[3], cs[3]), + SkipBlock([ + self.down, + ConvBlock(cs[3], cs[4]), + ConvBlock(cs[4], cs[4]), + SkipBlock([ + self.down, + ConvBlock(cs[4], cs[5]), + ConvBlock(cs[5], cs[5]), + ConvBlock(cs[5], cs[5]), + ConvBlock(cs[5], cs[4]), + self.up, + ]), + ConvBlock(cs[4] * 2, cs[4]), + ConvBlock(cs[4], cs[3]), + self.up, + ]), + ConvBlock(cs[3] * 2, cs[3]), + ConvBlock(cs[3], cs[2]), + self.up, + ]), + ConvBlock(cs[2] * 2, cs[2]), + ConvBlock(cs[2], cs[1]), + self.up, + ]), + ConvBlock(cs[1] * 2, cs[1]), + ConvBlock(cs[1], cs[0]), + self.up, + ]), + ConvBlock(cs[0] * 2, cs[0]), + nn.Conv2d(cs[0], 3, 3, padding=1), + ) + + def forward(self, input, t): + timestep_embed = expand_to_planes(self.timestep_embed(t[:, None]), input.shape) + v = self.net(torch.cat([input, timestep_embed], dim=1)) + alphas, sigmas = map(partial(append_dims, n=v.ndim), t_to_alpha_sigma(t)) + pred = input * alphas - v * sigmas + eps = input * sigmas + v * alphas + return DiffusionOutput(v, pred, eps) + +# %% +#@title 1.7 SuperRes Define +class DDIMSampler(object): + def __init__(self, model, schedule="linear", **kwargs): + super().__init__() + self.model = model + self.ddpm_num_timesteps = model.num_timesteps + self.schedule = schedule + + def register_buffer(self, name, attr): + if type(attr) == torch.Tensor: + if attr.device != torch.device("cuda"): + attr = attr.to(torch.device("cuda")) + setattr(self, name, attr) + + def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True): + self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps, + num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose) + alphas_cumprod = self.model.alphas_cumprod + assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep' + to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device) + + self.register_buffer('betas', to_torch(self.model.betas)) + self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) + self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev)) + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu()))) + self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu()))) + self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu()))) + self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu()))) + self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1))) + + # ddim sampling parameters + ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(), + ddim_timesteps=self.ddim_timesteps, + eta=ddim_eta,verbose=verbose) + self.register_buffer('ddim_sigmas', ddim_sigmas) + self.register_buffer('ddim_alphas', ddim_alphas) + self.register_buffer('ddim_alphas_prev', ddim_alphas_prev) + self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas)) + sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt( + (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * ( + 1 - self.alphas_cumprod / self.alphas_cumprod_prev)) + self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps) + + @torch.no_grad() + def sample(self, + S, + batch_size, + shape, + conditioning=None, + callback=None, + normals_sequence=None, + img_callback=None, + quantize_x0=False, + eta=0., + mask=None, + x0=None, + temperature=1., + noise_dropout=0., + score_corrector=None, + corrector_kwargs=None, + verbose=True, + x_T=None, + log_every_t=100, + **kwargs + ): + if conditioning is not None: + if isinstance(conditioning, dict): + cbs = conditioning[list(conditioning.keys())[0]].shape[0] + if cbs != batch_size: + print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}") + else: + if conditioning.shape[0] != batch_size: + print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}") + + self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose) + # sampling + C, H, W = shape + size = (batch_size, C, H, W) + # print(f'Data shape for DDIM sampling is {size}, eta {eta}') + + samples, intermediates = self.ddim_sampling(conditioning, size, + callback=callback, + img_callback=img_callback, + quantize_denoised=quantize_x0, + mask=mask, x0=x0, + ddim_use_original_steps=False, + noise_dropout=noise_dropout, + temperature=temperature, + score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + x_T=x_T, + log_every_t=log_every_t + ) + return samples, intermediates + + @torch.no_grad() + def ddim_sampling(self, cond, shape, + x_T=None, ddim_use_original_steps=False, + callback=None, timesteps=None, quantize_denoised=False, + mask=None, x0=None, img_callback=None, log_every_t=100, + temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None): + device = self.model.betas.device + b = shape[0] + if x_T is None: + img = torch.randn(shape, device=device) + else: + img = x_T + + if timesteps is None: + timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps + elif timesteps is not None and not ddim_use_original_steps: + subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1 + timesteps = self.ddim_timesteps[:subset_end] + + intermediates = {'x_inter': [img], 'pred_x0': [img]} + time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps) + total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0] + print(f"Running DDIM Sharpening with {total_steps} timesteps") + + iterator = tqdm(time_range, desc='DDIM Sharpening', total=total_steps) + + for i, step in enumerate(iterator): + index = total_steps - i - 1 + ts = torch.full((b,), step, device=device, dtype=torch.long) + + if mask is not None: + assert x0 is not None + img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass? + img = img_orig * mask + (1. - mask) * img + + outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps, + quantize_denoised=quantize_denoised, temperature=temperature, + noise_dropout=noise_dropout, score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs) + img, pred_x0 = outs + if callback: callback(i) + if img_callback: img_callback(pred_x0, i) + + if index % log_every_t == 0 or index == total_steps - 1: + intermediates['x_inter'].append(img) + intermediates['pred_x0'].append(pred_x0) + + return img, intermediates + + @torch.no_grad() + def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False, + temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None): + b, *_, device = *x.shape, x.device + e_t = self.model.apply_model(x, t, c) + if score_corrector is not None: + assert self.model.parameterization == "eps" + e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs) + + alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas + alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev + sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas + sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas + # select parameters corresponding to the currently considered timestep + a_t = torch.full((b, 1, 1, 1), alphas[index], device=device) + a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device) + sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device) + sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device) + + # current prediction for x_0 + pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt() + if quantize_denoised: + pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0) + # direction pointing to x_t + dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t + noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature + if noise_dropout > 0.: + noise = torch.nn.functional.dropout(noise, p=noise_dropout) + x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise + return x_prev, pred_x0 + + +def download_models(mode): + + if mode == "superresolution": + # this is the small bsr light model + url_conf = 'https://heibox.uni-heidelberg.de/f/31a76b13ea27482981b4/?dl=1' + url_ckpt = 'https://heibox.uni-heidelberg.de/f/578df07c8fc04ffbadf3/?dl=1' + + path_conf = f'{model_path}/superres/project.yaml' + path_ckpt = f'{model_path}/superres/last.ckpt' + + download_url(url_conf, path_conf) + download_url(url_ckpt, path_ckpt) + + path_conf = path_conf + '/?dl=1' # fix it + path_ckpt = path_ckpt + '/?dl=1' # fix it + return path_conf, path_ckpt + + else: + raise NotImplementedError + + +def load_model_from_config(config, ckpt): + print(f"Loading model from {ckpt}") + pl_sd = torch.load(ckpt, map_location="cpu") + global_step = pl_sd["global_step"] + sd = pl_sd["state_dict"] + model = instantiate_from_config(config.model) + m, u = model.load_state_dict(sd, strict=False) + model.cuda() + model.eval() + return {"model": model}, global_step + + +def get_model(mode): + path_conf, path_ckpt = download_models(mode) + config = OmegaConf.load(path_conf) + model, step = load_model_from_config(config, path_ckpt) + return model + + +def get_custom_cond(mode): + dest = "data/example_conditioning" + + if mode == "superresolution": + uploaded_img = files.upload() + filename = next(iter(uploaded_img)) + name, filetype = filename.split(".") # todo assumes just one dot in name ! + os.rename(f"{filename}", f"{dest}/{mode}/custom_{name}.{filetype}") + + elif mode == "text_conditional": + w = widgets.Text(value='A cake with cream!', disabled=True) + display.display(w) + + with open(f"{dest}/{mode}/custom_{w.value[:20]}.txt", 'w') as f: + f.write(w.value) + + elif mode == "class_conditional": + w = widgets.IntSlider(min=0, max=1000) + display.display(w) + with open(f"{dest}/{mode}/custom.txt", 'w') as f: + f.write(w.value) + + else: + raise NotImplementedError(f"cond not implemented for mode{mode}") + + +def get_cond_options(mode): + path = "data/example_conditioning" + path = os.path.join(path, mode) + onlyfiles = [f for f in sorted(os.listdir(path))] + return path, onlyfiles + + +def select_cond_path(mode): + path = "data/example_conditioning" # todo + path = os.path.join(path, mode) + onlyfiles = [f for f in sorted(os.listdir(path))] + + selected = widgets.RadioButtons( + options=onlyfiles, + description='Select conditioning:', + disabled=False + ) + display.display(selected) + selected_path = os.path.join(path, selected.value) + return selected_path + + +def get_cond(mode, img): + example = dict() + if mode == "superresolution": + up_f = 4 + # visualize_cond_img(selected_path) + + c = img + c = torch.unsqueeze(torchvision.transforms.ToTensor()(c), 0) + c_up = torchvision.transforms.functional.resize(c, size=[up_f * c.shape[2], up_f * c.shape[3]], antialias=True) + c_up = rearrange(c_up, '1 c h w -> 1 h w c') + c = rearrange(c, '1 c h w -> 1 h w c') + c = 2. * c - 1. + + c = c.to(torch.device("cuda")) + example["LR_image"] = c + example["image"] = c_up + + return example + + +def visualize_cond_img(path): + display.display(ipyimg(filename=path)) + + +def sr_run(model, img, task, custom_steps, eta, resize_enabled=False, classifier_ckpt=None, global_step=None): + # global stride + + example = get_cond(task, img) + + save_intermediate_vid = False + n_runs = 1 + masked = False + guider = None + ckwargs = None + mode = 'ddim' + ddim_use_x0_pred = False + temperature = 1. + eta = eta + make_progrow = True + custom_shape = None + + height, width = example["image"].shape[1:3] + split_input = height >= 128 and width >= 128 + + if split_input: + ks = 128 + stride = 64 + vqf = 4 # + model.split_input_params = {"ks": (ks, ks), "stride": (stride, stride), + "vqf": vqf, + "patch_distributed_vq": True, + "tie_braker": False, + "clip_max_weight": 0.5, + "clip_min_weight": 0.01, + "clip_max_tie_weight": 0.5, + "clip_min_tie_weight": 0.01} + else: + if hasattr(model, "split_input_params"): + delattr(model, "split_input_params") + + invert_mask = False + + x_T = None + for n in range(n_runs): + if custom_shape is not None: + x_T = torch.randn(1, custom_shape[1], custom_shape[2], custom_shape[3]).to(model.device) + x_T = repeat(x_T, '1 c h w -> b c h w', b=custom_shape[0]) + + logs = make_convolutional_sample(example, model, + mode=mode, custom_steps=custom_steps, + eta=eta, swap_mode=False , masked=masked, + invert_mask=invert_mask, quantize_x0=False, + custom_schedule=None, decode_interval=10, + resize_enabled=resize_enabled, custom_shape=custom_shape, + temperature=temperature, noise_dropout=0., + corrector=guider, corrector_kwargs=ckwargs, x_T=x_T, save_intermediate_vid=save_intermediate_vid, + make_progrow=make_progrow,ddim_use_x0_pred=ddim_use_x0_pred + ) + return logs + + +@torch.no_grad() +def convsample_ddim(model, cond, steps, shape, eta=1.0, callback=None, normals_sequence=None, + mask=None, x0=None, quantize_x0=False, img_callback=None, + temperature=1., noise_dropout=0., score_corrector=None, + corrector_kwargs=None, x_T=None, log_every_t=None + ): + + ddim = DDIMSampler(model) + bs = shape[0] # dont know where this comes from but wayne + shape = shape[1:] # cut batch dim + # print(f"Sampling with eta = {eta}; steps: {steps}") + samples, intermediates = ddim.sample(steps, batch_size=bs, shape=shape, conditioning=cond, callback=callback, + normals_sequence=normals_sequence, quantize_x0=quantize_x0, eta=eta, + mask=mask, x0=x0, temperature=temperature, verbose=False, + score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, x_T=x_T) + + return samples, intermediates + + +@torch.no_grad() +def make_convolutional_sample(batch, model, mode="vanilla", custom_steps=None, eta=1.0, swap_mode=False, masked=False, + invert_mask=True, quantize_x0=False, custom_schedule=None, decode_interval=1000, + resize_enabled=False, custom_shape=None, temperature=1., noise_dropout=0., corrector=None, + corrector_kwargs=None, x_T=None, save_intermediate_vid=False, make_progrow=True,ddim_use_x0_pred=False): + log = dict() + + z, c, x, xrec, xc = model.get_input(batch, model.first_stage_key, + return_first_stage_outputs=True, + force_c_encode=not (hasattr(model, 'split_input_params') + and model.cond_stage_key == 'coordinates_bbox'), + return_original_cond=True) + + log_every_t = 1 if save_intermediate_vid else None + + if custom_shape is not None: + z = torch.randn(custom_shape) + # print(f"Generating {custom_shape[0]} samples of shape {custom_shape[1:]}") + + z0 = None + + log["input"] = x + log["reconstruction"] = xrec + + if ismap(xc): + log["original_conditioning"] = model.to_rgb(xc) + if hasattr(model, 'cond_stage_key'): + log[model.cond_stage_key] = model.to_rgb(xc) + + else: + log["original_conditioning"] = xc if xc is not None else torch.zeros_like(x) + if model.cond_stage_model: + log[model.cond_stage_key] = xc if xc is not None else torch.zeros_like(x) + if model.cond_stage_key =='class_label': + log[model.cond_stage_key] = xc[model.cond_stage_key] + + with model.ema_scope("Plotting"): + t0 = time.time() + img_cb = None + + sample, intermediates = convsample_ddim(model, c, steps=custom_steps, shape=z.shape, + eta=eta, + quantize_x0=quantize_x0, img_callback=img_cb, mask=None, x0=z0, + temperature=temperature, noise_dropout=noise_dropout, + score_corrector=corrector, corrector_kwargs=corrector_kwargs, + x_T=x_T, log_every_t=log_every_t) + t1 = time.time() + + if ddim_use_x0_pred: + sample = intermediates['pred_x0'][-1] + + x_sample = model.decode_first_stage(sample) + + try: + x_sample_noquant = model.decode_first_stage(sample, force_not_quantize=True) + log["sample_noquant"] = x_sample_noquant + log["sample_diff"] = torch.abs(x_sample_noquant - x_sample) + except: + pass + + log["sample"] = x_sample + log["time"] = t1 - t0 + + return log + +sr_diffMode = 'superresolution' +sr_model = get_model('superresolution') + + + + + + +def do_superres(img, filepath): + + if args.sharpen_preset == 'Faster': + sr_diffusion_steps = "25" + sr_pre_downsample = '1/2' + if args.sharpen_preset == 'Fast': + sr_diffusion_steps = "100" + sr_pre_downsample = '1/2' + if args.sharpen_preset == 'Slow': + sr_diffusion_steps = "25" + sr_pre_downsample = 'None' + if args.sharpen_preset == 'Very Slow': + sr_diffusion_steps = "100" + sr_pre_downsample = 'None' + + + sr_post_downsample = 'Original Size' + sr_diffusion_steps = int(sr_diffusion_steps) + sr_eta = 1.0 + sr_downsample_method = 'Lanczos' + + gc.collect() + torch.cuda.empty_cache() + + im_og = img + width_og, height_og = im_og.size + + #Downsample Pre + if sr_pre_downsample == '1/2': + downsample_rate = 2 + elif sr_pre_downsample == '1/4': + downsample_rate = 4 + else: + downsample_rate = 1 + + width_downsampled_pre = width_og//downsample_rate + height_downsampled_pre = height_og//downsample_rate + + if downsample_rate != 1: + # print(f'Downsampling from [{width_og}, {height_og}] to [{width_downsampled_pre}, {height_downsampled_pre}]') + im_og = im_og.resize((width_downsampled_pre, height_downsampled_pre), Image.LANCZOS) + # im_og.save('/content/temp.png') + # filepath = '/content/temp.png' + + logs = sr_run(sr_model["model"], im_og, sr_diffMode, sr_diffusion_steps, sr_eta) + + sample = logs["sample"] + sample = sample.detach().cpu() + sample = torch.clamp(sample, -1., 1.) + sample = (sample + 1.) / 2. * 255 + sample = sample.numpy().astype(np.uint8) + sample = np.transpose(sample, (0, 2, 3, 1)) + a = Image.fromarray(sample[0]) + + #Downsample Post + if sr_post_downsample == '1/2': + downsample_rate = 2 + elif sr_post_downsample == '1/4': + downsample_rate = 4 + else: + downsample_rate = 1 + + width, height = a.size + width_downsampled_post = width//downsample_rate + height_downsampled_post = height//downsample_rate + + if sr_downsample_method == 'Lanczos': + aliasing = Image.LANCZOS + else: + aliasing = Image.NEAREST + + if downsample_rate != 1: + # print(f'Downsampling from [{width}, {height}] to [{width_downsampled_post}, {height_downsampled_post}]') + a = a.resize((width_downsampled_post, height_downsampled_post), aliasing) + elif sr_post_downsample == 'Original Size': + # print(f'Downsampling from [{width}, {height}] to Original Size [{width_og}, {height_og}]') + a = a.resize((width_og, height_og), aliasing) + + display.display(a) + a.save(filepath) + return + print(f'Processing finished!') + + +# %% +""" +# 2. Diffusion and CLIP model settings +""" + +# %% +#@markdown ####**Models Settings:** +diffusion_model = "512x512_diffusion_uncond_finetune_008100" #@param ["256x256_diffusion_uncond", "512x512_diffusion_uncond_finetune_008100"] +use_secondary_model = True #@param {type: 'boolean'} + +timestep_respacing = '50' # param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000'] +diffusion_steps = 1000 # param {type: 'number'} +use_checkpoint = True #@param {type: 'boolean'} +ViTB32 = True #@param{type:"boolean"} +ViTB16 = True #@param{type:"boolean"} +ViTL14 = False #@param{type:"boolean"} +RN101 = False #@param{type:"boolean"} +RN50 = True #@param{type:"boolean"} +RN50x4 = False #@param{type:"boolean"} +RN50x16 = False #@param{type:"boolean"} +RN50x64 = False #@param{type:"boolean"} +SLIPB16 = False # param{type:"boolean"} +SLIPL16 = False # param{type:"boolean"} + +#@markdown If you're having issues with model downloads, check this to compare SHA's: +check_model_SHA = False #@param{type:"boolean"} + +model_256_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a' +model_512_SHA = '9c111ab89e214862b76e1fa6a1b3f1d329b1a88281885943d2cdbe357ad57648' +model_secondary_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a' + +model_256_link = 'https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt' +model_512_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/512x512_diffusion_uncond_finetune_008100.pt' +model_secondary_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/secondary_model_imagenet_2.pth' + +model_256_path = f'{model_path}/256x256_diffusion_uncond.pt' +model_512_path = f'{model_path}/512x512_diffusion_uncond_finetune_008100.pt' +model_secondary_path = f'{model_path}/secondary_model_imagenet_2.pth' + +# Download the diffusion model +if diffusion_model == '256x256_diffusion_uncond': + if os.path.exists(model_256_path) and check_model_SHA: + print('Checking 256 Diffusion File') + with open(model_256_path,"rb") as f: + bytes = f.read() + hash = hashlib.sha256(bytes).hexdigest(); + if hash == model_256_SHA: + print('256 Model SHA matches') + model_256_downloaded = True + else: + print("256 Model SHA doesn't match, redownloading...") + wget(model_256_link, out=model_path) + model_256_downloaded = True + elif os.path.exists(model_256_path) and not check_model_SHA or model_256_downloaded == True: + print('256 Model already downloaded, check check_model_SHA if the file is corrupt') + else: + wget(model_256_link, out=model_path) + model_256_downloaded = True +elif diffusion_model == '512x512_diffusion_uncond_finetune_008100': + if os.path.exists(model_512_path) and check_model_SHA: + print('Checking 512 Diffusion File') + with open(model_512_path,"rb") as f: + bytes = f.read() + hash = hashlib.sha256(bytes).hexdigest(); + if hash == model_512_SHA: + print('512 Model SHA matches') + model_512_downloaded = True + else: + print("512 Model SHA doesn't match, redownloading...") + wget(model_512_link, out=model_path) + model_512_downloaded = True + elif os.path.exists(model_512_path) and not check_model_SHA or model_512_downloaded == True: + print('512 Model already downloaded, check check_model_SHA if the file is corrupt') + else: + wget(model_512_link, out=model_path) + model_512_downloaded = True + + +# Download the secondary diffusion model v2 +if use_secondary_model == True: + if os.path.exists(model_secondary_path) and check_model_SHA: + print('Checking Secondary Diffusion File') + with open(model_secondary_path,"rb") as f: + bytes = f.read() + hash = hashlib.sha256(bytes).hexdigest(); + if hash == model_secondary_SHA: + print('Secondary Model SHA matches') + model_secondary_downloaded = True + else: + print("Secondary Model SHA doesn't match, redownloading...") + wget(model_secondary_link, out=model_path) + model_secondary_downloaded = True + elif os.path.exists(model_secondary_path) and not check_model_SHA or model_secondary_downloaded == True: + print('Secondary Model already downloaded, check check_model_SHA if the file is corrupt') + else: + wget(model_secondary_link, out=model_path) + model_secondary_downloaded = True + +model_config = model_and_diffusion_defaults() +if diffusion_model == '512x512_diffusion_uncond_finetune_008100': + model_config.update({ + 'attention_resolutions': '32, 16, 8', + 'class_cond': False, + 'diffusion_steps': diffusion_steps, + 'rescale_timesteps': True, + 'timestep_respacing': timestep_respacing, + 'image_size': 512, + 'learn_sigma': True, + 'noise_schedule': 'linear', + 'num_channels': 256, + 'num_head_channels': 64, + 'num_res_blocks': 2, + 'resblock_updown': True, + 'use_checkpoint': use_checkpoint, + 'use_fp16': True, + 'use_scale_shift_norm': True, + }) +elif diffusion_model == '256x256_diffusion_uncond': + model_config.update({ + 'attention_resolutions': '32, 16, 8', + 'class_cond': False, + 'diffusion_steps': diffusion_steps, + 'rescale_timesteps': True, + 'timestep_respacing': timestep_respacing, + 'image_size': 256, + 'learn_sigma': True, + 'noise_schedule': 'linear', + 'num_channels': 256, + 'num_head_channels': 64, + 'num_res_blocks': 2, + 'resblock_updown': True, + 'use_checkpoint': use_checkpoint, + 'use_fp16': True, + 'use_scale_shift_norm': True, + }) + +secondary_model_ver = 2 +model_default = model_config['image_size'] + + + +if secondary_model_ver == 2: + secondary_model = SecondaryDiffusionImageNet2() + secondary_model.load_state_dict(torch.load(f'{model_path}/secondary_model_imagenet_2.pth', map_location='cpu')) +secondary_model.eval().requires_grad_(False).to(device) + +clip_models = [] +if ViTB32 is True: clip_models.append(clip.load('ViT-B/32', jit=False)[0].eval().requires_grad_(False).to(device)) +if ViTB16 is True: clip_models.append(clip.load('ViT-B/16', jit=False)[0].eval().requires_grad_(False).to(device) ) +if ViTL14 is True: clip_models.append(clip.load('ViT-L/14', jit=False)[0].eval().requires_grad_(False).to(device) ) +if RN50 is True: clip_models.append(clip.load('RN50', jit=False)[0].eval().requires_grad_(False).to(device)) +if RN50x4 is True: clip_models.append(clip.load('RN50x4', jit=False)[0].eval().requires_grad_(False).to(device)) +if RN50x16 is True: clip_models.append(clip.load('RN50x16', jit=False)[0].eval().requires_grad_(False).to(device)) +if RN50x64 is True: clip_models.append(clip.load('RN50x64', jit=False)[0].eval().requires_grad_(False).to(device)) +if RN101 is True: clip_models.append(clip.load('RN101', jit=False)[0].eval().requires_grad_(False).to(device)) + +if SLIPB16: + SLIPB16model = SLIP_VITB16(ssl_mlp_dim=4096, ssl_emb_dim=256) + if not os.path.exists(f'{model_path}/slip_base_100ep.pt'): + wget("https://dl.fbaipublicfiles.com/slip/slip_base_100ep.pt", out=model_path) + sd = torch.load(f'{model_path}/slip_base_100ep.pt') + real_sd = {} + for k, v in sd['state_dict'].items(): + real_sd['.'.join(k.split('.')[1:])] = v + del sd + SLIPB16model.load_state_dict(real_sd) + SLIPB16model.requires_grad_(False).eval().to(device) + + clip_models.append(SLIPB16model) + +if SLIPL16: + SLIPL16model = SLIP_VITL16(ssl_mlp_dim=4096, ssl_emb_dim=256) + if not os.path.exists(f'{model_path}/slip_large_100ep.pt'): + wget("https://dl.fbaipublicfiles.com/slip/slip_large_100ep.pt", out=model_path) + sd = torch.load(f'{model_path}/slip_large_100ep.pt') + real_sd = {} + for k, v in sd['state_dict'].items(): + real_sd['.'.join(k.split('.')[1:])] = v + del sd + SLIPL16model.load_state_dict(real_sd) + SLIPL16model.requires_grad_(False).eval().to(device) + + clip_models.append(SLIPL16model) + +normalize = T.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711]) +lpips_model = lpips.LPIPS(net='vgg').to(device) + + +# %% +""" +# 3. Settings +""" + +# %% +#@markdown ####**Basic Settings:** +batch_name = 'TimeToDisco' #@param{type: 'string'} +steps = 250 #@param [25,50,100,150,250,500,1000]{type: 'raw', allow-input: true} +width_height = [1280, 768]#@param{type: 'raw'} +clip_guidance_scale = 5000 #@param{type: 'number'} +tv_scale = 0#@param{type: 'number'} +range_scale = 150#@param{type: 'number'} +sat_scale = 0#@param{type: 'number'} +cutn_batches = 4 #@param{type: 'number'} +skip_augs = False#@param{type: 'boolean'} + +#@markdown --- + +#@markdown ####**Init Settings:** +init_image = None #@param{type: 'string'} +init_scale = 1000 #@param{type: 'integer'} +skip_steps = 0 #@param{type: 'integer'} +#@markdown *Make sure you set skip_steps to ~50% of your steps if you want to use an init image.* + +#Get corrected sizes +side_x = (width_height[0]//64)*64; +side_y = (width_height[1]//64)*64; +if side_x != width_height[0] or side_y != width_height[1]: + print(f'Changing output size to {side_x}x{side_y}. Dimensions must by multiples of 64.') + +#Update Model Settings +timestep_respacing = f'ddim{steps}' +diffusion_steps = (1000//steps)*steps if steps < 1000 else steps +model_config.update({ + 'timestep_respacing': timestep_respacing, + 'diffusion_steps': diffusion_steps, +}) + +#Make folder for batch +batchFolder = f'{outDirPath}/{batch_name}' +createPath(batchFolder) + + +# %% +""" +### Animation Settings +""" + +# %% +#@markdown ####**Animation Mode:** +animation_mode = 'None' #@param ['None', '2D', '3D', 'Video Input'] {type:'string'} +#@markdown *For animation, you probably want to turn `cutn_batches` to 1 to make it quicker.* + + +#@markdown --- + +#@markdown ####**Video Input Settings:** +if is_colab: + video_init_path = "/content/training.mp4" #@param {type: 'string'} +else: + video_init_path = "training.mp4" #@param {type: 'string'} +extract_nth_frame = 2 #@param {type:"number"} + +if animation_mode == "Video Input": + if is_colab: + videoFramesFolder = f'/content/videoFrames' + else: + videoFramesFolder = f'videoFrames' + createPath(videoFramesFolder) + print(f"Exporting Video Frames (1 every {extract_nth_frame})...") + try: + for f in pathlib.Path(f'{videoFramesFolder}').glob('*.jpg'): + f.unlink() + except: + print('') + vf = f'"select=not(mod(n\,{extract_nth_frame}))"' + subprocess.run(['ffmpeg', '-i', f'{video_init_path}', '-vf', f'{vf}', '-vsync', 'vfr', '-q:v', '2', '-loglevel', 'error', '-stats', f'{videoFramesFolder}/%04d.jpg'], stdout=subprocess.PIPE).stdout.decode('utf-8') + #!ffmpeg -i {video_init_path} -vf {vf} -vsync vfr -q:v 2 -loglevel error -stats {videoFramesFolder}/%04d.jpg + + +#@markdown --- + +#@markdown ####**2D Animation Settings:** +#@markdown `zoom` is a multiplier of dimensions, 1 is no zoom. + +key_frames = True #@param {type:"boolean"} +max_frames = 10000#@param {type:"number"} + +if animation_mode == "Video Input": + max_frames = len(glob(f'{videoFramesFolder}/*.jpg')) + +interp_spline = 'Linear' #Do not change, currently will not look good. param ['Linear','Quadratic','Cubic']{type:"string"} +angle = "0:(0)"#@param {type:"string"} +zoom = "0: (1), 10: (1.05)"#@param {type:"string"} +translation_x = "0: (0)"#@param {type:"string"} +translation_y = "0: (0)"#@param {type:"string"} +translation_z = "0: (10.0)"#@param {type:"string"} +rotation_3d_x = "0: (0)"#@param {type:"string"} +rotation_3d_y = "0: (0)"#@param {type:"string"} +rotation_3d_z = "0: (0)"#@param {type:"string"} +midas_depth_model = "dpt_large"#@param {type:"string"} +midas_weight = 0.3#@param {type:"number"} +near_plane = 200#@param {type:"number"} +far_plane = 10000#@param {type:"number"} +fov = 40#@param {type:"number"} +padding_mode = 'border'#@param {type:"string"} +sampling_mode = 'bicubic'#@param {type:"string"} + +#@markdown --- + +#@markdown ####**Coherency Settings:** +#@markdown `frame_scale` tries to guide the new frame to looking like the old one. A good default is 1500. +frames_scale = 1500 #@param{type: 'integer'} +#@markdown `frame_skip_steps` will blur the previous frame - higher values will flicker less but struggle to add enough new detail to zoom into. +frames_skip_steps = '60%' #@param ['40%', '50%', '60%', '70%', '80%'] {type: 'string'} + + +def parse_key_frames(string, prompt_parser=None): + """Given a string representing frame numbers paired with parameter values at that frame, + return a dictionary with the frame numbers as keys and the parameter values as the values. + + Parameters + ---------- + string: string + Frame numbers paired with parameter values at that frame number, in the format + 'framenumber1: (parametervalues1), framenumber2: (parametervalues2), ...' + prompt_parser: function or None, optional + If provided, prompt_parser will be applied to each string of parameter values. + + Returns + ------- + dict + Frame numbers as keys, parameter values at that frame number as values + + Raises + ------ + RuntimeError + If the input string does not match the expected format. + + Examples + -------- + >>> parse_key_frames("10:(Apple: 1| Orange: 0), 20: (Apple: 0| Orange: 1| Peach: 1)") + {10: 'Apple: 1| Orange: 0', 20: 'Apple: 0| Orange: 1| Peach: 1'} + + >>> parse_key_frames("10:(Apple: 1| Orange: 0), 20: (Apple: 0| Orange: 1| Peach: 1)", prompt_parser=lambda x: x.lower())) + {10: 'apple: 1| orange: 0', 20: 'apple: 0| orange: 1| peach: 1'} + """ + import re + pattern = r'((?P[0-9]+):[\s]*[\(](?P[\S\s]*?)[\)])' + frames = dict() + for match_object in re.finditer(pattern, string): + frame = int(match_object.groupdict()['frame']) + param = match_object.groupdict()['param'] + if prompt_parser: + frames[frame] = prompt_parser(param) + else: + frames[frame] = param + + if frames == {} and len(string) != 0: + raise RuntimeError('Key Frame string not correctly formatted') + return frames + +def get_inbetweens(key_frames, integer=False): + """Given a dict with frame numbers as keys and a parameter value as values, + return a pandas Series containing the value of the parameter at every frame from 0 to max_frames. + Any values not provided in the input dict are calculated by linear interpolation between + the values of the previous and next provided frames. If there is no previous provided frame, then + the value is equal to the value of the next provided frame, or if there is no next provided frame, + then the value is equal to the value of the previous provided frame. If no frames are provided, + all frame values are NaN. + + Parameters + ---------- + key_frames: dict + A dict with integer frame numbers as keys and numerical values of a particular parameter as values. + integer: Bool, optional + If True, the values of the output series are converted to integers. + Otherwise, the values are floats. + + Returns + ------- + pd.Series + A Series with length max_frames representing the parameter values for each frame. + + Examples + -------- + >>> max_frames = 5 + >>> get_inbetweens({1: 5, 3: 6}) + 0 5.0 + 1 5.0 + 2 5.5 + 3 6.0 + 4 6.0 + dtype: float64 + + >>> get_inbetweens({1: 5, 3: 6}, integer=True) + 0 5 + 1 5 + 2 5 + 3 6 + 4 6 + dtype: int64 + """ + key_frame_series = pd.Series([np.nan for a in range(max_frames)]) + + for i, value in key_frames.items(): + key_frame_series[i] = value + key_frame_series = key_frame_series.astype(float) + + interp_method = interp_spline + + if interp_method == 'Cubic' and len(key_frames.items()) <=3: + interp_method = 'Quadratic' + + if interp_method == 'Quadratic' and len(key_frames.items()) <= 2: + interp_method = 'Linear' + + + key_frame_series[0] = key_frame_series[key_frame_series.first_valid_index()] + key_frame_series[max_frames-1] = key_frame_series[key_frame_series.last_valid_index()] + # key_frame_series = key_frame_series.interpolate(method=intrp_method,order=1, limit_direction='both') + key_frame_series = key_frame_series.interpolate(method=interp_method.lower(),limit_direction='both') + if integer: + return key_frame_series.astype(int) + return key_frame_series + +def split_prompts(prompts): + prompt_series = pd.Series([np.nan for a in range(max_frames)]) + for i, prompt in prompts.items(): + prompt_series[i] = prompt + # prompt_series = prompt_series.astype(str) + prompt_series = prompt_series.ffill().bfill() + return prompt_series + +if key_frames: + try: + angle_series = get_inbetweens(parse_key_frames(angle)) + except RuntimeError as e: + print( + "WARNING: You have selected to use key frames, but you have not " + "formatted `angle` correctly for key frames.\n" + "Attempting to interpret `angle` as " + f'"0: ({angle})"\n' + "Please read the instructions to find out how to use key frames " + "correctly.\n" + ) + angle = f"0: ({angle})" + angle_series = get_inbetweens(parse_key_frames(angle)) + + try: + zoom_series = get_inbetweens(parse_key_frames(zoom)) + except RuntimeError as e: + print( + "WARNING: You have selected to use key frames, but you have not " + "formatted `zoom` correctly for key frames.\n" + "Attempting to interpret `zoom` as " + f'"0: ({zoom})"\n' + "Please read the instructions to find out how to use key frames " + "correctly.\n" + ) + zoom = f"0: ({zoom})" + zoom_series = get_inbetweens(parse_key_frames(zoom)) + + try: + translation_x_series = get_inbetweens(parse_key_frames(translation_x)) + except RuntimeError as e: + print( + "WARNING: You have selected to use key frames, but you have not " + "formatted `translation_x` correctly for key frames.\n" + "Attempting to interpret `translation_x` as " + f'"0: ({translation_x})"\n' + "Please read the instructions to find out how to use key frames " + "correctly.\n" + ) + translation_x = f"0: ({translation_x})" + translation_x_series = get_inbetweens(parse_key_frames(translation_x)) + + try: + translation_y_series = get_inbetweens(parse_key_frames(translation_y)) + except RuntimeError as e: + print( + "WARNING: You have selected to use key frames, but you have not " + "formatted `translation_y` correctly for key frames.\n" + "Attempting to interpret `translation_y` as " + f'"0: ({translation_y})"\n' + "Please read the instructions to find out how to use key frames " + "correctly.\n" + ) + translation_y = f"0: ({translation_y})" + translation_y_series = get_inbetweens(parse_key_frames(translation_y)) + + try: + translation_z_series = get_inbetweens(parse_key_frames(translation_z)) + except RuntimeError as e: + print( + "WARNING: You have selected to use key frames, but you have not " + "formatted `translation_z` correctly for key frames.\n" + "Attempting to interpret `translation_z` as " + f'"0: ({translation_z})"\n' + "Please read the instructions to find out how to use key frames " + "correctly.\n" + ) + translation_z = f"0: ({translation_z})" + translation_z_series = get_inbetweens(parse_key_frames(translation_z)) + + try: + rotation_3d_x_series = get_inbetweens(parse_key_frames(rotation_3d_x)) + except RuntimeError as e: + print( + "WARNING: You have selected to use key frames, but you have not " + "formatted `rotation_3d_x` correctly for key frames.\n" + "Attempting to interpret `rotation_3d_x` as " + f'"0: ({rotation_3d_x})"\n' + "Please read the instructions to find out how to use key frames " + "correctly.\n" + ) + rotation_3d_x = f"0: ({rotation_3d_x})" + rotation_3d_x_series = get_inbetweens(parse_key_frames(rotation_3d_x)) + + try: + rotation_3d_y_series = get_inbetweens(parse_key_frames(rotation_3d_y)) + except RuntimeError as e: + print( + "WARNING: You have selected to use key frames, but you have not " + "formatted `rotation_3d_y` correctly for key frames.\n" + "Attempting to interpret `rotation_3d_y` as " + f'"0: ({rotation_3d_y})"\n' + "Please read the instructions to find out how to use key frames " + "correctly.\n" + ) + rotation_3d_y = f"0: ({rotation_3d_y})" + rotation_3d_y_series = get_inbetweens(parse_key_frames(rotation_3d_y)) + + try: + rotation_3d_z_series = get_inbetweens(parse_key_frames(rotation_3d_z)) + except RuntimeError as e: + print( + "WARNING: You have selected to use key frames, but you have not " + "formatted `rotation_3d_z` correctly for key frames.\n" + "Attempting to interpret `rotation_3d_z` as " + f'"0: ({rotation_3d_z})"\n' + "Please read the instructions to find out how to use key frames " + "correctly.\n" + ) + rotation_3d_z = f"0: ({rotation_3d_z})" + rotation_3d_z_series = get_inbetweens(parse_key_frames(rotation_3d_z)) + +else: + angle = float(angle) + zoom = float(zoom) + translation_x = float(translation_x) + translation_y = float(translation_y) + translation_z = float(translation_z) + rotation_3d_x = float(rotation_3d_x) + rotation_3d_y = float(rotation_3d_y) + rotation_3d_z = float(rotation_3d_z) + + +# %% +""" +### Extra Settings + Partial Saves, Diffusion Sharpening, Advanced Settings, Cutn Scheduling +""" + +# %% +#@markdown ####**Saving:** + +intermediate_saves = 0#@param{type: 'raw'} +intermediates_in_subfolder = True #@param{type: 'boolean'} +#@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 + +#@markdown A value of `2` will save a copy at 33% and 66%. 0 will save none. + +#@markdown A value of `[5, 9, 34, 45]` will save at steps 5, 9, 34, and 45. (Make sure to include the brackets) + + +if type(intermediate_saves) is not list: + if intermediate_saves: + steps_per_checkpoint = math.floor((steps - skip_steps - 1) // (intermediate_saves+1)) + steps_per_checkpoint = steps_per_checkpoint if steps_per_checkpoint > 0 else 1 + print(f'Will save every {steps_per_checkpoint} steps') + else: + steps_per_checkpoint = steps+10 +else: + steps_per_checkpoint = None + +if intermediate_saves and intermediates_in_subfolder is True: + partialFolder = f'{batchFolder}/partials' + createPath(partialFolder) + + #@markdown --- + +#@markdown ####**SuperRes Sharpening:** +#@markdown *Sharpen each image using latent-diffusion. Does not run in animation mode. `keep_unsharp` will save both versions.* +sharpen_preset = 'Off' #@param ['Off', 'Faster', 'Fast', 'Slow', 'Very Slow'] +keep_unsharp = True #@param{type: 'boolean'} + +if sharpen_preset != 'Off' and keep_unsharp is True: + unsharpenFolder = f'{batchFolder}/unsharpened' + createPath(unsharpenFolder) + + + #@markdown --- + +#@markdown ####**Advanced Settings:** +#@markdown *There are a few extra advanced settings available if you double click this cell.* + +#@markdown *Perlin init will replace your init, so uncheck if using one.* + +perlin_init = False #@param{type: 'boolean'} +perlin_mode = 'mixed' #@param ['mixed', 'color', 'gray'] +set_seed = 'random_seed' #@param{type: 'string'} +eta = 0.8#@param{type: 'number'} +clamp_grad = True #@param{type: 'boolean'} +clamp_max = 0.05 #@param{type: 'number'} + + +### EXTRA ADVANCED SETTINGS: +randomize_class = True +clip_denoised = False +fuzzy_prompt = False +rand_mag = 0.05 + + + #@markdown --- + +#@markdown ####**Cutn Scheduling:** +#@markdown Format: `[40]*400+[20]*600` = 40 cuts for the first 400 /1000 steps, then 20 for the last 600/1000 + +#@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. + +cut_overview = "[12]*400+[4]*600" #@param {type: 'string'} +cut_innercut ="[4]*400+[12]*600"#@param {type: 'string'} +cut_ic_pow = 1#@param {type: 'number'} +cut_icgray_p = "[0.2]*400+[0]*600"#@param {type: 'string'} + + +# %% +""" +### Prompts +`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. +""" + +# %% +text_prompts = { + 0: ["A beautiful painting of a singular lighthouse, shining its light across a tumultuous sea of blood by greg rutkowski and thomas kinkade, Trending on artstation.", "yellow color scheme"], + 100: ["This set of prompts start at frame 100","This prompt has weight five:5"], +} + +image_prompts = { + # 0:['ImagePromptsWorkButArentVeryGood.png:2',], +} + + +# %% +""" +# 4. Diffuse! +""" + +# %% +#@title Do the Run! +#@markdown `n_batches` ignored with animation modes. +display_rate = 50 #@param{type: 'number'} +n_batches = 50 #@param{type: 'number'} + +batch_size = 1 + +def move_files(start_num, end_num, old_folder, new_folder): + for i in range(start_num, end_num): + old_file = old_folder + f'/{batch_name}({batchNum})_{i:04}.png' + new_file = new_folder + f'/{batch_name}({batchNum})_{i:04}.png' + os.rename(old_file, new_file) + +#@markdown --- + + +resume_run = False #@param{type: 'boolean'} +run_to_resume = 'latest' #@param{type: 'string'} +resume_from_frame = 'latest' #@param{type: 'string'} +retain_overwritten_frames = False #@param{type: 'boolean'} +if retain_overwritten_frames is True: + retainFolder = f'{batchFolder}/retained' + createPath(retainFolder) + + +skip_step_ratio = int(frames_skip_steps.rstrip("%")) / 100 +calc_frames_skip_steps = math.floor(steps * skip_step_ratio) + + +if steps <= calc_frames_skip_steps: + sys.exit("ERROR: You can't skip more steps than your total steps") + +if resume_run: + if run_to_resume == 'latest': + try: + batchNum + except: + batchNum = len(glob(f"{batchFolder}/{batch_name}(*)_settings.txt"))-1 + else: + batchNum = int(run_to_resume) + if resume_from_frame == 'latest': + start_frame = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png")) + else: + start_frame = int(resume_from_frame)+1 + if retain_overwritten_frames is True: + existing_frames = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png")) + frames_to_save = existing_frames - start_frame + print(f'Moving {frames_to_save} frames to the Retained folder') + move_files(start_frame, existing_frames, batchFolder, retainFolder) +else: + start_frame = 0 + batchNum = len(glob(batchFolder+"/*.txt")) + while path.isfile(f"{batchFolder}/{batch_name}({batchNum})_settings.txt") is True or path.isfile(f"{batchFolder}/{batch_name}-{batchNum}_settings.txt") is True: + batchNum += 1 + +print(f'Starting Run: {batch_name}({batchNum}) at frame {start_frame}') + +if set_seed == 'random_seed': + random.seed() + seed = random.randint(0, 2**32) + # print(f'Using seed: {seed}') +else: + seed = int(set_seed) + +args = { + 'batchNum': batchNum, + 'prompts_series':split_prompts(text_prompts) if text_prompts else None, + 'image_prompts_series':split_prompts(image_prompts) if image_prompts else None, + 'seed': seed, + 'display_rate':display_rate, + 'n_batches':n_batches if animation_mode == 'None' else 1, + 'batch_size':batch_size, + 'batch_name': batch_name, + 'steps': steps, + 'width_height': width_height, + 'clip_guidance_scale': clip_guidance_scale, + 'tv_scale': tv_scale, + 'range_scale': range_scale, + 'sat_scale': sat_scale, + 'cutn_batches': cutn_batches, + 'init_image': init_image, + 'init_scale': init_scale, + 'skip_steps': skip_steps, + 'sharpen_preset': sharpen_preset, + 'keep_unsharp': keep_unsharp, + 'side_x': side_x, + 'side_y': side_y, + 'timestep_respacing': timestep_respacing, + 'diffusion_steps': diffusion_steps, + 'animation_mode': animation_mode, + 'video_init_path': video_init_path, + 'extract_nth_frame': extract_nth_frame, + 'key_frames': key_frames, + 'max_frames': max_frames if animation_mode != "None" else 1, + 'interp_spline': interp_spline, + 'start_frame': start_frame, + 'angle': angle, + 'zoom': zoom, + 'translation_x': translation_x, + 'translation_y': translation_y, + 'translation_z': translation_z, + 'rotation_3d_x': rotation_3d_x, + 'rotation_3d_y': rotation_3d_y, + 'rotation_3d_z': rotation_3d_z, + 'midas_depth_model': midas_depth_model, + 'midas_weight': midas_weight, + 'near_plane': near_plane, + 'far_plane': far_plane, + 'fov': fov, + 'padding_mode': padding_mode, + 'sampling_mode': sampling_mode, + 'angle_series':angle_series, + 'zoom_series':zoom_series, + 'translation_x_series':translation_x_series, + 'translation_y_series':translation_y_series, + 'translation_z_series':translation_z_series, + 'rotation_3d_x_series':rotation_3d_x_series, + 'rotation_3d_y_series':rotation_3d_y_series, + 'rotation_3d_z_series':rotation_3d_z_series, + 'frames_scale': frames_scale, + 'calc_frames_skip_steps': calc_frames_skip_steps, + 'skip_step_ratio': skip_step_ratio, + 'calc_frames_skip_steps': calc_frames_skip_steps, + 'text_prompts': text_prompts, + 'image_prompts': image_prompts, + 'cut_overview': eval(cut_overview), + 'cut_innercut': eval(cut_innercut), + 'cut_ic_pow': cut_ic_pow, + 'cut_icgray_p': eval(cut_icgray_p), + 'intermediate_saves': intermediate_saves, + 'intermediates_in_subfolder': intermediates_in_subfolder, + 'steps_per_checkpoint': steps_per_checkpoint, + 'perlin_init': perlin_init, + 'perlin_mode': perlin_mode, + 'set_seed': set_seed, + 'eta': eta, + 'clamp_grad': clamp_grad, + 'clamp_max': clamp_max, + 'skip_augs': skip_augs, + 'randomize_class': randomize_class, + 'clip_denoised': clip_denoised, + 'fuzzy_prompt': fuzzy_prompt, + 'rand_mag': rand_mag, +} + +args = SimpleNamespace(**args) + +print('Prepping model...') +model, diffusion = create_model_and_diffusion(**model_config) +model.load_state_dict(torch.load(f'{model_path}/{diffusion_model}.pt', map_location='cpu')) +model.requires_grad_(False).eval().to(device) +for name, param in model.named_parameters(): + if 'qkv' in name or 'norm' in name or 'proj' in name: + param.requires_grad_() +if model_config['use_fp16']: + model.convert_to_fp16() + +gc.collect() +torch.cuda.empty_cache() +try: + do_run() +except KeyboardInterrupt: + pass +finally: + print('Seed used:', seed) + gc.collect() + torch.cuda.empty_cache() + + +# %% +""" +# 5. Create the video +""" + +# %% +# @title ### **Create video** +#@markdown Video file will save in the same folder as your images. + +skip_video_for_run_all = True #@param {type: 'boolean'} + +if skip_video_for_run_all == True: + print('Skipping video creation, uncheck skip_video_for_run_all if you want to run it') + +else: + # import subprocess in case this cell is run without the above cells + import subprocess + from base64 import b64encode + + latest_run = batchNum + + folder = batch_name #@param + run = latest_run #@param + final_frame = 'final_frame' + + + init_frame = 1#@param {type:"number"} This is the frame where the video will start + 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. + fps = 12#@param {type:"number"} + # view_video_in_cell = True #@param {type: 'boolean'} + + frames = [] + # tqdm.write('Generating video...') + + if last_frame == 'final_frame': + last_frame = len(glob(batchFolder+f"/{folder}({run})_*.png")) + print(f'Total frames: {last_frame}') + + image_path = f"{outDirPath}/{folder}/{folder}({run})_%04d.png" + filepath = f"{outDirPath}/{folder}/{folder}({run}).mp4" + + + cmd = [ + 'ffmpeg', + '-y', + '-vcodec', + 'png', + '-r', + str(fps), + '-start_number', + str(init_frame), + '-i', + image_path, + '-frames:v', + str(last_frame+1), + '-c:v', + 'libx264', + '-vf', + f'fps={fps}', + '-pix_fmt', + 'yuv420p', + '-crf', + '17', + '-preset', + 'veryslow', + filepath + ] + + process = subprocess.Popen(cmd, cwd=f'{batchFolder}', stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = process.communicate() + if process.returncode != 0: + print(stderr) + raise RuntimeError(stderr) + else: + print("The video is ready and saved to the images folder") + + # if view_video_in_cell: + # mp4 = open(filepath,'rb').read() + # data_url = "data:video/mp4;base64," + b64encode(mp4).decode() + # display.HTML(f'') \ No newline at end of file From 553cdaad713ed67d0fc7463254ee2d2aba188526 Mon Sep 17 00:00:00 2001 From: aletts Date: Thu, 10 Mar 2022 17:13:21 -0500 Subject: [PATCH 06/74] IPython magic commands replaced by Python code --- Disco_Diffusion.ipynb | 556 +++++++++++++++++++++--------------------- disco.py | 40 ++- 2 files changed, 317 insertions(+), 279 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index c2df85ef..b00db904 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -12,25 +12,28 @@ }, { "cell_type": "markdown", - "metadata": { - "id": "1YwMUyt9LHG1" - }, + "metadata": {}, "source": [ "# Disco Diffusion v5 - Now with 3D animation\n", "\n", "In case of confusion, Disco is the name of this notebook edit. The diffusion model in use is Katherine Crowson's fine-tuned 512x512 model\n", "\n", - "For issues, 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", - "\n", - "Credits & Changelog ⬇️\n" + "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)" ] }, { "cell_type": "markdown", - "metadata": { - "id": "wX5omb9C7Bjz" - }, + "metadata": {}, + "source": [ + "### Credits & Changelog \u2b07\ufe0f" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, "source": [ + "#### Credits\n", + "\n", "Original notebook by Katherine Crowson (https://github.com/crowsonkb, https://twitter.com/RiversHaveWings). It uses either OpenAI's 256x256 unconditional ImageNet or Katherine Crowson's fine-tuned 512x512 diffusion model (https://github.com/openai/guided-diffusion), together with CLIP (https://github.com/openai/CLIP) to connect text prompts with images.\n", "\n", "Modified by Daniel Russell (https://github.com/russelldc, https://twitter.com/danielrussruss) to include (hopefully) optimal params for quick generations in 15-100 timesteps rather than 1000, as well as more robust augmentations.\n", @@ -53,73 +56,101 @@ ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "id": "wDSYhyjqZQI9" - }, - "outputs": [], + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### License" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "@title Licensed under the MIT License\n", + "\n", + "Copyright (c) 2021 Katherine Crowson \n", + "\n", + "Permission is hereby granted, free of charge, to any person obtaining a copy\n", + "of this software and associated documentation files (the \"Software\"), to deal\n", + "in the Software without restriction, including without limitation the rights\n", + "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n", + "copies of the Software, and to permit persons to whom the Software is\n", + "furnished to do so, subject to the following conditions:\n", + "\n", + "The above copyright notice and this permission notice shall be included in\n", + "all copies or substantial portions of the Software.\n", + "\n", + "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n", + "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n", + "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n", + "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n", + "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", + "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n", + "THE SOFTWARE.\n", + "\n", + "--\n", + "\n", + "MIT License\n", + "\n", + "Copyright (c) 2019 Intel ISL (Intel Intelligent Systems Lab)\n", + "\n", + "Permission is hereby granted, free of charge, to any person obtaining a copy\n", + "of this software and associated documentation files (the \"Software\"), to deal\n", + "in the Software without restriction, including without limitation the rights\n", + "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n", + "copies of the Software, and to permit persons to whom the Software is\n", + "furnished to do so, subject to the following conditions:\n", + "\n", + "The above copyright notice and this permission notice shall be included in all\n", + "copies or substantial portions of the Software.\n", + "\n", + "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n", + "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n", + "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n", + "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n", + "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", + "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n", + "SOFTWARE.\n", + "\n", + "--\n", + "\n", + "Licensed under the MIT License\n", + "\n", + "Copyright (c) 2021 Maxwell Ingham\n", + "\n", + "Copyright (c) 2022 Adam Letts \n", + "\n", + "Permission is hereby granted, free of charge, to any person obtaining a copy\n", + "of this software and associated documentation files (the \"Software\"), to deal\n", + "in the Software without restriction, including without limitation the rights\n", + "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n", + "copies of the Software, and to permit persons to whom the Software is\n", + "furnished to do so, subject to the following conditions:\n", + "\n", + "The above copyright notice and this permission notice shall be included in\n", + "all copies or substantial portions of the Software.\n", + "\n", + "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n", + "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n", + "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n", + "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n", + "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", + "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n", + "THE SOFTWARE." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, "source": [ - "# @title Licensed under the MIT License\n", - "\n", - "# Copyright (c) 2021 Katherine Crowson \n", - "\n", - "# Permission is hereby granted, free of charge, to any person obtaining a copy\n", - "# of this software and associated documentation files (the \"Software\"), to deal\n", - "# in the Software without restriction, including without limitation the rights\n", - "# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n", - "# copies of the Software, and to permit persons to whom the Software is\n", - "# furnished to do so, subject to the following conditions:\n", - "\n", - "# The above copyright notice and this permission notice shall be included in\n", - "# all copies or substantial portions of the Software.\n", - "\n", - "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n", - "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n", - "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n", - "# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n", - "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", - "# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n", - "# THE SOFTWARE.\n", - "\n", - "# --\n", - "\n", - "# @title Licensed under the MIT License\n", - "\n", - "# Copyright (c) 2021 Maxwell Ingham \n", - "# Copyright (c) 2022 Adam Letts \n", - "\n", - "# Permission is hereby granted, free of charge, to any person obtaining a copy\n", - "# of this software and associated documentation files (the \"Software\"), to deal\n", - "# in the Software without restriction, including without limitation the rights\n", - "# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n", - "# copies of the Software, and to permit persons to whom the Software is\n", - "# furnished to do so, subject to the following conditions:\n", - "\n", - "# The above copyright notice and this permission notice shall be included in\n", - "# all copies or substantial portions of the Software.\n", - "\n", - "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n", - "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n", - "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n", - "# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n", - "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n", - "# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n", - "# THE SOFTWARE." + "#### Changelog" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "id": "qFB3nwLSQI8X" - }, - "outputs": [], + "metadata": {}, "source": [ "#@title <- View Changelog\n", - "\n", "skip_for_run_all = True #@param {type: 'boolean'}\n", "\n", "if skip_for_run_all == False:\n", @@ -188,24 +219,27 @@ " v4.92 Update: Feb 20th 2022 - gandamu / Adam Letts\n", "\n", " Separated transform code\n", + "\n", + " v5.01 Update: Match 10th 2022 - gandamu / Adam Letts\n", + "\n", + " IPython magic commands replaced by Python code\n", + "\n", " '''\n", - " )" - ] + " )\n" + ], + "outputs": [], + "execution_count": null }, { "cell_type": "markdown", - "metadata": { - "id": "XTu6AjLyFQUq" - }, + "metadata": {}, "source": [ - "#Tutorial" + "# Tutorial" ] }, { "cell_type": "markdown", - "metadata": { - "id": "YR806W0wi3He" - }, + "metadata": {}, "source": [ "**Diffusion settings (Defaults are heavily outdated)**\n", "---\n", @@ -251,41 +285,56 @@ "`timestep_respacing` | Modify this value to decrease the number of timesteps. | ddim100\n", "`diffusion_steps` || 1000\n", "**Diffusion:**\n", - "`clip_models` | Models of CLIP to load. Typically the more, the better but they all come at a hefty VRAM cost. | ViT-B/32, ViT-B/16, RN50x4" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "_9Eg9Kf5FlfK" - }, - "source": [ + "`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\n", + "\n", "# 1. Set Up" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "id": "qZ3rNuAWAewx" - }, - "outputs": [], + "metadata": {}, "source": [ "#@title 1.1 Check GPU Status\n", - "!nvidia-smi -L" - ] + "import subprocess\n", + "simple_nvidia_smi_display = False#@param {type:\"boolean\"}\n", + "if simple_nvidia_smi_display:\n", + " #!nvidia-smi\n", + " nvidiasmi_output = subprocess.run(['nvidia-smi', '-L'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " print(nvidiasmi_output)\n", + "else:\n", + " #!nvidia-smi -i 0 -e 0\n", + " nvidiasmi_output = subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " print(nvidiasmi_output)\n", + " nvidiasmi_ecc_note = subprocess.run(['nvidia-smi', '-i', '0', '-e', '0'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " print(nvidiasmi_ecc_note)" + ], + "outputs": [], + "execution_count": null }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "id": "yZsjzwS0YGo6" - }, - "outputs": [], + "metadata": {}, "source": [ "#@title 1.2 Prepare Folders\n", + "import subprocess\n", + "import sys\n", + "import ipykernel\n", + "\n", + "def gitclone(url):\n", + " res = subprocess.run(['git', 'clone', url], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " print(res)\n", + "\n", + "def pipi(modulestr):\n", + " res = subprocess.run(['pip', 'install', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " print(res)\n", + "\n", + "def pipie(modulestr):\n", + " res = subprocess.run(['git', 'install', '-e', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " print(res)\n", + "\n", + "def wget(url, outputdir):\n", + " res = subprocess.run(['wget', url, '-P', f'{outputdir}'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " print(res)\n", "\n", "try:\n", " from google.colab import drive\n", @@ -338,20 +387,18 @@ "\n", "# libraries = f'{root_path}/libraries'\n", "# createPath(libraries)" - ] + ], + "outputs": [], + "execution_count": null }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "id": "JmbrcrhpBPC6" - }, - "outputs": [], + "metadata": {}, "source": [ "#@title ### 1.3 Install and import dependencies\n", "\n", "from os.path import exists as path_exists\n", + "import pathlib, shutil\n", "\n", "if not is_colab:\n", " # 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", @@ -373,23 +420,31 @@ "model_secondary_downloaded = False\n", "\n", "if is_colab:\n", - " !git clone https://github.com/openai/CLIP\n", - " # !git clone https://github.com/facebookresearch/SLIP.git\n", - " !git clone https://github.com/crowsonkb/guided-diffusion\n", - " !git clone https://github.com/assafshocher/ResizeRight.git\n", - " !pip install -e ./CLIP\n", - " !pip install -e ./guided-diffusion\n", - " !pip install lpips datetime timm\n", - " !apt install imagemagick\n", - " !git clone https://github.com/isl-org/MiDaS.git\n", - " !git clone https://github.com/alembics/disco-diffusion-dev.git\n", + " gitclone(\"https://github.com/openai/CLIP\")\n", + " #gitclone(\"https://github.com/facebookresearch/SLIP.git\")\n", + " gitclone(\"https://github.com/crowsonkb/guided-diffusion\")\n", + " gitclone(\"https://github.com/assafshocher/ResizeRight.git\")\n", + " pipie(\"./CLIP\")\n", + " pipie(\"./guided-diffusion\")\n", + " multipip_res = subprocess.run(['pip', 'install', 'lpips', 'datetime', 'timm', 'ftfy'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " print(multipip_res)\n", + " subprocess.run(['apt', 'install', 'imagemagick'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " gitclone(\"https://github.com/isl-org/MiDaS.git\")\n", + " gitclone(\"https://github.com/alembics/disco-diffusion.git\")\n", + " pipi(\"pytorch-lightning\")\n", + " pipi(\"omegaconf\")\n", + " pipi(\"einops\")\n", " # Rename a file to avoid a name conflict..\n", - " !mv MiDaS/utils.py MiDaS/midas_utils.py\n", - " !cp disco-diffusion-dev/disco_xform_utils.py disco_xform_utils.py\n", + " try:\n", + " os.rename(\"MiDaS/utils.py\", \"MiDaS/midas_utils.py\")\n", + " shutil.copyfile(\"disco-diffusion/disco_xform_utils.py\", \"disco_xform_utils.py\")\n", + " except:\n", + " pass\n", "\n", - "!mkdir model\n", + "if not path_exists(f'{model_path}'):\n", + " pathlib.Path(model_path).mkdir(parents=True, exist_ok=True)\n", "if not path_exists(f'{model_path}/dpt_large-midas-2f21e586.pt'):\n", - " !wget https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt -P {model_path}\n", + " wget(\"https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt\", out=model_path)\n", "\n", "import sys\n", "import torch\n", @@ -402,8 +457,9 @@ " torch.version.cuda.replace(\".\",\"\"),\n", " f\"_pyt{pyt_version_str}\"\n", " ])\n", - " !pip install fvcore iopath\n", - " !pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html\n", + " multipip_res = subprocess.run(['pip', 'install', 'fvcore', 'iopath'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " print(multipip_res)\n", + " subprocess.run(['pip', 'install', '--no-index', '--no-cache-dir', 'pytorch3d', '-f', f'https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", "\n", "# sys.path.append('./SLIP')\n", "sys.path.append('./ResizeRight')\n", @@ -443,10 +499,10 @@ "\n", "#SuperRes\n", "if is_colab:\n", - " !git clone https://github.com/CompVis/latent-diffusion.git\n", - " !git clone https://github.com/CompVis/taming-transformers\n", - " !pip install -e ./taming-transformers\n", - " !pip install ipywidgets omegaconf>=2.0.0 pytorch-lightning>=1.0.8 torch-fidelity einops wandb\n", + " gitclone(\"https://github.com/CompVis/latent-diffusion.git\")\n", + " gitclone(\"https://github.com/CompVis/taming-transformers\")\n", + " pipie(\"./taming-transformers\")\n", + " pipi(\"ipywidgets omegaconf>=2.0.0 pytorch-lightning>=1.0.8 torch-fidelity einops wandb\")\n", "\n", "#SuperRes\n", "import ipywidgets as widgets\n", @@ -455,20 +511,22 @@ "sys.path.append('./taming-transformers')\n", "from taming.models import vqgan # checking correct import from taming\n", "from torchvision.datasets.utils import download_url\n", + "\n", "if is_colab:\n", - " %cd '/content/latent-diffusion'\n", + " os.chdir('/content/latent-diffusion')\n", "else:\n", - " %cd 'latent-diffusion'\n", + " #os.chdir('latent-diffusion')\n", + " sys.path.append('latent-diffusion')\n", "from functools import partial\n", "from ldm.util import instantiate_from_config\n", "from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like\n", "# from ldm.models.diffusion.ddim import DDIMSampler\n", "from ldm.util import ismap\n", "if is_colab:\n", - " %cd '/content'\n", + " os.chdir('/content')\n", " from google.colab import files\n", "else:\n", - " %cd $PROJECT_DIR\n", + " os.chdir(f'{PROJECT_DIR}')\n", "from IPython.display import Image as ipyimg\n", "from numpy import asarray\n", "from einops import rearrange, repeat\n", @@ -481,11 +539,11 @@ "# AdaBins stuff\n", "if USE_ADABINS:\n", " if is_colab:\n", - " !git clone https://github.com/shariqfarooq123/AdaBins.git\n", + " gitclone(\"https://github.com/shariqfarooq123/AdaBins.git\")\n", " if not path_exists(f'{model_path}/AdaBins_nyu.pt'):\n", - " !wget https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt -P {model_path}\n", - " !mkdir pretrained\n", - " !cp -P {model_path}/AdaBins_nyu.pt pretrained/AdaBins_nyu.pt\n", + " wget(\"https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt\", out=model_path)\n", + " pathlib.Path(\"pretrained\").mkdir(parents=True, exist_ok=True)\n", + " shutil.copyfile(f\"{model_path}/AdaBins_nyu.pt\", \"pretrained/AdaBins_nyu.pt\")\n", " sys.path.append('./AdaBins')\n", " from infer import InferenceHelper\n", " MAX_ADABINS_AREA = 500000\n", @@ -498,16 +556,16 @@ "if torch.cuda.get_device_capability(DEVICE) == (8,0): ## A100 fix thanks to Emad\n", " print('Disabling CUDNN for A100 gpu', file=sys.stderr)\n", " torch.backends.cudnn.enabled = False" - ] + ], + "outputs": [], + "execution_count": null }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "BLk3J0h3MtON" - }, - "outputs": [], + "metadata": {}, "source": [ + "#@title ### 1.4 Define Midas functions\n", + "\n", "from midas.dpt_depth import DPTDepthModel\n", "from midas.midas_net import MidasNet\n", "from midas.midas_net_custom import MidasNet_small\n", @@ -606,19 +664,16 @@ " midas_model.to(DEVICE)\n", "\n", " print(f\"MiDaS '{midas_model_type}' depth model initialized.\")\n", - " return midas_model, midas_transform, net_w, net_h, resize_mode, normalization\n" - ] + " return midas_model, midas_transform, net_w, net_h, resize_mode, normalization" + ], + "outputs": [], + "execution_count": null }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "id": "FpZczxnOnPIU" - }, - "outputs": [], + "metadata": {}, "source": [ - "#@title 1.4 Define necessary functions\n", + "#@title 1.5 Define necessary functions\n", "\n", "# https://gist.github.com/adefossez/0646dbe9ed4005480a2407c62aac8869\n", "\n", @@ -1365,20 +1420,16 @@ " }\n", " # print('Settings:', setting_list)\n", " with open(f\"{batchFolder}/{batch_name}({batchNum})_settings.txt\", \"w+\") as f: #save settings\n", - " json.dump(setting_list, f, ensure_ascii=False, indent=4)\n", - " " - ] + " json.dump(setting_list, f, ensure_ascii=False, indent=4)" + ], + "outputs": [], + "execution_count": null }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "id": "TI4oAu0N4ksZ" - }, - "outputs": [], + "metadata": {}, "source": [ - "#@title 1.5 Define the secondary diffusion model\n", + "#@title 1.6 Define the secondary diffusion model\n", "\n", "def append_dims(x, n):\n", " return x[(Ellipsis, *(None,) * (n - x.ndim))]\n", @@ -1540,19 +1591,16 @@ " alphas, sigmas = map(partial(append_dims, n=v.ndim), t_to_alpha_sigma(t))\n", " pred = input * alphas - v * sigmas\n", " eps = input * sigmas + v * alphas\n", - " return DiffusionOutput(v, pred, eps)\n" - ] + " return DiffusionOutput(v, pred, eps)" + ], + "outputs": [], + "execution_count": null }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "id": "NJS2AUAnvn-D" - }, - "outputs": [], + "metadata": {}, "source": [ - "#@title 1.6 SuperRes Define\n", + "#@title 1.7 SuperRes Define\n", "class DDIMSampler(object):\n", " def __init__(self, model, schedule=\"linear\", **kwargs):\n", " super().__init__()\n", @@ -2074,25 +2122,20 @@ " a.save(filepath)\n", " return\n", " print(f'Processing finished!')\n" - ] + ], + "outputs": [], + "execution_count": null }, { "cell_type": "markdown", - "metadata": { - "id": "CQVtY1Ixnqx4" - }, + "metadata": {}, "source": [ "# 2. Diffusion and CLIP model settings" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "id": "Fpbody2NCR7w" - }, - "outputs": [], + "metadata": {}, "source": [ "#@markdown ####**Models Settings:**\n", "diffusion_model = \"512x512_diffusion_uncond_finetune_008100\" #@param [\"256x256_diffusion_uncond\", \"512x512_diffusion_uncond_finetune_008100\"]\n", @@ -2139,12 +2182,12 @@ " model_256_downloaded = True\n", " else: \n", " print(\"256 Model SHA doesn't match, redownloading...\")\n", - " !wget --continue {model_256_link} -P {model_path}\n", + " wget(model_256_link, out=model_path)\n", " model_256_downloaded = True\n", " elif os.path.exists(model_256_path) and not check_model_SHA or model_256_downloaded == True:\n", " print('256 Model already downloaded, check check_model_SHA if the file is corrupt')\n", " else: \n", - " !wget --continue {model_256_link} -P {model_path}\n", + " wget(model_256_link, out=model_path)\n", " model_256_downloaded = True\n", "elif diffusion_model == '512x512_diffusion_uncond_finetune_008100':\n", " if os.path.exists(model_512_path) and check_model_SHA:\n", @@ -2157,12 +2200,12 @@ " model_512_downloaded = True\n", " else: \n", " print(\"512 Model SHA doesn't match, redownloading...\")\n", - " !wget --continue {model_512_link} -P {model_path}\n", + " wget(model_512_link, out=model_path)\n", " model_512_downloaded = True\n", " elif os.path.exists(model_512_path) and not check_model_SHA or model_512_downloaded == True:\n", " print('512 Model already downloaded, check check_model_SHA if the file is corrupt')\n", " else: \n", - " !wget --continue {model_512_link} -P {model_path}\n", + " wget(model_512_link, out=model_path)\n", " model_512_downloaded = True\n", "\n", "\n", @@ -2178,12 +2221,12 @@ " model_secondary_downloaded = True\n", " else: \n", " print(\"Secondary Model SHA doesn't match, redownloading...\")\n", - " !wget --continue {model_secondary_link} -P {model_path}\n", + " wget(model_secondary_link, out=model_path)\n", " model_secondary_downloaded = True\n", " elif os.path.exists(model_secondary_path) and not check_model_SHA or model_secondary_downloaded == True:\n", " print('Secondary Model already downloaded, check check_model_SHA if the file is corrupt')\n", " else: \n", - " !wget --continue {model_secondary_link} -P {model_path}\n", + " wget(model_secondary_link, out=model_path)\n", " model_secondary_downloaded = True\n", "\n", "model_config = model_and_diffusion_defaults()\n", @@ -2247,7 +2290,7 @@ "if SLIPB16:\n", " SLIPB16model = SLIP_VITB16(ssl_mlp_dim=4096, ssl_emb_dim=256)\n", " if not os.path.exists(f'{model_path}/slip_base_100ep.pt'):\n", - " !wget https://dl.fbaipublicfiles.com/slip/slip_base_100ep.pt -P {model_path}\n", + " wget(\"https://dl.fbaipublicfiles.com/slip/slip_base_100ep.pt\", out=model_path)\n", " sd = torch.load(f'{model_path}/slip_base_100ep.pt')\n", " real_sd = {}\n", " for k, v in sd['state_dict'].items():\n", @@ -2261,7 +2304,7 @@ "if SLIPL16:\n", " SLIPL16model = SLIP_VITL16(ssl_mlp_dim=4096, ssl_emb_dim=256)\n", " if not os.path.exists(f'{model_path}/slip_large_100ep.pt'):\n", - " !wget https://dl.fbaipublicfiles.com/slip/slip_large_100ep.pt -P {model_path}\n", + " wget(\"https://dl.fbaipublicfiles.com/slip/slip_large_100ep.pt\", out=model_path)\n", " sd = torch.load(f'{model_path}/slip_large_100ep.pt')\n", " real_sd = {}\n", " for k, v in sd['state_dict'].items():\n", @@ -2273,26 +2316,21 @@ " clip_models.append(SLIPL16model)\n", "\n", "normalize = T.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711])\n", - "lpips_model = lpips.LPIPS(net='vgg').to(device)" - ] + "lpips_model = lpips.LPIPS(net='vgg').to(device)\n" + ], + "outputs": [], + "execution_count": null }, { "cell_type": "markdown", - "metadata": { - "id": "kjtsXaszn-bB" - }, + "metadata": {}, "source": [ "# 3. Settings" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "id": "U0PwzFZbLfcy" - }, - "outputs": [], + "metadata": {}, "source": [ "#@markdown ####**Basic Settings:**\n", "batch_name = 'TimeToDisco' #@param{type: 'string'}\n", @@ -2330,25 +2368,20 @@ "#Make folder for batch\n", "batchFolder = f'{outDirPath}/{batch_name}'\n", "createPath(batchFolder)\n" - ] + ], + "outputs": [], + "execution_count": null }, { "cell_type": "markdown", - "metadata": { - "id": "CnkTNXJAPzL2" - }, + "metadata": {}, "source": [ - "###Animation Settings" + "### Animation Settings" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "id": "djPY2_4kHgV2" - }, - "outputs": [], + "metadata": {}, "source": [ "#@markdown ####**Animation Mode:**\n", "animation_mode = 'None' #@param ['None', '2D', '3D', 'Video Input'] {type:'string'}\n", @@ -2372,11 +2405,13 @@ " createPath(videoFramesFolder)\n", " print(f\"Exporting Video Frames (1 every {extract_nth_frame})...\")\n", " try:\n", - " !rm {videoFramesFolder}/*.jpg\n", + " for f in pathlib.Path(f'{videoFramesFolder}').glob('*.jpg'):\n", + " f.unlink()\n", " except:\n", " print('')\n", " vf = f'\"select=not(mod(n\\,{extract_nth_frame}))\"'\n", - " !ffmpeg -i {video_init_path} -vf {vf} -vsync vfr -q:v 2 -loglevel error -stats {videoFramesFolder}/%04d.jpg\n", + " subprocess.run(['ffmpeg', '-i', f'{video_init_path}', '-vf', f'{vf}', '-vsync', 'vfr', '-q:v', '2', '-loglevel', 'error', '-stats', f'{videoFramesFolder}/%04d.jpg'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " #!ffmpeg -i {video_init_path} -vf {vf} -vsync vfr -q:v 2 -loglevel error -stats {videoFramesFolder}/%04d.jpg\n", "\n", "\n", "#@markdown ---\n", @@ -2654,14 +2689,14 @@ " translation_z = float(translation_z)\n", " rotation_3d_x = float(rotation_3d_x)\n", " rotation_3d_y = float(rotation_3d_y)\n", - " rotation_3d_z = float(rotation_3d_z)" - ] + " rotation_3d_z = float(rotation_3d_z)\n" + ], + "outputs": [], + "execution_count": null }, { "cell_type": "markdown", - "metadata": { - "id": "u1VHzHvNx5fd" - }, + "metadata": {}, "source": [ "### Extra Settings\n", " Partial Saves, Diffusion Sharpening, Advanced Settings, Cutn Scheduling" @@ -2669,12 +2704,7 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "id": "lCLMxtILyAHA" - }, - "outputs": [], + "metadata": {}, "source": [ "#@markdown ####**Saving:**\n", "\n", @@ -2745,27 +2775,22 @@ "cut_overview = \"[12]*400+[4]*600\" #@param {type: 'string'} \n", "cut_innercut =\"[4]*400+[12]*600\"#@param {type: 'string'} \n", "cut_ic_pow = 1#@param {type: 'number'} \n", - "cut_icgray_p = \"[0.2]*400+[0]*600\"#@param {type: 'string'} \n", - "\n" - ] + "cut_icgray_p = \"[0.2]*400+[0]*600\"#@param {type: 'string'}\n" + ], + "outputs": [], + "execution_count": null }, { "cell_type": "markdown", - "metadata": { - "id": "XIwh5RvNpk4K" - }, + "metadata": {}, "source": [ - "###Prompts\n", + "### Prompts\n", "`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." ] }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "BGBzhk3dpcGO" - }, - "outputs": [], + "metadata": {}, "source": [ "text_prompts = {\n", " 0: [\"A beautiful painting of a singular lighthouse, shining its light across a tumultuous sea of blood by greg rutkowski and thomas kinkade, Trending on artstation.\", \"yellow color scheme\"],\n", @@ -2774,26 +2799,21 @@ "\n", "image_prompts = {\n", " # 0:['ImagePromptsWorkButArentVeryGood.png:2',],\n", - "}" - ] + "}\n" + ], + "outputs": [], + "execution_count": null }, { "cell_type": "markdown", - "metadata": { - "id": "Nf9hTc8YLoLx" - }, + "metadata": {}, "source": [ "# 4. Diffuse!" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "id": "LHLiO56OfwgD" - }, - "outputs": [], + "metadata": {}, "source": [ "#@title Do the Run!\n", "#@markdown `n_batches` ignored with animation modes.\n", @@ -2961,26 +2981,21 @@ "finally:\n", " print('Seed used:', seed)\n", " gc.collect()\n", - " torch.cuda.empty_cache()" - ] + " torch.cuda.empty_cache()\n" + ], + "outputs": [], + "execution_count": null }, { "cell_type": "markdown", - "metadata": { - "id": "EZUg3bfzazgW" - }, + "metadata": {}, "source": [ "# 5. Create the video" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "cellView": "form", - "id": "HV54fuU3pMzJ" - }, - "outputs": [], + "metadata": {}, "source": [ "# @title ### **Create video**\n", "#@markdown Video file will save in the same folder as your images.\n", @@ -3056,27 +3071,16 @@ " # mp4 = open(filepath,'rb').read()\n", " # data_url = \"data:video/mp4;base64,\" + b64encode(mp4).decode()\n", " # display.HTML(f'')" - ] + ], + "outputs": [], + "execution_count": null } ], "metadata": { - "accelerator": "GPU", - "colab": { - "collapsed_sections": [ - "1YwMUyt9LHG1", - "XTu6AjLyFQUq", - "_9Eg9Kf5FlfK", - "CnkTNXJAPzL2", - "u1VHzHvNx5fd" - ], - "machine_shape": "hm", - "name": "Disco Diffusion v4.1 [w/ Video Inits, Recovery & DDIM Sharpen].ipynb", - "private_outputs": true, - "provenance": [], - "include_colab_link": true - }, + "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 3", + "language": "python", "name": "python3" }, "language_info": { @@ -3089,9 +3093,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.7" + "version": "3.6.1" } }, "nbformat": 4, - "nbformat_minor": 0 -} + "nbformat_minor": 4 +} \ No newline at end of file diff --git a/disco.py b/disco.py index 43125417..095ce4ce 100644 --- a/disco.py +++ b/disco.py @@ -1,3 +1,7 @@ +# %% +"""Open In Colab""" + + # %% """ # Disco Diffusion v5 - Now with 3D animation @@ -44,7 +48,7 @@ # %% """ -Licensed under the MIT License +@title Licensed under the MIT License Copyright (c) 2021 Katherine Crowson @@ -68,9 +72,34 @@ -- -@title Licensed under the MIT License +MIT License + +Copyright (c) 2019 Intel ISL (Intel Intelligent Systems Lab) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +-- + +Licensed under the MIT License + +Copyright (c) 2021 Maxwell Ingham -Copyright (c) 2021 Maxwell Ingham Copyright (c) 2022 Adam Letts Permission is hereby granted, free of charge, to any person obtaining a copy @@ -167,6 +196,11 @@ v4.92 Update: Feb 20th 2022 - gandamu / Adam Letts Separated transform code + + v5.01 Update: Match 10th 2022 - gandamu / Adam Letts + + IPython magic commands replaced by Python code + ''' ) From f4858c79f4102735af4068206b74cb99b84549ad Mon Sep 17 00:00:00 2001 From: aletts Date: Thu, 10 Mar 2022 17:27:21 -0500 Subject: [PATCH 07/74] Manually adding some metadata to the notebook --- Disco_Diffusion.ipynb | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index b00db904..47ba1cd3 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -23,7 +23,9 @@ }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "id": "1YwMUyt9LHG1" + }, "source": [ "### Credits & Changelog \u2b07\ufe0f" ] @@ -232,7 +234,9 @@ }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "id": "XTu6AjLyFQUq" + }, "source": [ "# Tutorial" ] @@ -292,7 +296,9 @@ }, { "cell_type": "code", - "metadata": {}, + "metadata": { + "id": "_9Eg9Kf5FlfK" + }, "source": [ "#@title 1.1 Check GPU Status\n", "import subprocess\n", @@ -2374,7 +2380,9 @@ }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "id": "CnkTNXJAPzL2" + }, "source": [ "### Animation Settings" ] @@ -2696,7 +2704,9 @@ }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "id": "u1VHzHvNx5fd" + }, "source": [ "### Extra Settings\n", " Partial Saves, Diffusion Sharpening, Advanced Settings, Cutn Scheduling" @@ -3078,6 +3088,21 @@ ], "metadata": { "anaconda-cloud": {}, + "accelerator": "GPU", + "colab": { + "collapsed_sections": [ + "1YwMUyt9LHG1", + "XTu6AjLyFQUq", + "_9Eg9Kf5FlfK", + "CnkTNXJAPzL2", + "u1VHzHvNx5fd" + ], + "machine_shape": "hm", + "name": "Disco Diffusion v5 [w/ 3D animation]", + "private_outputs": true, + "provenance": [], + "include_colab_link": true + }, "kernelspec": { "display_name": "Python 3", "language": "python", From 3ac9d2f68a7d541ecdf2c9b3318d3f81ba3cb3e5 Mon Sep 17 00:00:00 2001 From: aletts Date: Thu, 10 Mar 2022 22:14:33 -0500 Subject: [PATCH 08/74] Attempting quick fix to broken calls to wget() --- Disco_Diffusion.ipynb | 20 ++++++++++---------- disco.py | 22 +++++++++++----------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 8751532d..15d30f51 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -450,7 +450,7 @@ "if not path_exists(f'{model_path}'):\n", " pathlib.Path(model_path).mkdir(parents=True, exist_ok=True)\n", "if not path_exists(f'{model_path}/dpt_large-midas-2f21e586.pt'):\n", - " wget(\"https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt\", out=model_path)\n", + " wget(\"https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt\", model_path)\n", "\n", "import sys\n", "import torch\n", @@ -547,7 +547,7 @@ " if is_colab:\n", " gitclone(\"https://github.com/shariqfarooq123/AdaBins.git\")\n", " if not path_exists(f'{model_path}/AdaBins_nyu.pt'):\n", - " wget(\"https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt\", out=model_path)\n", + " wget(\"https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt\", model_path)\n", " pathlib.Path(\"pretrained\").mkdir(parents=True, exist_ok=True)\n", " shutil.copyfile(f\"{model_path}/AdaBins_nyu.pt\", \"pretrained/AdaBins_nyu.pt\")\n", " sys.path.append('./AdaBins')\n", @@ -2191,12 +2191,12 @@ " model_256_downloaded = True\n", " else: \n", " print(\"256 Model SHA doesn't match, redownloading...\")\n", - " wget(model_256_link, out=model_path)\n", + " wget(model_256_link, model_path)\n", " model_256_downloaded = True\n", " elif os.path.exists(model_256_path) and not check_model_SHA or model_256_downloaded == True:\n", " print('256 Model already downloaded, check check_model_SHA if the file is corrupt')\n", " else: \n", - " wget(model_256_link, out=model_path)\n", + " wget(model_256_link, model_path)\n", " model_256_downloaded = True\n", "elif diffusion_model == '512x512_diffusion_uncond_finetune_008100':\n", " if os.path.exists(model_512_path) and check_model_SHA:\n", @@ -2209,12 +2209,12 @@ " model_512_downloaded = True\n", " else: \n", " print(\"512 Model SHA doesn't match, redownloading...\")\n", - " wget(model_512_link, out=model_path)\n", + " wget(model_512_link, model_path)\n", " model_512_downloaded = True\n", " elif os.path.exists(model_512_path) and not check_model_SHA or model_512_downloaded == True:\n", " print('512 Model already downloaded, check check_model_SHA if the file is corrupt')\n", " else: \n", - " wget(model_512_link, out=model_path)\n", + " wget(model_512_link, model_path)\n", " model_512_downloaded = True\n", "\n", "\n", @@ -2230,12 +2230,12 @@ " model_secondary_downloaded = True\n", " else: \n", " print(\"Secondary Model SHA doesn't match, redownloading...\")\n", - " wget(model_secondary_link, out=model_path)\n", + " wget(model_secondary_link, model_path)\n", " model_secondary_downloaded = True\n", " elif os.path.exists(model_secondary_path) and not check_model_SHA or model_secondary_downloaded == True:\n", " print('Secondary Model already downloaded, check check_model_SHA if the file is corrupt')\n", " else: \n", - " wget(model_secondary_link, out=model_path)\n", + " wget(model_secondary_link, model_path)\n", " model_secondary_downloaded = True\n", "\n", "model_config = model_and_diffusion_defaults()\n", @@ -2299,7 +2299,7 @@ "if SLIPB16:\n", " SLIPB16model = SLIP_VITB16(ssl_mlp_dim=4096, ssl_emb_dim=256)\n", " if not os.path.exists(f'{model_path}/slip_base_100ep.pt'):\n", - " wget(\"https://dl.fbaipublicfiles.com/slip/slip_base_100ep.pt\", out=model_path)\n", + " wget(\"https://dl.fbaipublicfiles.com/slip/slip_base_100ep.pt\", model_path)\n", " sd = torch.load(f'{model_path}/slip_base_100ep.pt')\n", " real_sd = {}\n", " for k, v in sd['state_dict'].items():\n", @@ -2313,7 +2313,7 @@ "if SLIPL16:\n", " SLIPL16model = SLIP_VITL16(ssl_mlp_dim=4096, ssl_emb_dim=256)\n", " if not os.path.exists(f'{model_path}/slip_large_100ep.pt'):\n", - " wget(\"https://dl.fbaipublicfiles.com/slip/slip_large_100ep.pt\", out=model_path)\n", + " wget(\"https://dl.fbaipublicfiles.com/slip/slip_large_100ep.pt\", model_path)\n", " sd = torch.load(f'{model_path}/slip_large_100ep.pt')\n", " real_sd = {}\n", " for k, v in sd['state_dict'].items():\n", diff --git a/disco.py b/disco.py index 095ce4ce..2a763746 100644 --- a/disco.py +++ b/disco.py @@ -400,7 +400,7 @@ def createPath(filepath): if not path_exists(f'{model_path}'): pathlib.Path(model_path).mkdir(parents=True, exist_ok=True) if not path_exists(f'{model_path}/dpt_large-midas-2f21e586.pt'): - wget("https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", out=model_path) + wget("https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", model_path) import sys import torch @@ -497,7 +497,7 @@ def createPath(filepath): if is_colab: gitclone("https://github.com/shariqfarooq123/AdaBins.git") if not path_exists(f'{model_path}/AdaBins_nyu.pt'): - wget("https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt", out=model_path) + wget("https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt", model_path) pathlib.Path("pretrained").mkdir(parents=True, exist_ok=True) shutil.copyfile(f"{model_path}/AdaBins_nyu.pt", "pretrained/AdaBins_nyu.pt") sys.path.append('./AdaBins') @@ -2107,12 +2107,12 @@ def do_superres(img, filepath): model_256_downloaded = True else: print("256 Model SHA doesn't match, redownloading...") - wget(model_256_link, out=model_path) + wget(model_256_link, model_path) model_256_downloaded = True elif os.path.exists(model_256_path) and not check_model_SHA or model_256_downloaded == True: print('256 Model already downloaded, check check_model_SHA if the file is corrupt') else: - wget(model_256_link, out=model_path) + wget(model_256_link, model_path) model_256_downloaded = True elif diffusion_model == '512x512_diffusion_uncond_finetune_008100': if os.path.exists(model_512_path) and check_model_SHA: @@ -2125,12 +2125,12 @@ def do_superres(img, filepath): model_512_downloaded = True else: print("512 Model SHA doesn't match, redownloading...") - wget(model_512_link, out=model_path) + wget(model_512_link, model_path) model_512_downloaded = True elif os.path.exists(model_512_path) and not check_model_SHA or model_512_downloaded == True: print('512 Model already downloaded, check check_model_SHA if the file is corrupt') else: - wget(model_512_link, out=model_path) + wget(model_512_link, model_path) model_512_downloaded = True @@ -2146,12 +2146,12 @@ def do_superres(img, filepath): model_secondary_downloaded = True else: print("Secondary Model SHA doesn't match, redownloading...") - wget(model_secondary_link, out=model_path) + wget(model_secondary_link, model_path) model_secondary_downloaded = True elif os.path.exists(model_secondary_path) and not check_model_SHA or model_secondary_downloaded == True: print('Secondary Model already downloaded, check check_model_SHA if the file is corrupt') else: - wget(model_secondary_link, out=model_path) + wget(model_secondary_link, model_path) model_secondary_downloaded = True model_config = model_and_diffusion_defaults() @@ -2215,7 +2215,7 @@ def do_superres(img, filepath): if SLIPB16: SLIPB16model = SLIP_VITB16(ssl_mlp_dim=4096, ssl_emb_dim=256) if not os.path.exists(f'{model_path}/slip_base_100ep.pt'): - wget("https://dl.fbaipublicfiles.com/slip/slip_base_100ep.pt", out=model_path) + wget("https://dl.fbaipublicfiles.com/slip/slip_base_100ep.pt", model_path) sd = torch.load(f'{model_path}/slip_base_100ep.pt') real_sd = {} for k, v in sd['state_dict'].items(): @@ -2229,7 +2229,7 @@ def do_superres(img, filepath): if SLIPL16: SLIPL16model = SLIP_VITL16(ssl_mlp_dim=4096, ssl_emb_dim=256) if not os.path.exists(f'{model_path}/slip_large_100ep.pt'): - wget("https://dl.fbaipublicfiles.com/slip/slip_large_100ep.pt", out=model_path) + wget("https://dl.fbaipublicfiles.com/slip/slip_large_100ep.pt", model_path) sd = torch.load(f'{model_path}/slip_large_100ep.pt') real_sd = {} for k, v in sd['state_dict'].items(): @@ -2953,4 +2953,4 @@ def move_files(start_num, end_num, old_folder, new_folder): # if view_video_in_cell: # mp4 = open(filepath,'rb').read() # data_url = "data:video/mp4;base64," + b64encode(mp4).decode() - # display.HTML(f'') \ No newline at end of file + # display.HTML(f'') From d6515c5e7d440148d58caf111a20a8887359023a Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Fri, 11 Mar 2022 23:07:05 -0500 Subject: [PATCH 09/74] Give Set Up its own top-level section (instead of having it stuck in Tutorial by accident) --- Disco_Diffusion.ipynb | 9 +++++++-- disco.py | 5 +++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 15d30f51..b3f223a9 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -289,8 +289,13 @@ "`timestep_respacing` | Modify this value to decrease the number of timesteps. | ddim100\n", "`diffusion_steps` || 1000\n", "**Diffusion:**\n", - "`clip_models` | Models of CLIP to load. Typically the more, the better but they all come at a hefty VRAM cost. | ViT-B/32, ViT-B/16, RN50x4\n", - "\n", + "`clip_models` | Models of CLIP to load. Typically the more, the better but they all come at a hefty VRAM cost. | ViT-B/32, ViT-B/16, RN50x4" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ "# 1. Set Up" ] }, diff --git a/disco.py b/disco.py index 2a763746..5e278f6d 100644 --- a/disco.py +++ b/disco.py @@ -257,10 +257,11 @@ `diffusion_steps` || 1000 **Diffusion:** `clip_models` | Models of CLIP to load. Typically the more, the better but they all come at a hefty VRAM cost. | ViT-B/32, ViT-B/16, RN50x4 - -# 1. Set Up """ +# %% +"""# 1. Set Up""" + # %% #@title 1.1 Check GPU Status import subprocess From f244fbb9b20b3504185ebd444c291dd7cba3ca1d Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Fri, 11 Mar 2022 23:31:29 -0500 Subject: [PATCH 10/74] Some PLMS vs DDIM changes made in the notebook weren't made in disco.py. This brings them over. --- disco.py | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/disco.py b/disco.py index 5e278f6d..44e624ef 100644 --- a/disco.py +++ b/disco.py @@ -1,6 +1,7 @@ # %% -"""Open In Colab""" - +""" +Open In Colab +""" # %% """ @@ -260,7 +261,9 @@ """ # %% -"""# 1. Set Up""" +""" +# 1. Set Up +""" # %% #@title 1.1 Check GPU Status @@ -1177,11 +1180,11 @@ def cond_fn(x, t, y=None): return grad * magnitude.clamp(max=args.clamp_max) / magnitude #min=-0.02, min=-clamp_max, return grad - if model_config['timestep_respacing'].startswith('ddim'): + if args.sampling_mode == 'ddim': sample_fn = diffusion.ddim_sample_loop_progressive else: - sample_fn = diffusion.p_sample_loop_progressive - + sample_fn = diffusion.plms_sample_loop_progressive + image_display = Output() for i in range(args.n_batches): @@ -1200,7 +1203,7 @@ def cond_fn(x, t, y=None): if perlin_init: init = regen_perlin() - if model_config['timestep_respacing'].startswith('ddim'): + if args.sampling_mode == 'ddim': samples = sample_fn( model, (batch_size, 3, args.side_y, args.side_x), @@ -1224,6 +1227,7 @@ def cond_fn(x, t, y=None): skip_timesteps=skip_steps, init_image=init, randomize_class=randomize_class, + order=2, ) @@ -1331,6 +1335,7 @@ def save_settings(): 'use_secondary_model': use_secondary_model, 'steps': steps, 'diffusion_steps': diffusion_steps, + 'sampling_mode': sampling_mode, 'ViTB32': ViTB32, 'ViTB16': ViTB16, 'ViTL14': ViTL14, @@ -2066,8 +2071,9 @@ def do_superres(img, filepath): #@markdown ####**Models Settings:** diffusion_model = "512x512_diffusion_uncond_finetune_008100" #@param ["256x256_diffusion_uncond", "512x512_diffusion_uncond_finetune_008100"] use_secondary_model = True #@param {type: 'boolean'} +sampling_mode = 'ddim' #@param ['plms','ddim'] -timestep_respacing = '50' # param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000'] +timestep_respacing = '250' # param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000'] diffusion_steps = 1000 # param {type: 'number'} use_checkpoint = True #@param {type: 'boolean'} ViTB32 = True #@param{type:"boolean"} @@ -2267,7 +2273,7 @@ def do_superres(img, filepath): #@markdown ####**Init Settings:** init_image = None #@param{type: 'string'} init_scale = 1000 #@param{type: 'integer'} -skip_steps = 0 #@param{type: 'integer'} +skip_steps = 10 #@param{type: 'integer'} #@markdown *Make sure you set skip_steps to ~50% of your steps if you want to use an init image.* #Get corrected sizes @@ -2711,6 +2717,14 @@ def split_prompts(prompts): display_rate = 50 #@param{type: 'number'} n_batches = 50 #@param{type: 'number'} +#Update Model Settings +timestep_respacing = f'ddim{steps}' +diffusion_steps = (1000//steps)*steps if steps < 1000 else steps +model_config.update({ + 'timestep_respacing': timestep_respacing, + 'diffusion_steps': diffusion_steps, +}) + batch_size = 1 def move_files(start_num, end_num, old_folder, new_folder): @@ -2780,6 +2794,7 @@ def move_files(start_num, end_num, old_folder, new_folder): 'batch_size':batch_size, 'batch_name': batch_name, 'steps': steps, + 'sampling_mode': sampling_mode, 'width_height': width_height, 'clip_guidance_scale': clip_guidance_scale, 'tv_scale': tv_scale, @@ -2954,4 +2969,4 @@ def move_files(start_num, end_num, old_folder, new_folder): # if view_video_in_cell: # mp4 = open(filepath,'rb').read() # data_url = "data:video/mp4;base64," + b64encode(mp4).decode() - # display.HTML(f'') + # display.HTML(f'') \ No newline at end of file From 52a3da87fe192acf8e0d5b9cd27fd18e56723656 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Sat, 12 Mar 2022 00:47:18 -0500 Subject: [PATCH 11/74] Adds a human-readable id to each cell. Collapses more cells by default, and makes more code appear as forms by default. Also restores some param UI fields. --- Disco_Diffusion.ipynb | 147 ++++++++++++++++++++++++++++++------------ disco.py | 10 +-- 2 files changed, 111 insertions(+), 46 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index b3f223a9..881e4823 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -12,7 +12,9 @@ }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "id": "TitleTop" + }, "source": [ "# Disco Diffusion v5 - Now with 3D animation\n", "\n", @@ -24,7 +26,7 @@ { "cell_type": "markdown", "metadata": { - "id": "1YwMUyt9LHG1" + "id": "CreditsChTop" }, "source": [ "### Credits & Changelog \u2b07\ufe0f" @@ -32,7 +34,9 @@ }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "id": "Credits" + }, "source": [ "#### Credits\n", "\n", @@ -59,16 +63,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "id": "LicenseTop" + }, "source": [ "#### License" ] }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "id": "License" + }, "source": [ - "@title Licensed under the MIT License\n", + "Licensed under the MIT License\n", "\n", "Copyright (c) 2021 Katherine Crowson \n", "\n", @@ -143,14 +151,19 @@ }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "id": "ChangelogTop" + }, "source": [ "#### Changelog" ] }, { "cell_type": "code", - "metadata": {}, + "metadata": { + "cellView": "form", + "id": "Changelog" + }, "source": [ "#@title <- View Changelog\n", "skip_for_run_all = True #@param {type: 'boolean'}\n", @@ -235,7 +248,7 @@ { "cell_type": "markdown", "metadata": { - "id": "XTu6AjLyFQUq" + "id": "TutorialTop" }, "source": [ "# Tutorial" @@ -243,7 +256,9 @@ }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "id": "DiffusionSet" + }, "source": [ "**Diffusion settings (Defaults are heavily outdated)**\n", "---\n", @@ -294,7 +309,9 @@ }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "id": "SetupTop" + }, "source": [ "# 1. Set Up" ] @@ -302,7 +319,8 @@ { "cell_type": "code", "metadata": { - "id": "_9Eg9Kf5FlfK" + "cellView": "form", + "id": "CheckGPU" }, "source": [ "#@title 1.1 Check GPU Status\n", @@ -324,7 +342,10 @@ }, { "cell_type": "code", - "metadata": {}, + "metadata": { + "cellView": "form", + "id": "PrepFolders" + }, "source": [ "#@title 1.2 Prepare Folders\n", "import subprocess\n", @@ -404,7 +425,10 @@ }, { "cell_type": "code", - "metadata": {}, + "metadata": { + "cellView": "form", + "id": "InstallDeps" + }, "source": [ "#@title ### 1.3 Install and import dependencies\n", "\n", @@ -573,7 +597,10 @@ }, { "cell_type": "code", - "metadata": {}, + "metadata": { + "cellView": "form", + "id": "DefMidasFns" + }, "source": [ "#@title ### 1.4 Define Midas functions\n", "\n", @@ -682,7 +709,10 @@ }, { "cell_type": "code", - "metadata": {}, + "metadata": { + "cellView": "form", + "id": "DefFns" + }, "source": [ "#@title 1.5 Define necessary functions\n", "\n", @@ -1440,7 +1470,10 @@ }, { "cell_type": "code", - "metadata": {}, + "metadata": { + "cellView": "form", + "id": "DefSecModel" + }, "source": [ "#@title 1.6 Define the secondary diffusion model\n", "\n", @@ -1611,7 +1644,10 @@ }, { "cell_type": "code", - "metadata": {}, + "metadata": { + "cellView": "form", + "id": "DefSuperRes" + }, "source": [ "#@title 1.7 SuperRes Define\n", "class DDIMSampler(object):\n", @@ -2141,22 +2177,26 @@ }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "id": "DiffClipSetTop" + }, "source": [ "# 2. Diffusion and CLIP model settings" ] }, { "cell_type": "code", - "metadata": {}, + "metadata": { + "id": "ModelSettings" + }, "source": [ "#@markdown ####**Models Settings:**\n", "diffusion_model = \"512x512_diffusion_uncond_finetune_008100\" #@param [\"256x256_diffusion_uncond\", \"512x512_diffusion_uncond_finetune_008100\"]\n", "use_secondary_model = True #@param {type: 'boolean'}\n", "sampling_mode = 'ddim' #@param ['plms','ddim'] \n", "\n", - "timestep_respacing = '250' # param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000'] \n", - "diffusion_steps = 1000 # param {type: 'number'}\n", + "timestep_respacing = '250' #@param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000'] \n", + "diffusion_steps = 1000 #@param {type: 'number'}\n", "use_checkpoint = True #@param {type: 'boolean'}\n", "ViTB32 = True #@param{type:\"boolean\"}\n", "ViTB16 = True #@param{type:\"boolean\"}\n", @@ -2166,8 +2206,8 @@ "RN50x4 = False #@param{type:\"boolean\"}\n", "RN50x16 = False #@param{type:\"boolean\"}\n", "RN50x64 = False #@param{type:\"boolean\"}\n", - "SLIPB16 = False # param{type:\"boolean\"}\n", - "SLIPL16 = False # param{type:\"boolean\"}\n", + "SLIPB16 = False #@param{type:\"boolean\"}\n", + "SLIPL16 = False #@param{type:\"boolean\"}\n", "\n", "#@markdown If you're having issues with model downloads, check this to compare SHA's:\n", "check_model_SHA = False #@param{type:\"boolean\"}\n", @@ -2337,14 +2377,18 @@ }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "id": "SettingsTop" + }, "source": [ "# 3. Settings" ] }, { "cell_type": "code", - "metadata": {}, + "metadata": { + "id": "BasicSettings" + }, "source": [ "#@markdown ####**Basic Settings:**\n", "batch_name = 'TimeToDisco' #@param{type: 'string'}\n", @@ -2389,7 +2433,7 @@ { "cell_type": "markdown", "metadata": { - "id": "CnkTNXJAPzL2" + "id": "AnimSetTop" }, "source": [ "### Animation Settings" @@ -2397,7 +2441,9 @@ }, { "cell_type": "code", - "metadata": {}, + "metadata": { + "id": "AnimSettings" + }, "source": [ "#@markdown ####**Animation Mode:**\n", "animation_mode = 'None' #@param ['None', '2D', '3D', 'Video Input'] {type:'string'}\n", @@ -2713,7 +2759,7 @@ { "cell_type": "markdown", "metadata": { - "id": "u1VHzHvNx5fd" + "id": "ExtraSetTop" }, "source": [ "### Extra Settings\n", @@ -2722,7 +2768,9 @@ }, { "cell_type": "code", - "metadata": {}, + "metadata": { + "id": "ExtraSettings" + }, "source": [ "#@markdown ####**Saving:**\n", "\n", @@ -2800,7 +2848,9 @@ }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "id": "PromptsTop" + }, "source": [ "### Prompts\n", "`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." @@ -2808,7 +2858,9 @@ }, { "cell_type": "code", - "metadata": {}, + "metadata": { + "id": "Prompts" + }, "source": [ "text_prompts = {\n", " 0: [\"A beautiful painting of a singular lighthouse, shining its light across a tumultuous sea of blood by greg rutkowski and thomas kinkade, Trending on artstation.\", \"yellow color scheme\"],\n", @@ -2824,14 +2876,18 @@ }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "id": "DiffuseTop" + }, "source": [ "# 4. Diffuse!" ] }, { "cell_type": "code", - "metadata": {}, + "metadata": { + "id": "DoTheRun" + }, "source": [ "#@title Do the Run!\n", "#@markdown `n_batches` ignored with animation modes.\n", @@ -3015,14 +3071,18 @@ }, { "cell_type": "markdown", - "metadata": {}, + "metadata": { + "id": "CreateVidTop" + }, "source": [ "# 5. Create the video" ] }, { "cell_type": "code", - "metadata": {}, + "metadata": { + "id": "CreateVid" + }, "source": [ "# @title ### **Create video**\n", "#@markdown Video file will save in the same folder as your images.\n", @@ -3108,11 +3168,16 @@ "accelerator": "GPU", "colab": { "collapsed_sections": [ - "1YwMUyt9LHG1", - "XTu6AjLyFQUq", - "_9Eg9Kf5FlfK", - "CnkTNXJAPzL2", - "u1VHzHvNx5fd" + "CreditsChTop", + "TutorialTop", + "CheckGPU", + "InstallDeps", + "DefMidasFns", + "DefFns", + "DefSecModel", + "DefSuperRes", + "AnimSetTop", + "ExtraSetTop" ], "machine_shape": "hm", "name": "Disco Diffusion v5 [w/ 3D animation]", diff --git a/disco.py b/disco.py index 44e624ef..e06ea5ec 100644 --- a/disco.py +++ b/disco.py @@ -49,7 +49,7 @@ # %% """ -@title Licensed under the MIT License +Licensed under the MIT License Copyright (c) 2021 Katherine Crowson @@ -2073,8 +2073,8 @@ def do_superres(img, filepath): use_secondary_model = True #@param {type: 'boolean'} sampling_mode = 'ddim' #@param ['plms','ddim'] -timestep_respacing = '250' # param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000'] -diffusion_steps = 1000 # param {type: 'number'} +timestep_respacing = '250' #@param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000'] +diffusion_steps = 1000 #@param {type: 'number'} use_checkpoint = True #@param {type: 'boolean'} ViTB32 = True #@param{type:"boolean"} ViTB16 = True #@param{type:"boolean"} @@ -2084,8 +2084,8 @@ def do_superres(img, filepath): RN50x4 = False #@param{type:"boolean"} RN50x16 = False #@param{type:"boolean"} RN50x64 = False #@param{type:"boolean"} -SLIPB16 = False # param{type:"boolean"} -SLIPL16 = False # param{type:"boolean"} +SLIPB16 = False #@param{type:"boolean"} +SLIPL16 = False #@param{type:"boolean"} #@markdown If you're having issues with model downloads, check this to compare SHA's: check_model_SHA = False #@param{type:"boolean"} From 7c5e365f74cbe31f09029f531948f9073be62a12 Mon Sep 17 00:00:00 2001 From: Nate Baer Date: Sat, 12 Mar 2022 23:48:33 -0800 Subject: [PATCH 12/74] Check if using secondary model before loading it --- Disco_Diffusion.ipynb | 5 ++--- disco.py | 5 ++--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 881e4823..9a6ff1d4 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -2321,15 +2321,14 @@ " 'use_scale_shift_norm': True,\n", " })\n", "\n", - "secondary_model_ver = 2\n", "model_default = model_config['image_size']\n", "\n", "\n", "\n", - "if secondary_model_ver == 2:\n", + "if use_secondary_model:\n", " secondary_model = SecondaryDiffusionImageNet2()\n", " secondary_model.load_state_dict(torch.load(f'{model_path}/secondary_model_imagenet_2.pth', map_location='cpu'))\n", - "secondary_model.eval().requires_grad_(False).to(device)\n", + " secondary_model.eval().requires_grad_(False).to(device)\n", "\n", "clip_models = []\n", "if ViTB32 is True: clip_models.append(clip.load('ViT-B/32', jit=False)[0].eval().requires_grad_(False).to(device)) \n", diff --git a/disco.py b/disco.py index e06ea5ec..58ad5b5f 100644 --- a/disco.py +++ b/disco.py @@ -2199,15 +2199,14 @@ def do_superres(img, filepath): 'use_scale_shift_norm': True, }) -secondary_model_ver = 2 model_default = model_config['image_size'] -if secondary_model_ver == 2: +if use_secondary_model: secondary_model = SecondaryDiffusionImageNet2() secondary_model.load_state_dict(torch.load(f'{model_path}/secondary_model_imagenet_2.pth', map_location='cpu')) -secondary_model.eval().requires_grad_(False).to(device) + secondary_model.eval().requires_grad_(False).to(device) clip_models = [] if ViTB32 is True: clip_models.append(clip.load('ViT-B/32', jit=False)[0].eval().requires_grad_(False).to(device)) From 9e3d032e505ef0a4fec864f57e340b747b072a66 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Tue, 29 Mar 2022 23:08:34 -0400 Subject: [PATCH 13/74] Adds basic/original zippy turbo mode - with working resume functionality --- Disco_Diffusion.ipynb | 26 ++++++++++++++++++++++++++ disco.py | 26 ++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 881e4823..c7a6a025 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -1110,6 +1110,18 @@ " args.fov, padding_mode=args.padding_mode,\n", " sampling_mode=args.sampling_mode, midas_weight=args.midas_weight)\n", " next_step_pil.save('prevFrameScaled.png')\n", + "\n", + " ### Turbo mode - skip some diffusions to save time \n", + " if turbo_mode == True and frame_num > 10 and frame_num % int(turbo_steps) != 0:\n", + " print('turbo mode is on this frame: skipping clip diffusion steps')\n", + " filename = f'{args.batch_name}({args.batchNum})_{frame_num:04}.png'\n", + " next_step_pil.save(f'{batchFolder}/{filename}') #save it as this frame\n", + " next_step_pil.save(f'{img_filepath}') # save it also as prev_frame for next iteration\n", + " continue\n", + " elif turbo_mode == True:\n", + " print('turbo mode is OFF this frame')\n", + " #else: no turbo\n", + "\n", " init_image = 'prevFrameScaled.png'\n", " init_scale = args.frames_scale\n", " skip_steps = args.calc_frames_skip_steps\n", @@ -1460,6 +1472,8 @@ " 'sampling_mode': sampling_mode,\n", " 'video_init_path':video_init_path,\n", " 'extract_nth_frame':extract_nth_frame,\n", + " 'turbo_mode':turbo_mode,\n", + " 'turbo_steps':turbo_steps,\n", " }\n", " # print('Settings:', setting_list)\n", " with open(f\"{batchFolder}/{batch_name}({batchNum})_settings.txt\", \"w+\") as f: #save settings\n", @@ -2504,6 +2518,14 @@ "padding_mode = 'border'#@param {type:\"string\"}\n", "sampling_mode = 'bicubic'#@param {type:\"string\"}\n", "\n", + "#======= TURBO MODE\n", + "#@markdown ---\n", + "#@markdown ####**Turbo Mode (3D anim only):**\n", + "#@markdown (Starts after frame 10,) skips diffusion steps and just uses MIDAS depth map to warp images for skipped frames.\n", + "#@markdown Speeds up rendering by 2x-4x, and may improve image coherence between frames.\n", + "\n", + "turbo_mode = True #@param {type:\"boolean\"}\n", + "turbo_steps = \"3\" #@param [\"2\",\"3\",\"4\"] {type:'string'}\n", "#@markdown ---\n", "\n", "#@markdown ####**Coherency Settings:**\n", @@ -2939,8 +2961,12 @@ " batchNum = int(run_to_resume)\n", " if resume_from_frame == 'latest':\n", " start_frame = len(glob(batchFolder+f\"/{batch_name}({batchNum})_*.png\"))\n", + " if turbo_mode == True and start_frame > 10 and start_frame % int(turbo_steps) != 0:\n", + " start_frame = start_frame - (start_frame % int(turbo_steps))\n", " else:\n", " start_frame = int(resume_from_frame)+1\n", + " if turbo_mode == True and start_frame > 10 and start_frame % int(turbo_steps) != 0:\n", + " start_frame = start_frame - (start_frame % int(turbo_steps))\n", " if retain_overwritten_frames is True:\n", " existing_frames = len(glob(batchFolder+f\"/{batch_name}({batchNum})_*.png\"))\n", " frames_to_save = existing_frames - start_frame\n", diff --git a/disco.py b/disco.py index e06ea5ec..a8205394 100644 --- a/disco.py +++ b/disco.py @@ -1017,6 +1017,18 @@ def do_run(): args.fov, padding_mode=args.padding_mode, sampling_mode=args.sampling_mode, midas_weight=args.midas_weight) next_step_pil.save('prevFrameScaled.png') + + ### Turbo mode - skip some diffusions to save time + if turbo_mode == True and frame_num > 10 and frame_num % int(turbo_steps) != 0: + print('turbo mode is on this frame: skipping clip diffusion steps') + filename = f'{args.batch_name}({args.batchNum})_{frame_num:04}.png' + next_step_pil.save(f'{batchFolder}/{filename}') #save it as this frame + next_step_pil.save(f'{img_filepath}') # save it also as prev_frame for next iteration + continue + elif turbo_mode == True: + print('turbo mode is OFF this frame') + #else: no turbo + init_image = 'prevFrameScaled.png' init_scale = args.frames_scale skip_steps = args.calc_frames_skip_steps @@ -1367,6 +1379,8 @@ def save_settings(): 'sampling_mode': sampling_mode, 'video_init_path':video_init_path, 'extract_nth_frame':extract_nth_frame, + 'turbo_mode':turbo_mode, + 'turbo_steps':turbo_steps, } # print('Settings:', setting_list) with open(f"{batchFolder}/{batch_name}({batchNum})_settings.txt", "w+") as f: #save settings @@ -2360,6 +2374,14 @@ def do_superres(img, filepath): padding_mode = 'border'#@param {type:"string"} sampling_mode = 'bicubic'#@param {type:"string"} +#======= TURBO MODE +#@markdown --- +#@markdown ####**Turbo Mode (3D anim only):** +#@markdown (Starts after frame 10,) skips diffusion steps and just uses MIDAS depth map to warp images for skipped frames. +#@markdown Speeds up rendering by 2x-4x, and may improve image coherence between frames. + +turbo_mode = True #@param {type:"boolean"} +turbo_steps = "3" #@param ["2","3","4"] {type:'string'} #@markdown --- #@markdown ####**Coherency Settings:** @@ -2762,8 +2784,12 @@ def move_files(start_num, end_num, old_folder, new_folder): batchNum = int(run_to_resume) if resume_from_frame == 'latest': start_frame = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png")) + if turbo_mode == True and start_frame > 10 and start_frame % int(turbo_steps) != 0: + start_frame = start_frame - (start_frame % int(turbo_steps)) else: start_frame = int(resume_from_frame)+1 + if turbo_mode == True and start_frame > 10 and start_frame % int(turbo_steps) != 0: + start_frame = start_frame - (start_frame % int(turbo_steps)) if retain_overwritten_frames is True: existing_frames = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png")) frames_to_save = existing_frames - start_frame From b350675b76256ab027d22bbc8df707ab97941dce Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Tue, 29 Mar 2022 23:34:56 -0400 Subject: [PATCH 14/74] Add original simple turbo blending --- Disco_Diffusion.ipynb | 43 ++++++++++++++++++++++++++++++------------- disco.py | 43 ++++++++++++++++++++++++++++++------------- 2 files changed, 60 insertions(+), 26 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index c7a6a025..77160f90 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -1111,16 +1111,20 @@ " sampling_mode=args.sampling_mode, midas_weight=args.midas_weight)\n", " next_step_pil.save('prevFrameScaled.png')\n", "\n", - " ### Turbo mode - skip some diffusions to save time \n", - " if turbo_mode == True and frame_num > 10 and frame_num % int(turbo_steps) != 0:\n", - " print('turbo mode is on this frame: skipping clip diffusion steps')\n", - " filename = f'{args.batch_name}({args.batchNum})_{frame_num:04}.png'\n", - " next_step_pil.save(f'{batchFolder}/{filename}') #save it as this frame\n", - " next_step_pil.save(f'{img_filepath}') # save it also as prev_frame for next iteration\n", - " continue\n", - " elif turbo_mode == True:\n", - " print('turbo mode is OFF this frame')\n", - " #else: no turbo\n", + " ### Turbo mode - skip some diffusions to save time\n", + " turbo_blend = False # default to normal frame saving later\n", + " if turbo_mode and frame_num > 10: #preroll is 10 frames\n", + " if frame_num % int(turbo_steps) != 0:\n", + " print('turbo skip this frame: skipping clip diffusion steps')\n", + " filename = f'{args.batch_name}({args.batchNum})_{frame_num:04}.png'\n", + " next_step_pil.save(f'{batchFolder}/{filename}') #save it as this frame. done.\n", + " next_step_pil.save(f'{img_filepath}') # save it also as prev_frame to feed next iteration\n", + " turbo_blend = False # default to normal-frame-saving later\n", + " continue\n", + " else:\n", + " if turbo_frame_blend:\n", + " turbo_blend = True # blend frames for smoothness..\n", + " print('clip/diff this frame - generate clip diff image')\n", "\n", " init_image = 'prevFrameScaled.png'\n", " init_scale = args.frames_scale\n", @@ -1393,6 +1397,17 @@ " image.save(f'{unsharpenFolder}/{filename}')\n", " else:\n", " image.save(f'{batchFolder}/{filename}')\n", + " if args.animation_mode == \"3D\":\n", + " # If turbo_blend, save a blended image\n", + " if turbo_mode and turbo_blend:\n", + " # Mix new image with prevFrameScaled\n", + " newFrame = cv2.imread('prevFrame.png') # This is already updated..\n", + " prev_frame_warped = cv2.imread('prevFrameScaled.png')\n", + " blendedImage = cv2.addWeighted(newFrame, 0.5, prev_frame_warped, 0.5, 0.0)\n", + " cv2.imwrite(f'{batchFolder}/{filename}',blendedImage)\n", + " turbo_blend = False # reset to false\n", + " else:\n", + " image.save(f'{batchFolder}/{filename}')\n", " # if frame_num != args.max_frames-1:\n", " # display.clear_output()\n", "\n", @@ -1474,6 +1489,7 @@ " 'extract_nth_frame':extract_nth_frame,\n", " 'turbo_mode':turbo_mode,\n", " 'turbo_steps':turbo_steps,\n", + " 'turbo_frame_blend':turbo_frame_blend,\n", " }\n", " # print('Settings:', setting_list)\n", " with open(f\"{batchFolder}/{batch_name}({batchNum})_settings.txt\", \"w+\") as f: #save settings\n", @@ -2521,11 +2537,12 @@ "#======= TURBO MODE\n", "#@markdown ---\n", "#@markdown ####**Turbo Mode (3D anim only):**\n", - "#@markdown (Starts after frame 10,) skips diffusion steps and just uses MIDAS depth map to warp images for skipped frames.\n", - "#@markdown Speeds up rendering by 2x-4x, and may improve image coherence between frames.\n", + "#@markdown (Starts after frame 10,) skips diffusion steps and just uses depth map to warp images for skipped frames.\n", + "#@markdown Speeds up rendering by 2x-4x, and may improve image coherence between frames. frame_blend_mode smooths abrupt texture changes across 2 frames.\n", "\n", "turbo_mode = True #@param {type:\"boolean\"}\n", - "turbo_steps = \"3\" #@param [\"2\",\"3\",\"4\"] {type:'string'}\n", + "turbo_steps = \"3\" #@param [\"2\",\"3\",\"4\",\"5\",\"6\"] {type:\"string\"}\n", + "turbo_frame_blend = True #@param {type:\"boolean\"}\n", "#@markdown ---\n", "\n", "#@markdown ####**Coherency Settings:**\n", diff --git a/disco.py b/disco.py index a8205394..2a195031 100644 --- a/disco.py +++ b/disco.py @@ -1018,16 +1018,20 @@ def do_run(): sampling_mode=args.sampling_mode, midas_weight=args.midas_weight) next_step_pil.save('prevFrameScaled.png') - ### Turbo mode - skip some diffusions to save time - if turbo_mode == True and frame_num > 10 and frame_num % int(turbo_steps) != 0: - print('turbo mode is on this frame: skipping clip diffusion steps') - filename = f'{args.batch_name}({args.batchNum})_{frame_num:04}.png' - next_step_pil.save(f'{batchFolder}/{filename}') #save it as this frame - next_step_pil.save(f'{img_filepath}') # save it also as prev_frame for next iteration - continue - elif turbo_mode == True: - print('turbo mode is OFF this frame') - #else: no turbo + ### Turbo mode - skip some diffusions to save time + turbo_blend = False # default to normal frame saving later + if turbo_mode and frame_num > 10: #preroll is 10 frames + if frame_num % int(turbo_steps) != 0: + print('turbo skip this frame: skipping clip diffusion steps') + filename = f'{args.batch_name}({args.batchNum})_{frame_num:04}.png' + next_step_pil.save(f'{batchFolder}/{filename}') #save it as this frame. done. + next_step_pil.save(f'{img_filepath}') # save it also as prev_frame to feed next iteration + turbo_blend = False # default to normal-frame-saving later + continue + else: + if turbo_frame_blend: + turbo_blend = True # blend frames for smoothness.. + print('clip/diff this frame - generate clip diff image') init_image = 'prevFrameScaled.png' init_scale = args.frames_scale @@ -1300,6 +1304,17 @@ def cond_fn(x, t, y=None): image.save(f'{unsharpenFolder}/{filename}') else: image.save(f'{batchFolder}/{filename}') + if args.animation_mode == "3D": + # If turbo_blend, save a blended image + if turbo_mode and turbo_blend: + # Mix new image with prevFrameScaled + newFrame = cv2.imread('prevFrame.png') # This is already updated.. + prev_frame_warped = cv2.imread('prevFrameScaled.png') + blendedImage = cv2.addWeighted(newFrame, 0.5, prev_frame_warped, 0.5, 0.0) + cv2.imwrite(f'{batchFolder}/{filename}',blendedImage) + turbo_blend = False # reset to false + else: + image.save(f'{batchFolder}/{filename}') # if frame_num != args.max_frames-1: # display.clear_output() @@ -1381,6 +1396,7 @@ def save_settings(): 'extract_nth_frame':extract_nth_frame, 'turbo_mode':turbo_mode, 'turbo_steps':turbo_steps, + 'turbo_frame_blend':turbo_frame_blend, } # print('Settings:', setting_list) with open(f"{batchFolder}/{batch_name}({batchNum})_settings.txt", "w+") as f: #save settings @@ -2377,11 +2393,12 @@ def do_superres(img, filepath): #======= TURBO MODE #@markdown --- #@markdown ####**Turbo Mode (3D anim only):** -#@markdown (Starts after frame 10,) skips diffusion steps and just uses MIDAS depth map to warp images for skipped frames. -#@markdown Speeds up rendering by 2x-4x, and may improve image coherence between frames. +#@markdown (Starts after frame 10,) skips diffusion steps and just uses depth map to warp images for skipped frames. +#@markdown Speeds up rendering by 2x-4x, and may improve image coherence between frames. frame_blend_mode smooths abrupt texture changes across 2 frames. turbo_mode = True #@param {type:"boolean"} -turbo_steps = "3" #@param ["2","3","4"] {type:'string'} +turbo_steps = "3" #@param ["2","3","4","5","6"] {type:"string"} +turbo_frame_blend = True #@param {type:"boolean"} #@markdown --- #@markdown ####**Coherency Settings:** From 0e366efcf907e48e42a79d80d3e7e7c1246397c0 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Wed, 30 Mar 2022 13:42:17 -0400 Subject: [PATCH 15/74] Adds improved zippy turbo blending --- Disco_Diffusion.ipynb | 138 +++++++++++++++++++++++++----------------- disco.py | 138 +++++++++++++++++++++++++----------------- 2 files changed, 166 insertions(+), 110 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 77160f90..3d55ced6 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -392,14 +392,8 @@ " root_path = '.'\n", "\n", "import os\n", - "from os import path\n", - "#Simple create paths taken with modifications from Datamosh's Batch VQGAN+CLIP notebook\n", "def createPath(filepath):\n", - " if path.exists(filepath) == False:\n", - " os.makedirs(filepath)\n", - " print(f'Made {filepath}')\n", - " else:\n", - " print(f'filepath {filepath} exists.')\n", + " os.makedirs(filepath, exist_ok=True)\n", "\n", "initDirPath = f'{root_path}/init_images'\n", "createPath(initDirPath)\n", @@ -432,7 +426,6 @@ "source": [ "#@title ### 1.3 Install and import dependencies\n", "\n", - "from os.path import exists as path_exists\n", "import pathlib, shutil\n", "\n", "if not is_colab:\n", @@ -476,9 +469,9 @@ " except:\n", " pass\n", "\n", - "if not path_exists(f'{model_path}'):\n", + "if not os.path.exists(f'{model_path}'):\n", " pathlib.Path(model_path).mkdir(parents=True, exist_ok=True)\n", - "if not path_exists(f'{model_path}/dpt_large-midas-2f21e586.pt'):\n", + "if not os.path.exists(f'{model_path}/dpt_large-midas-2f21e586.pt'):\n", " wget(\"https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt\", model_path)\n", "\n", "import sys\n", @@ -575,7 +568,7 @@ "if USE_ADABINS:\n", " if is_colab:\n", " gitclone(\"https://github.com/shariqfarooq123/AdaBins.git\")\n", - " if not path_exists(f'{model_path}/AdaBins_nyu.pt'):\n", + " if not os.path.exists(f'{model_path}/AdaBins_nyu.pt'):\n", " wget(\"https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt\", model_path)\n", " pathlib.Path(\"pretrained\").mkdir(parents=True, exist_ok=True)\n", " shutil.copyfile(f\"{model_path}/AdaBins_nyu.pt\", \"pretrained/AdaBins_nyu.pt\")\n", @@ -1003,6 +996,44 @@ "\n", "stop_on_next_loop = False # Make sure GPU memory doesn't get corrupted from cancelling the run mid-way through, allow a full frame to complete\n", "\n", + "def do_3d_step(img_filepath, frame_num, midas_model, midas_transform):\n", + " global seed\n", + "\n", + " if args.key_frames:\n", + " translation_x = args.translation_x_series[frame_num]\n", + " translation_y = args.translation_y_series[frame_num]\n", + " translation_z = args.translation_z_series[frame_num]\n", + " rotation_3d_x = args.rotation_3d_x_series[frame_num]\n", + " rotation_3d_y = args.rotation_3d_y_series[frame_num]\n", + " rotation_3d_z = args.rotation_3d_z_series[frame_num]\n", + " print(\n", + " f'translation_x: {translation_x}',\n", + " f'translation_y: {translation_y}',\n", + " f'translation_z: {translation_z}',\n", + " f'rotation_3d_x: {rotation_3d_x}',\n", + " f'rotation_3d_y: {rotation_3d_y}',\n", + " f'rotation_3d_z: {rotation_3d_z}',\n", + " )\n", + "\n", + " if frame_num > 0:\n", + " seed = seed + 1\n", + " if resume_run and frame_num == start_frame:\n", + " img_filepath = batchFolder+f\"/{batch_name}({batchNum})_{start_frame-1:04}.png\"\n", + " else:\n", + " img_filepath = '/content/prevFrame.png' if is_colab else 'prevFrame.png'\n", + " trans_scale = 1.0/200.0\n", + " translate_xyz = [-translation_x*trans_scale, translation_y*trans_scale, -translation_z*trans_scale]\n", + " rotate_xyz = [rotation_3d_x, rotation_3d_y, rotation_3d_z]\n", + " print('translation:',translate_xyz)\n", + " print('rotation:',rotate_xyz)\n", + " rot_mat = p3dT.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), \"XYZ\").unsqueeze(0)\n", + " print(\"rot_mat: \" + str(rot_mat))\n", + " next_step_pil = dxf.transform_image_3d(img_filepath, midas_model, midas_transform, DEVICE,\n", + " rot_mat, translate_xyz, args.near_plane, args.far_plane,\n", + " args.fov, padding_mode=args.padding_mode,\n", + " sampling_mode=args.sampling_mode, midas_weight=args.midas_weight)\n", + " return next_step_pil\n", + "\n", "def do_run():\n", " seed = args.seed\n", " print(range(args.start_frame, args.max_frames))\n", @@ -1072,58 +1103,45 @@ " skip_steps = args.calc_frames_skip_steps\n", "\n", " if args.animation_mode == \"3D\":\n", - " if args.key_frames:\n", - " angle = args.angle_series[frame_num]\n", - " #zoom = args.zoom_series[frame_num]\n", - " translation_x = args.translation_x_series[frame_num]\n", - " translation_y = args.translation_y_series[frame_num]\n", - " translation_z = args.translation_z_series[frame_num]\n", - " rotation_3d_x = args.rotation_3d_x_series[frame_num]\n", - " rotation_3d_y = args.rotation_3d_y_series[frame_num]\n", - " rotation_3d_z = args.rotation_3d_z_series[frame_num]\n", - " print(\n", - " f'angle: {angle}',\n", - " #f'zoom: {zoom}',\n", - " f'translation_x: {translation_x}',\n", - " f'translation_y: {translation_y}',\n", - " f'translation_z: {translation_z}',\n", - " f'rotation_3d_x: {rotation_3d_x}',\n", - " f'rotation_3d_y: {rotation_3d_y}',\n", - " f'rotation_3d_z: {rotation_3d_z}',\n", - " )\n", - "\n", - " if frame_num > 0:\n", + " if frame_num == 0:\n", + " turbo_blend = False\n", + " else:\n", " seed = seed + 1 \n", " if resume_run and frame_num == start_frame:\n", " img_filepath = batchFolder+f\"/{batch_name}({batchNum})_{start_frame-1:04}.png\"\n", + " if turbo_mode and frame_num > turbo_preroll:\n", + " shutil.copyfile(img_filepath, 'oldFrameScaled.png')\n", " else:\n", " img_filepath = '/content/prevFrame.png' if is_colab else 'prevFrame.png'\n", - " trans_scale = 1.0/200.0\n", - " translate_xyz = [-translation_x*trans_scale, translation_y*trans_scale, -translation_z*trans_scale]\n", - " rotate_xyz = [rotation_3d_x, rotation_3d_y, rotation_3d_z]\n", - " print('translation:',translate_xyz)\n", - " print('rotation:',rotate_xyz)\n", - " rot_mat = p3dT.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), \"XYZ\").unsqueeze(0)\n", - " print(\"rot_mat: \" + str(rot_mat))\n", - " next_step_pil = dxf.transform_image_3d(img_filepath, midas_model, midas_transform, DEVICE,\n", - " rot_mat, translate_xyz, args.near_plane, args.far_plane,\n", - " args.fov, padding_mode=args.padding_mode,\n", - " sampling_mode=args.sampling_mode, midas_weight=args.midas_weight)\n", + "\n", + " next_step_pil = do_3d_step(img_filepath, frame_num, midas_model, midas_transform)\n", " next_step_pil.save('prevFrameScaled.png')\n", "\n", - " ### Turbo mode - skip some diffusions to save time\n", - " turbo_blend = False # default to normal frame saving later\n", - " if turbo_mode and frame_num > 10: #preroll is 10 frames\n", - " if frame_num % int(turbo_steps) != 0:\n", + " ### Turbo mode - skip some diffusions, use 3d morph for clarity and to save time\n", + " turbo_blend = False # default for non-turbo frame saving\n", + " if turbo_mode == True and frame_num == turbo_preroll: #start tracking oldframe\n", + " next_step_pil.save('oldFrameScaled.png')#stash for later blending \n", + " if turbo_mode == True and frame_num > turbo_preroll:\n", + " #set up 2 warped image sequences, old & new, to blend toward new diff image\n", + " old_frame = do_3d_step('oldFrameScaled.png', frame_num, midas_model, midas_transform)\n", + " old_frame.save('oldFrameScaled.png')\n", + " if frame_num % int(turbo_steps) != 0: \n", " print('turbo skip this frame: skipping clip diffusion steps')\n", " filename = f'{args.batch_name}({args.batchNum})_{frame_num:04}.png'\n", - " next_step_pil.save(f'{batchFolder}/{filename}') #save it as this frame. done.\n", + " blend_factor = ((frame_num % int(turbo_steps))+1)/int(turbo_steps)\n", + " print('turbo skip this frame: skipping clip diffusion steps and saving blended frame')\n", + " newWarpedImg = cv2.imread('prevFrameScaled.png')#this is already updated..\n", + " oldWarpedImg = cv2.imread('oldFrameScaled.png')\n", + " blendedImage = cv2.addWeighted(newWarpedImg, blend_factor, oldWarpedImg,1-blend_factor, 0.0)\n", + " cv2.imwrite(f'{batchFolder}/{filename}',blendedImage)\n", " next_step_pil.save(f'{img_filepath}') # save it also as prev_frame to feed next iteration\n", - " turbo_blend = False # default to normal-frame-saving later\n", + " turbo_blend = False\n", " continue\n", " else:\n", - " if turbo_frame_blend:\n", - " turbo_blend = True # blend frames for smoothness..\n", + " #if not a skip frame, will run diffusion and need to blend.\n", + " oldWarpedImg = cv2.imread('prevFrameScaled.png')\n", + " cv2.imwrite(f'oldFrameScaled.png',oldWarpedImg)#swap in for blending later \n", + " turbo_blend = True # flag to blend frames after diff generated...\n", " print('clip/diff this frame - generate clip diff image')\n", "\n", " init_image = 'prevFrameScaled.png'\n", @@ -1162,7 +1180,7 @@ " else:\n", " image_prompt = []\n", "\n", - " print(f'Frame Prompt: {frame_prompt}')\n", + " print(f'Frame {frame_num} Prompt: {frame_prompt}')\n", "\n", " model_stats = []\n", " for clip_model in clip_models:\n", @@ -1489,6 +1507,7 @@ " 'extract_nth_frame':extract_nth_frame,\n", " 'turbo_mode':turbo_mode,\n", " 'turbo_steps':turbo_steps,\n", + " 'turbo_preroll':turbo_preroll,\n", " 'turbo_frame_blend':turbo_frame_blend,\n", " }\n", " # print('Settings:', setting_list)\n", @@ -2542,7 +2561,16 @@ "\n", "turbo_mode = True #@param {type:\"boolean\"}\n", "turbo_steps = \"3\" #@param [\"2\",\"3\",\"4\",\"5\",\"6\"] {type:\"string\"}\n", + "turbo_preroll = 10 # frames\n", "turbo_frame_blend = True #@param {type:\"boolean\"}\n", + "\n", + "#insist turbo be used only w 3d anim.\n", + "if turbo_mode and animation_mode != '3D':\n", + " print('=====')\n", + " print('Turbo mode only available with 3D animations. Disabling Turbo.')\n", + " print('=====')\n", + " turbo_mode = False\n", + "\n", "#@markdown ---\n", "\n", "#@markdown ####**Coherency Settings:**\n", @@ -2978,11 +3006,11 @@ " batchNum = int(run_to_resume)\n", " if resume_from_frame == 'latest':\n", " start_frame = len(glob(batchFolder+f\"/{batch_name}({batchNum})_*.png\"))\n", - " if turbo_mode == True and start_frame > 10 and start_frame % int(turbo_steps) != 0:\n", + " if turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0:\n", " start_frame = start_frame - (start_frame % int(turbo_steps))\n", " else:\n", " start_frame = int(resume_from_frame)+1\n", - " if turbo_mode == True and start_frame > 10 and start_frame % int(turbo_steps) != 0:\n", + " if turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0:\n", " start_frame = start_frame - (start_frame % int(turbo_steps))\n", " if retain_overwritten_frames is True:\n", " existing_frames = len(glob(batchFolder+f\"/{batch_name}({batchNum})_*.png\"))\n", @@ -2992,7 +3020,7 @@ "else:\n", " start_frame = 0\n", " batchNum = len(glob(batchFolder+\"/*.txt\"))\n", - " 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", + " while os.path.isfile(f\"{batchFolder}/{batch_name}({batchNum})_settings.txt\") is True or os.path.isfile(f\"{batchFolder}/{batch_name}-{batchNum}_settings.txt\") is True:\n", " batchNum += 1\n", "\n", "print(f'Starting Run: {batch_name}({batchNum}) at frame {start_frame}')\n", diff --git a/disco.py b/disco.py index 2a195031..ff055d6d 100644 --- a/disco.py +++ b/disco.py @@ -326,14 +326,8 @@ def wget(url, outputdir): root_path = '.' import os -from os import path -#Simple create paths taken with modifications from Datamosh's Batch VQGAN+CLIP notebook def createPath(filepath): - if path.exists(filepath) == False: - os.makedirs(filepath) - print(f'Made {filepath}') - else: - print(f'filepath {filepath} exists.') + os.makedirs(filepath, exist_ok=True) initDirPath = f'{root_path}/init_images' createPath(initDirPath) @@ -357,7 +351,6 @@ def createPath(filepath): # %% #@title ### 1.3 Install and import dependencies -from os.path import exists as path_exists import pathlib, shutil if not is_colab: @@ -401,9 +394,9 @@ def createPath(filepath): except: pass -if not path_exists(f'{model_path}'): +if not os.path.exists(f'{model_path}'): pathlib.Path(model_path).mkdir(parents=True, exist_ok=True) -if not path_exists(f'{model_path}/dpt_large-midas-2f21e586.pt'): +if not os.path.exists(f'{model_path}/dpt_large-midas-2f21e586.pt'): wget("https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", model_path) import sys @@ -500,7 +493,7 @@ def createPath(filepath): if USE_ADABINS: if is_colab: gitclone("https://github.com/shariqfarooq123/AdaBins.git") - if not path_exists(f'{model_path}/AdaBins_nyu.pt'): + if not os.path.exists(f'{model_path}/AdaBins_nyu.pt'): wget("https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt", model_path) pathlib.Path("pretrained").mkdir(parents=True, exist_ok=True) shutil.copyfile(f"{model_path}/AdaBins_nyu.pt", "pretrained/AdaBins_nyu.pt") @@ -910,6 +903,44 @@ def range_loss(input): stop_on_next_loop = False # Make sure GPU memory doesn't get corrupted from cancelling the run mid-way through, allow a full frame to complete +def do_3d_step(img_filepath, frame_num, midas_model, midas_transform): + global seed + + if args.key_frames: + translation_x = args.translation_x_series[frame_num] + translation_y = args.translation_y_series[frame_num] + translation_z = args.translation_z_series[frame_num] + rotation_3d_x = args.rotation_3d_x_series[frame_num] + rotation_3d_y = args.rotation_3d_y_series[frame_num] + rotation_3d_z = args.rotation_3d_z_series[frame_num] + print( + f'translation_x: {translation_x}', + f'translation_y: {translation_y}', + f'translation_z: {translation_z}', + f'rotation_3d_x: {rotation_3d_x}', + f'rotation_3d_y: {rotation_3d_y}', + f'rotation_3d_z: {rotation_3d_z}', + ) + + if frame_num > 0: + seed = seed + 1 + if resume_run and frame_num == start_frame: + img_filepath = batchFolder+f"/{batch_name}({batchNum})_{start_frame-1:04}.png" + else: + img_filepath = '/content/prevFrame.png' if is_colab else 'prevFrame.png' + trans_scale = 1.0/200.0 + translate_xyz = [-translation_x*trans_scale, translation_y*trans_scale, -translation_z*trans_scale] + rotate_xyz = [rotation_3d_x, rotation_3d_y, rotation_3d_z] + print('translation:',translate_xyz) + print('rotation:',rotate_xyz) + rot_mat = p3dT.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), "XYZ").unsqueeze(0) + print("rot_mat: " + str(rot_mat)) + next_step_pil = dxf.transform_image_3d(img_filepath, midas_model, midas_transform, DEVICE, + rot_mat, translate_xyz, args.near_plane, args.far_plane, + args.fov, padding_mode=args.padding_mode, + sampling_mode=args.sampling_mode, midas_weight=args.midas_weight) + return next_step_pil + def do_run(): seed = args.seed print(range(args.start_frame, args.max_frames)) @@ -979,58 +1010,45 @@ def do_run(): skip_steps = args.calc_frames_skip_steps if args.animation_mode == "3D": - if args.key_frames: - angle = args.angle_series[frame_num] - #zoom = args.zoom_series[frame_num] - translation_x = args.translation_x_series[frame_num] - translation_y = args.translation_y_series[frame_num] - translation_z = args.translation_z_series[frame_num] - rotation_3d_x = args.rotation_3d_x_series[frame_num] - rotation_3d_y = args.rotation_3d_y_series[frame_num] - rotation_3d_z = args.rotation_3d_z_series[frame_num] - print( - f'angle: {angle}', - #f'zoom: {zoom}', - f'translation_x: {translation_x}', - f'translation_y: {translation_y}', - f'translation_z: {translation_z}', - f'rotation_3d_x: {rotation_3d_x}', - f'rotation_3d_y: {rotation_3d_y}', - f'rotation_3d_z: {rotation_3d_z}', - ) - - if frame_num > 0: + if frame_num == 0: + turbo_blend = False + else: seed = seed + 1 if resume_run and frame_num == start_frame: img_filepath = batchFolder+f"/{batch_name}({batchNum})_{start_frame-1:04}.png" + if turbo_mode and frame_num > turbo_preroll: + shutil.copyfile(img_filepath, 'oldFrameScaled.png') else: img_filepath = '/content/prevFrame.png' if is_colab else 'prevFrame.png' - trans_scale = 1.0/200.0 - translate_xyz = [-translation_x*trans_scale, translation_y*trans_scale, -translation_z*trans_scale] - rotate_xyz = [rotation_3d_x, rotation_3d_y, rotation_3d_z] - print('translation:',translate_xyz) - print('rotation:',rotate_xyz) - rot_mat = p3dT.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), "XYZ").unsqueeze(0) - print("rot_mat: " + str(rot_mat)) - next_step_pil = dxf.transform_image_3d(img_filepath, midas_model, midas_transform, DEVICE, - rot_mat, translate_xyz, args.near_plane, args.far_plane, - args.fov, padding_mode=args.padding_mode, - sampling_mode=args.sampling_mode, midas_weight=args.midas_weight) + + next_step_pil = do_3d_step(img_filepath, frame_num, midas_model, midas_transform) next_step_pil.save('prevFrameScaled.png') - ### Turbo mode - skip some diffusions to save time - turbo_blend = False # default to normal frame saving later - if turbo_mode and frame_num > 10: #preroll is 10 frames - if frame_num % int(turbo_steps) != 0: + ### Turbo mode - skip some diffusions, use 3d morph for clarity and to save time + turbo_blend = False # default for non-turbo frame saving + if turbo_mode == True and frame_num == turbo_preroll: #start tracking oldframe + next_step_pil.save('oldFrameScaled.png')#stash for later blending + if turbo_mode == True and frame_num > turbo_preroll: + #set up 2 warped image sequences, old & new, to blend toward new diff image + old_frame = do_3d_step('oldFrameScaled.png', frame_num, midas_model, midas_transform) + old_frame.save('oldFrameScaled.png') + if frame_num % int(turbo_steps) != 0: print('turbo skip this frame: skipping clip diffusion steps') filename = f'{args.batch_name}({args.batchNum})_{frame_num:04}.png' - next_step_pil.save(f'{batchFolder}/{filename}') #save it as this frame. done. + blend_factor = ((frame_num % int(turbo_steps))+1)/int(turbo_steps) + print('turbo skip this frame: skipping clip diffusion steps and saving blended frame') + newWarpedImg = cv2.imread('prevFrameScaled.png')#this is already updated.. + oldWarpedImg = cv2.imread('oldFrameScaled.png') + blendedImage = cv2.addWeighted(newWarpedImg, blend_factor, oldWarpedImg,1-blend_factor, 0.0) + cv2.imwrite(f'{batchFolder}/{filename}',blendedImage) next_step_pil.save(f'{img_filepath}') # save it also as prev_frame to feed next iteration - turbo_blend = False # default to normal-frame-saving later + turbo_blend = False continue else: - if turbo_frame_blend: - turbo_blend = True # blend frames for smoothness.. + #if not a skip frame, will run diffusion and need to blend. + oldWarpedImg = cv2.imread('prevFrameScaled.png') + cv2.imwrite(f'oldFrameScaled.png',oldWarpedImg)#swap in for blending later + turbo_blend = True # flag to blend frames after diff generated... print('clip/diff this frame - generate clip diff image') init_image = 'prevFrameScaled.png' @@ -1069,7 +1087,7 @@ def do_run(): else: image_prompt = [] - print(f'Frame Prompt: {frame_prompt}') + print(f'Frame {frame_num} Prompt: {frame_prompt}') model_stats = [] for clip_model in clip_models: @@ -1396,6 +1414,7 @@ def save_settings(): 'extract_nth_frame':extract_nth_frame, 'turbo_mode':turbo_mode, 'turbo_steps':turbo_steps, + 'turbo_preroll':turbo_preroll, 'turbo_frame_blend':turbo_frame_blend, } # print('Settings:', setting_list) @@ -2398,7 +2417,16 @@ def do_superres(img, filepath): turbo_mode = True #@param {type:"boolean"} turbo_steps = "3" #@param ["2","3","4","5","6"] {type:"string"} +turbo_preroll = 10 # frames turbo_frame_blend = True #@param {type:"boolean"} + +#insist turbo be used only w 3d anim. +if turbo_mode and animation_mode != '3D': + print('=====') + print('Turbo mode only available with 3D animations. Disabling Turbo.') + print('=====') + turbo_mode = False + #@markdown --- #@markdown ####**Coherency Settings:** @@ -2801,11 +2829,11 @@ def move_files(start_num, end_num, old_folder, new_folder): batchNum = int(run_to_resume) if resume_from_frame == 'latest': start_frame = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png")) - if turbo_mode == True and start_frame > 10 and start_frame % int(turbo_steps) != 0: + if turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0: start_frame = start_frame - (start_frame % int(turbo_steps)) else: start_frame = int(resume_from_frame)+1 - if turbo_mode == True and start_frame > 10 and start_frame % int(turbo_steps) != 0: + if turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0: start_frame = start_frame - (start_frame % int(turbo_steps)) if retain_overwritten_frames is True: existing_frames = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png")) @@ -2815,7 +2843,7 @@ def move_files(start_num, end_num, old_folder, new_folder): else: start_frame = 0 batchNum = len(glob(batchFolder+"/*.txt")) - while path.isfile(f"{batchFolder}/{batch_name}({batchNum})_settings.txt") is True or path.isfile(f"{batchFolder}/{batch_name}-{batchNum}_settings.txt") is True: + while os.path.isfile(f"{batchFolder}/{batch_name}({batchNum})_settings.txt") is True or os.path.isfile(f"{batchFolder}/{batch_name}-{batchNum}_settings.txt") is True: batchNum += 1 print(f'Starting Run: {batch_name}({batchNum}) at frame {start_frame}') From 1704be96f8345f0191ca0801ddd539f5643d6dc2 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Wed, 30 Mar 2022 14:29:54 -0400 Subject: [PATCH 16/74] Slight turbo mode cleanup. Added questionable code to protect people who may modify the settings code (or that may hurt them - It could go either way) --- Disco_Diffusion.ipynb | 53 ++++++++++++++++++++++--------------------- disco.py | 53 ++++++++++++++++++++++--------------------- 2 files changed, 54 insertions(+), 52 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 3d55ced6..aeb6be6c 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -1119,30 +1119,31 @@ "\n", " ### Turbo mode - skip some diffusions, use 3d morph for clarity and to save time\n", " turbo_blend = False # default for non-turbo frame saving\n", - " if turbo_mode == True and frame_num == turbo_preroll: #start tracking oldframe\n", - " next_step_pil.save('oldFrameScaled.png')#stash for later blending \n", - " if turbo_mode == True and frame_num > turbo_preroll:\n", - " #set up 2 warped image sequences, old & new, to blend toward new diff image\n", - " old_frame = do_3d_step('oldFrameScaled.png', frame_num, midas_model, midas_transform)\n", - " old_frame.save('oldFrameScaled.png')\n", - " if frame_num % int(turbo_steps) != 0: \n", - " print('turbo skip this frame: skipping clip diffusion steps')\n", - " filename = f'{args.batch_name}({args.batchNum})_{frame_num:04}.png'\n", - " blend_factor = ((frame_num % int(turbo_steps))+1)/int(turbo_steps)\n", - " print('turbo skip this frame: skipping clip diffusion steps and saving blended frame')\n", - " newWarpedImg = cv2.imread('prevFrameScaled.png')#this is already updated..\n", - " oldWarpedImg = cv2.imread('oldFrameScaled.png')\n", - " blendedImage = cv2.addWeighted(newWarpedImg, blend_factor, oldWarpedImg,1-blend_factor, 0.0)\n", - " cv2.imwrite(f'{batchFolder}/{filename}',blendedImage)\n", - " next_step_pil.save(f'{img_filepath}') # save it also as prev_frame to feed next iteration\n", - " turbo_blend = False\n", - " continue\n", - " else:\n", - " #if not a skip frame, will run diffusion and need to blend.\n", - " oldWarpedImg = cv2.imread('prevFrameScaled.png')\n", - " cv2.imwrite(f'oldFrameScaled.png',oldWarpedImg)#swap in for blending later \n", - " turbo_blend = True # flag to blend frames after diff generated...\n", - " print('clip/diff this frame - generate clip diff image')\n", + " if turbo_mode:\n", + " if frame_num == turbo_preroll: #start tracking oldframe\n", + " next_step_pil.save('oldFrameScaled.png')#stash for later blending \n", + " elif frame_num > turbo_preroll:\n", + " #set up 2 warped image sequences, old & new, to blend toward new diff image\n", + " old_frame = do_3d_step('oldFrameScaled.png', frame_num, midas_model, midas_transform)\n", + " old_frame.save('oldFrameScaled.png')\n", + " if frame_num % int(turbo_steps) != 0: \n", + " print('turbo skip this frame: skipping clip diffusion steps')\n", + " filename = f'{args.batch_name}({args.batchNum})_{frame_num:04}.png'\n", + " blend_factor = ((frame_num % int(turbo_steps))+1)/int(turbo_steps)\n", + " print('turbo skip this frame: skipping clip diffusion steps and saving blended frame')\n", + " newWarpedImg = cv2.imread('prevFrameScaled.png')#this is already updated..\n", + " oldWarpedImg = cv2.imread('oldFrameScaled.png')\n", + " blendedImage = cv2.addWeighted(newWarpedImg, blend_factor, oldWarpedImg,1-blend_factor, 0.0)\n", + " cv2.imwrite(f'{batchFolder}/{filename}',blendedImage)\n", + " next_step_pil.save(f'{img_filepath}') # save it also as prev_frame to feed next iteration\n", + " turbo_blend = False\n", + " continue\n", + " else:\n", + " #if not a skip frame, will run diffusion and need to blend.\n", + " oldWarpedImg = cv2.imread('prevFrameScaled.png')\n", + " cv2.imwrite(f'oldFrameScaled.png',oldWarpedImg)#swap in for blending later \n", + " turbo_blend = True # flag to blend frames after diff generated...\n", + " print('clip/diff this frame - generate clip diff image')\n", "\n", " init_image = 'prevFrameScaled.png'\n", " init_scale = args.frames_scale\n", @@ -3006,11 +3007,11 @@ " batchNum = int(run_to_resume)\n", " if resume_from_frame == 'latest':\n", " start_frame = len(glob(batchFolder+f\"/{batch_name}({batchNum})_*.png\"))\n", - " if turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0:\n", + " if animation_mode != '3D' and turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0:\n", " start_frame = start_frame - (start_frame % int(turbo_steps))\n", " else:\n", " start_frame = int(resume_from_frame)+1\n", - " if turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0:\n", + " if animation_mode != '3D' and turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0:\n", " start_frame = start_frame - (start_frame % int(turbo_steps))\n", " if retain_overwritten_frames is True:\n", " existing_frames = len(glob(batchFolder+f\"/{batch_name}({batchNum})_*.png\"))\n", diff --git a/disco.py b/disco.py index ff055d6d..5f67d1ff 100644 --- a/disco.py +++ b/disco.py @@ -1026,30 +1026,31 @@ def do_run(): ### Turbo mode - skip some diffusions, use 3d morph for clarity and to save time turbo_blend = False # default for non-turbo frame saving - if turbo_mode == True and frame_num == turbo_preroll: #start tracking oldframe - next_step_pil.save('oldFrameScaled.png')#stash for later blending - if turbo_mode == True and frame_num > turbo_preroll: - #set up 2 warped image sequences, old & new, to blend toward new diff image - old_frame = do_3d_step('oldFrameScaled.png', frame_num, midas_model, midas_transform) - old_frame.save('oldFrameScaled.png') - if frame_num % int(turbo_steps) != 0: - print('turbo skip this frame: skipping clip diffusion steps') - filename = f'{args.batch_name}({args.batchNum})_{frame_num:04}.png' - blend_factor = ((frame_num % int(turbo_steps))+1)/int(turbo_steps) - print('turbo skip this frame: skipping clip diffusion steps and saving blended frame') - newWarpedImg = cv2.imread('prevFrameScaled.png')#this is already updated.. - oldWarpedImg = cv2.imread('oldFrameScaled.png') - blendedImage = cv2.addWeighted(newWarpedImg, blend_factor, oldWarpedImg,1-blend_factor, 0.0) - cv2.imwrite(f'{batchFolder}/{filename}',blendedImage) - next_step_pil.save(f'{img_filepath}') # save it also as prev_frame to feed next iteration - turbo_blend = False - continue - else: - #if not a skip frame, will run diffusion and need to blend. - oldWarpedImg = cv2.imread('prevFrameScaled.png') - cv2.imwrite(f'oldFrameScaled.png',oldWarpedImg)#swap in for blending later - turbo_blend = True # flag to blend frames after diff generated... - print('clip/diff this frame - generate clip diff image') + if turbo_mode: + if frame_num == turbo_preroll: #start tracking oldframe + next_step_pil.save('oldFrameScaled.png')#stash for later blending + elif frame_num > turbo_preroll: + #set up 2 warped image sequences, old & new, to blend toward new diff image + old_frame = do_3d_step('oldFrameScaled.png', frame_num, midas_model, midas_transform) + old_frame.save('oldFrameScaled.png') + if frame_num % int(turbo_steps) != 0: + print('turbo skip this frame: skipping clip diffusion steps') + filename = f'{args.batch_name}({args.batchNum})_{frame_num:04}.png' + blend_factor = ((frame_num % int(turbo_steps))+1)/int(turbo_steps) + print('turbo skip this frame: skipping clip diffusion steps and saving blended frame') + newWarpedImg = cv2.imread('prevFrameScaled.png')#this is already updated.. + oldWarpedImg = cv2.imread('oldFrameScaled.png') + blendedImage = cv2.addWeighted(newWarpedImg, blend_factor, oldWarpedImg,1-blend_factor, 0.0) + cv2.imwrite(f'{batchFolder}/{filename}',blendedImage) + next_step_pil.save(f'{img_filepath}') # save it also as prev_frame to feed next iteration + turbo_blend = False + continue + else: + #if not a skip frame, will run diffusion and need to blend. + oldWarpedImg = cv2.imread('prevFrameScaled.png') + cv2.imwrite(f'oldFrameScaled.png',oldWarpedImg)#swap in for blending later + turbo_blend = True # flag to blend frames after diff generated... + print('clip/diff this frame - generate clip diff image') init_image = 'prevFrameScaled.png' init_scale = args.frames_scale @@ -2829,11 +2830,11 @@ def move_files(start_num, end_num, old_folder, new_folder): batchNum = int(run_to_resume) if resume_from_frame == 'latest': start_frame = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png")) - if turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0: + if animation_mode != '3D' and turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0: start_frame = start_frame - (start_frame % int(turbo_steps)) else: start_frame = int(resume_from_frame)+1 - if turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0: + if animation_mode != '3D' and turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0: start_frame = start_frame - (start_frame % int(turbo_steps)) if retain_overwritten_frames is True: existing_frames = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png")) From 464bc1cff1763809e5c41e08d24e1caa2b339a97 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Wed, 30 Mar 2022 14:42:31 -0400 Subject: [PATCH 17/74] Adds some documentation for Turbo Mode and disables it by default --- Disco_Diffusion.ipynb | 16 ++++++++++++---- disco.py | 15 ++++++++++++--- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index aeb6be6c..80541746 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -16,7 +16,7 @@ "id": "TitleTop" }, "source": [ - "# Disco Diffusion v5 - Now with 3D animation\n", + "# Disco Diffusion v5.1 - Now with Turbo\n", "\n", "In case of confusion, Disco is the name of this notebook edit. The diffusion model in use is Katherine Crowson's fine-tuned 512x512 model\n", "\n", @@ -58,7 +58,9 @@ "\n", "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", "\n", - "3D animation implementation added by Adam Letts (https://twitter.com/gandamu_ml) in collaboration with Somnai." + "3D animation implementation added by Adam Letts (https://twitter.com/gandamu_ml) in collaboration with Somnai.\n", + "\n", + "Turbo feature by Chris Allen (https://twitter.com/zippy731)" ] }, { @@ -235,10 +237,15 @@ "\n", " Separated transform code\n", "\n", - " v5.01 Update: Match 10th 2022 - gandamu / Adam Letts\n", + " v5.01 Update: March 10th 2022 - gandamu / Adam Letts\n", "\n", " IPython magic commands replaced by Python code\n", "\n", + " v5.1 Update: March 30th 2022 - zippy / Chris Allen - c/o gandamu / Adam Letts\n", + "\n", + " Integrated Turbo+Smooth features from Disco Diffusion Turbo -- just the implementation, without its defaults.\n", + " Implemented resume of turbo animations in such a way that it's now possible to resume from different batch folders and batch numbers.\n", + "\n", " '''\n", " )\n" ], @@ -2559,8 +2566,9 @@ "#@markdown ####**Turbo Mode (3D anim only):**\n", "#@markdown (Starts after frame 10,) skips diffusion steps and just uses depth map to warp images for skipped frames.\n", "#@markdown Speeds up rendering by 2x-4x, and may improve image coherence between frames. frame_blend_mode smooths abrupt texture changes across 2 frames.\n", + "#@markdown For different settings tuned for Turbo Mode, refer to the original Disco-Turbo Github: https://github.com/zippy731/disco-diffusion-turbo\n", "\n", - "turbo_mode = True #@param {type:\"boolean\"}\n", + "turbo_mode = False #@param {type:\"boolean\"}\n", "turbo_steps = \"3\" #@param [\"2\",\"3\",\"4\",\"5\",\"6\"] {type:\"string\"}\n", "turbo_preroll = 10 # frames\n", "turbo_frame_blend = True #@param {type:\"boolean\"}\n", diff --git a/disco.py b/disco.py index 5f67d1ff..231bbfe6 100644 --- a/disco.py +++ b/disco.py @@ -5,7 +5,7 @@ # %% """ -# Disco Diffusion v5 - Now with 3D animation +# Disco Diffusion v5.1 - Now with Turbo 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 @@ -40,6 +40,8 @@ Somnai (https://twitter.com/Somnai_dreams) added Diffusion Animation techniques, QoL improvements and various implementations of tech and techniques, mostly listed in the changelog below. 3D animation implementation added by Adam Letts (https://twitter.com/gandamu_ml) in collaboration with Somnai. + +Turbo feature by Chris Allen (https://twitter.com/zippy731) """ # %% @@ -198,10 +200,16 @@ Separated transform code - v5.01 Update: Match 10th 2022 - gandamu / Adam Letts + v5.01 Update: March 10th 2022 - gandamu / Adam Letts IPython magic commands replaced by Python code + v5.1 Update: March 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts + + Integrated Turbo+Smooth features from Disco Diffusion Turbo -- just the implementation, without its defaults. + + Implemented resume of turbo animations in such a way that it's now possible to resume from different batch folders and batch numbers. + ''' ) @@ -2415,8 +2423,9 @@ def do_superres(img, filepath): #@markdown ####**Turbo Mode (3D anim only):** #@markdown (Starts after frame 10,) skips diffusion steps and just uses depth map to warp images for skipped frames. #@markdown Speeds up rendering by 2x-4x, and may improve image coherence between frames. frame_blend_mode smooths abrupt texture changes across 2 frames. +#@markdown For different settings tuned for Turbo Mode, refer to the original Disco-Turbo Github: https://github.com/zippy731/disco-diffusion-turbo -turbo_mode = True #@param {type:"boolean"} +turbo_mode = False #@param {type:"boolean"} turbo_steps = "3" #@param ["2","3","4","5","6"] {type:"string"} turbo_preroll = 10 # frames turbo_frame_blend = True #@param {type:"boolean"} From cd5d94479c45aa6bad8f606c6cc0068c7584a893 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Wed, 30 Mar 2022 15:15:20 -0400 Subject: [PATCH 18/74] 3D rotation parameter units are now degrees rather than radians --- Disco_Diffusion.ipynb | 11 ++++++++--- disco.py | 6 ++++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 80541746..707838e0 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -241,11 +241,14 @@ "\n", " IPython magic commands replaced by Python code\n", "\n", - " v5.1 Update: March 30th 2022 - zippy / Chris Allen - c/o gandamu / Adam Letts\n", + " v5.1 Update: March 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts\n", "\n", " Integrated Turbo+Smooth features from Disco Diffusion Turbo -- just the implementation, without its defaults.\n", + "\n", " Implemented resume of turbo animations in such a way that it's now possible to resume from different batch folders and batch numbers.\n", "\n", + " 3D rotation parameter units are now degrees (rather than radians)\n", + "\n", " '''\n", " )\n" ], @@ -1030,9 +1033,10 @@ " img_filepath = '/content/prevFrame.png' if is_colab else 'prevFrame.png'\n", " trans_scale = 1.0/200.0\n", " translate_xyz = [-translation_x*trans_scale, translation_y*trans_scale, -translation_z*trans_scale]\n", - " rotate_xyz = [rotation_3d_x, rotation_3d_y, rotation_3d_z]\n", + " rotate_xyz_degrees = [rotation_3d_x, rotation_3d_y, rotation_3d_z]\n", " print('translation:',translate_xyz)\n", - " print('rotation:',rotate_xyz)\n", + " print('rotation:',rotate_xyz_degrees)\n", + " rotate_xyz = [math.radians(rotate_xyz_degrees[0]), math.radians(rotate_xyz_degrees[1]), math.radians(rotate_xyz_degrees[2])]\n", " rot_mat = p3dT.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), \"XYZ\").unsqueeze(0)\n", " print(\"rot_mat: \" + str(rot_mat))\n", " next_step_pil = dxf.transform_image_3d(img_filepath, midas_model, midas_transform, DEVICE,\n", @@ -2537,6 +2541,7 @@ "\n", "#@markdown ####**2D Animation Settings:**\n", "#@markdown `zoom` is a multiplier of dimensions, 1 is no zoom.\n", + "#@markdown All rotations are provided in degrees.\n", "\n", "key_frames = True #@param {type:\"boolean\"}\n", "max_frames = 10000#@param {type:\"number\"}\n", diff --git a/disco.py b/disco.py index 231bbfe6..f3903f2d 100644 --- a/disco.py +++ b/disco.py @@ -938,9 +938,10 @@ def do_3d_step(img_filepath, frame_num, midas_model, midas_transform): img_filepath = '/content/prevFrame.png' if is_colab else 'prevFrame.png' trans_scale = 1.0/200.0 translate_xyz = [-translation_x*trans_scale, translation_y*trans_scale, -translation_z*trans_scale] - rotate_xyz = [rotation_3d_x, rotation_3d_y, rotation_3d_z] + rotate_xyz_degrees = [rotation_3d_x, rotation_3d_y, rotation_3d_z] print('translation:',translate_xyz) - print('rotation:',rotate_xyz) + print('rotation:',rotate_xyz_degrees) + rotate_xyz = [math.radians(rotate_xyz_degrees[0]), math.radians(rotate_xyz_degrees[1]), math.radians(rotate_xyz_degrees[2])] rot_mat = p3dT.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), "XYZ").unsqueeze(0) print("rot_mat: " + str(rot_mat)) next_step_pil = dxf.transform_image_3d(img_filepath, midas_model, midas_transform, DEVICE, @@ -2394,6 +2395,7 @@ def do_superres(img, filepath): #@markdown ####**2D Animation Settings:** #@markdown `zoom` is a multiplier of dimensions, 1 is no zoom. +#@markdown All rotations are provided in degrees. key_frames = True #@param {type:"boolean"} max_frames = 10000#@param {type:"number"} From d82b8daaeda9da7883e546c84109feebd759aa83 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Wed, 30 Mar 2022 16:15:25 -0400 Subject: [PATCH 19/74] Correction to sampling_mode name collision. Now it is separated into diffusion_sampling_mode (for plms vs. ddim) and sampling_mode (for 3D transform sampling mode). --- Disco_Diffusion.ipynb | 18 ++++++++++-------- disco.py | 18 +++++++++++------- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 707838e0..b32bfe89 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -237,11 +237,11 @@ "\n", " Separated transform code\n", "\n", - " v5.01 Update: March 10th 2022 - gandamu / Adam Letts\n", + " v5.01 Update: Mar 10th 2022 - gandamu / Adam Letts\n", "\n", " IPython magic commands replaced by Python code\n", "\n", - " v5.1 Update: March 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts\n", + " v5.1 Update: Mar 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts\n", "\n", " Integrated Turbo+Smooth features from Disco Diffusion Turbo -- just the implementation, without its defaults.\n", "\n", @@ -249,6 +249,8 @@ "\n", " 3D rotation parameter units are now degrees (rather than radians)\n", "\n", + " Corrected name collision in sampling_mode (now diffusion_sampling_mode for plms/ddim, and sampling_mode for 3D transform sampling)\n", + "\n", " '''\n", " )\n" ], @@ -1319,7 +1321,7 @@ " return grad * magnitude.clamp(max=args.clamp_max) / magnitude #min=-0.02, min=-clamp_max, \n", " return grad\n", " \n", - " if args.sampling_mode == 'ddim':\n", + " if args.diffusion_sampling_mode == 'ddim':\n", " sample_fn = diffusion.ddim_sample_loop_progressive\n", " else:\n", " sample_fn = diffusion.plms_sample_loop_progressive\n", @@ -1342,7 +1344,7 @@ " if perlin_init:\n", " init = regen_perlin()\n", "\n", - " if args.sampling_mode == 'ddim':\n", + " if args.diffusion_sampling_mode == 'ddim':\n", " samples = sample_fn(\n", " model,\n", " (batch_size, 3, args.side_y, args.side_x),\n", @@ -1485,7 +1487,7 @@ " 'use_secondary_model': use_secondary_model,\n", " 'steps': steps,\n", " 'diffusion_steps': diffusion_steps,\n", - " 'sampling_mode': sampling_mode,\n", + " 'diffusion_sampling_mode': diffusion_sampling_mode,\n", " 'ViTB32': ViTB32,\n", " 'ViTB16': ViTB16,\n", " 'ViTL14': ViTL14,\n", @@ -2254,7 +2256,7 @@ "#@markdown ####**Models Settings:**\n", "diffusion_model = \"512x512_diffusion_uncond_finetune_008100\" #@param [\"256x256_diffusion_uncond\", \"512x512_diffusion_uncond_finetune_008100\"]\n", "use_secondary_model = True #@param {type: 'boolean'}\n", - "sampling_mode = 'ddim' #@param ['plms','ddim'] \n", + "diffusion_sampling_mode = 'ddim' #@param ['plms','ddim'] \n", "\n", "timestep_respacing = '250' #@param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000'] \n", "diffusion_steps = 1000 #@param {type: 'number'}\n", @@ -3056,7 +3058,7 @@ " 'batch_size':batch_size,\n", " 'batch_name': batch_name,\n", " 'steps': steps,\n", - " 'sampling_mode': sampling_mode,\n", + " 'diffusion_sampling_mode': diffusion_sampling_mode,\n", " 'width_height': width_height,\n", " 'clip_guidance_scale': clip_guidance_scale,\n", " 'tv_scale': tv_scale,\n", @@ -3265,7 +3267,7 @@ "ExtraSetTop" ], "machine_shape": "hm", - "name": "Disco Diffusion v5 [w/ 3D animation]", + "name": "Disco Diffusion v5.1 [w/ Turbo]", "private_outputs": true, "provenance": [], "include_colab_link": true diff --git a/disco.py b/disco.py index f3903f2d..16caaf0a 100644 --- a/disco.py +++ b/disco.py @@ -200,16 +200,20 @@ Separated transform code - v5.01 Update: March 10th 2022 - gandamu / Adam Letts + v5.01 Update: Mar 10th 2022 - gandamu / Adam Letts IPython magic commands replaced by Python code - v5.1 Update: March 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts + v5.1 Update: Mar 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts Integrated Turbo+Smooth features from Disco Diffusion Turbo -- just the implementation, without its defaults. Implemented resume of turbo animations in such a way that it's now possible to resume from different batch folders and batch numbers. + 3D rotation parameter units are now degrees (rather than radians) + + Corrected name collision in sampling_mode (now diffusion_sampling_mode for plms/ddim, and sampling_mode for 3D transform sampling) + ''' ) @@ -1224,7 +1228,7 @@ def cond_fn(x, t, y=None): return grad * magnitude.clamp(max=args.clamp_max) / magnitude #min=-0.02, min=-clamp_max, return grad - if args.sampling_mode == 'ddim': + if args.diffusion_sampling_mode == 'ddim': sample_fn = diffusion.ddim_sample_loop_progressive else: sample_fn = diffusion.plms_sample_loop_progressive @@ -1247,7 +1251,7 @@ def cond_fn(x, t, y=None): if perlin_init: init = regen_perlin() - if args.sampling_mode == 'ddim': + if args.diffusion_sampling_mode == 'ddim': samples = sample_fn( model, (batch_size, 3, args.side_y, args.side_x), @@ -1390,7 +1394,7 @@ def save_settings(): 'use_secondary_model': use_secondary_model, 'steps': steps, 'diffusion_steps': diffusion_steps, - 'sampling_mode': sampling_mode, + 'diffusion_sampling_mode': diffusion_sampling_mode, 'ViTB32': ViTB32, 'ViTB16': ViTB16, 'ViTL14': ViTL14, @@ -2130,7 +2134,7 @@ def do_superres(img, filepath): #@markdown ####**Models Settings:** diffusion_model = "512x512_diffusion_uncond_finetune_008100" #@param ["256x256_diffusion_uncond", "512x512_diffusion_uncond_finetune_008100"] use_secondary_model = True #@param {type: 'boolean'} -sampling_mode = 'ddim' #@param ['plms','ddim'] +diffusion_sampling_mode = 'ddim' #@param ['plms','ddim'] timestep_respacing = '250' #@param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000'] diffusion_steps = 1000 #@param {type: 'number'} @@ -2877,7 +2881,7 @@ def move_files(start_num, end_num, old_folder, new_folder): 'batch_size':batch_size, 'batch_name': batch_name, 'steps': steps, - 'sampling_mode': sampling_mode, + 'diffusion_sampling_mode': diffusion_sampling_mode, 'width_height': width_height, 'clip_guidance_scale': clip_guidance_scale, 'tv_scale': tv_scale, From 5f03abe6cda7bf3896424fcf7b935bae908a894d Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Wed, 30 Mar 2022 16:36:29 -0400 Subject: [PATCH 20/74] Adds video_init_frame_continuity parameter. Removes some extraneous code from do_3d_step() --- Disco_Diffusion.ipynb | 46 ++++++++++++++++++++----------------------- disco.py | 46 ++++++++++++++++++++----------------------- 2 files changed, 42 insertions(+), 50 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index b32bfe89..e6faf4a9 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -1009,8 +1009,6 @@ "stop_on_next_loop = False # Make sure GPU memory doesn't get corrupted from cancelling the run mid-way through, allow a full frame to complete\n", "\n", "def do_3d_step(img_filepath, frame_num, midas_model, midas_transform):\n", - " global seed\n", - "\n", " if args.key_frames:\n", " translation_x = args.translation_x_series[frame_num]\n", " translation_y = args.translation_y_series[frame_num]\n", @@ -1027,25 +1025,19 @@ " f'rotation_3d_z: {rotation_3d_z}',\n", " )\n", "\n", - " if frame_num > 0:\n", - " seed = seed + 1\n", - " if resume_run and frame_num == start_frame:\n", - " img_filepath = batchFolder+f\"/{batch_name}({batchNum})_{start_frame-1:04}.png\"\n", - " else:\n", - " img_filepath = '/content/prevFrame.png' if is_colab else 'prevFrame.png'\n", - " trans_scale = 1.0/200.0\n", - " translate_xyz = [-translation_x*trans_scale, translation_y*trans_scale, -translation_z*trans_scale]\n", - " rotate_xyz_degrees = [rotation_3d_x, rotation_3d_y, rotation_3d_z]\n", - " print('translation:',translate_xyz)\n", - " print('rotation:',rotate_xyz_degrees)\n", - " rotate_xyz = [math.radians(rotate_xyz_degrees[0]), math.radians(rotate_xyz_degrees[1]), math.radians(rotate_xyz_degrees[2])]\n", - " rot_mat = p3dT.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), \"XYZ\").unsqueeze(0)\n", - " print(\"rot_mat: \" + str(rot_mat))\n", - " next_step_pil = dxf.transform_image_3d(img_filepath, midas_model, midas_transform, DEVICE,\n", - " rot_mat, translate_xyz, args.near_plane, args.far_plane,\n", - " args.fov, padding_mode=args.padding_mode,\n", - " sampling_mode=args.sampling_mode, midas_weight=args.midas_weight)\n", - " return next_step_pil\n", + " trans_scale = 1.0/200.0\n", + " translate_xyz = [-translation_x*trans_scale, translation_y*trans_scale, -translation_z*trans_scale]\n", + " rotate_xyz_degrees = [rotation_3d_x, rotation_3d_y, rotation_3d_z]\n", + " print('translation:',translate_xyz)\n", + " print('rotation:',rotate_xyz_degrees)\n", + " rotate_xyz = [math.radians(rotate_xyz_degrees[0]), math.radians(rotate_xyz_degrees[1]), math.radians(rotate_xyz_degrees[2])]\n", + " rot_mat = p3dT.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), \"XYZ\").unsqueeze(0)\n", + " print(\"rot_mat: \" + str(rot_mat))\n", + " next_step_pil = dxf.transform_image_3d(img_filepath, midas_model, midas_transform, DEVICE,\n", + " rot_mat, translate_xyz, args.near_plane, args.far_plane,\n", + " args.fov, padding_mode=args.padding_mode,\n", + " sampling_mode=args.sampling_mode, midas_weight=args.midas_weight)\n", + " return next_step_pil\n", "\n", "def do_run():\n", " seed = args.seed\n", @@ -1089,7 +1081,7 @@ " )\n", " \n", " if frame_num > 0:\n", - " seed = seed + 1 \n", + " seed += 1\n", " if resume_run and frame_num == start_frame:\n", " img_0 = cv2.imread(batchFolder+f\"/{batch_name}({batchNum})_{start_frame-1:04}.png\")\n", " else:\n", @@ -1119,7 +1111,7 @@ " if frame_num == 0:\n", " turbo_blend = False\n", " else:\n", - " seed = seed + 1 \n", + " seed += 1 \n", " if resume_run and frame_num == start_frame:\n", " img_filepath = batchFolder+f\"/{batch_name}({batchNum})_{start_frame-1:04}.png\"\n", " if turbo_mode and frame_num > turbo_preroll:\n", @@ -1163,7 +1155,8 @@ " skip_steps = args.calc_frames_skip_steps\n", "\n", " if args.animation_mode == \"Video Input\":\n", - " seed = seed + 1 \n", + " if not video_init_seed_continuity:\n", + " seed += 1\n", " init_image = f'{videoFramesFolder}/{frame_num+1:04}.jpg'\n", " init_scale = args.frames_scale\n", " skip_steps = args.calc_frames_skip_steps\n", @@ -1519,6 +1512,7 @@ " 'sampling_mode': sampling_mode,\n", " 'video_init_path':video_init_path,\n", " 'extract_nth_frame':extract_nth_frame,\n", + " 'video_init_seed_continuity': video_init_seed_continuity,\n", " 'turbo_mode':turbo_mode,\n", " 'turbo_steps':turbo_steps,\n", " 'turbo_preroll':turbo_preroll,\n", @@ -2520,7 +2514,8 @@ " video_init_path = \"/content/training.mp4\" #@param {type: 'string'}\n", "else:\n", " video_init_path = \"training.mp4\" #@param {type: 'string'}\n", - "extract_nth_frame = 2 #@param {type:\"number\"} \n", + "extract_nth_frame = 2 #@param {type: 'number'}\n", + "video_init_seed_continuity = True #@param {type: 'boolean'}\n", "\n", "if animation_mode == \"Video Input\":\n", " if is_colab:\n", @@ -3077,6 +3072,7 @@ " 'animation_mode': animation_mode,\n", " 'video_init_path': video_init_path,\n", " 'extract_nth_frame': extract_nth_frame,\n", + " 'video_init_seed_continuity': video_init_seed_continuity,\n", " 'key_frames': key_frames,\n", " 'max_frames': max_frames if animation_mode != \"None\" else 1,\n", " 'interp_spline': interp_spline,\n", diff --git a/disco.py b/disco.py index 16caaf0a..155930f5 100644 --- a/disco.py +++ b/disco.py @@ -916,8 +916,6 @@ def range_loss(input): stop_on_next_loop = False # Make sure GPU memory doesn't get corrupted from cancelling the run mid-way through, allow a full frame to complete def do_3d_step(img_filepath, frame_num, midas_model, midas_transform): - global seed - if args.key_frames: translation_x = args.translation_x_series[frame_num] translation_y = args.translation_y_series[frame_num] @@ -934,25 +932,19 @@ def do_3d_step(img_filepath, frame_num, midas_model, midas_transform): f'rotation_3d_z: {rotation_3d_z}', ) - if frame_num > 0: - seed = seed + 1 - if resume_run and frame_num == start_frame: - img_filepath = batchFolder+f"/{batch_name}({batchNum})_{start_frame-1:04}.png" - else: - img_filepath = '/content/prevFrame.png' if is_colab else 'prevFrame.png' - trans_scale = 1.0/200.0 - translate_xyz = [-translation_x*trans_scale, translation_y*trans_scale, -translation_z*trans_scale] - rotate_xyz_degrees = [rotation_3d_x, rotation_3d_y, rotation_3d_z] - print('translation:',translate_xyz) - print('rotation:',rotate_xyz_degrees) - rotate_xyz = [math.radians(rotate_xyz_degrees[0]), math.radians(rotate_xyz_degrees[1]), math.radians(rotate_xyz_degrees[2])] - rot_mat = p3dT.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), "XYZ").unsqueeze(0) - print("rot_mat: " + str(rot_mat)) - next_step_pil = dxf.transform_image_3d(img_filepath, midas_model, midas_transform, DEVICE, - rot_mat, translate_xyz, args.near_plane, args.far_plane, - args.fov, padding_mode=args.padding_mode, - sampling_mode=args.sampling_mode, midas_weight=args.midas_weight) - return next_step_pil + trans_scale = 1.0/200.0 + translate_xyz = [-translation_x*trans_scale, translation_y*trans_scale, -translation_z*trans_scale] + rotate_xyz_degrees = [rotation_3d_x, rotation_3d_y, rotation_3d_z] + print('translation:',translate_xyz) + print('rotation:',rotate_xyz_degrees) + rotate_xyz = [math.radians(rotate_xyz_degrees[0]), math.radians(rotate_xyz_degrees[1]), math.radians(rotate_xyz_degrees[2])] + rot_mat = p3dT.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), "XYZ").unsqueeze(0) + print("rot_mat: " + str(rot_mat)) + next_step_pil = dxf.transform_image_3d(img_filepath, midas_model, midas_transform, DEVICE, + rot_mat, translate_xyz, args.near_plane, args.far_plane, + args.fov, padding_mode=args.padding_mode, + sampling_mode=args.sampling_mode, midas_weight=args.midas_weight) + return next_step_pil def do_run(): seed = args.seed @@ -996,7 +988,7 @@ def do_run(): ) if frame_num > 0: - seed = seed + 1 + seed += 1 if resume_run and frame_num == start_frame: img_0 = cv2.imread(batchFolder+f"/{batch_name}({batchNum})_{start_frame-1:04}.png") else: @@ -1026,7 +1018,7 @@ def do_run(): if frame_num == 0: turbo_blend = False else: - seed = seed + 1 + seed += 1 if resume_run and frame_num == start_frame: img_filepath = batchFolder+f"/{batch_name}({batchNum})_{start_frame-1:04}.png" if turbo_mode and frame_num > turbo_preroll: @@ -1070,7 +1062,8 @@ def do_run(): skip_steps = args.calc_frames_skip_steps if args.animation_mode == "Video Input": - seed = seed + 1 + if not video_init_seed_continuity: + seed += 1 init_image = f'{videoFramesFolder}/{frame_num+1:04}.jpg' init_scale = args.frames_scale skip_steps = args.calc_frames_skip_steps @@ -1426,6 +1419,7 @@ def save_settings(): 'sampling_mode': sampling_mode, 'video_init_path':video_init_path, 'extract_nth_frame':extract_nth_frame, + 'video_init_seed_continuity': video_init_seed_continuity, 'turbo_mode':turbo_mode, 'turbo_steps':turbo_steps, 'turbo_preroll':turbo_preroll, @@ -2376,7 +2370,8 @@ def do_superres(img, filepath): video_init_path = "/content/training.mp4" #@param {type: 'string'} else: video_init_path = "training.mp4" #@param {type: 'string'} -extract_nth_frame = 2 #@param {type:"number"} +extract_nth_frame = 2 #@param {type: 'number'} +video_init_seed_continuity = True #@param {type: 'boolean'} if animation_mode == "Video Input": if is_colab: @@ -2900,6 +2895,7 @@ def move_files(start_num, end_num, old_folder, new_folder): 'animation_mode': animation_mode, 'video_init_path': video_init_path, 'extract_nth_frame': extract_nth_frame, + 'video_init_seed_continuity': video_init_seed_continuity, 'key_frames': key_frames, 'max_frames': max_frames if animation_mode != "None" else 1, 'interp_spline': interp_spline, From 3a82f98a42aec8c8296cc0eec3d4dd82d4352d83 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Wed, 30 Mar 2022 16:39:49 -0400 Subject: [PATCH 21/74] Adds changelog note for video_init_seed_continuity --- Disco_Diffusion.ipynb | 2 ++ disco.py | 2 ++ 2 files changed, 4 insertions(+) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index e6faf4a9..babfd640 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -251,6 +251,8 @@ "\n", " Corrected name collision in sampling_mode (now diffusion_sampling_mode for plms/ddim, and sampling_mode for 3D transform sampling)\n", "\n", + " Added video_init_seed_continuity option to make init video animations more continuous\n", + "\n", " '''\n", " )\n" ], diff --git a/disco.py b/disco.py index 155930f5..44b40946 100644 --- a/disco.py +++ b/disco.py @@ -214,6 +214,8 @@ Corrected name collision in sampling_mode (now diffusion_sampling_mode for plms/ddim, and sampling_mode for 3D transform sampling) + Added video_init_seed_continuity option to make init video animations more continuous + ''' ) From 3735124ac32ee55a599c45a206427757bbe1cc64 Mon Sep 17 00:00:00 2001 From: MSFTserver Date: Wed, 30 Mar 2022 11:47:22 -0700 Subject: [PATCH 22/74] update for lite version of pytorch3d update pytorch3d to lite version that uses a slimmed down repo only containing what we need --- disco.py | 16 +++------------- disco_xform_utils.py | 6 +++--- 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/disco.py b/disco.py index e06ea5ec..0fda094a 100644 --- a/disco.py +++ b/disco.py @@ -384,6 +384,7 @@ def createPath(filepath): #gitclone("https://github.com/facebookresearch/SLIP.git") gitclone("https://github.com/crowsonkb/guided-diffusion") gitclone("https://github.com/assafshocher/ResizeRight.git") + gitclone("https://github.com/MSFTserver/pytorch3d-lite.git") pipie("./CLIP") pipie("./guided-diffusion") multipip_res = subprocess.run(['pip', 'install', 'lpips', 'datetime', 'timm', 'ftfy'], stdout=subprocess.PIPE).stdout.decode('utf-8') @@ -409,19 +410,8 @@ def createPath(filepath): import sys import torch -#Install pytorch3d -if is_colab: - pyt_version_str=torch.__version__.split("+")[0].replace(".", "") - version_str="".join([ - f"py3{sys.version_info.minor}_cu", - torch.version.cuda.replace(".",""), - f"_pyt{pyt_version_str}" - ]) - multipip_res = subprocess.run(['pip', 'install', 'fvcore', 'iopath'], stdout=subprocess.PIPE).stdout.decode('utf-8') - print(multipip_res) - subprocess.run(['pip', 'install', '--no-index', '--no-cache-dir', 'pytorch3d', '-f', f'https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html'], stdout=subprocess.PIPE).stdout.decode('utf-8') - # sys.path.append('./SLIP') +sys.path.append('./pytorch3d-lite') sys.path.append('./ResizeRight') sys.path.append('./MiDaS') from dataclasses import dataclass @@ -625,7 +615,7 @@ def init_midas_depth_model(midas_model_type="dpt_large", optimize=True): # https://gist.github.com/adefossez/0646dbe9ed4005480a2407c62aac8869 -import pytorch3d.transforms as p3dT +import py3d_tools as p3dT import disco_xform_utils as dxf def interp(t): diff --git a/disco_xform_utils.py b/disco_xform_utils.py index 9d4f1b84..9e08a8af 100644 --- a/disco_xform_utils.py +++ b/disco_xform_utils.py @@ -1,5 +1,5 @@ import torch, torchvision -import pytorch3d.renderer.cameras as p3dCam +import py3d_tools as p3d import midas_utils from PIL import Image import numpy as np @@ -81,8 +81,8 @@ def transform_image_3d(img_filepath, midas_model, midas_transform, device, rot_m depth_tensor = torch.from_numpy(depth_map).squeeze().to(device) pixel_aspect = 1.0 # really.. the aspect of an individual pixel! (so usually 1.0) - persp_cam_old = p3dCam.FoVPerspectiveCameras(near, far, pixel_aspect, fov=fov_deg, degrees=True, device=device) - persp_cam_new = p3dCam.FoVPerspectiveCameras(near, far, pixel_aspect, fov=fov_deg, degrees=True, R=rot_mat, T=torch.tensor([translate]), device=device) + persp_cam_old = p3d.FoVPerspectiveCameras(near, far, pixel_aspect, fov=fov_deg, degrees=True, device=device) + persp_cam_new = p3d.FoVPerspectiveCameras(near, far, pixel_aspect, fov=fov_deg, degrees=True, R=rot_mat, T=torch.tensor([translate]), device=device) # range of [-1,1] is important to torch grid_sample's padding handling y,x = torch.meshgrid(torch.linspace(-1.,1.,h,dtype=torch.float32,device=device),torch.linspace(-1.,1.,w,dtype=torch.float32,device=device)) From eda578a6327a89a5b88c77be6223ec1289dffd8c Mon Sep 17 00:00:00 2001 From: Max Date: Fri, 1 Apr 2022 15:22:24 +1100 Subject: [PATCH 23/74] Removal of confusing, redundant step params. --- disco.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/disco.py b/disco.py index 44b40946..9d397fd6 100644 --- a/disco.py +++ b/disco.py @@ -2132,8 +2132,7 @@ def do_superres(img, filepath): use_secondary_model = True #@param {type: 'boolean'} diffusion_sampling_mode = 'ddim' #@param ['plms','ddim'] -timestep_respacing = '250' #@param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000'] -diffusion_steps = 1000 #@param {type: 'number'} + use_checkpoint = True #@param {type: 'boolean'} ViTB32 = True #@param{type:"boolean"} ViTB16 = True #@param{type:"boolean"} @@ -2225,9 +2224,9 @@ def do_superres(img, filepath): model_config.update({ 'attention_resolutions': '32, 16, 8', 'class_cond': False, - 'diffusion_steps': diffusion_steps, + 'diffusion_steps': 1000, #No need to edit this, it is taken care of later. 'rescale_timesteps': True, - 'timestep_respacing': timestep_respacing, + 'timestep_respacing': 250, #No need to edit this, it is taken care of later. 'image_size': 512, 'learn_sigma': True, 'noise_schedule': 'linear', @@ -2243,9 +2242,9 @@ def do_superres(img, filepath): model_config.update({ 'attention_resolutions': '32, 16, 8', 'class_cond': False, - 'diffusion_steps': diffusion_steps, + 'diffusion_steps': 1000, #No need to edit this, it is taken care of later. 'rescale_timesteps': True, - 'timestep_respacing': timestep_respacing, + 'timestep_respacing': 250, #No need to edit this, it is taken care of later. 'image_size': 256, 'learn_sigma': True, 'noise_schedule': 'linear', From 0325457e48c639a97b97e91b335969968fb612a5 Mon Sep 17 00:00:00 2001 From: Chris Allen <48918354+zippy731@users.noreply.github.com> Date: Sat, 2 Apr 2022 15:23:13 -0700 Subject: [PATCH 24/74] remove references to turbo_blend Is redundant. Turbo always blends. --- disco.py | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/disco.py b/disco.py index 44b40946..37686774 100644 --- a/disco.py +++ b/disco.py @@ -1018,7 +1018,7 @@ def do_run(): if args.animation_mode == "3D": if frame_num == 0: - turbo_blend = False + pass else: seed += 1 if resume_run and frame_num == start_frame: @@ -1032,7 +1032,6 @@ def do_run(): next_step_pil.save('prevFrameScaled.png') ### Turbo mode - skip some diffusions, use 3d morph for clarity and to save time - turbo_blend = False # default for non-turbo frame saving if turbo_mode: if frame_num == turbo_preroll: #start tracking oldframe next_step_pil.save('oldFrameScaled.png')#stash for later blending @@ -1050,13 +1049,11 @@ def do_run(): blendedImage = cv2.addWeighted(newWarpedImg, blend_factor, oldWarpedImg,1-blend_factor, 0.0) cv2.imwrite(f'{batchFolder}/{filename}',blendedImage) next_step_pil.save(f'{img_filepath}') # save it also as prev_frame to feed next iteration - turbo_blend = False continue else: #if not a skip frame, will run diffusion and need to blend. oldWarpedImg = cv2.imread('prevFrameScaled.png') cv2.imwrite(f'oldFrameScaled.png',oldWarpedImg)#swap in for blending later - turbo_blend = True # flag to blend frames after diff generated... print('clip/diff this frame - generate clip diff image') init_image = 'prevFrameScaled.png' @@ -1332,14 +1329,13 @@ def cond_fn(x, t, y=None): else: image.save(f'{batchFolder}/{filename}') if args.animation_mode == "3D": - # If turbo_blend, save a blended image - if turbo_mode and turbo_blend: + # If turbo, save a blended image + if turbo_mode: # Mix new image with prevFrameScaled newFrame = cv2.imread('prevFrame.png') # This is already updated.. prev_frame_warped = cv2.imread('prevFrameScaled.png') blendedImage = cv2.addWeighted(newFrame, 0.5, prev_frame_warped, 0.5, 0.0) cv2.imwrite(f'{batchFolder}/{filename}',blendedImage) - turbo_blend = False # reset to false else: image.save(f'{batchFolder}/{filename}') # if frame_num != args.max_frames-1: @@ -1425,7 +1421,6 @@ def save_settings(): 'turbo_mode':turbo_mode, 'turbo_steps':turbo_steps, 'turbo_preroll':turbo_preroll, - 'turbo_frame_blend':turbo_frame_blend, } # print('Settings:', setting_list) with open(f"{batchFolder}/{batch_name}({batchNum})_settings.txt", "w+") as f: #save settings @@ -2431,7 +2426,6 @@ def do_superres(img, filepath): turbo_mode = False #@param {type:"boolean"} turbo_steps = "3" #@param ["2","3","4","5","6"] {type:"string"} turbo_preroll = 10 # frames -turbo_frame_blend = True #@param {type:"boolean"} #insist turbo be used only w 3d anim. if turbo_mode and animation_mode != '3D': @@ -3054,4 +3048,4 @@ def move_files(start_num, end_num, old_folder, new_folder): # if view_video_in_cell: # mp4 = open(filepath,'rb').read() # data_url = "data:video/mp4;base64," + b64encode(mp4).decode() - # display.HTML(f'') \ No newline at end of file + # display.HTML(f'') From c6f8dfe5f052f1f084df970e4ebd2d39c9c3a344 Mon Sep 17 00:00:00 2001 From: Chris Allen <48918354+zippy731@users.noreply.github.com> Date: Sat, 2 Apr 2022 17:52:18 -0700 Subject: [PATCH 25/74] correct turbo blend factor for diff frames --- disco.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/disco.py b/disco.py index 37686774..060d3ba0 100644 --- a/disco.py +++ b/disco.py @@ -1332,9 +1332,10 @@ def cond_fn(x, t, y=None): # If turbo, save a blended image if turbo_mode: # Mix new image with prevFrameScaled + blend_factor = (1)/int(turbo_steps) newFrame = cv2.imread('prevFrame.png') # This is already updated.. prev_frame_warped = cv2.imread('prevFrameScaled.png') - blendedImage = cv2.addWeighted(newFrame, 0.5, prev_frame_warped, 0.5, 0.0) + blendedImage = cv2.addWeighted(newFrame, blend_factor, prev_frame_warped, (1-blend_factor), 0.0) cv2.imwrite(f'{batchFolder}/{filename}',blendedImage) else: image.save(f'{batchFolder}/{filename}') @@ -3049,3 +3050,4 @@ def move_files(start_num, end_num, old_folder, new_folder): # mp4 = open(filepath,'rb').read() # data_url = "data:video/mp4;base64," + b64encode(mp4).decode() # display.HTML(f'') + From 5fa73e031d4f911ac1280e2aa22a280b64978150 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Sun, 3 Apr 2022 01:26:49 -0400 Subject: [PATCH 26/74] Apply zippy's disco.py changes to the .ipynb --- Disco_Diffusion.ipynb | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index babfd640..12ff53fd 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -1111,7 +1111,7 @@ "\n", " if args.animation_mode == \"3D\":\n", " if frame_num == 0:\n", - " turbo_blend = False\n", + " pass\n", " else:\n", " seed += 1 \n", " if resume_run and frame_num == start_frame:\n", @@ -1125,7 +1125,6 @@ " next_step_pil.save('prevFrameScaled.png')\n", "\n", " ### Turbo mode - skip some diffusions, use 3d morph for clarity and to save time\n", - " turbo_blend = False # default for non-turbo frame saving\n", " if turbo_mode:\n", " if frame_num == turbo_preroll: #start tracking oldframe\n", " next_step_pil.save('oldFrameScaled.png')#stash for later blending \n", @@ -1143,13 +1142,11 @@ " blendedImage = cv2.addWeighted(newWarpedImg, blend_factor, oldWarpedImg,1-blend_factor, 0.0)\n", " cv2.imwrite(f'{batchFolder}/{filename}',blendedImage)\n", " next_step_pil.save(f'{img_filepath}') # save it also as prev_frame to feed next iteration\n", - " turbo_blend = False\n", " continue\n", " else:\n", " #if not a skip frame, will run diffusion and need to blend.\n", " oldWarpedImg = cv2.imread('prevFrameScaled.png')\n", " cv2.imwrite(f'oldFrameScaled.png',oldWarpedImg)#swap in for blending later \n", - " turbo_blend = True # flag to blend frames after diff generated...\n", " print('clip/diff this frame - generate clip diff image')\n", "\n", " init_image = 'prevFrameScaled.png'\n", @@ -1425,14 +1422,14 @@ " else:\n", " image.save(f'{batchFolder}/{filename}')\n", " if args.animation_mode == \"3D\":\n", - " # If turbo_blend, save a blended image\n", - " if turbo_mode and turbo_blend:\n", + " # If turbo, save a blended image\n", + " if turbo_mode:\n", " # Mix new image with prevFrameScaled\n", + " blend_factor = (1)/int(turbo_steps)\n", " newFrame = cv2.imread('prevFrame.png') # This is already updated..\n", " prev_frame_warped = cv2.imread('prevFrameScaled.png')\n", - " blendedImage = cv2.addWeighted(newFrame, 0.5, prev_frame_warped, 0.5, 0.0)\n", + " blendedImage = cv2.addWeighted(newFrame, blend_factor, prev_frame_warped, (1-blend_factor), 0.0)\n", " cv2.imwrite(f'{batchFolder}/{filename}',blendedImage)\n", - " turbo_blend = False # reset to false\n", " else:\n", " image.save(f'{batchFolder}/{filename}')\n", " # if frame_num != args.max_frames-1:\n", @@ -1518,7 +1515,6 @@ " 'turbo_mode':turbo_mode,\n", " 'turbo_steps':turbo_steps,\n", " 'turbo_preroll':turbo_preroll,\n", - " 'turbo_frame_blend':turbo_frame_blend,\n", " }\n", " # print('Settings:', setting_list)\n", " with open(f\"{batchFolder}/{batch_name}({batchNum})_settings.txt\", \"w+\") as f: #save settings\n", @@ -2575,7 +2571,6 @@ "turbo_mode = False #@param {type:\"boolean\"}\n", "turbo_steps = \"3\" #@param [\"2\",\"3\",\"4\",\"5\",\"6\"] {type:\"string\"}\n", "turbo_preroll = 10 # frames\n", - "turbo_frame_blend = True #@param {type:\"boolean\"}\n", "\n", "#insist turbo be used only w 3d anim.\n", "if turbo_mode and animation_mode != '3D':\n", @@ -3242,7 +3237,8 @@ " # if view_video_in_cell:\n", " # mp4 = open(filepath,'rb').read()\n", " # data_url = \"data:video/mp4;base64,\" + b64encode(mp4).decode()\n", - " # display.HTML(f'')" + " # display.HTML(f'')\n", + " \n" ], "outputs": [], "execution_count": null From 1fd599cd02d161871d4913b9acf8df3720d75e51 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Sun, 3 Apr 2022 08:41:36 -0400 Subject: [PATCH 27/74] Apply HostServer's disco.py changes for pytorch3d-lite to the .ipynb --- Disco_Diffusion.ipynb | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 12ff53fd..df48f196 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -466,6 +466,7 @@ " #gitclone(\"https://github.com/facebookresearch/SLIP.git\")\n", " gitclone(\"https://github.com/crowsonkb/guided-diffusion\")\n", " gitclone(\"https://github.com/assafshocher/ResizeRight.git\")\n", + " gitclone(\"https://github.com/MSFTserver/pytorch3d-lite.git\")\n", " pipie(\"./CLIP\")\n", " pipie(\"./guided-diffusion\")\n", " multipip_res = subprocess.run(['pip', 'install', 'lpips', 'datetime', 'timm', 'ftfy'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", @@ -491,19 +492,8 @@ "import sys\n", "import torch\n", "\n", - "#Install pytorch3d\n", - "if is_colab:\n", - " pyt_version_str=torch.__version__.split(\"+\")[0].replace(\".\", \"\")\n", - " version_str=\"\".join([\n", - " f\"py3{sys.version_info.minor}_cu\",\n", - " torch.version.cuda.replace(\".\",\"\"),\n", - " f\"_pyt{pyt_version_str}\"\n", - " ])\n", - " multipip_res = subprocess.run(['pip', 'install', 'fvcore', 'iopath'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", - " print(multipip_res)\n", - " subprocess.run(['pip', 'install', '--no-index', '--no-cache-dir', 'pytorch3d', '-f', f'https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", - "\n", "# sys.path.append('./SLIP')\n", + "sys.path.append('./pytorch3d-lite')\n", "sys.path.append('./ResizeRight')\n", "sys.path.append('./MiDaS')\n", "from dataclasses import dataclass\n", @@ -725,7 +715,7 @@ "\n", "# https://gist.github.com/adefossez/0646dbe9ed4005480a2407c62aac8869\n", "\n", - "import pytorch3d.transforms as p3dT\n", + "import py3d_tools as p3dT\n", "import disco_xform_utils as dxf\n", "\n", "def interp(t):\n", From a1f25c79ecb7cc5ff14c39a626c9ce47425a10f1 Mon Sep 17 00:00:00 2001 From: MSFTserver Date: Sun, 3 Apr 2022 12:49:26 -0700 Subject: [PATCH 28/74] remove super resolution fix image saving remove slip duplicate remove super resolution add meta data to ipynb --- Disco_Diffusion.ipynb | 657 ++------------------------------------ README.md | 10 + disco.py | 722 +++++++----------------------------------- 3 files changed, 160 insertions(+), 1229 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index df48f196..97fea4a2 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -241,7 +241,7 @@ "\n", " IPython magic commands replaced by Python code\n", "\n", - " v5.1 Update: Mar 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts\n", + " v5.1 Update: Mar 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts / MSFTserver aka HostsServer\n", "\n", " Integrated Turbo+Smooth features from Disco Diffusion Turbo -- just the implementation, without its defaults.\n", "\n", @@ -253,8 +253,12 @@ "\n", " Added video_init_seed_continuity option to make init video animations more continuous\n", "\n", + " Removed pytorch3d from needing to be compiled with a lite version specifically made for Disco Diffusion\n", + "\n", + " Remove Super Resolution\n", + "\n", " '''\n", - " )\n" + " )" ], "outputs": [], "execution_count": null @@ -528,32 +532,7 @@ "import random\n", "from ipywidgets import Output\n", "import hashlib\n", - "\n", - "#SuperRes\n", - "if is_colab:\n", - " gitclone(\"https://github.com/CompVis/latent-diffusion.git\")\n", - " gitclone(\"https://github.com/CompVis/taming-transformers\")\n", - " pipie(\"./taming-transformers\")\n", - " pipi(\"ipywidgets omegaconf>=2.0.0 pytorch-lightning>=1.0.8 torch-fidelity einops wandb\")\n", - "\n", - "#SuperRes\n", - "import ipywidgets as widgets\n", - "import os\n", - "sys.path.append(\".\")\n", - "sys.path.append('./taming-transformers')\n", - "from taming.models import vqgan # checking correct import from taming\n", - "from torchvision.datasets.utils import download_url\n", - "\n", - "if is_colab:\n", - " os.chdir('/content/latent-diffusion')\n", - "else:\n", - " #os.chdir('latent-diffusion')\n", - " sys.path.append('latent-diffusion')\n", "from functools import partial\n", - "from ldm.util import instantiate_from_config\n", - "from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like\n", - "# from ldm.models.diffusion.ddim import DDIMSampler\n", - "from ldm.util import ismap\n", "if is_colab:\n", " os.chdir('/content')\n", " from google.colab import files\n", @@ -1356,7 +1335,6 @@ " \n", " # with run_display:\n", " # display.clear_output(wait=True)\n", - " imgToSharpen = None\n", " for j, sample in enumerate(samples): \n", " cur_t -= 1\n", " intermediateStep = False\n", @@ -1405,31 +1383,20 @@ " save_settings()\n", " if args.animation_mode != \"None\":\n", " image.save('prevFrame.png')\n", - " if args.sharpen_preset != \"Off\" and animation_mode == \"None\":\n", - " imgToSharpen = image\n", - " if args.keep_unsharp is True:\n", - " image.save(f'{unsharpenFolder}/{filename}')\n", - " else:\n", - " image.save(f'{batchFolder}/{filename}')\n", - " if args.animation_mode == \"3D\":\n", - " # If turbo, save a blended image\n", - " if turbo_mode:\n", - " # Mix new image with prevFrameScaled\n", - " blend_factor = (1)/int(turbo_steps)\n", - " newFrame = cv2.imread('prevFrame.png') # This is already updated..\n", - " prev_frame_warped = cv2.imread('prevFrameScaled.png')\n", - " blendedImage = cv2.addWeighted(newFrame, blend_factor, prev_frame_warped, (1-blend_factor), 0.0)\n", - " cv2.imwrite(f'{batchFolder}/{filename}',blendedImage)\n", - " else:\n", - " image.save(f'{batchFolder}/{filename}')\n", + " image.save(f'{batchFolder}/{filename}')\n", + " if args.animation_mode == \"3D\":\n", + " # If turbo, save a blended image\n", + " if turbo_mode:\n", + " # Mix new image with prevFrameScaled\n", + " blend_factor = (1)/int(turbo_steps)\n", + " newFrame = cv2.imread('prevFrame.png') # This is already updated..\n", + " prev_frame_warped = cv2.imread('prevFrameScaled.png')\n", + " blendedImage = cv2.addWeighted(newFrame, blend_factor, prev_frame_warped, (1-blend_factor), 0.0)\n", + " cv2.imwrite(f'{batchFolder}/{filename}',blendedImage)\n", + " else:\n", + " image.save(f'{batchFolder}/{filename}')\n", " # if frame_num != args.max_frames-1:\n", " # display.clear_output()\n", - "\n", - " with image_display: \n", - " if args.sharpen_preset != \"Off\" and animation_mode == \"None\":\n", - " print('Starting Diffusion Sharpening...')\n", - " do_superres(imgToSharpen, f'{batchFolder}/{filename}')\n", - " display.clear_output()\n", " \n", " plt.plot(np.array(loss_values), 'r')\n", "\n", @@ -1687,539 +1654,6 @@ "outputs": [], "execution_count": null }, - { - "cell_type": "code", - "metadata": { - "cellView": "form", - "id": "DefSuperRes" - }, - "source": [ - "#@title 1.7 SuperRes Define\n", - "class DDIMSampler(object):\n", - " def __init__(self, model, schedule=\"linear\", **kwargs):\n", - " super().__init__()\n", - " self.model = model\n", - " self.ddpm_num_timesteps = model.num_timesteps\n", - " self.schedule = schedule\n", - "\n", - " def register_buffer(self, name, attr):\n", - " if type(attr) == torch.Tensor:\n", - " if attr.device != torch.device(\"cuda\"):\n", - " attr = attr.to(torch.device(\"cuda\"))\n", - " setattr(self, name, attr)\n", - "\n", - " def make_schedule(self, ddim_num_steps, ddim_discretize=\"uniform\", ddim_eta=0., verbose=True):\n", - " self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,\n", - " num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)\n", - " alphas_cumprod = self.model.alphas_cumprod\n", - " assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'\n", - " to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)\n", - "\n", - " self.register_buffer('betas', to_torch(self.model.betas))\n", - " self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))\n", - " self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))\n", - "\n", - " # calculations for diffusion q(x_t | x_{t-1}) and others\n", - " self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))\n", - " self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))\n", - " self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))\n", - " self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))\n", - " self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))\n", - "\n", - " # ddim sampling parameters\n", - " ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),\n", - " ddim_timesteps=self.ddim_timesteps,\n", - " eta=ddim_eta,verbose=verbose)\n", - " self.register_buffer('ddim_sigmas', ddim_sigmas)\n", - " self.register_buffer('ddim_alphas', ddim_alphas)\n", - " self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)\n", - " self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))\n", - " sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(\n", - " (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (\n", - " 1 - self.alphas_cumprod / self.alphas_cumprod_prev))\n", - " self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)\n", - "\n", - " @torch.no_grad()\n", - " def sample(self,\n", - " S,\n", - " batch_size,\n", - " shape,\n", - " conditioning=None,\n", - " callback=None,\n", - " normals_sequence=None,\n", - " img_callback=None,\n", - " quantize_x0=False,\n", - " eta=0.,\n", - " mask=None,\n", - " x0=None,\n", - " temperature=1.,\n", - " noise_dropout=0.,\n", - " score_corrector=None,\n", - " corrector_kwargs=None,\n", - " verbose=True,\n", - " x_T=None,\n", - " log_every_t=100,\n", - " **kwargs\n", - " ):\n", - " if conditioning is not None:\n", - " if isinstance(conditioning, dict):\n", - " cbs = conditioning[list(conditioning.keys())[0]].shape[0]\n", - " if cbs != batch_size:\n", - " print(f\"Warning: Got {cbs} conditionings but batch-size is {batch_size}\")\n", - " else:\n", - " if conditioning.shape[0] != batch_size:\n", - " print(f\"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}\")\n", - "\n", - " self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)\n", - " # sampling\n", - " C, H, W = shape\n", - " size = (batch_size, C, H, W)\n", - " # print(f'Data shape for DDIM sampling is {size}, eta {eta}')\n", - "\n", - " samples, intermediates = self.ddim_sampling(conditioning, size,\n", - " callback=callback,\n", - " img_callback=img_callback,\n", - " quantize_denoised=quantize_x0,\n", - " mask=mask, x0=x0,\n", - " ddim_use_original_steps=False,\n", - " noise_dropout=noise_dropout,\n", - " temperature=temperature,\n", - " score_corrector=score_corrector,\n", - " corrector_kwargs=corrector_kwargs,\n", - " x_T=x_T,\n", - " log_every_t=log_every_t\n", - " )\n", - " return samples, intermediates\n", - "\n", - " @torch.no_grad()\n", - " def ddim_sampling(self, cond, shape,\n", - " x_T=None, ddim_use_original_steps=False,\n", - " callback=None, timesteps=None, quantize_denoised=False,\n", - " mask=None, x0=None, img_callback=None, log_every_t=100,\n", - " temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):\n", - " device = self.model.betas.device\n", - " b = shape[0]\n", - " if x_T is None:\n", - " img = torch.randn(shape, device=device)\n", - " else:\n", - " img = x_T\n", - "\n", - " if timesteps is None:\n", - " timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps\n", - " elif timesteps is not None and not ddim_use_original_steps:\n", - " subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1\n", - " timesteps = self.ddim_timesteps[:subset_end]\n", - "\n", - " intermediates = {'x_inter': [img], 'pred_x0': [img]}\n", - " time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)\n", - " total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]\n", - " print(f\"Running DDIM Sharpening with {total_steps} timesteps\")\n", - "\n", - " iterator = tqdm(time_range, desc='DDIM Sharpening', total=total_steps)\n", - "\n", - " for i, step in enumerate(iterator):\n", - " index = total_steps - i - 1\n", - " ts = torch.full((b,), step, device=device, dtype=torch.long)\n", - "\n", - " if mask is not None:\n", - " assert x0 is not None\n", - " img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?\n", - " img = img_orig * mask + (1. - mask) * img\n", - "\n", - " outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,\n", - " quantize_denoised=quantize_denoised, temperature=temperature,\n", - " noise_dropout=noise_dropout, score_corrector=score_corrector,\n", - " corrector_kwargs=corrector_kwargs)\n", - " img, pred_x0 = outs\n", - " if callback: callback(i)\n", - " if img_callback: img_callback(pred_x0, i)\n", - "\n", - " if index % log_every_t == 0 or index == total_steps - 1:\n", - " intermediates['x_inter'].append(img)\n", - " intermediates['pred_x0'].append(pred_x0)\n", - "\n", - " return img, intermediates\n", - "\n", - " @torch.no_grad()\n", - " def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,\n", - " temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):\n", - " b, *_, device = *x.shape, x.device\n", - " e_t = self.model.apply_model(x, t, c)\n", - " if score_corrector is not None:\n", - " assert self.model.parameterization == \"eps\"\n", - " e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)\n", - "\n", - " alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas\n", - " alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev\n", - " sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas\n", - " sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas\n", - " # select parameters corresponding to the currently considered timestep\n", - " a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)\n", - " a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)\n", - " sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)\n", - " sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)\n", - "\n", - " # current prediction for x_0\n", - " pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()\n", - " if quantize_denoised:\n", - " pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)\n", - " # direction pointing to x_t\n", - " dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t\n", - " noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature\n", - " if noise_dropout > 0.:\n", - " noise = torch.nn.functional.dropout(noise, p=noise_dropout)\n", - " x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise\n", - " return x_prev, pred_x0\n", - "\n", - "\n", - "def download_models(mode):\n", - "\n", - " if mode == \"superresolution\":\n", - " # this is the small bsr light model\n", - " url_conf = 'https://heibox.uni-heidelberg.de/f/31a76b13ea27482981b4/?dl=1'\n", - " url_ckpt = 'https://heibox.uni-heidelberg.de/f/578df07c8fc04ffbadf3/?dl=1'\n", - "\n", - " path_conf = f'{model_path}/superres/project.yaml'\n", - " path_ckpt = f'{model_path}/superres/last.ckpt'\n", - "\n", - " download_url(url_conf, path_conf)\n", - " download_url(url_ckpt, path_ckpt)\n", - "\n", - " path_conf = path_conf + '/?dl=1' # fix it\n", - " path_ckpt = path_ckpt + '/?dl=1' # fix it\n", - " return path_conf, path_ckpt\n", - "\n", - " else:\n", - " raise NotImplementedError\n", - "\n", - "\n", - "def load_model_from_config(config, ckpt):\n", - " print(f\"Loading model from {ckpt}\")\n", - " pl_sd = torch.load(ckpt, map_location=\"cpu\")\n", - " global_step = pl_sd[\"global_step\"]\n", - " sd = pl_sd[\"state_dict\"]\n", - " model = instantiate_from_config(config.model)\n", - " m, u = model.load_state_dict(sd, strict=False)\n", - " model.cuda()\n", - " model.eval()\n", - " return {\"model\": model}, global_step\n", - "\n", - "\n", - "def get_model(mode):\n", - " path_conf, path_ckpt = download_models(mode)\n", - " config = OmegaConf.load(path_conf)\n", - " model, step = load_model_from_config(config, path_ckpt)\n", - " return model\n", - "\n", - "\n", - "def get_custom_cond(mode):\n", - " dest = \"data/example_conditioning\"\n", - "\n", - " if mode == \"superresolution\":\n", - " uploaded_img = files.upload()\n", - " filename = next(iter(uploaded_img))\n", - " name, filetype = filename.split(\".\") # todo assumes just one dot in name !\n", - " os.rename(f\"{filename}\", f\"{dest}/{mode}/custom_{name}.{filetype}\")\n", - "\n", - " elif mode == \"text_conditional\":\n", - " w = widgets.Text(value='A cake with cream!', disabled=True)\n", - " display.display(w)\n", - "\n", - " with open(f\"{dest}/{mode}/custom_{w.value[:20]}.txt\", 'w') as f:\n", - " f.write(w.value)\n", - "\n", - " elif mode == \"class_conditional\":\n", - " w = widgets.IntSlider(min=0, max=1000)\n", - " display.display(w)\n", - " with open(f\"{dest}/{mode}/custom.txt\", 'w') as f:\n", - " f.write(w.value)\n", - "\n", - " else:\n", - " raise NotImplementedError(f\"cond not implemented for mode{mode}\")\n", - "\n", - "\n", - "def get_cond_options(mode):\n", - " path = \"data/example_conditioning\"\n", - " path = os.path.join(path, mode)\n", - " onlyfiles = [f for f in sorted(os.listdir(path))]\n", - " return path, onlyfiles\n", - "\n", - "\n", - "def select_cond_path(mode):\n", - " path = \"data/example_conditioning\" # todo\n", - " path = os.path.join(path, mode)\n", - " onlyfiles = [f for f in sorted(os.listdir(path))]\n", - "\n", - " selected = widgets.RadioButtons(\n", - " options=onlyfiles,\n", - " description='Select conditioning:',\n", - " disabled=False\n", - " )\n", - " display.display(selected)\n", - " selected_path = os.path.join(path, selected.value)\n", - " return selected_path\n", - "\n", - "\n", - "def get_cond(mode, img):\n", - " example = dict()\n", - " if mode == \"superresolution\":\n", - " up_f = 4\n", - " # visualize_cond_img(selected_path)\n", - "\n", - " c = img\n", - " c = torch.unsqueeze(torchvision.transforms.ToTensor()(c), 0)\n", - " c_up = torchvision.transforms.functional.resize(c, size=[up_f * c.shape[2], up_f * c.shape[3]], antialias=True)\n", - " c_up = rearrange(c_up, '1 c h w -> 1 h w c')\n", - " c = rearrange(c, '1 c h w -> 1 h w c')\n", - " c = 2. * c - 1.\n", - "\n", - " c = c.to(torch.device(\"cuda\"))\n", - " example[\"LR_image\"] = c\n", - " example[\"image\"] = c_up\n", - "\n", - " return example\n", - "\n", - "\n", - "def visualize_cond_img(path):\n", - " display.display(ipyimg(filename=path))\n", - "\n", - "\n", - "def sr_run(model, img, task, custom_steps, eta, resize_enabled=False, classifier_ckpt=None, global_step=None):\n", - " # global stride\n", - "\n", - " example = get_cond(task, img)\n", - "\n", - " save_intermediate_vid = False\n", - " n_runs = 1\n", - " masked = False\n", - " guider = None\n", - " ckwargs = None\n", - " mode = 'ddim'\n", - " ddim_use_x0_pred = False\n", - " temperature = 1.\n", - " eta = eta\n", - " make_progrow = True\n", - " custom_shape = None\n", - "\n", - " height, width = example[\"image\"].shape[1:3]\n", - " split_input = height >= 128 and width >= 128\n", - "\n", - " if split_input:\n", - " ks = 128\n", - " stride = 64\n", - " vqf = 4 #\n", - " model.split_input_params = {\"ks\": (ks, ks), \"stride\": (stride, stride),\n", - " \"vqf\": vqf,\n", - " \"patch_distributed_vq\": True,\n", - " \"tie_braker\": False,\n", - " \"clip_max_weight\": 0.5,\n", - " \"clip_min_weight\": 0.01,\n", - " \"clip_max_tie_weight\": 0.5,\n", - " \"clip_min_tie_weight\": 0.01}\n", - " else:\n", - " if hasattr(model, \"split_input_params\"):\n", - " delattr(model, \"split_input_params\")\n", - "\n", - " invert_mask = False\n", - "\n", - " x_T = None\n", - " for n in range(n_runs):\n", - " if custom_shape is not None:\n", - " x_T = torch.randn(1, custom_shape[1], custom_shape[2], custom_shape[3]).to(model.device)\n", - " x_T = repeat(x_T, '1 c h w -> b c h w', b=custom_shape[0])\n", - "\n", - " logs = make_convolutional_sample(example, model,\n", - " mode=mode, custom_steps=custom_steps,\n", - " eta=eta, swap_mode=False , masked=masked,\n", - " invert_mask=invert_mask, quantize_x0=False,\n", - " custom_schedule=None, decode_interval=10,\n", - " resize_enabled=resize_enabled, custom_shape=custom_shape,\n", - " temperature=temperature, noise_dropout=0.,\n", - " corrector=guider, corrector_kwargs=ckwargs, x_T=x_T, save_intermediate_vid=save_intermediate_vid,\n", - " make_progrow=make_progrow,ddim_use_x0_pred=ddim_use_x0_pred\n", - " )\n", - " return logs\n", - "\n", - "\n", - "@torch.no_grad()\n", - "def convsample_ddim(model, cond, steps, shape, eta=1.0, callback=None, normals_sequence=None,\n", - " mask=None, x0=None, quantize_x0=False, img_callback=None,\n", - " temperature=1., noise_dropout=0., score_corrector=None,\n", - " corrector_kwargs=None, x_T=None, log_every_t=None\n", - " ):\n", - "\n", - " ddim = DDIMSampler(model)\n", - " bs = shape[0] # dont know where this comes from but wayne\n", - " shape = shape[1:] # cut batch dim\n", - " # print(f\"Sampling with eta = {eta}; steps: {steps}\")\n", - " samples, intermediates = ddim.sample(steps, batch_size=bs, shape=shape, conditioning=cond, callback=callback,\n", - " normals_sequence=normals_sequence, quantize_x0=quantize_x0, eta=eta,\n", - " mask=mask, x0=x0, temperature=temperature, verbose=False,\n", - " score_corrector=score_corrector,\n", - " corrector_kwargs=corrector_kwargs, x_T=x_T)\n", - "\n", - " return samples, intermediates\n", - "\n", - "\n", - "@torch.no_grad()\n", - "def make_convolutional_sample(batch, model, mode=\"vanilla\", custom_steps=None, eta=1.0, swap_mode=False, masked=False,\n", - " invert_mask=True, quantize_x0=False, custom_schedule=None, decode_interval=1000,\n", - " resize_enabled=False, custom_shape=None, temperature=1., noise_dropout=0., corrector=None,\n", - " corrector_kwargs=None, x_T=None, save_intermediate_vid=False, make_progrow=True,ddim_use_x0_pred=False):\n", - " log = dict()\n", - "\n", - " z, c, x, xrec, xc = model.get_input(batch, model.first_stage_key,\n", - " return_first_stage_outputs=True,\n", - " force_c_encode=not (hasattr(model, 'split_input_params')\n", - " and model.cond_stage_key == 'coordinates_bbox'),\n", - " return_original_cond=True)\n", - "\n", - " log_every_t = 1 if save_intermediate_vid else None\n", - "\n", - " if custom_shape is not None:\n", - " z = torch.randn(custom_shape)\n", - " # print(f\"Generating {custom_shape[0]} samples of shape {custom_shape[1:]}\")\n", - "\n", - " z0 = None\n", - "\n", - " log[\"input\"] = x\n", - " log[\"reconstruction\"] = xrec\n", - "\n", - " if ismap(xc):\n", - " log[\"original_conditioning\"] = model.to_rgb(xc)\n", - " if hasattr(model, 'cond_stage_key'):\n", - " log[model.cond_stage_key] = model.to_rgb(xc)\n", - "\n", - " else:\n", - " log[\"original_conditioning\"] = xc if xc is not None else torch.zeros_like(x)\n", - " if model.cond_stage_model:\n", - " log[model.cond_stage_key] = xc if xc is not None else torch.zeros_like(x)\n", - " if model.cond_stage_key =='class_label':\n", - " log[model.cond_stage_key] = xc[model.cond_stage_key]\n", - "\n", - " with model.ema_scope(\"Plotting\"):\n", - " t0 = time.time()\n", - " img_cb = None\n", - "\n", - " sample, intermediates = convsample_ddim(model, c, steps=custom_steps, shape=z.shape,\n", - " eta=eta,\n", - " quantize_x0=quantize_x0, img_callback=img_cb, mask=None, x0=z0,\n", - " temperature=temperature, noise_dropout=noise_dropout,\n", - " score_corrector=corrector, corrector_kwargs=corrector_kwargs,\n", - " x_T=x_T, log_every_t=log_every_t)\n", - " t1 = time.time()\n", - "\n", - " if ddim_use_x0_pred:\n", - " sample = intermediates['pred_x0'][-1]\n", - "\n", - " x_sample = model.decode_first_stage(sample)\n", - "\n", - " try:\n", - " x_sample_noquant = model.decode_first_stage(sample, force_not_quantize=True)\n", - " log[\"sample_noquant\"] = x_sample_noquant\n", - " log[\"sample_diff\"] = torch.abs(x_sample_noquant - x_sample)\n", - " except:\n", - " pass\n", - "\n", - " log[\"sample\"] = x_sample\n", - " log[\"time\"] = t1 - t0\n", - "\n", - " return log\n", - "\n", - "sr_diffMode = 'superresolution'\n", - "sr_model = get_model('superresolution')\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "def do_superres(img, filepath):\n", - "\n", - " if args.sharpen_preset == 'Faster':\n", - " sr_diffusion_steps = \"25\" \n", - " sr_pre_downsample = '1/2' \n", - " if args.sharpen_preset == 'Fast':\n", - " sr_diffusion_steps = \"100\" \n", - " sr_pre_downsample = '1/2' \n", - " if args.sharpen_preset == 'Slow':\n", - " sr_diffusion_steps = \"25\" \n", - " sr_pre_downsample = 'None' \n", - " if args.sharpen_preset == 'Very Slow':\n", - " sr_diffusion_steps = \"100\" \n", - " sr_pre_downsample = 'None' \n", - "\n", - "\n", - " sr_post_downsample = 'Original Size'\n", - " sr_diffusion_steps = int(sr_diffusion_steps)\n", - " sr_eta = 1.0 \n", - " sr_downsample_method = 'Lanczos' \n", - "\n", - " gc.collect()\n", - " torch.cuda.empty_cache()\n", - "\n", - " im_og = img\n", - " width_og, height_og = im_og.size\n", - "\n", - " #Downsample Pre\n", - " if sr_pre_downsample == '1/2':\n", - " downsample_rate = 2\n", - " elif sr_pre_downsample == '1/4':\n", - " downsample_rate = 4\n", - " else:\n", - " downsample_rate = 1\n", - "\n", - " width_downsampled_pre = width_og//downsample_rate\n", - " height_downsampled_pre = height_og//downsample_rate\n", - "\n", - " if downsample_rate != 1:\n", - " # print(f'Downsampling from [{width_og}, {height_og}] to [{width_downsampled_pre}, {height_downsampled_pre}]')\n", - " im_og = im_og.resize((width_downsampled_pre, height_downsampled_pre), Image.LANCZOS)\n", - " # im_og.save('/content/temp.png')\n", - " # filepath = '/content/temp.png'\n", - "\n", - " logs = sr_run(sr_model[\"model\"], im_og, sr_diffMode, sr_diffusion_steps, sr_eta)\n", - "\n", - " sample = logs[\"sample\"]\n", - " sample = sample.detach().cpu()\n", - " sample = torch.clamp(sample, -1., 1.)\n", - " sample = (sample + 1.) / 2. * 255\n", - " sample = sample.numpy().astype(np.uint8)\n", - " sample = np.transpose(sample, (0, 2, 3, 1))\n", - " a = Image.fromarray(sample[0])\n", - "\n", - " #Downsample Post\n", - " if sr_post_downsample == '1/2':\n", - " downsample_rate = 2\n", - " elif sr_post_downsample == '1/4':\n", - " downsample_rate = 4\n", - " else:\n", - " downsample_rate = 1\n", - "\n", - " width, height = a.size\n", - " width_downsampled_post = width//downsample_rate\n", - " height_downsampled_post = height//downsample_rate\n", - "\n", - " if sr_downsample_method == 'Lanczos':\n", - " aliasing = Image.LANCZOS\n", - " else:\n", - " aliasing = Image.NEAREST\n", - "\n", - " if downsample_rate != 1:\n", - " # print(f'Downsampling from [{width}, {height}] to [{width_downsampled_post}, {height_downsampled_post}]')\n", - " a = a.resize((width_downsampled_post, height_downsampled_post), aliasing)\n", - " elif sr_post_downsample == 'Original Size':\n", - " # print(f'Downsampling from [{width}, {height}] to Original Size [{width_og}, {height_og}]')\n", - " a = a.resize((width_og, height_og), aliasing)\n", - "\n", - " display.display(a)\n", - " a.save(filepath)\n", - " return\n", - " print(f'Processing finished!')\n" - ], - "outputs": [], - "execution_count": null - }, { "cell_type": "markdown", "metadata": { @@ -2240,8 +1674,7 @@ "use_secondary_model = True #@param {type: 'boolean'}\n", "diffusion_sampling_mode = 'ddim' #@param ['plms','ddim'] \n", "\n", - "timestep_respacing = '250' #@param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000'] \n", - "diffusion_steps = 1000 #@param {type: 'number'}\n", + "\n", "use_checkpoint = True #@param {type: 'boolean'}\n", "ViTB32 = True #@param{type:\"boolean\"}\n", "ViTB16 = True #@param{type:\"boolean\"}\n", @@ -2333,9 +1766,9 @@ " model_config.update({\n", " 'attention_resolutions': '32, 16, 8',\n", " 'class_cond': False,\n", - " 'diffusion_steps': diffusion_steps,\n", + " 'diffusion_steps': 1000, #No need to edit this, it is taken care of later.\n", " 'rescale_timesteps': True,\n", - " 'timestep_respacing': timestep_respacing,\n", + " 'timestep_respacing': 250, #No need to edit this, it is taken care of later.\n", " 'image_size': 512,\n", " 'learn_sigma': True,\n", " 'noise_schedule': 'linear',\n", @@ -2351,9 +1784,9 @@ " model_config.update({\n", " 'attention_resolutions': '32, 16, 8',\n", " 'class_cond': False,\n", - " 'diffusion_steps': diffusion_steps,\n", + " 'diffusion_steps': 1000, #No need to edit this, it is taken care of later.\n", " 'rescale_timesteps': True,\n", - " 'timestep_respacing': timestep_respacing,\n", + " 'timestep_respacing': 250, #No need to edit this, it is taken care of later.\n", " 'image_size': 256,\n", " 'learn_sigma': True,\n", " 'noise_schedule': 'linear',\n", @@ -2398,24 +1831,10 @@ " SLIPB16model.load_state_dict(real_sd)\n", " SLIPB16model.requires_grad_(False).eval().to(device)\n", "\n", - " clip_models.append(SLIPB16model)\n", - "\n", - "if SLIPL16:\n", - " SLIPL16model = SLIP_VITL16(ssl_mlp_dim=4096, ssl_emb_dim=256)\n", - " if not os.path.exists(f'{model_path}/slip_large_100ep.pt'):\n", - " wget(\"https://dl.fbaipublicfiles.com/slip/slip_large_100ep.pt\", model_path)\n", - " sd = torch.load(f'{model_path}/slip_large_100ep.pt')\n", - " real_sd = {}\n", - " for k, v in sd['state_dict'].items():\n", - " real_sd['.'.join(k.split('.')[1:])] = v\n", - " del sd\n", - " SLIPL16model.load_state_dict(real_sd)\n", - " SLIPL16model.requires_grad_(False).eval().to(device)\n", - "\n", " clip_models.append(SLIPL16model)\n", "\n", "normalize = T.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711])\n", - "lpips_model = lpips.LPIPS(net='vgg').to(device)\n" + "lpips_model = lpips.LPIPS(net='vgg').to(device)" ], "outputs": [], "execution_count": null @@ -2470,7 +1889,7 @@ "\n", "#Make folder for batch\n", "batchFolder = f'{outDirPath}/{batch_name}'\n", - "createPath(batchFolder)\n" + "createPath(batchFolder)" ], "outputs": [], "execution_count": null @@ -2816,7 +2235,7 @@ " translation_z = float(translation_z)\n", " rotation_3d_x = float(rotation_3d_x)\n", " rotation_3d_y = float(rotation_3d_y)\n", - " rotation_3d_z = float(rotation_3d_z)\n" + " rotation_3d_z = float(rotation_3d_z)" ], "outputs": [], "execution_count": null @@ -2828,7 +2247,7 @@ }, "source": [ "### Extra Settings\n", - " Partial Saves, Diffusion Sharpening, Advanced Settings, Cutn Scheduling" + " Partial Saves, Advanced Settings, Cutn Scheduling" ] }, { @@ -2864,18 +2283,6 @@ "\n", " #@markdown ---\n", "\n", - "#@markdown ####**SuperRes Sharpening:**\n", - "#@markdown *Sharpen each image using latent-diffusion. Does not run in animation mode. `keep_unsharp` will save both versions.*\n", - "sharpen_preset = 'Off' #@param ['Off', 'Faster', 'Fast', 'Slow', 'Very Slow']\n", - "keep_unsharp = True #@param{type: 'boolean'}\n", - "\n", - "if sharpen_preset != 'Off' and keep_unsharp is True:\n", - " unsharpenFolder = f'{batchFolder}/unsharpened'\n", - " createPath(unsharpenFolder)\n", - "\n", - "\n", - " #@markdown ---\n", - "\n", "#@markdown ####**Advanced Settings:**\n", "#@markdown *There are a few extra advanced settings available if you double click this cell.*\n", "\n", @@ -2906,7 +2313,7 @@ "cut_overview = \"[12]*400+[4]*600\" #@param {type: 'string'} \n", "cut_innercut =\"[4]*400+[12]*600\"#@param {type: 'string'} \n", "cut_ic_pow = 1#@param {type: 'number'} \n", - "cut_icgray_p = \"[0.2]*400+[0]*600\"#@param {type: 'string'}\n" + "cut_icgray_p = \"[0.2]*400+[0]*600\"#@param {type: 'string'}" ], "outputs": [], "execution_count": null @@ -2934,7 +2341,7 @@ "\n", "image_prompts = {\n", " # 0:['ImagePromptsWorkButArentVeryGood.png:2',],\n", - "}\n" + "}" ], "outputs": [], "execution_count": null @@ -3050,8 +2457,6 @@ " 'init_image': init_image,\n", " 'init_scale': init_scale,\n", " 'skip_steps': skip_steps,\n", - " 'sharpen_preset': sharpen_preset,\n", - " 'keep_unsharp': keep_unsharp,\n", " 'side_x': side_x,\n", " 'side_y': side_y,\n", " 'timestep_respacing': timestep_respacing,\n", @@ -3134,7 +2539,7 @@ "finally:\n", " print('Seed used:', seed)\n", " gc.collect()\n", - " torch.cuda.empty_cache()\n" + " torch.cuda.empty_cache()" ], "outputs": [], "execution_count": null @@ -3228,7 +2633,7 @@ " # mp4 = open(filepath,'rb').read()\n", " # data_url = \"data:video/mp4;base64,\" + b64encode(mp4).decode()\n", " # display.HTML(f'')\n", - " \n" + " " ], "outputs": [], "execution_count": null diff --git a/README.md b/README.md index a793b8c8..a35472b7 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,16 @@ A frankensteinian amalgamation of notebooks, models and techniques for the gener #### v5 Update: Feb 20th 2022 - gandamu / Adam Letts * Added 3D animation mode. Uses weighted combination of AdaBins and MiDaS depth estimation models. Uses pytorch3d for 3D transforms on Colab and/or Linux. +#### v5.1 Update: Mar 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts / MSFTserver aka HostsServer + +* Integrated Turbo+Smooth features from Disco Diffusion Turbo -- just the implementation, without its defaults. +* Implemented resume of turbo animations in such a way that it's now possible to resume from different batch folders and batch numbers. +* 3D rotation parameter units are now degrees (rather than radians) +* Corrected name collision in sampling_mode (now diffusion_sampling_mode for plms/ddim, and sampling_mode for 3D transform sampling) +* Added video_init_seed_continuity option to make init video animations more continuous +* Removed pytorch3d from needing to be compiled with a lite version specifically made for Disco Diffusion +* Remove Super Resolution + ## Notebook Provenance diff --git a/disco.py b/disco.py index 82c523e7..c7001ab2 100644 --- a/disco.py +++ b/disco.py @@ -1,9 +1,16 @@ # %% +# !! {"metadata": { +# !! "id": "view-in-github", +# !! "colab_type": "text" +# !! }} """ Open In Colab """ # %% +# !! {"metadata": { +# !! "id": "TitleTop" +# !! }} """ # Disco Diffusion v5.1 - Now with Turbo @@ -13,11 +20,17 @@ """ # %% +# !! {"metadata": { +# !! "id": "CreditsChTop" +# !! }} """ ### Credits & Changelog ⬇️ """ # %% +# !! {"metadata": { +# !! "id": "Credits" +# !! }} """ #### Credits @@ -45,11 +58,17 @@ """ # %% +# !! {"metadata": { +# !! "id": "LicenseTop" +# !! }} """ #### License """ # %% +# !! {"metadata": { +# !! "id": "License" +# !! }} """ Licensed under the MIT License @@ -125,11 +144,18 @@ """ # %% +# !! {"metadata": { +# !! "id": "ChangelogTop" +# !! }} """ #### Changelog """ # %% +# !! {"metadata": { +# !! "cellView": "form", +# !! "id": "Changelog" +# !! }} #@title <- View Changelog skip_for_run_all = True #@param {type: 'boolean'} @@ -204,7 +230,7 @@ IPython magic commands replaced by Python code - v5.1 Update: Mar 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts + v5.1 Update: Mar 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts / MSFTserver aka HostsServer Integrated Turbo+Smooth features from Disco Diffusion Turbo -- just the implementation, without its defaults. @@ -216,16 +242,26 @@ Added video_init_seed_continuity option to make init video animations more continuous + Removed pytorch3d from needing to be compiled with a lite version specifically made for Disco Diffusion + + Remove Super Resolution + ''' ) # %% +# !! {"metadata": { +# !! "id": "TutorialTop" +# !! }} """ # Tutorial """ # %% +# !! {"metadata": { +# !! "id": "DiffusionSet" +# !! }} """ **Diffusion settings (Defaults are heavily outdated)** --- @@ -275,11 +311,18 @@ """ # %% +# !! {"metadata": { +# !! "id": "SetupTop" +# !! }} """ # 1. Set Up """ # %% +# !! {"metadata": { +# !! "cellView": "form", +# !! "id": "CheckGPU" +# !! }} #@title 1.1 Check GPU Status import subprocess simple_nvidia_smi_display = False#@param {type:"boolean"} @@ -295,6 +338,10 @@ print(nvidiasmi_ecc_note) # %% +# !! {"metadata": { +# !! "cellView": "form", +# !! "id": "PrepFolders" +# !! }} #@title 1.2 Prepare Folders import subprocess import sys @@ -363,6 +410,10 @@ def createPath(filepath): # createPath(libraries) # %% +# !! {"metadata": { +# !! "cellView": "form", +# !! "id": "InstallDeps" +# !! }} #@title ### 1.3 Install and import dependencies import pathlib, shutil @@ -453,32 +504,7 @@ def createPath(filepath): import random from ipywidgets import Output import hashlib - -#SuperRes -if is_colab: - gitclone("https://github.com/CompVis/latent-diffusion.git") - gitclone("https://github.com/CompVis/taming-transformers") - pipie("./taming-transformers") - pipi("ipywidgets omegaconf>=2.0.0 pytorch-lightning>=1.0.8 torch-fidelity einops wandb") - -#SuperRes -import ipywidgets as widgets -import os -sys.path.append(".") -sys.path.append('./taming-transformers') -from taming.models import vqgan # checking correct import from taming -from torchvision.datasets.utils import download_url - -if is_colab: - os.chdir('/content/latent-diffusion') -else: - #os.chdir('latent-diffusion') - sys.path.append('latent-diffusion') from functools import partial -from ldm.util import instantiate_from_config -from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like -# from ldm.models.diffusion.ddim import DDIMSampler -from ldm.util import ismap if is_colab: os.chdir('/content') from google.colab import files @@ -515,6 +541,10 @@ def createPath(filepath): torch.backends.cudnn.enabled = False # %% +# !! {"metadata": { +# !! "cellView": "form", +# !! "id": "DefMidasFns" +# !! }} #@title ### 1.4 Define Midas functions from midas.dpt_depth import DPTDepthModel @@ -618,6 +648,10 @@ def init_midas_depth_model(midas_model_type="dpt_large", optimize=True): return midas_model, midas_transform, net_w, net_h, resize_mode, normalization # %% +# !! {"metadata": { +# !! "cellView": "form", +# !! "id": "DefFns" +# !! }} #@title 1.5 Define necessary functions # https://gist.github.com/adefossez/0646dbe9ed4005480a2407c62aac8869 @@ -1263,7 +1297,6 @@ def cond_fn(x, t, y=None): # with run_display: # display.clear_output(wait=True) - imgToSharpen = None for j, sample in enumerate(samples): cur_t -= 1 intermediateStep = False @@ -1312,31 +1345,20 @@ def cond_fn(x, t, y=None): save_settings() if args.animation_mode != "None": image.save('prevFrame.png') - if args.sharpen_preset != "Off" and animation_mode == "None": - imgToSharpen = image - if args.keep_unsharp is True: - image.save(f'{unsharpenFolder}/{filename}') - else: - image.save(f'{batchFolder}/{filename}') - if args.animation_mode == "3D": - # If turbo, save a blended image - if turbo_mode: - # Mix new image with prevFrameScaled - blend_factor = (1)/int(turbo_steps) - newFrame = cv2.imread('prevFrame.png') # This is already updated.. - prev_frame_warped = cv2.imread('prevFrameScaled.png') - blendedImage = cv2.addWeighted(newFrame, blend_factor, prev_frame_warped, (1-blend_factor), 0.0) - cv2.imwrite(f'{batchFolder}/{filename}',blendedImage) - else: - image.save(f'{batchFolder}/{filename}') + image.save(f'{batchFolder}/{filename}') + if args.animation_mode == "3D": + # If turbo, save a blended image + if turbo_mode: + # Mix new image with prevFrameScaled + blend_factor = (1)/int(turbo_steps) + newFrame = cv2.imread('prevFrame.png') # This is already updated.. + prev_frame_warped = cv2.imread('prevFrameScaled.png') + blendedImage = cv2.addWeighted(newFrame, blend_factor, prev_frame_warped, (1-blend_factor), 0.0) + cv2.imwrite(f'{batchFolder}/{filename}',blendedImage) + else: + image.save(f'{batchFolder}/{filename}') # if frame_num != args.max_frames-1: # display.clear_output() - - with image_display: - if args.sharpen_preset != "Off" and animation_mode == "None": - print('Starting Diffusion Sharpening...') - do_superres(imgToSharpen, f'{batchFolder}/{filename}') - display.clear_output() plt.plot(np.array(loss_values), 'r') @@ -1418,6 +1440,10 @@ def save_settings(): json.dump(setting_list, f, ensure_ascii=False, indent=4) # %% +# !! {"metadata": { +# !! "cellView": "form", +# !! "id": "DefSecModel" +# !! }} #@title 1.6 Define the secondary diffusion model def append_dims(x, n): @@ -1582,537 +1608,19 @@ def forward(self, input, t): eps = input * sigmas + v * alphas return DiffusionOutput(v, pred, eps) -# %% -#@title 1.7 SuperRes Define -class DDIMSampler(object): - def __init__(self, model, schedule="linear", **kwargs): - super().__init__() - self.model = model - self.ddpm_num_timesteps = model.num_timesteps - self.schedule = schedule - - def register_buffer(self, name, attr): - if type(attr) == torch.Tensor: - if attr.device != torch.device("cuda"): - attr = attr.to(torch.device("cuda")) - setattr(self, name, attr) - - def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True): - self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps, - num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose) - alphas_cumprod = self.model.alphas_cumprod - assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep' - to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device) - - self.register_buffer('betas', to_torch(self.model.betas)) - self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) - self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev)) - - # calculations for diffusion q(x_t | x_{t-1}) and others - self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu()))) - self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu()))) - self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu()))) - self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu()))) - self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1))) - - # ddim sampling parameters - ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(), - ddim_timesteps=self.ddim_timesteps, - eta=ddim_eta,verbose=verbose) - self.register_buffer('ddim_sigmas', ddim_sigmas) - self.register_buffer('ddim_alphas', ddim_alphas) - self.register_buffer('ddim_alphas_prev', ddim_alphas_prev) - self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas)) - sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt( - (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * ( - 1 - self.alphas_cumprod / self.alphas_cumprod_prev)) - self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps) - - @torch.no_grad() - def sample(self, - S, - batch_size, - shape, - conditioning=None, - callback=None, - normals_sequence=None, - img_callback=None, - quantize_x0=False, - eta=0., - mask=None, - x0=None, - temperature=1., - noise_dropout=0., - score_corrector=None, - corrector_kwargs=None, - verbose=True, - x_T=None, - log_every_t=100, - **kwargs - ): - if conditioning is not None: - if isinstance(conditioning, dict): - cbs = conditioning[list(conditioning.keys())[0]].shape[0] - if cbs != batch_size: - print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}") - else: - if conditioning.shape[0] != batch_size: - print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}") - - self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose) - # sampling - C, H, W = shape - size = (batch_size, C, H, W) - # print(f'Data shape for DDIM sampling is {size}, eta {eta}') - - samples, intermediates = self.ddim_sampling(conditioning, size, - callback=callback, - img_callback=img_callback, - quantize_denoised=quantize_x0, - mask=mask, x0=x0, - ddim_use_original_steps=False, - noise_dropout=noise_dropout, - temperature=temperature, - score_corrector=score_corrector, - corrector_kwargs=corrector_kwargs, - x_T=x_T, - log_every_t=log_every_t - ) - return samples, intermediates - - @torch.no_grad() - def ddim_sampling(self, cond, shape, - x_T=None, ddim_use_original_steps=False, - callback=None, timesteps=None, quantize_denoised=False, - mask=None, x0=None, img_callback=None, log_every_t=100, - temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None): - device = self.model.betas.device - b = shape[0] - if x_T is None: - img = torch.randn(shape, device=device) - else: - img = x_T - - if timesteps is None: - timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps - elif timesteps is not None and not ddim_use_original_steps: - subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1 - timesteps = self.ddim_timesteps[:subset_end] - - intermediates = {'x_inter': [img], 'pred_x0': [img]} - time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps) - total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0] - print(f"Running DDIM Sharpening with {total_steps} timesteps") - - iterator = tqdm(time_range, desc='DDIM Sharpening', total=total_steps) - - for i, step in enumerate(iterator): - index = total_steps - i - 1 - ts = torch.full((b,), step, device=device, dtype=torch.long) - - if mask is not None: - assert x0 is not None - img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass? - img = img_orig * mask + (1. - mask) * img - - outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps, - quantize_denoised=quantize_denoised, temperature=temperature, - noise_dropout=noise_dropout, score_corrector=score_corrector, - corrector_kwargs=corrector_kwargs) - img, pred_x0 = outs - if callback: callback(i) - if img_callback: img_callback(pred_x0, i) - - if index % log_every_t == 0 or index == total_steps - 1: - intermediates['x_inter'].append(img) - intermediates['pred_x0'].append(pred_x0) - - return img, intermediates - - @torch.no_grad() - def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False, - temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None): - b, *_, device = *x.shape, x.device - e_t = self.model.apply_model(x, t, c) - if score_corrector is not None: - assert self.model.parameterization == "eps" - e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs) - - alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas - alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev - sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas - sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas - # select parameters corresponding to the currently considered timestep - a_t = torch.full((b, 1, 1, 1), alphas[index], device=device) - a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device) - sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device) - sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device) - - # current prediction for x_0 - pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt() - if quantize_denoised: - pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0) - # direction pointing to x_t - dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t - noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature - if noise_dropout > 0.: - noise = torch.nn.functional.dropout(noise, p=noise_dropout) - x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise - return x_prev, pred_x0 - - -def download_models(mode): - - if mode == "superresolution": - # this is the small bsr light model - url_conf = 'https://heibox.uni-heidelberg.de/f/31a76b13ea27482981b4/?dl=1' - url_ckpt = 'https://heibox.uni-heidelberg.de/f/578df07c8fc04ffbadf3/?dl=1' - - path_conf = f'{model_path}/superres/project.yaml' - path_ckpt = f'{model_path}/superres/last.ckpt' - - download_url(url_conf, path_conf) - download_url(url_ckpt, path_ckpt) - - path_conf = path_conf + '/?dl=1' # fix it - path_ckpt = path_ckpt + '/?dl=1' # fix it - return path_conf, path_ckpt - - else: - raise NotImplementedError - - -def load_model_from_config(config, ckpt): - print(f"Loading model from {ckpt}") - pl_sd = torch.load(ckpt, map_location="cpu") - global_step = pl_sd["global_step"] - sd = pl_sd["state_dict"] - model = instantiate_from_config(config.model) - m, u = model.load_state_dict(sd, strict=False) - model.cuda() - model.eval() - return {"model": model}, global_step - - -def get_model(mode): - path_conf, path_ckpt = download_models(mode) - config = OmegaConf.load(path_conf) - model, step = load_model_from_config(config, path_ckpt) - return model - - -def get_custom_cond(mode): - dest = "data/example_conditioning" - - if mode == "superresolution": - uploaded_img = files.upload() - filename = next(iter(uploaded_img)) - name, filetype = filename.split(".") # todo assumes just one dot in name ! - os.rename(f"{filename}", f"{dest}/{mode}/custom_{name}.{filetype}") - - elif mode == "text_conditional": - w = widgets.Text(value='A cake with cream!', disabled=True) - display.display(w) - - with open(f"{dest}/{mode}/custom_{w.value[:20]}.txt", 'w') as f: - f.write(w.value) - - elif mode == "class_conditional": - w = widgets.IntSlider(min=0, max=1000) - display.display(w) - with open(f"{dest}/{mode}/custom.txt", 'w') as f: - f.write(w.value) - - else: - raise NotImplementedError(f"cond not implemented for mode{mode}") - - -def get_cond_options(mode): - path = "data/example_conditioning" - path = os.path.join(path, mode) - onlyfiles = [f for f in sorted(os.listdir(path))] - return path, onlyfiles - - -def select_cond_path(mode): - path = "data/example_conditioning" # todo - path = os.path.join(path, mode) - onlyfiles = [f for f in sorted(os.listdir(path))] - - selected = widgets.RadioButtons( - options=onlyfiles, - description='Select conditioning:', - disabled=False - ) - display.display(selected) - selected_path = os.path.join(path, selected.value) - return selected_path - - -def get_cond(mode, img): - example = dict() - if mode == "superresolution": - up_f = 4 - # visualize_cond_img(selected_path) - - c = img - c = torch.unsqueeze(torchvision.transforms.ToTensor()(c), 0) - c_up = torchvision.transforms.functional.resize(c, size=[up_f * c.shape[2], up_f * c.shape[3]], antialias=True) - c_up = rearrange(c_up, '1 c h w -> 1 h w c') - c = rearrange(c, '1 c h w -> 1 h w c') - c = 2. * c - 1. - - c = c.to(torch.device("cuda")) - example["LR_image"] = c - example["image"] = c_up - - return example - - -def visualize_cond_img(path): - display.display(ipyimg(filename=path)) - - -def sr_run(model, img, task, custom_steps, eta, resize_enabled=False, classifier_ckpt=None, global_step=None): - # global stride - - example = get_cond(task, img) - - save_intermediate_vid = False - n_runs = 1 - masked = False - guider = None - ckwargs = None - mode = 'ddim' - ddim_use_x0_pred = False - temperature = 1. - eta = eta - make_progrow = True - custom_shape = None - - height, width = example["image"].shape[1:3] - split_input = height >= 128 and width >= 128 - - if split_input: - ks = 128 - stride = 64 - vqf = 4 # - model.split_input_params = {"ks": (ks, ks), "stride": (stride, stride), - "vqf": vqf, - "patch_distributed_vq": True, - "tie_braker": False, - "clip_max_weight": 0.5, - "clip_min_weight": 0.01, - "clip_max_tie_weight": 0.5, - "clip_min_tie_weight": 0.01} - else: - if hasattr(model, "split_input_params"): - delattr(model, "split_input_params") - - invert_mask = False - - x_T = None - for n in range(n_runs): - if custom_shape is not None: - x_T = torch.randn(1, custom_shape[1], custom_shape[2], custom_shape[3]).to(model.device) - x_T = repeat(x_T, '1 c h w -> b c h w', b=custom_shape[0]) - - logs = make_convolutional_sample(example, model, - mode=mode, custom_steps=custom_steps, - eta=eta, swap_mode=False , masked=masked, - invert_mask=invert_mask, quantize_x0=False, - custom_schedule=None, decode_interval=10, - resize_enabled=resize_enabled, custom_shape=custom_shape, - temperature=temperature, noise_dropout=0., - corrector=guider, corrector_kwargs=ckwargs, x_T=x_T, save_intermediate_vid=save_intermediate_vid, - make_progrow=make_progrow,ddim_use_x0_pred=ddim_use_x0_pred - ) - return logs - - -@torch.no_grad() -def convsample_ddim(model, cond, steps, shape, eta=1.0, callback=None, normals_sequence=None, - mask=None, x0=None, quantize_x0=False, img_callback=None, - temperature=1., noise_dropout=0., score_corrector=None, - corrector_kwargs=None, x_T=None, log_every_t=None - ): - - ddim = DDIMSampler(model) - bs = shape[0] # dont know where this comes from but wayne - shape = shape[1:] # cut batch dim - # print(f"Sampling with eta = {eta}; steps: {steps}") - samples, intermediates = ddim.sample(steps, batch_size=bs, shape=shape, conditioning=cond, callback=callback, - normals_sequence=normals_sequence, quantize_x0=quantize_x0, eta=eta, - mask=mask, x0=x0, temperature=temperature, verbose=False, - score_corrector=score_corrector, - corrector_kwargs=corrector_kwargs, x_T=x_T) - - return samples, intermediates - - -@torch.no_grad() -def make_convolutional_sample(batch, model, mode="vanilla", custom_steps=None, eta=1.0, swap_mode=False, masked=False, - invert_mask=True, quantize_x0=False, custom_schedule=None, decode_interval=1000, - resize_enabled=False, custom_shape=None, temperature=1., noise_dropout=0., corrector=None, - corrector_kwargs=None, x_T=None, save_intermediate_vid=False, make_progrow=True,ddim_use_x0_pred=False): - log = dict() - - z, c, x, xrec, xc = model.get_input(batch, model.first_stage_key, - return_first_stage_outputs=True, - force_c_encode=not (hasattr(model, 'split_input_params') - and model.cond_stage_key == 'coordinates_bbox'), - return_original_cond=True) - - log_every_t = 1 if save_intermediate_vid else None - - if custom_shape is not None: - z = torch.randn(custom_shape) - # print(f"Generating {custom_shape[0]} samples of shape {custom_shape[1:]}") - - z0 = None - - log["input"] = x - log["reconstruction"] = xrec - - if ismap(xc): - log["original_conditioning"] = model.to_rgb(xc) - if hasattr(model, 'cond_stage_key'): - log[model.cond_stage_key] = model.to_rgb(xc) - - else: - log["original_conditioning"] = xc if xc is not None else torch.zeros_like(x) - if model.cond_stage_model: - log[model.cond_stage_key] = xc if xc is not None else torch.zeros_like(x) - if model.cond_stage_key =='class_label': - log[model.cond_stage_key] = xc[model.cond_stage_key] - - with model.ema_scope("Plotting"): - t0 = time.time() - img_cb = None - - sample, intermediates = convsample_ddim(model, c, steps=custom_steps, shape=z.shape, - eta=eta, - quantize_x0=quantize_x0, img_callback=img_cb, mask=None, x0=z0, - temperature=temperature, noise_dropout=noise_dropout, - score_corrector=corrector, corrector_kwargs=corrector_kwargs, - x_T=x_T, log_every_t=log_every_t) - t1 = time.time() - - if ddim_use_x0_pred: - sample = intermediates['pred_x0'][-1] - - x_sample = model.decode_first_stage(sample) - - try: - x_sample_noquant = model.decode_first_stage(sample, force_not_quantize=True) - log["sample_noquant"] = x_sample_noquant - log["sample_diff"] = torch.abs(x_sample_noquant - x_sample) - except: - pass - - log["sample"] = x_sample - log["time"] = t1 - t0 - - return log - -sr_diffMode = 'superresolution' -sr_model = get_model('superresolution') - - - - - - -def do_superres(img, filepath): - - if args.sharpen_preset == 'Faster': - sr_diffusion_steps = "25" - sr_pre_downsample = '1/2' - if args.sharpen_preset == 'Fast': - sr_diffusion_steps = "100" - sr_pre_downsample = '1/2' - if args.sharpen_preset == 'Slow': - sr_diffusion_steps = "25" - sr_pre_downsample = 'None' - if args.sharpen_preset == 'Very Slow': - sr_diffusion_steps = "100" - sr_pre_downsample = 'None' - - - sr_post_downsample = 'Original Size' - sr_diffusion_steps = int(sr_diffusion_steps) - sr_eta = 1.0 - sr_downsample_method = 'Lanczos' - - gc.collect() - torch.cuda.empty_cache() - - im_og = img - width_og, height_og = im_og.size - - #Downsample Pre - if sr_pre_downsample == '1/2': - downsample_rate = 2 - elif sr_pre_downsample == '1/4': - downsample_rate = 4 - else: - downsample_rate = 1 - - width_downsampled_pre = width_og//downsample_rate - height_downsampled_pre = height_og//downsample_rate - - if downsample_rate != 1: - # print(f'Downsampling from [{width_og}, {height_og}] to [{width_downsampled_pre}, {height_downsampled_pre}]') - im_og = im_og.resize((width_downsampled_pre, height_downsampled_pre), Image.LANCZOS) - # im_og.save('/content/temp.png') - # filepath = '/content/temp.png' - - logs = sr_run(sr_model["model"], im_og, sr_diffMode, sr_diffusion_steps, sr_eta) - - sample = logs["sample"] - sample = sample.detach().cpu() - sample = torch.clamp(sample, -1., 1.) - sample = (sample + 1.) / 2. * 255 - sample = sample.numpy().astype(np.uint8) - sample = np.transpose(sample, (0, 2, 3, 1)) - a = Image.fromarray(sample[0]) - - #Downsample Post - if sr_post_downsample == '1/2': - downsample_rate = 2 - elif sr_post_downsample == '1/4': - downsample_rate = 4 - else: - downsample_rate = 1 - - width, height = a.size - width_downsampled_post = width//downsample_rate - height_downsampled_post = height//downsample_rate - - if sr_downsample_method == 'Lanczos': - aliasing = Image.LANCZOS - else: - aliasing = Image.NEAREST - - if downsample_rate != 1: - # print(f'Downsampling from [{width}, {height}] to [{width_downsampled_post}, {height_downsampled_post}]') - a = a.resize((width_downsampled_post, height_downsampled_post), aliasing) - elif sr_post_downsample == 'Original Size': - # print(f'Downsampling from [{width}, {height}] to Original Size [{width_og}, {height_og}]') - a = a.resize((width_og, height_og), aliasing) - - display.display(a) - a.save(filepath) - return - print(f'Processing finished!') - # %% +# !! {"metadata": { +# !! "id": "DiffClipSetTop" +# !! }} """ # 2. Diffusion and CLIP model settings """ # %% +# !! {"metadata": { +# !! "id": "ModelSettings" +# !! }} #@markdown ####**Models Settings:** diffusion_model = "512x512_diffusion_uncond_finetune_008100" #@param ["256x256_diffusion_uncond", "512x512_diffusion_uncond_finetune_008100"] use_secondary_model = True #@param {type: 'boolean'} @@ -2275,20 +1783,6 @@ def do_superres(img, filepath): SLIPB16model.load_state_dict(real_sd) SLIPB16model.requires_grad_(False).eval().to(device) - clip_models.append(SLIPB16model) - -if SLIPL16: - SLIPL16model = SLIP_VITL16(ssl_mlp_dim=4096, ssl_emb_dim=256) - if not os.path.exists(f'{model_path}/slip_large_100ep.pt'): - wget("https://dl.fbaipublicfiles.com/slip/slip_large_100ep.pt", model_path) - sd = torch.load(f'{model_path}/slip_large_100ep.pt') - real_sd = {} - for k, v in sd['state_dict'].items(): - real_sd['.'.join(k.split('.')[1:])] = v - del sd - SLIPL16model.load_state_dict(real_sd) - SLIPL16model.requires_grad_(False).eval().to(device) - clip_models.append(SLIPL16model) normalize = T.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711]) @@ -2296,11 +1790,17 @@ def do_superres(img, filepath): # %% +# !! {"metadata": { +# !! "id": "SettingsTop" +# !! }} """ # 3. Settings """ # %% +# !! {"metadata": { +# !! "id": "BasicSettings" +# !! }} #@markdown ####**Basic Settings:** batch_name = 'TimeToDisco' #@param{type: 'string'} steps = 250 #@param [25,50,100,150,250,500,1000]{type: 'raw', allow-input: true} @@ -2340,11 +1840,17 @@ def do_superres(img, filepath): # %% +# !! {"metadata": { +# !! "id": "AnimSetTop" +# !! }} """ ### Animation Settings """ # %% +# !! {"metadata": { +# !! "id": "AnimSettings" +# !! }} #@markdown ####**Animation Mode:** animation_mode = 'None' #@param ['None', '2D', '3D', 'Video Input'] {type:'string'} #@markdown *For animation, you probably want to turn `cutn_batches` to 1 to make it quicker.* @@ -2675,12 +2181,18 @@ def split_prompts(prompts): # %% +# !! {"metadata": { +# !! "id": "ExtraSetTop" +# !! }} """ ### Extra Settings - Partial Saves, Diffusion Sharpening, Advanced Settings, Cutn Scheduling + Partial Saves, Advanced Settings, Cutn Scheduling """ # %% +# !! {"metadata": { +# !! "id": "ExtraSettings" +# !! }} #@markdown ####**Saving:** intermediate_saves = 0#@param{type: 'raw'} @@ -2706,18 +2218,6 @@ def split_prompts(prompts): partialFolder = f'{batchFolder}/partials' createPath(partialFolder) - #@markdown --- - -#@markdown ####**SuperRes Sharpening:** -#@markdown *Sharpen each image using latent-diffusion. Does not run in animation mode. `keep_unsharp` will save both versions.* -sharpen_preset = 'Off' #@param ['Off', 'Faster', 'Fast', 'Slow', 'Very Slow'] -keep_unsharp = True #@param{type: 'boolean'} - -if sharpen_preset != 'Off' and keep_unsharp is True: - unsharpenFolder = f'{batchFolder}/unsharpened' - createPath(unsharpenFolder) - - #@markdown --- #@markdown ####**Advanced Settings:** @@ -2754,12 +2254,18 @@ def split_prompts(prompts): # %% +# !! {"metadata": { +# !! "id": "PromptsTop" +# !! }} """ ### Prompts `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. """ # %% +# !! {"metadata": { +# !! "id": "Prompts" +# !! }} text_prompts = { 0: ["A beautiful painting of a singular lighthouse, shining its light across a tumultuous sea of blood by greg rutkowski and thomas kinkade, Trending on artstation.", "yellow color scheme"], 100: ["This set of prompts start at frame 100","This prompt has weight five:5"], @@ -2771,11 +2277,17 @@ def split_prompts(prompts): # %% +# !! {"metadata": { +# !! "id": "DiffuseTop" +# !! }} """ # 4. Diffuse! """ # %% +# !! {"metadata": { +# !! "id": "DoTheRun" +# !! }} #@title Do the Run! #@markdown `n_batches` ignored with animation modes. display_rate = 50 #@param{type: 'number'} @@ -2872,8 +2384,6 @@ def move_files(start_num, end_num, old_folder, new_folder): 'init_image': init_image, 'init_scale': init_scale, 'skip_steps': skip_steps, - 'sharpen_preset': sharpen_preset, - 'keep_unsharp': keep_unsharp, 'side_x': side_x, 'side_y': side_y, 'timestep_respacing': timestep_respacing, @@ -2960,11 +2470,17 @@ def move_files(start_num, end_num, old_folder, new_folder): # %% +# !! {"metadata": { +# !! "id": "CreateVidTop" +# !! }} """ # 5. Create the video """ # %% +# !! {"metadata": { +# !! "id": "CreateVid" +# !! }} # @title ### **Create video** #@markdown Video file will save in the same folder as your images. From c509aa1b9c00b2323a1fd95c5b0fc667bb12be4c Mon Sep 17 00:00:00 2001 From: MSFTserver Date: Sun, 3 Apr 2022 21:07:35 -0700 Subject: [PATCH 29/74] remove slip --- disco.py | 21 ++------------------- 1 file changed, 2 insertions(+), 19 deletions(-) diff --git a/disco.py b/disco.py index c7001ab2..3e4a56ab 100644 --- a/disco.py +++ b/disco.py @@ -246,6 +246,8 @@ Remove Super Resolution + Remove SLIP Models + ''' ) @@ -439,7 +441,6 @@ def createPath(filepath): if is_colab: gitclone("https://github.com/openai/CLIP") - #gitclone("https://github.com/facebookresearch/SLIP.git") gitclone("https://github.com/crowsonkb/guided-diffusion") gitclone("https://github.com/assafshocher/ResizeRight.git") gitclone("https://github.com/MSFTserver/pytorch3d-lite.git") @@ -468,7 +469,6 @@ def createPath(filepath): import sys import torch -# sys.path.append('./SLIP') sys.path.append('./pytorch3d-lite') sys.path.append('./ResizeRight') sys.path.append('./MiDaS') @@ -496,7 +496,6 @@ def createPath(filepath): sys.path.append('./guided-diffusion') import clip from resize_right import resize -# from models import SLIP_VITB16, SLIP, SLIP_VITL16 from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults from datetime import datetime import numpy as np @@ -1636,8 +1635,6 @@ def forward(self, input, t): RN50x4 = False #@param{type:"boolean"} RN50x16 = False #@param{type:"boolean"} RN50x64 = False #@param{type:"boolean"} -SLIPB16 = False #@param{type:"boolean"} -SLIPL16 = False #@param{type:"boolean"} #@markdown If you're having issues with model downloads, check this to compare SHA's: check_model_SHA = False #@param{type:"boolean"} @@ -1771,20 +1768,6 @@ def forward(self, input, t): if RN50x64 is True: clip_models.append(clip.load('RN50x64', jit=False)[0].eval().requires_grad_(False).to(device)) if RN101 is True: clip_models.append(clip.load('RN101', jit=False)[0].eval().requires_grad_(False).to(device)) -if SLIPB16: - SLIPB16model = SLIP_VITB16(ssl_mlp_dim=4096, ssl_emb_dim=256) - if not os.path.exists(f'{model_path}/slip_base_100ep.pt'): - wget("https://dl.fbaipublicfiles.com/slip/slip_base_100ep.pt", model_path) - sd = torch.load(f'{model_path}/slip_base_100ep.pt') - real_sd = {} - for k, v in sd['state_dict'].items(): - real_sd['.'.join(k.split('.')[1:])] = v - del sd - SLIPB16model.load_state_dict(real_sd) - SLIPB16model.requires_grad_(False).eval().to(device) - - clip_models.append(SLIPL16model) - normalize = T.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711]) lpips_model = lpips.LPIPS(net='vgg').to(device) From bcc6f174a6379419ae64245c54f6e296743dfaa0 Mon Sep 17 00:00:00 2001 From: MSFTserver Date: Sun, 3 Apr 2022 21:56:41 -0700 Subject: [PATCH 30/74] update install to be crossplatform --- Disco_Diffusion.ipynb | 137 ++++++++++++++++++++++-------------------- README.md | 3 +- disco.py | 116 ++++++++++++++++++++--------------- 3 files changed, 142 insertions(+), 114 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 97fea4a2..01e6e25d 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -257,6 +257,8 @@ "\n", " Remove Super Resolution\n", "\n", + " Remove SLIP Models\n", + "\n", " '''\n", " )" ], @@ -366,9 +368,7 @@ }, "source": [ "#@title 1.2 Prepare Folders\n", - "import subprocess\n", - "import sys\n", - "import ipykernel\n", + "import subprocess, os, sys, ipykernel\n", "\n", "def gitclone(url):\n", " res = subprocess.run(['git', 'clone', url], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", @@ -407,7 +407,7 @@ " else:\n", " root_path = '/content'\n", "else:\n", - " root_path = '.'\n", + " root_path = os.getcwd()\n", "\n", "import os\n", "def createPath(filepath):\n", @@ -420,13 +420,13 @@ "\n", "if is_colab:\n", " if google_drive and not save_models_to_google_drive or not google_drive:\n", - " model_path = '/content/model'\n", + " model_path = '/content/models'\n", " createPath(model_path)\n", " if google_drive and save_models_to_google_drive:\n", - " model_path = f'{root_path}/model'\n", + " model_path = f'{root_path}/models'\n", " createPath(model_path)\n", "else:\n", - " model_path = f'{root_path}/model'\n", + " model_path = f'{root_path}/models'\n", " createPath(model_path)\n", "\n", "# libraries = f'{root_path}/libraries'\n", @@ -444,7 +444,7 @@ "source": [ "#@title ### 1.3 Install and import dependencies\n", "\n", - "import pathlib, shutil\n", + "import pathlib, shutil, os, sys\n", "\n", "if not is_colab:\n", " # 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", @@ -458,48 +458,70 @@ " root_path = f'/content'\n", " model_path = '/content/models' \n", "else:\n", - " root_path = f'.'\n", - " model_path = f'{root_path}/model'\n", + " root_path = os.getcwd()\n", + " model_path = f'{root_path}/models'\n", "\n", "model_256_downloaded = False\n", "model_512_downloaded = False\n", "model_secondary_downloaded = False\n", "\n", + "multipip_res = subprocess.run(['pip', 'install', 'lpips', 'datetime', 'timm', 'ftfy', 'einops', 'pytorch-lightning', 'omegaconf'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + "print(multipip_res)\n", + "\n", "if is_colab:\n", - " gitclone(\"https://github.com/openai/CLIP\")\n", - " #gitclone(\"https://github.com/facebookresearch/SLIP.git\")\n", - " gitclone(\"https://github.com/crowsonkb/guided-diffusion\")\n", - " gitclone(\"https://github.com/assafshocher/ResizeRight.git\")\n", - " gitclone(\"https://github.com/MSFTserver/pytorch3d-lite.git\")\n", - " pipie(\"./CLIP\")\n", - " pipie(\"./guided-diffusion\")\n", - " multipip_res = subprocess.run(['pip', 'install', 'lpips', 'datetime', 'timm', 'ftfy'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", - " print(multipip_res)\n", " subprocess.run(['apt', 'install', 'imagemagick'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", - " gitclone(\"https://github.com/isl-org/MiDaS.git\")\n", - " gitclone(\"https://github.com/alembics/disco-diffusion.git\")\n", - " pipi(\"pytorch-lightning\")\n", - " pipi(\"omegaconf\")\n", - " pipi(\"einops\")\n", - " # Rename a file to avoid a name conflict..\n", - " try:\n", - " os.rename(\"MiDaS/utils.py\", \"MiDaS/midas_utils.py\")\n", - " shutil.copyfile(\"disco-diffusion/disco_xform_utils.py\", \"disco_xform_utils.py\")\n", - " except:\n", - " pass\n", "\n", - "if not os.path.exists(f'{model_path}'):\n", - " pathlib.Path(model_path).mkdir(parents=True, exist_ok=True)\n", - "if not os.path.exists(f'{model_path}/dpt_large-midas-2f21e586.pt'):\n", - " wget(\"https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt\", model_path)\n", + "try:\n", + " import clip\n", + "except:\n", + " if os.path.exists(\"CLIP\") is not True:\n", + " gitclone(\"https://github.com/openai/CLIP\")\n", + " sys.path.append(f'{root_path}/CLIP')\n", "\n", - "import sys\n", - "import torch\n", + "try:\n", + " from guided_diffusion.script_util import create_model_and_diffusion\n", + "except:\n", + " if os.path.exists(\"guided-diffusion\") is not True:\n", + " gitclone(\"https://github.com/crowsonkb/guided-diffusion\")\n", + " sys.path.append(f'{PROJECT_DIR}/guided-diffusion')\n", + "\n", + "try:\n", + " from resize_right import resize\n", + "except:\n", + " if os.path.exists(\"resize_right\") is not True:\n", + " gitclone(\"https://github.com/assafshocher/ResizeRight.git\")\n", + " sys.path.append(f'{PROJECT_DIR}/ResizeRight')\n", "\n", - "# sys.path.append('./SLIP')\n", - "sys.path.append('./pytorch3d-lite')\n", - "sys.path.append('./ResizeRight')\n", - "sys.path.append('./MiDaS')\n", + "try:\n", + " import py3d_tools\n", + "except:\n", + " if os.path.exists('pytorch3d-lite') is not True:\n", + " gitclone(\"https://github.com/MSFTserver/pytorch3d-lite.git\")\n", + " sys.path.append(f'{PROJECT_DIR}/pytorch3d-lite')\n", + "\n", + "try:\n", + " from midas.dpt_depth import DPTDepthModel\n", + "except:\n", + " if os.path.exists('MiDaS') is not True:\n", + " gitclone(\"https://github.com/isl-org/MiDaS.git\")\n", + " if os.path.exists('MiDaS/midas_utils.py') is not True:\n", + " shutil.move('MiDaS/utils.py', 'MiDaS/midas_utils.py')\n", + " if not os.path.exists(f'{model_path}/dpt_large-midas-2f21e586.pt'):\n", + " wget(\"https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt\", model_path)\n", + " sys.path.append(f'{PROJECT_DIR}/MiDaS')\n", + "\n", + "try:\n", + " sys.path.append(PROJECT_DIR)\n", + " import disco_xform_utils as dxf\n", + "except:\n", + " if os.path.exists(\"disco-diffusion\") is not True:\n", + " gitclone(\"https://github.com/alembics/disco-diffusion.git\")\n", + " # Rename a file to avoid a name conflict..\n", + " if os.path.exists('disco_xform_utils.py') is not True:\n", + " shutil.move('disco-diffusion/disco_xform_utils.py', 'disco_xform_utils.py')\n", + " sys.path.append(PROJECT_DIR)\n", + "\n", + "import torch\n", "from dataclasses import dataclass\n", "from functools import partial\n", "import cv2\n", @@ -520,11 +542,8 @@ "import torchvision.transforms as T\n", "import torchvision.transforms.functional as TF\n", "from tqdm.notebook import tqdm\n", - "sys.path.append('./CLIP')\n", - "sys.path.append('./guided-diffusion')\n", "import clip\n", "from resize_right import resize\n", - "# from models import SLIP_VITB16, SLIP, SLIP_VITL16\n", "from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults\n", "from datetime import datetime\n", "import numpy as np\n", @@ -549,13 +568,15 @@ "\n", "# AdaBins stuff\n", "if USE_ADABINS:\n", - " if is_colab:\n", - " gitclone(\"https://github.com/shariqfarooq123/AdaBins.git\")\n", - " if not os.path.exists(f'{model_path}/AdaBins_nyu.pt'):\n", - " wget(\"https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt\", model_path)\n", - " pathlib.Path(\"pretrained\").mkdir(parents=True, exist_ok=True)\n", - " shutil.copyfile(f\"{model_path}/AdaBins_nyu.pt\", \"pretrained/AdaBins_nyu.pt\")\n", - " sys.path.append('./AdaBins')\n", + " try:\n", + " from infer import InferenceHelper\n", + " except:\n", + " if os.path.exists(\"AdaBins\") is not True:\n", + " gitclone(\"https://github.com/shariqfarooq123/AdaBins.git\")\n", + " if not path_exists(f'{model_path}/pretrained/AdaBins_nyu.pt'):\n", + " os.makedirs(f'{model_path}/pretrained')\n", + " wget(\"https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt\", f'{model_path}/pretrained')\n", + " sys.path.append(f'{os.getcwd()}/AdaBins')\n", " from infer import InferenceHelper\n", " MAX_ADABINS_AREA = 500000\n", "\n", @@ -1684,8 +1705,6 @@ "RN50x4 = False #@param{type:\"boolean\"}\n", "RN50x16 = False #@param{type:\"boolean\"}\n", "RN50x64 = False #@param{type:\"boolean\"}\n", - "SLIPB16 = False #@param{type:\"boolean\"}\n", - "SLIPL16 = False #@param{type:\"boolean\"}\n", "\n", "#@markdown If you're having issues with model downloads, check this to compare SHA's:\n", "check_model_SHA = False #@param{type:\"boolean\"}\n", @@ -1819,20 +1838,6 @@ "if RN50x64 is True: clip_models.append(clip.load('RN50x64', jit=False)[0].eval().requires_grad_(False).to(device)) \n", "if RN101 is True: clip_models.append(clip.load('RN101', jit=False)[0].eval().requires_grad_(False).to(device)) \n", "\n", - "if SLIPB16:\n", - " SLIPB16model = SLIP_VITB16(ssl_mlp_dim=4096, ssl_emb_dim=256)\n", - " if not os.path.exists(f'{model_path}/slip_base_100ep.pt'):\n", - " wget(\"https://dl.fbaipublicfiles.com/slip/slip_base_100ep.pt\", model_path)\n", - " sd = torch.load(f'{model_path}/slip_base_100ep.pt')\n", - " real_sd = {}\n", - " for k, v in sd['state_dict'].items():\n", - " real_sd['.'.join(k.split('.')[1:])] = v\n", - " del sd\n", - " SLIPB16model.load_state_dict(real_sd)\n", - " SLIPB16model.requires_grad_(False).eval().to(device)\n", - "\n", - " clip_models.append(SLIPL16model)\n", - "\n", "normalize = T.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711])\n", "lpips_model = lpips.LPIPS(net='vgg').to(device)" ], diff --git a/README.md b/README.md index a35472b7..ca0ee582 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,8 @@ A frankensteinian amalgamation of notebooks, models and techniques for the gener * Added video_init_seed_continuity option to make init video animations more continuous * Removed pytorch3d from needing to be compiled with a lite version specifically made for Disco Diffusion * Remove Super Resolution - +* Remove Slip Models +* Update for crossplatform support ## Notebook Provenance diff --git a/disco.py b/disco.py index 3e4a56ab..c7d5b423 100644 --- a/disco.py +++ b/disco.py @@ -345,9 +345,7 @@ # !! "id": "PrepFolders" # !! }} #@title 1.2 Prepare Folders -import subprocess -import sys -import ipykernel +import subprocess, os, sys, ipykernel def gitclone(url): res = subprocess.run(['git', 'clone', url], stdout=subprocess.PIPE).stdout.decode('utf-8') @@ -386,7 +384,7 @@ def wget(url, outputdir): else: root_path = '/content' else: - root_path = '.' + root_path = os.getcwd() import os def createPath(filepath): @@ -399,13 +397,13 @@ def createPath(filepath): if is_colab: if google_drive and not save_models_to_google_drive or not google_drive: - model_path = '/content/model' + model_path = '/content/models' createPath(model_path) if google_drive and save_models_to_google_drive: - model_path = f'{root_path}/model' + model_path = f'{root_path}/models' createPath(model_path) else: - model_path = f'{root_path}/model' + model_path = f'{root_path}/models' createPath(model_path) # libraries = f'{root_path}/libraries' @@ -418,7 +416,7 @@ def createPath(filepath): # !! }} #@title ### 1.3 Install and import dependencies -import pathlib, shutil +import pathlib, shutil, os, sys if not is_colab: # If running locally, there's a good chance your env will need this in order to not crash upon np.matmul() or similar operations. @@ -432,46 +430,70 @@ def createPath(filepath): root_path = f'/content' model_path = '/content/models' else: - root_path = f'.' - model_path = f'{root_path}/model' + root_path = os.getcwd() + model_path = f'{root_path}/models' model_256_downloaded = False model_512_downloaded = False model_secondary_downloaded = False +multipip_res = subprocess.run(['pip', 'install', 'lpips', 'datetime', 'timm', 'ftfy', 'einops', 'pytorch-lightning', 'omegaconf'], stdout=subprocess.PIPE).stdout.decode('utf-8') +print(multipip_res) + if is_colab: - gitclone("https://github.com/openai/CLIP") - gitclone("https://github.com/crowsonkb/guided-diffusion") - gitclone("https://github.com/assafshocher/ResizeRight.git") - gitclone("https://github.com/MSFTserver/pytorch3d-lite.git") - pipie("./CLIP") - pipie("./guided-diffusion") - multipip_res = subprocess.run(['pip', 'install', 'lpips', 'datetime', 'timm', 'ftfy'], stdout=subprocess.PIPE).stdout.decode('utf-8') - print(multipip_res) subprocess.run(['apt', 'install', 'imagemagick'], stdout=subprocess.PIPE).stdout.decode('utf-8') - gitclone("https://github.com/isl-org/MiDaS.git") - gitclone("https://github.com/alembics/disco-diffusion.git") - pipi("pytorch-lightning") - pipi("omegaconf") - pipi("einops") - # Rename a file to avoid a name conflict.. - try: - os.rename("MiDaS/utils.py", "MiDaS/midas_utils.py") - shutil.copyfile("disco-diffusion/disco_xform_utils.py", "disco_xform_utils.py") - except: - pass -if not os.path.exists(f'{model_path}'): - pathlib.Path(model_path).mkdir(parents=True, exist_ok=True) -if not os.path.exists(f'{model_path}/dpt_large-midas-2f21e586.pt'): - wget("https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", model_path) +try: + import clip +except: + if os.path.exists("CLIP") is not True: + gitclone("https://github.com/openai/CLIP") + sys.path.append(f'{root_path}/CLIP') + +try: + from guided_diffusion.script_util import create_model_and_diffusion +except: + if os.path.exists("guided-diffusion") is not True: + gitclone("https://github.com/crowsonkb/guided-diffusion") + sys.path.append(f'{PROJECT_DIR}/guided-diffusion') -import sys -import torch +try: + from resize_right import resize +except: + if os.path.exists("resize_right") is not True: + gitclone("https://github.com/assafshocher/ResizeRight.git") + sys.path.append(f'{PROJECT_DIR}/ResizeRight') -sys.path.append('./pytorch3d-lite') -sys.path.append('./ResizeRight') -sys.path.append('./MiDaS') +try: + import py3d_tools +except: + if os.path.exists('pytorch3d-lite') is not True: + gitclone("https://github.com/MSFTserver/pytorch3d-lite.git") + sys.path.append(f'{PROJECT_DIR}/pytorch3d-lite') + +try: + from midas.dpt_depth import DPTDepthModel +except: + if os.path.exists('MiDaS') is not True: + gitclone("https://github.com/isl-org/MiDaS.git") + if os.path.exists('MiDaS/midas_utils.py') is not True: + shutil.move('MiDaS/utils.py', 'MiDaS/midas_utils.py') + if not os.path.exists(f'{model_path}/dpt_large-midas-2f21e586.pt'): + wget("https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", model_path) + sys.path.append(f'{PROJECT_DIR}/MiDaS') + +try: + sys.path.append(PROJECT_DIR) + import disco_xform_utils as dxf +except: + if os.path.exists("disco-diffusion") is not True: + gitclone("https://github.com/alembics/disco-diffusion.git") + # Rename a file to avoid a name conflict.. + if os.path.exists('disco_xform_utils.py') is not True: + shutil.move('disco-diffusion/disco_xform_utils.py', 'disco_xform_utils.py') + sys.path.append(PROJECT_DIR) + +import torch from dataclasses import dataclass from functools import partial import cv2 @@ -492,8 +514,6 @@ def createPath(filepath): import torchvision.transforms as T import torchvision.transforms.functional as TF from tqdm.notebook import tqdm -sys.path.append('./CLIP') -sys.path.append('./guided-diffusion') import clip from resize_right import resize from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults @@ -520,13 +540,15 @@ def createPath(filepath): # AdaBins stuff if USE_ADABINS: - if is_colab: - gitclone("https://github.com/shariqfarooq123/AdaBins.git") - if not os.path.exists(f'{model_path}/AdaBins_nyu.pt'): - wget("https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt", model_path) - pathlib.Path("pretrained").mkdir(parents=True, exist_ok=True) - shutil.copyfile(f"{model_path}/AdaBins_nyu.pt", "pretrained/AdaBins_nyu.pt") - sys.path.append('./AdaBins') + try: + from infer import InferenceHelper + except: + if os.path.exists("AdaBins") is not True: + gitclone("https://github.com/shariqfarooq123/AdaBins.git") + if not path_exists(f'{model_path}/pretrained/AdaBins_nyu.pt'): + os.makedirs(f'{model_path}/pretrained') + wget("https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt", f'{model_path}/pretrained') + sys.path.append(f'{os.getcwd()}/AdaBins') from infer import InferenceHelper MAX_ADABINS_AREA = 500000 From 0947434ec37df4f7f691536defe6ac00be91d540 Mon Sep 17 00:00:00 2001 From: MSFTserver Date: Sun, 3 Apr 2022 22:45:12 -0700 Subject: [PATCH 31/74] update clip imports and path exists check --- disco.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/disco.py b/disco.py index c7d5b423..2137b020 100644 --- a/disco.py +++ b/disco.py @@ -444,11 +444,11 @@ def createPath(filepath): subprocess.run(['apt', 'install', 'imagemagick'], stdout=subprocess.PIPE).stdout.decode('utf-8') try: - import clip + import CLIP except: if os.path.exists("CLIP") is not True: gitclone("https://github.com/openai/CLIP") - sys.path.append(f'{root_path}/CLIP') + sys.path.append(f'{PROJECT_DIR}/CLIP') try: from guided_diffusion.script_util import create_model_and_diffusion @@ -514,7 +514,7 @@ def createPath(filepath): import torchvision.transforms as T import torchvision.transforms.functional as TF from tqdm.notebook import tqdm -import clip +import CLIP from resize_right import resize from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults from datetime import datetime @@ -545,7 +545,7 @@ def createPath(filepath): except: if os.path.exists("AdaBins") is not True: gitclone("https://github.com/shariqfarooq123/AdaBins.git") - if not path_exists(f'{model_path}/pretrained/AdaBins_nyu.pt'): + if not os.path.exists(f'{model_path}/pretrained/AdaBins_nyu.pt'): os.makedirs(f'{model_path}/pretrained') wget("https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt", f'{model_path}/pretrained') sys.path.append(f'{os.getcwd()}/AdaBins') From 2a2755941044c2dab414aee16df135661e63db0e Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Mon, 4 Apr 2022 13:56:54 -0400 Subject: [PATCH 32/74] Synchronize .ipynb with .py. Apply removal of timestep_respacing and diffusion_steps to .ipynb --- Disco_Diffusion.ipynb | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index df48f196..84c63605 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -2240,8 +2240,7 @@ "use_secondary_model = True #@param {type: 'boolean'}\n", "diffusion_sampling_mode = 'ddim' #@param ['plms','ddim'] \n", "\n", - "timestep_respacing = '250' #@param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000'] \n", - "diffusion_steps = 1000 #@param {type: 'number'}\n", + "\n", "use_checkpoint = True #@param {type: 'boolean'}\n", "ViTB32 = True #@param{type:\"boolean\"}\n", "ViTB16 = True #@param{type:\"boolean\"}\n", @@ -2333,9 +2332,9 @@ " model_config.update({\n", " 'attention_resolutions': '32, 16, 8',\n", " 'class_cond': False,\n", - " 'diffusion_steps': diffusion_steps,\n", + " 'diffusion_steps': 1000, #No need to edit this, it is taken care of later.\n", " 'rescale_timesteps': True,\n", - " 'timestep_respacing': timestep_respacing,\n", + " 'timestep_respacing': 250, #No need to edit this, it is taken care of later.\n", " 'image_size': 512,\n", " 'learn_sigma': True,\n", " 'noise_schedule': 'linear',\n", @@ -2351,9 +2350,9 @@ " model_config.update({\n", " 'attention_resolutions': '32, 16, 8',\n", " 'class_cond': False,\n", - " 'diffusion_steps': diffusion_steps,\n", + " 'diffusion_steps': 1000, #No need to edit this, it is taken care of later.\n", " 'rescale_timesteps': True,\n", - " 'timestep_respacing': timestep_respacing,\n", + " 'timestep_respacing': 250, #No need to edit this, it is taken care of later.\n", " 'image_size': 256,\n", " 'learn_sigma': True,\n", " 'noise_schedule': 'linear',\n", From 246c9524e109d2d03c52746b99f311802e08cb78 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Mon, 4 Apr 2022 14:03:17 -0400 Subject: [PATCH 33/74] Update README.md --- README.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ca0ee582..22e34ebc 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ A frankensteinian amalgamation of notebooks, models and techniques for the gener #### v5 Update: Feb 20th 2022 - gandamu / Adam Letts * Added 3D animation mode. Uses weighted combination of AdaBins and MiDaS depth estimation models. Uses pytorch3d for 3D transforms on Colab and/or Linux. -#### v5.1 Update: Mar 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts / MSFTserver aka HostsServer +#### v5.1 Update: Mar 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts * Integrated Turbo+Smooth features from Disco Diffusion Turbo -- just the implementation, without its defaults. * Implemented resume of turbo animations in such a way that it's now possible to resume from different batch folders and batch numbers. @@ -57,6 +57,13 @@ A frankensteinian amalgamation of notebooks, models and techniques for the gener * Remove Slip Models * Update for crossplatform support +#### v5.1 Update: Apr 4th 2022 - MSFTserver aka HostsServer + +* Removed pytorch3d from needing to be compiled with a lite version specifically made for Disco Diffusion +* Remove Super Resolution +* Remove Slip Models +* Update for crossplatform support + ## Notebook Provenance 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. From 0a2024855de11b885354857f8f3114322b639945 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Mon, 4 Apr 2022 14:10:07 -0400 Subject: [PATCH 34/74] In disco.py, split out new MSFTServer/HostsServer Apr 4th 2022 changes in the changelist notes - and added mention of the crossplatform support update --- disco.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/disco.py b/disco.py index 2137b020..31e61158 100644 --- a/disco.py +++ b/disco.py @@ -230,7 +230,7 @@ IPython magic commands replaced by Python code - v5.1 Update: Mar 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts / MSFTserver aka HostsServer + v5.1 Update: Mar 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts Integrated Turbo+Smooth features from Disco Diffusion Turbo -- just the implementation, without its defaults. @@ -242,12 +242,16 @@ Added video_init_seed_continuity option to make init video animations more continuous + v5.1 Update: Apr 4th 2022 - MSFTserver aka HostsServer + Removed pytorch3d from needing to be compiled with a lite version specifically made for Disco Diffusion Remove Super Resolution Remove SLIP Models + Update for crossplatform support + ''' ) From 483c8281e66048ce551af69db349bc84225bfa34 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Mon, 4 Apr 2022 14:12:38 -0400 Subject: [PATCH 35/74] Adding "update for crossplatform support" to .ipynb for consistency with the readme --- Disco_Diffusion.ipynb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 01e6e25d..7e35c644 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -259,6 +259,8 @@ "\n", " Remove SLIP Models\n", "\n", + " Update for crossplatform support\n", + "\n", " '''\n", " )" ], From 4d0bba9d6d82e6471731d1c51ac414bf8cef09df Mon Sep 17 00:00:00 2001 From: Chris Allen <48918354+zippy731@users.noreply.github.com> Date: Mon, 4 Apr 2022 11:43:38 -0700 Subject: [PATCH 36/74] Don't run Turbo on frame 0 it needs precursors that are not there yet. --- Disco_Diffusion.ipynb | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index c85ca425..3da90f11 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -1100,9 +1100,7 @@ " skip_steps = args.calc_frames_skip_steps\n", "\n", " if args.animation_mode == \"3D\":\n", - " if frame_num == 0:\n", - " pass\n", - " else:\n", + " if frame_num > 0:\n", " seed += 1 \n", " if resume_run and frame_num == start_frame:\n", " img_filepath = batchFolder+f\"/{batch_name}({batchNum})_{start_frame-1:04}.png\"\n", @@ -1413,7 +1411,7 @@ " image.save(f'{batchFolder}/{filename}')\n", " if args.animation_mode == \"3D\":\n", " # If turbo, save a blended image\n", - " if turbo_mode:\n", + " if turbo_mode and frame_num > 0:\n", " # Mix new image with prevFrameScaled\n", " blend_factor = (1)/int(turbo_steps)\n", " newFrame = cv2.imread('prevFrame.png') # This is already updated..\n", @@ -3274,4 +3272,4 @@ }, "nbformat": 4, "nbformat_minor": 4 -} \ No newline at end of file +} From b54ec1e4681ef33b7b1a24b5966fb7b00da33d24 Mon Sep 17 00:00:00 2001 From: Chris Allen <48918354+zippy731@users.noreply.github.com> Date: Mon, 4 Apr 2022 11:46:10 -0700 Subject: [PATCH 37/74] Don't run Turbo on frame 0 it needs precursors that are not there yet. --- disco.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/disco.py b/disco.py index 6345fa0a..b34e403f 100644 --- a/disco.py +++ b/disco.py @@ -1007,9 +1007,7 @@ def do_run(): skip_steps = args.calc_frames_skip_steps if args.animation_mode == "3D": - if frame_num == 0: - pass - else: + if frame_num > 0: seed += 1 if resume_run and frame_num == start_frame: img_filepath = batchFolder+f"/{batch_name}({batchNum})_{start_frame-1:04}.png" @@ -1320,7 +1318,7 @@ def cond_fn(x, t, y=None): image.save(f'{batchFolder}/{filename}') if args.animation_mode == "3D": # If turbo, save a blended image - if turbo_mode: + if turbo_mode and frame_num > 0: # Mix new image with prevFrameScaled blend_factor = (1)/int(turbo_steps) newFrame = cv2.imread('prevFrame.png') # This is already updated.. From a3e0d1f6b41fa002aefdc6007b36715c03bce66d Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Tue, 5 Apr 2022 11:29:08 -0400 Subject: [PATCH 38/74] Apply missed disco.py changes for import changes to .ipynb --- Disco_Diffusion.ipynb | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index c0a455b0..48814e2e 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -444,8 +444,6 @@ "id": "InstallDeps" }, "source": [ - "#@title ### 1.3 Install and import dependencies\n", - "\n", "import pathlib, shutil, os, sys\n", "\n", "if not is_colab:\n", @@ -474,11 +472,11 @@ " subprocess.run(['apt', 'install', 'imagemagick'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", "\n", "try:\n", - " import clip\n", + " import CLIP\n", "except:\n", " if os.path.exists(\"CLIP\") is not True:\n", " gitclone(\"https://github.com/openai/CLIP\")\n", - " sys.path.append(f'{root_path}/CLIP')\n", + " sys.path.append(f'{PROJECT_DIR}/CLIP')\n", "\n", "try:\n", " from guided_diffusion.script_util import create_model_and_diffusion\n", @@ -544,7 +542,7 @@ "import torchvision.transforms as T\n", "import torchvision.transforms.functional as TF\n", "from tqdm.notebook import tqdm\n", - "import clip\n", + "import CLIP\n", "from resize_right import resize\n", "from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults\n", "from datetime import datetime\n", @@ -575,7 +573,7 @@ " except:\n", " if os.path.exists(\"AdaBins\") is not True:\n", " gitclone(\"https://github.com/shariqfarooq123/AdaBins.git\")\n", - " if not path_exists(f'{model_path}/pretrained/AdaBins_nyu.pt'):\n", + " if not os.path.exists(f'{model_path}/pretrained/AdaBins_nyu.pt'):\n", " os.makedirs(f'{model_path}/pretrained')\n", " wget(\"https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt\", f'{model_path}/pretrained')\n", " sys.path.append(f'{os.getcwd()}/AdaBins')\n", From 0a62f25e761ce02900a8a24df2c9cd376979d4ca Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Tue, 5 Apr 2022 11:44:59 -0400 Subject: [PATCH 39/74] Fix import of CLIP --- Disco_Diffusion.ipynb | 4 ++-- disco.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 48814e2e..b56e04d9 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -472,7 +472,7 @@ " subprocess.run(['apt', 'install', 'imagemagick'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", "\n", "try:\n", - " import CLIP\n", + " from CLIP import clip\n", "except:\n", " if os.path.exists(\"CLIP\") is not True:\n", " gitclone(\"https://github.com/openai/CLIP\")\n", @@ -542,7 +542,7 @@ "import torchvision.transforms as T\n", "import torchvision.transforms.functional as TF\n", "from tqdm.notebook import tqdm\n", - "import CLIP\n", + "from CLIP import clip\n", "from resize_right import resize\n", "from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults\n", "from datetime import datetime\n", diff --git a/disco.py b/disco.py index d25daed4..92d712c2 100644 --- a/disco.py +++ b/disco.py @@ -448,7 +448,7 @@ def createPath(filepath): subprocess.run(['apt', 'install', 'imagemagick'], stdout=subprocess.PIPE).stdout.decode('utf-8') try: - import CLIP + from CLIP import clip except: if os.path.exists("CLIP") is not True: gitclone("https://github.com/openai/CLIP") @@ -518,7 +518,7 @@ def createPath(filepath): import torchvision.transforms as T import torchvision.transforms.functional as TF from tqdm.notebook import tqdm -import CLIP +from CLIP import clip from resize_right import resize from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults from datetime import datetime From 0abd40b5843309cc26c93f960c44d8c9e6c5757d Mon Sep 17 00:00:00 2001 From: MSFTserver Date: Tue, 5 Apr 2022 08:54:09 -0700 Subject: [PATCH 40/74] fix titles --- Disco_Diffusion.ipynb | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index b56e04d9..52555440 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -241,7 +241,7 @@ "\n", " IPython magic commands replaced by Python code\n", "\n", - " v5.1 Update: Mar 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts / MSFTserver aka HostsServer\n", + " v5.1 Update: Mar 30th 2022 - zippy / Chris Allen and gandamu / Adam Letts\n", "\n", " Integrated Turbo+Smooth features from Disco Diffusion Turbo -- just the implementation, without its defaults.\n", "\n", @@ -253,6 +253,8 @@ "\n", " Added video_init_seed_continuity option to make init video animations more continuous\n", "\n", + " v5.1 Update: Apr 4th 2022 - MSFTserver aka HostsServer\n", + "\n", " Removed pytorch3d from needing to be compiled with a lite version specifically made for Disco Diffusion\n", "\n", " Remove Super Resolution\n", @@ -444,6 +446,8 @@ "id": "InstallDeps" }, "source": [ + "#@title ### 1.3 Install and import dependencies\n", + "\n", "import pathlib, shutil, os, sys\n", "\n", "if not is_colab:\n", @@ -2683,4 +2687,4 @@ }, "nbformat": 4, "nbformat_minor": 4 -} +} \ No newline at end of file From 753dbeae31939c0f748319feab1719ab69f91b31 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Tue, 5 Apr 2022 12:33:11 -0400 Subject: [PATCH 41/74] Fix AdaBins model installation --- Disco_Diffusion.ipynb | 8 ++++---- disco.py | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 52555440..6c1c809f 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -577,10 +577,10 @@ " except:\n", " if os.path.exists(\"AdaBins\") is not True:\n", " gitclone(\"https://github.com/shariqfarooq123/AdaBins.git\")\n", - " if not os.path.exists(f'{model_path}/pretrained/AdaBins_nyu.pt'):\n", - " os.makedirs(f'{model_path}/pretrained')\n", - " wget(\"https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt\", f'{model_path}/pretrained')\n", - " sys.path.append(f'{os.getcwd()}/AdaBins')\n", + " if not os.path.exists(f'{PROJECT_DIR}/pretrained/AdaBins_nyu.pt'):\n", + " createPath(f'{PROJECT_DIR}/pretrained')\n", + " wget("https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt", f'{PROJECT_DIR}/pretrained')\n", + " sys.path.append(f'{PROJECT_DIR}/AdaBins')\n", " from infer import InferenceHelper\n", " MAX_ADABINS_AREA = 500000\n", "\n", diff --git a/disco.py b/disco.py index 92d712c2..d34383ce 100644 --- a/disco.py +++ b/disco.py @@ -549,10 +549,10 @@ def createPath(filepath): except: if os.path.exists("AdaBins") is not True: gitclone("https://github.com/shariqfarooq123/AdaBins.git") - if not os.path.exists(f'{model_path}/pretrained/AdaBins_nyu.pt'): - os.makedirs(f'{model_path}/pretrained') - wget("https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt", f'{model_path}/pretrained') - sys.path.append(f'{os.getcwd()}/AdaBins') + if not os.path.exists(f'{PROJECT_DIR}/pretrained/AdaBins_nyu.pt'): + createPath(f'{PROJECT_DIR}/pretrained') + wget("https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt", f'{PROJECT_DIR}/pretrained') + sys.path.append(f'{PROJECT_DIR}/AdaBins') from infer import InferenceHelper MAX_ADABINS_AREA = 500000 From 6edc2f2db7881618520bb49ef92b51999e56506a Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Tue, 5 Apr 2022 12:37:13 -0400 Subject: [PATCH 42/74] Correction to double-quote escaping in ipynb --- Disco_Diffusion.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 6c1c809f..3dcc774c 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -579,7 +579,7 @@ " gitclone(\"https://github.com/shariqfarooq123/AdaBins.git\")\n", " if not os.path.exists(f'{PROJECT_DIR}/pretrained/AdaBins_nyu.pt'):\n", " createPath(f'{PROJECT_DIR}/pretrained')\n", - " wget("https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt", f'{PROJECT_DIR}/pretrained')\n", + " wget(\"https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt\", f'{PROJECT_DIR}/pretrained')\n", " sys.path.append(f'{PROJECT_DIR}/AdaBins')\n", " from infer import InferenceHelper\n", " MAX_ADABINS_AREA = 500000\n", From da2cde7d4e0eb63106366b1141fcee2cd9b1c276 Mon Sep 17 00:00:00 2001 From: cansakirt <3201154+cansakirt@users.noreply.github.com> Date: Tue, 5 Apr 2022 15:07:19 -0400 Subject: [PATCH 43/74] fix typo Typo on line 307 that breaks the tutorial table is fixed. --- Disco_Diffusion.ipynb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 3dcc774c..fecc12aa 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -304,7 +304,7 @@ "**Init settings:**\n", "`init_image` | URL or local path | None\n", "`init_scale` | This enhances the effect of the init image, a good value is 1000 | 0\n", - "`skip_steps Controls the starting point along the diffusion timesteps | 0\n", + "`skip_steps` | Controls the starting point along the diffusion timesteps | 0\n", "`perlin_init` | Option to start with random perlin noise | False\n", "`perlin_mode` | ('gray', 'color') | 'mixed'\n", "**Advanced:**\n", @@ -2687,4 +2687,4 @@ }, "nbformat": 4, "nbformat_minor": 4 -} \ No newline at end of file +} From 7bed123ec51b13be145a3454aafc3edaa759d6eb Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Tue, 5 Apr 2022 16:55:06 -0400 Subject: [PATCH 44/74] Fix Video Input mode's ffmpeg subprocess call, and improve imports --- Disco_Diffusion.ipynb | 27 ++++++++++++--------------- disco.py | 23 ++++++++++------------- 2 files changed, 22 insertions(+), 28 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index fecc12aa..d6e96735 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -478,52 +478,49 @@ "try:\n", " from CLIP import clip\n", "except:\n", - " if os.path.exists(\"CLIP\") is not True:\n", + " if not os.path.exists(\"CLIP\"):\n", " gitclone(\"https://github.com/openai/CLIP\")\n", " sys.path.append(f'{PROJECT_DIR}/CLIP')\n", "\n", "try:\n", " from guided_diffusion.script_util import create_model_and_diffusion\n", "except:\n", - " if os.path.exists(\"guided-diffusion\") is not True:\n", + " if not os.path.exists(\"guided-diffusion\"):\n", " gitclone(\"https://github.com/crowsonkb/guided-diffusion\")\n", " sys.path.append(f'{PROJECT_DIR}/guided-diffusion')\n", "\n", "try:\n", " from resize_right import resize\n", "except:\n", - " if os.path.exists(\"resize_right\") is not True:\n", + " if not os.path.exists(\"ResizeRight\"):\n", " gitclone(\"https://github.com/assafshocher/ResizeRight.git\")\n", " sys.path.append(f'{PROJECT_DIR}/ResizeRight')\n", "\n", "try:\n", " import py3d_tools\n", "except:\n", - " if os.path.exists('pytorch3d-lite') is not True:\n", + " if not os.path.exists('pytorch3d-lite'):\n", " gitclone(\"https://github.com/MSFTserver/pytorch3d-lite.git\")\n", " sys.path.append(f'{PROJECT_DIR}/pytorch3d-lite')\n", "\n", "try:\n", " from midas.dpt_depth import DPTDepthModel\n", "except:\n", - " if os.path.exists('MiDaS') is not True:\n", + " if not os.path.exists('MiDaS'):\n", " gitclone(\"https://github.com/isl-org/MiDaS.git\")\n", - " if os.path.exists('MiDaS/midas_utils.py') is not True:\n", + " if not os.path.exists('MiDaS/midas_utils.py'):\n", " shutil.move('MiDaS/utils.py', 'MiDaS/midas_utils.py')\n", " if not os.path.exists(f'{model_path}/dpt_large-midas-2f21e586.pt'):\n", " wget(\"https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt\", model_path)\n", " sys.path.append(f'{PROJECT_DIR}/MiDaS')\n", "\n", "try:\n", - " sys.path.append(PROJECT_DIR)\n", + " sys.path.append(f'{PROJECT_DIR}/disco-diffusion')\n", " import disco_xform_utils as dxf\n", "except:\n", - " if os.path.exists(\"disco-diffusion\") is not True:\n", + " if not os.path.exists(\"disco-diffusion\"):\n", " gitclone(\"https://github.com/alembics/disco-diffusion.git\")\n", - " # Rename a file to avoid a name conflict..\n", - " if os.path.exists('disco_xform_utils.py') is not True:\n", - " shutil.move('disco-diffusion/disco_xform_utils.py', 'disco_xform_utils.py')\n", - " sys.path.append(PROJECT_DIR)\n", + " sys.path.append(f'{PROJECT_DIR}/disco-diffusion')\n", "\n", "import torch\n", "from dataclasses import dataclass\n", @@ -1672,7 +1669,7 @@ " alphas, sigmas = map(partial(append_dims, n=v.ndim), t_to_alpha_sigma(t))\n", " pred = input * alphas - v * sigmas\n", " eps = input * sigmas + v * alphas\n", - " return DiffusionOutput(v, pred, eps)" + " return DiffusionOutput(v, pred, eps)\n" ], "outputs": [], "execution_count": null @@ -1895,7 +1892,7 @@ "\n", "#Make folder for batch\n", "batchFolder = f'{outDirPath}/{batch_name}'\n", - "createPath(batchFolder)" + "createPath(batchFolder)\n" ], "outputs": [], "execution_count": null @@ -1942,7 +1939,7 @@ " f.unlink()\n", " except:\n", " print('')\n", - " vf = f'\"select=not(mod(n\\,{extract_nth_frame}))\"'\n", + " vf = f'select=not(mod(n\\,{extract_nth_frame}))'\n", " subprocess.run(['ffmpeg', '-i', f'{video_init_path}', '-vf', f'{vf}', '-vsync', 'vfr', '-q:v', '2', '-loglevel', 'error', '-stats', f'{videoFramesFolder}/%04d.jpg'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", " #!ffmpeg -i {video_init_path} -vf {vf} -vsync vfr -q:v 2 -loglevel error -stats {videoFramesFolder}/%04d.jpg\n", "\n", diff --git a/disco.py b/disco.py index d34383ce..7087b759 100644 --- a/disco.py +++ b/disco.py @@ -450,52 +450,49 @@ def createPath(filepath): try: from CLIP import clip except: - if os.path.exists("CLIP") is not True: + if not os.path.exists("CLIP"): gitclone("https://github.com/openai/CLIP") sys.path.append(f'{PROJECT_DIR}/CLIP') try: from guided_diffusion.script_util import create_model_and_diffusion except: - if os.path.exists("guided-diffusion") is not True: + if not os.path.exists("guided-diffusion"): gitclone("https://github.com/crowsonkb/guided-diffusion") sys.path.append(f'{PROJECT_DIR}/guided-diffusion') try: from resize_right import resize except: - if os.path.exists("resize_right") is not True: + if not os.path.exists("ResizeRight"): gitclone("https://github.com/assafshocher/ResizeRight.git") sys.path.append(f'{PROJECT_DIR}/ResizeRight') try: import py3d_tools except: - if os.path.exists('pytorch3d-lite') is not True: + if not os.path.exists('pytorch3d-lite'): gitclone("https://github.com/MSFTserver/pytorch3d-lite.git") sys.path.append(f'{PROJECT_DIR}/pytorch3d-lite') try: from midas.dpt_depth import DPTDepthModel except: - if os.path.exists('MiDaS') is not True: + if not os.path.exists('MiDaS'): gitclone("https://github.com/isl-org/MiDaS.git") - if os.path.exists('MiDaS/midas_utils.py') is not True: + if not os.path.exists('MiDaS/midas_utils.py'): shutil.move('MiDaS/utils.py', 'MiDaS/midas_utils.py') if not os.path.exists(f'{model_path}/dpt_large-midas-2f21e586.pt'): wget("https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", model_path) sys.path.append(f'{PROJECT_DIR}/MiDaS') try: - sys.path.append(PROJECT_DIR) + sys.path.append(f'{PROJECT_DIR}/disco-diffusion') import disco_xform_utils as dxf except: - if os.path.exists("disco-diffusion") is not True: + if not os.path.exists("disco-diffusion"): gitclone("https://github.com/alembics/disco-diffusion.git") - # Rename a file to avoid a name conflict.. - if os.path.exists('disco_xform_utils.py') is not True: - shutil.move('disco-diffusion/disco_xform_utils.py', 'disco_xform_utils.py') - sys.path.append(PROJECT_DIR) + sys.path.append(f'{PROJECT_DIR}/disco-diffusion') import torch from dataclasses import dataclass @@ -1884,7 +1881,7 @@ def forward(self, input, t): f.unlink() except: print('') - vf = f'"select=not(mod(n\,{extract_nth_frame}))"' + vf = f'select=not(mod(n\,{extract_nth_frame}))' subprocess.run(['ffmpeg', '-i', f'{video_init_path}', '-vf', f'{vf}', '-vsync', 'vfr', '-q:v', '2', '-loglevel', 'error', '-stats', f'{videoFramesFolder}/%04d.jpg'], stdout=subprocess.PIPE).stdout.decode('utf-8') #!ffmpeg -i {video_init_path} -vf {vf} -vsync vfr -q:v 2 -loglevel error -stats {videoFramesFolder}/%04d.jpg From 45edd374fbb67670982e4d26f9e4fc6c1b101008 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Tue, 5 Apr 2022 21:10:41 -0400 Subject: [PATCH 45/74] Fix disco_xform_utils import --- Disco_Diffusion.ipynb | 6 ++++-- disco.py | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index d6e96735..2f1197e8 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -515,12 +515,14 @@ " sys.path.append(f'{PROJECT_DIR}/MiDaS')\n", "\n", "try:\n", - " sys.path.append(f'{PROJECT_DIR}/disco-diffusion')\n", + " sys.path.append(PROJECT_DIR)\n", " import disco_xform_utils as dxf\n", "except:\n", " if not os.path.exists(\"disco-diffusion\"):\n", " gitclone(\"https://github.com/alembics/disco-diffusion.git\")\n", - " sys.path.append(f'{PROJECT_DIR}/disco-diffusion')\n", + " if os.path.exists('disco_xform_utils.py') is not True:\n", + " shutil.move('disco-diffusion/disco_xform_utils.py', 'disco_xform_utils.py')\n", + " sys.path.append(PROJECT_DIR)\n", "\n", "import torch\n", "from dataclasses import dataclass\n", diff --git a/disco.py b/disco.py index 7087b759..4095f6a7 100644 --- a/disco.py +++ b/disco.py @@ -487,12 +487,14 @@ def createPath(filepath): sys.path.append(f'{PROJECT_DIR}/MiDaS') try: - sys.path.append(f'{PROJECT_DIR}/disco-diffusion') + sys.path.append(PROJECT_DIR) import disco_xform_utils as dxf except: if not os.path.exists("disco-diffusion"): gitclone("https://github.com/alembics/disco-diffusion.git") - sys.path.append(f'{PROJECT_DIR}/disco-diffusion') + if os.path.exists('disco_xform_utils.py') is not True: + shutil.move('disco-diffusion/disco_xform_utils.py', 'disco_xform_utils.py') + sys.path.append(PROJECT_DIR) import torch from dataclasses import dataclass From 6b73eaf8866a5b23d2d87b96fe654ee53e422ece Mon Sep 17 00:00:00 2001 From: MSFTserver Date: Tue, 5 Apr 2022 21:33:39 -0700 Subject: [PATCH 46/74] add compilers --- make_notebook.py | 103 +++++++++++++++++++++++++++++++++++++++++++++++ make_py.py | 48 ++++++++++++++++++++++ 2 files changed, 151 insertions(+) create mode 100644 make_notebook.py create mode 100644 make_py.py diff --git a/make_notebook.py b/make_notebook.py new file mode 100644 index 00000000..a26d2a7d --- /dev/null +++ b/make_notebook.py @@ -0,0 +1,103 @@ +import json +import sys +from os import path + +header_comment = '# %%\n' + +def py2nb(py_str): + # remove leading header comment + if py_str.startswith(header_comment): + py_str = py_str[len(header_comment):] + + cells = [] + chunks = py_str.split('\n\n%s' % header_comment) + + for chunk in chunks: + cell_type = 'code' + new_json = {'metadata':{}} + if chunk.startswith('# !!'): + new_json = json.loads("\n".join([x.strip() for x in chunk.splitlines() if '# !!' in x]).replace('# !!','')) + chunk = "\n".join([x for x in chunk.splitlines() if '# !!' not in x]) + if chunk.startswith("'''"): + chunk = chunk.strip("'\n") + cell_type = 'markdown' + elif chunk.startswith('"""'): + chunk = chunk.strip('"\n') + cell_type = 'markdown' + + cell = { + 'cell_type': cell_type, + 'metadata': new_json['metadata'], + 'source': chunk.splitlines(True), + } + + if cell_type == 'code': + cell.update({'outputs': [], 'execution_count': None}) + + cells.append(cell) + + notebook = { + 'cells': cells, + 'metadata': { + 'anaconda-cloud': {}, + 'accelerator': 'GPU', + 'colab': { + 'collapsed_sections': [ + 'CreditsChTop', + 'TutorialTop', + 'CheckGPU', + 'InstallDeps', + 'DefMidasFns', + 'DefFns', + 'DefSecModel', + 'DefSuperRes', + 'AnimSetTop', + 'ExtraSetTop' + ], + 'machine_shape': 'hm', + 'name': 'Disco Diffusion v5.1 [w/ Turbo]', + 'private_outputs': True, + 'provenance': [], + 'include_colab_link': True + }, + 'kernelspec': { + 'display_name': 'Python 3', + 'language': 'python', + 'name': 'python3' + }, + 'language_info': { + 'codemirror_mode': { + 'name': 'ipython', + 'version': 3 + }, + 'file_extension': '.py', + 'mimetype': 'text/x-python', + 'name': 'python', + 'nbconvert_exporter': 'python', + 'pygments_lexer': 'ipython3', + 'version': '3.6.1' + } + }, + 'nbformat': 4, + 'nbformat_minor': 4 + } + + return notebook + + +def convert(in_file, out_file): + _, in_ext = path.splitext(in_file) + _, out_ext = path.splitext(out_file) + + if in_ext == '.py' and out_ext == '.ipynb': + with open(in_file, 'r', encoding='utf-8') as f: + py_str = f.read() + notebook = py2nb(py_str) + with open(out_file, 'w', encoding='utf-8') as f: + json.dump(notebook, f, indent=2) + + else: + raise(Exception('Extensions must be .ipynb and .py or vice versa')) + + +convert('disco.py', 'Disco_Diffusion.ipynb') diff --git a/make_py.py b/make_py.py new file mode 100644 index 00000000..b952fb09 --- /dev/null +++ b/make_py.py @@ -0,0 +1,48 @@ +import json +import sys +from os import path + +header_comment = '# %%\n' + +def nb2py(notebook): + result = [] + cells = notebook['cells'] + + for cell in cells: + cell_type = cell['cell_type'] + metadata = cell['metadata'] + format_metadata = json.dumps(metadata,indent=2).split("\n") + reformat_metadata = '# !! {"metadata":' + for key in format_metadata: + if key == '{': + reformat_metadata+=f"{key}\n" + elif key == '}': + reformat_metadata+="# !! "+key+"}\n" + else: + reformat_metadata+=f'# !! {key}\n' + + if cell_type == 'markdown': + result.append('%s"""\n%s\n"""'% + (header_comment+reformat_metadata, ''.join(cell['source']))) + + if cell_type == 'code': + result.append("%s%s" % (header_comment+reformat_metadata, ''.join(cell['source']))) + + return '\n\n'.join(result) + +def convert(in_file, out_file): + _, in_ext = path.splitext(in_file) + _, out_ext = path.splitext(out_file) + + if in_ext == '.ipynb' and out_ext == '.py': + with open(in_file, 'r', encoding='utf-8') as f: + notebook = json.load(f) + py_str = nb2py(notebook) + with open(out_file, 'w', encoding='utf-8') as f: + f.write(py_str) + + else: + raise(Exception('Extensions must be .ipynb and .py or vice versa')) + + +convert('Disco_Diffusion.ipynb', 'disco.py') From fa2eff3550dc063ebfe9e6ed913b94efa0e1092e Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Wed, 6 Apr 2022 16:19:31 -0400 Subject: [PATCH 47/74] Allow low-res 3D animations. i.e. upscale for AdaBins --- Disco_Diffusion.ipynb | 34 +++++++++++++++++----------------- disco.py | 30 +++++++++++++++--------------- disco_xform_utils.py | 9 ++++++++- 3 files changed, 40 insertions(+), 33 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 2f1197e8..275821d6 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -296,25 +296,25 @@ "`image_prompts` | Think of these images more as a description of their contents. | N/A\n", "**Image quality:**\n", "`clip_guidance_scale` | Controls how much the image should look like the prompt. | 1000\n", - "`tv_scale` | Controls the smoothness of the final output. | 150\n", - "`range_scale` | Controls how far out of range RGB values are allowed to be. | 150\n", + "`tv_scale` | Controls the smoothness of the final output. | 150\n", + "`range_scale` | Controls how far out of range RGB values are allowed to be. | 150\n", "`sat_scale` | Controls how much saturation is allowed. From nshepperd's JAX notebook. | 0\n", "`cutn` | Controls how many crops to take from the image. | 16\n", - "`cutn_batches` | Accumulate CLIP gradient from multiple batches of cuts | 2\n", + "`cutn_batches` | Accumulate CLIP gradient from multiple batches of cuts. | 2\n", "**Init settings:**\n", - "`init_image` | URL or local path | None\n", - "`init_scale` | This enhances the effect of the init image, a good value is 1000 | 0\n", + "`init_image` | URL or local path | None\n", + "`init_scale` | This enhances the effect of the init image, a good value is 1000 | 0\n", "`skip_steps` | Controls the starting point along the diffusion timesteps | 0\n", - "`perlin_init` | Option to start with random perlin noise | False\n", - "`perlin_mode` | ('gray', 'color') | 'mixed'\n", + "`perlin_init` | Option to start with random perlin noise | False\n", + "`perlin_mode` | ('gray', 'color') | 'mixed'\n", "**Advanced:**\n", - "`skip_augs` |Controls whether to skip torchvision augmentations | False\n", - "`randomize_class` |Controls whether the imagenet class is randomly changed each iteration | True\n", - "`clip_denoised` |Determines whether CLIP discriminates a noisy or denoised image | False\n", - "`clamp_grad` |Experimental: Using adaptive clip grad in the cond_fn | True\n", + "`skip_augs` | Controls whether to skip torchvision augmentations | False\n", + "`randomize_class` | Controls whether the imagenet class is randomly changed each iteration | True\n", + "`clip_denoised` | Determines whether CLIP discriminates a noisy or denoised image | False\n", + "`clamp_grad` | Experimental: Using adaptive clip grad in the cond_fn | True\n", "`seed` | Choose a random seed and print it at end of run for reproduction | random_seed\n", "`fuzzy_prompt` | Controls whether to add multiple noisy prompts to the prompt losses | False\n", - "`rand_mag` |Controls the magnitude of the random noise | 0.1\n", + "`rand_mag` | Controls the magnitude of the random noise | 0.1\n", "`eta` | DDIM hyperparameter | 0.5\n", "\n", "..\n", @@ -325,10 +325,10 @@ "Setting | Description | Default\n", "--- | --- | ---\n", "**Diffusion:**\n", - "`timestep_respacing` | Modify this value to decrease the number of timesteps. | ddim100\n", + "`timestep_respacing` | Modify this value to decrease the number of timesteps. | ddim100\n", "`diffusion_steps` || 1000\n", "**Diffusion:**\n", - "`clip_models` | Models of CLIP to load. Typically the more, the better but they all come at a hefty VRAM cost. | ViT-B/32, ViT-B/16, RN50x4" + "`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" ] }, { @@ -1671,7 +1671,7 @@ " alphas, sigmas = map(partial(append_dims, n=v.ndim), t_to_alpha_sigma(t))\n", " pred = input * alphas - v * sigmas\n", " eps = input * sigmas + v * alphas\n", - " return DiffusionOutput(v, pred, eps)\n" + " return DiffusionOutput(v, pred, eps)" ], "outputs": [], "execution_count": null @@ -1894,7 +1894,7 @@ "\n", "#Make folder for batch\n", "batchFolder = f'{outDirPath}/{batch_name}'\n", - "createPath(batchFolder)\n" + "createPath(batchFolder)" ], "outputs": [], "execution_count": null @@ -2686,4 +2686,4 @@ }, "nbformat": 4, "nbformat_minor": 4 -} +} \ No newline at end of file diff --git a/disco.py b/disco.py index 4095f6a7..5410f9cb 100644 --- a/disco.py +++ b/disco.py @@ -281,25 +281,25 @@ `image_prompts` | Think of these images more as a description of their contents. | N/A **Image quality:** `clip_guidance_scale` | Controls how much the image should look like the prompt. | 1000 -`tv_scale` | Controls the smoothness of the final output. | 150 -`range_scale` | Controls how far out of range RGB values are allowed to be. | 150 +`tv_scale` | Controls the smoothness of the final output. | 150 +`range_scale` | Controls how far out of range RGB values are allowed to be. | 150 `sat_scale` | Controls how much saturation is allowed. From nshepperd's JAX notebook. | 0 `cutn` | Controls how many crops to take from the image. | 16 -`cutn_batches` | Accumulate CLIP gradient from multiple batches of cuts | 2 +`cutn_batches` | Accumulate CLIP gradient from multiple batches of cuts. | 2 **Init settings:** -`init_image` | URL or local path | None -`init_scale` | This enhances the effect of the init image, a good value is 1000 | 0 -`skip_steps Controls the starting point along the diffusion timesteps | 0 -`perlin_init` | Option to start with random perlin noise | False -`perlin_mode` | ('gray', 'color') | 'mixed' +`init_image` | URL or local path | None +`init_scale` | This enhances the effect of the init image, a good value is 1000 | 0 +`skip_steps` | Controls the starting point along the diffusion timesteps | 0 +`perlin_init` | Option to start with random perlin noise | False +`perlin_mode` | ('gray', 'color') | 'mixed' **Advanced:** -`skip_augs` |Controls whether to skip torchvision augmentations | False -`randomize_class` |Controls whether the imagenet class is randomly changed each iteration | True -`clip_denoised` |Determines whether CLIP discriminates a noisy or denoised image | False -`clamp_grad` |Experimental: Using adaptive clip grad in the cond_fn | True +`skip_augs` | Controls whether to skip torchvision augmentations | False +`randomize_class` | Controls whether the imagenet class is randomly changed each iteration | True +`clip_denoised` | Determines whether CLIP discriminates a noisy or denoised image | False +`clamp_grad` | Experimental: Using adaptive clip grad in the cond_fn | True `seed` | Choose a random seed and print it at end of run for reproduction | random_seed `fuzzy_prompt` | Controls whether to add multiple noisy prompts to the prompt losses | False -`rand_mag` |Controls the magnitude of the random noise | 0.1 +`rand_mag` | Controls the magnitude of the random noise | 0.1 `eta` | DDIM hyperparameter | 0.5 .. @@ -310,10 +310,10 @@ Setting | Description | Default --- | --- | --- **Diffusion:** -`timestep_respacing` | Modify this value to decrease the number of timesteps. | ddim100 +`timestep_respacing` | Modify this value to decrease the number of timesteps. | ddim100 `diffusion_steps` || 1000 **Diffusion:** -`clip_models` | Models of CLIP to load. Typically the more, the better but they all come at a hefty VRAM cost. | ViT-B/32, ViT-B/16, RN50x4 +`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 """ # %% diff --git a/disco_xform_utils.py b/disco_xform_utils.py index 9e08a8af..af1cbaa0 100644 --- a/disco_xform_utils.py +++ b/disco_xform_utils.py @@ -12,6 +12,7 @@ sys.exit() MAX_ADABINS_AREA = 500000 +MIN_ADABINS_AREA = 448*448 @torch.no_grad() def transform_image_3d(img_filepath, midas_model, midas_transform, device, rot_mat=torch.eye(3).unsqueeze(0), translate=(0.,0.,-0.04), near=2000, far=20000, fov_deg=60, padding_mode='border', sampling_mode='bicubic', midas_weight = 0.3): @@ -33,11 +34,17 @@ def transform_image_3d(img_filepath, midas_model, midas_transform, device, rot_m if image_pil_area > MAX_ADABINS_AREA: scale = math.sqrt(MAX_ADABINS_AREA) / math.sqrt(image_pil_area) depth_input = img_pil.resize((int(w*scale), int(h*scale)), Image.LANCZOS) # LANCZOS is supposed to be good for downsampling. + elif image_pil_area < MIN_ADABINS_AREA: + scale = math.sqrt(MIN_ADABINS_AREA) / math.sqrt(image_pil_area) + depth_input = img_pil.resize((int(w*scale), int(h*scale)), Image.BICUBIC) else: depth_input = img_pil try: _, adabins_depth = infer_helper.predict_pil(depth_input) - adabins_depth = torchvision.transforms.functional.resize(torch.from_numpy(adabins_depth), image_tensor.shape[-2:], interpolation=torchvision.transforms.functional.InterpolationMode.BICUBIC).squeeze().to(device) + if image_pil_area != MAX_ADABINS_AREA: + adabins_depth = torchvision.transforms.functional.resize(torch.from_numpy(adabins_depth), image_tensor.shape[-2:], interpolation=torchvision.transforms.functional.InterpolationMode.BICUBIC).squeeze().to(device) + else: + adabins_depth = torch.from_numpy(adabins_depth).squeeze().to(device) adabins_depth_np = adabins_depth.cpu().numpy() except: pass From 8108d615ec6ce1baff7b42cff07a7f83c4024cb7 Mon Sep 17 00:00:00 2001 From: Chris Allen <48918354+zippy731@users.noreply.github.com> Date: Thu, 7 Apr 2022 10:09:07 -0700 Subject: [PATCH 48/74] Update Tutorial Section add links to guide and discord --- Disco_Diffusion.ipynb | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 275821d6..483a783e 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -286,8 +286,14 @@ "source": [ "**Diffusion settings (Defaults are heavily outdated)**\n", "---\n", + "\n", + "Disco Diffusion is complex, and continually evolving with new features. The most current documentation on on Disco Diffusion settings can be found in the unofficial guidebook:\n", + "\n", + "[Zippy's Disco Diffusion Cheatsheet](https://docs.google.com/document/d/1l8s7uS2dGqjztYSjPpzlmXLjl5PM3IGkRWI3IiCuK7g/edit)\n", "\n", - "This section is outdated as of v2\n", + "We also encourage users to join the [Disco Diffusion User Discord](https://discord.gg/XGZrFFCRfN) to learn from the active user community." + "\n", + "This section below is outdated as of v2\n", "\n", "Setting | Description | Default\n", "--- | --- | ---\n", @@ -2686,4 +2692,4 @@ }, "nbformat": 4, "nbformat_minor": 4 -} \ No newline at end of file +} From 07f6a5ba3961b01a79e6680ca16ee35cb29e8df5 Mon Sep 17 00:00:00 2001 From: Chris Allen <48918354+zippy731@users.noreply.github.com> Date: Thu, 7 Apr 2022 10:10:30 -0700 Subject: [PATCH 49/74] Update tutorial section add links to zippy guide and discord --- Disco_Diffusion.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 483a783e..d2e1c782 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -291,7 +291,7 @@ "\n", "[Zippy's Disco Diffusion Cheatsheet](https://docs.google.com/document/d/1l8s7uS2dGqjztYSjPpzlmXLjl5PM3IGkRWI3IiCuK7g/edit)\n", "\n", - "We also encourage users to join the [Disco Diffusion User Discord](https://discord.gg/XGZrFFCRfN) to learn from the active user community." + "We also encourage users to join the [Disco Diffusion User Discord](https://discord.gg/XGZrFFCRfN) to learn from the active user community.", "\n", "This section below is outdated as of v2\n", "\n", From e619691b5e732da7e4a95a1a7dfce0b282bface8 Mon Sep 17 00:00:00 2001 From: Chris Allen <48918354+zippy731@users.noreply.github.com> Date: Thu, 7 Apr 2022 10:13:25 -0700 Subject: [PATCH 50/74] Update Tutorial Section add links to guide and discord --- disco.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/disco.py b/disco.py index 5410f9cb..34bc59ba 100644 --- a/disco.py +++ b/disco.py @@ -271,8 +271,13 @@ """ **Diffusion settings (Defaults are heavily outdated)** --- +Disco Diffusion is complex, and continually evolving with new features. The most current documentation on on Disco Diffusion settings can be found in the unofficial guidebook: -This section is outdated as of v2 +[Zippy's Disco Diffusion Cheatsheet](https://docs.google.com/document/d/1l8s7uS2dGqjztYSjPpzlmXLjl5PM3IGkRWI3IiCuK7g/edit) + +We also encourage users to join the [Disco Diffusion User Discord](https://discord.gg/XGZrFFCRfN) to learn from the active user community. + +This section below is outdated as of v2 Setting | Description | Default --- | --- | --- From e4754e6a42743448fddd0c9a4d81c906ebd48456 Mon Sep 17 00:00:00 2001 From: Tom Mason Date: Fri, 8 Apr 2022 11:35:26 +0100 Subject: [PATCH 51/74] VR modifications for stereo 180 frames and spherical projection in utils --- Disco_Diffusion.ipynb | 68 ++++++++++++++++++++++++++++++++++++++----- disco_xform_utils.py | 20 +++++++++++-- 2 files changed, 78 insertions(+), 10 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index d2e1c782..67b41d9b 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -286,13 +286,13 @@ "source": [ "**Diffusion settings (Defaults are heavily outdated)**\n", "---\n", - "\n", - "Disco Diffusion is complex, and continually evolving with new features. The most current documentation on on Disco Diffusion settings can be found in the unofficial guidebook:\n", - "\n", + "\n", + "Disco Diffusion is complex, and continually evolving with new features. The most current documentation on on Disco Diffusion settings can be found in the unofficial guidebook:\n", + "\n", "[Zippy's Disco Diffusion Cheatsheet](https://docs.google.com/document/d/1l8s7uS2dGqjztYSjPpzlmXLjl5PM3IGkRWI3IiCuK7g/edit)\n", "\n", - "We also encourage users to join the [Disco Diffusion User Discord](https://discord.gg/XGZrFFCRfN) to learn from the active user community.", - "\n", + "We also encourage users to join the [Disco Diffusion User Discord](https://discord.gg/XGZrFFCRfN) to learn from the active user community.\n", + "\n", "This section below is outdated as of v2\n", "\n", "Setting | Description | Default\n", @@ -1423,11 +1423,30 @@ " cv2.imwrite(f'{batchFolder}/{filename}',blendedImage)\n", " else:\n", " image.save(f'{batchFolder}/{filename}')\n", + " \n", + " if vr_mode:\n", + " generate_eye_views(trans_scale,batchFolder,filename,frame_num,midas_model, midas_transform)\n", + " \n", " # if frame_num != args.max_frames-1:\n", " # display.clear_output()\n", " \n", " plt.plot(np.array(loss_values), 'r')\n", "\n", + "def generate_eye_views(trans_scale,batchFolder,filename,frame_num,midas_model, midas_transform):\n", + " for i in range(2):\n", + " theta = vr_eye_angle * (math.pi/180)\n", + " ray_origin = math.cos(theta) * vr_ipd / 2 * (-1.0 if i==0 else 1.0)\n", + " ray_rotation = (theta if i==0 else -theta)\n", + " translate_xyz = [-(ray_origin)*trans_scale, 0,0]\n", + " rotate_xyz = [0, (ray_rotation), 0]\n", + " rot_mat = p3dT.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), \"XYZ\").unsqueeze(0)\n", + " transformed_image = dxf.transform_image_3d(f'{batchFolder}/{filename}', midas_model, midas_transform, DEVICE,\n", + " rot_mat, translate_xyz, args.near_plane, args.far_plane,\n", + " args.fov, padding_mode=args.padding_mode,\n", + " sampling_mode=args.sampling_mode, midas_weight=args.midas_weight,spherical=True)\n", + " eye_file_path = batchFolder+f\"/frame_{frame_num-1:04}\" + ('_l' if i==0 else '_r')+'.png'\n", + " transformed_image.save(eye_file_path)\n", + "\n", "def save_settings():\n", " setting_list = {\n", " 'text_prompts': text_prompts,\n", @@ -1693,9 +1712,11 @@ }, { "cell_type": "code", + "execution_count": null, "metadata": { "id": "ModelSettings" }, + "outputs": [], "source": [ "#@markdown ####**Models Settings:**\n", "diffusion_model = \"512x512_diffusion_uncond_finetune_008100\" #@param [\"256x256_diffusion_uncond\", \"512x512_diffusion_uncond_finetune_008100\"]\n", @@ -2008,6 +2029,31 @@ "frames_skip_steps = '60%' #@param ['40%', '50%', '60%', '70%', '80%'] {type: 'string'}\n", "\n", "\n", + "#======= VR MODE\n", + "#@markdown ---\n", + "#@markdown ####**VR Mode (3D anim only):**\n", + "#@markdown Enables stereo rendering of left/right eye views (supporting Turbo) which use a different (fish-eye) camera projection matrix. \n", + "#@markdown Note the images you're prompting will work better if they have some inherent wide-angle aspect\n", + "#@markdown The generated images will need to be combined into left/right videos. These can then be stitched into the VR180 format.\n", + "#@markdown Google made the VR180 Creator tool but subsequently stopped supporting it. It's available for download in a few places including https://www.patrickgrunwald.de/vr180-creator-download\n", + "#@markdown The tool is not only good for stitching (videos and photos) but also for adding the correct metadata into existing videos, which is needed for services like YouTube to identify the format correctly.\n", + "#@markdown Watching YouTube VR videos isn't necessarily the easiest depending on your headset. For instance Oculus have a dedicated media studio and store which makes the files easier to access on a Quest https://creator.oculus.com/manage/mediastudio/\n", + "#@markdown The command to get ffmpeg to concat your frames for each eye is in the form: ffmpeg -framerate 15 -i frame_%4d_l.png l.mp4 (repeat for r)", + "\n", + "vr_mode = False\n", + "vr_eye_angle:0.5, #@param{type: 'number'}\n", + "#@markdown eye_angle is the y-axis rotation of the eyes towards the center\n", + "vr_ipd:5.0,\n", + "#@markdown interpupillary distance (between the eyes)\n", + " \n", + "#insist turbo be used only w 3d anim.\n", + "if vr_mode and animation_mode != '3D':\n", + " print('=====')\n", + " print('VR mode only available with 3D animations. Disabling VR.')\n", + " print('=====')\n", + " turbo_mode = False\n", + "\n", + "\n", "def parse_key_frames(string, prompt_parser=None):\n", " \"\"\"Given a string representing frame numbers paired with parameter values at that frame,\n", " return a dictionary with the frame numbers as keys and the parameter values as the values.\n", @@ -2341,9 +2387,11 @@ }, { "cell_type": "code", + "execution_count": null, "metadata": { "id": "Prompts" }, + "outputs": [], "source": [ "text_prompts = {\n", " 0: [\"A beautiful painting of a singular lighthouse, shining its light across a tumultuous sea of blood by greg rutkowski and thomas kinkade, Trending on artstation.\", \"yellow color scheme\"],\n", @@ -2368,9 +2416,11 @@ }, { "cell_type": "code", + "execution_count": null, "metadata": { "id": "DoTheRun" }, + "outputs": [], "source": [ "#@title Do the Run!\n", "#@markdown `n_batches` ignored with animation modes.\n", @@ -2566,9 +2616,11 @@ }, { "cell_type": "code", + "execution_count": null, "metadata": { "id": "CreateVid" }, + "outputs": [], "source": [ "# @title ### **Create video**\n", "#@markdown Video file will save in the same folder as your images.\n", @@ -2651,8 +2703,8 @@ } ], "metadata": { - "anaconda-cloud": {}, "accelerator": "GPU", + "anaconda-cloud": {}, "colab": { "collapsed_sections": [ "CreditsChTop", @@ -2666,11 +2718,11 @@ "AnimSetTop", "ExtraSetTop" ], + "include_colab_link": true, "machine_shape": "hm", "name": "Disco Diffusion v5.1 [w/ Turbo]", "private_outputs": true, - "provenance": [], - "include_colab_link": true + "provenance": [] }, "kernelspec": { "display_name": "Python 3", diff --git a/disco_xform_utils.py b/disco_xform_utils.py index af1cbaa0..107b6024 100644 --- a/disco_xform_utils.py +++ b/disco_xform_utils.py @@ -15,7 +15,7 @@ MIN_ADABINS_AREA = 448*448 @torch.no_grad() -def transform_image_3d(img_filepath, midas_model, midas_transform, device, rot_mat=torch.eye(3).unsqueeze(0), translate=(0.,0.,-0.04), near=2000, far=20000, fov_deg=60, padding_mode='border', sampling_mode='bicubic', midas_weight = 0.3): +def transform_image_3d(img_filepath, midas_model, midas_transform, device, rot_mat=torch.eye(3).unsqueeze(0), translate=(0.,0.,-0.04), near=2000, far=20000, fov_deg=60, padding_mode='border', sampling_mode='bicubic', midas_weight = 0.3,spherical=False): img_pil = Image.open(open(img_filepath, 'rb')).convert('RGB') w, h = img_pil.size image_tensor = torchvision.transforms.functional.to_tensor(img_pil).to(device) @@ -107,9 +107,25 @@ def transform_image_3d(img_filepath, midas_model, midas_transform, device, rot_m # coords_2d will have shape (N,H,W,2).. which is also what grid_sample needs. coords_2d = torch.nn.functional.affine_grid(identity_2d_batch, [1,1,h,w], align_corners=False) offset_coords_2d = coords_2d - torch.reshape(offset_xy, (h,w,2)).unsqueeze(0) - new_image = torch.nn.functional.grid_sample(image_tensor.add(1/512 - 0.0001).unsqueeze(0), offset_coords_2d, mode=sampling_mode, padding_mode=padding_mode, align_corners=False) + + if spherical: + spherical_grid = get_spherical_projection(h, w, torch.tensor([0,0], device=device), -0.4,device=device)#align_corners=False + stage_image = torch.nn.functional.grid_sample(image_tensor.add(1/512 - 0.0001).unsqueeze(0), offset_coords_2d, mode=sampling_mode, padding_mode=padding_mode, align_corners=True) + new_image = torch.nn.functional.grid_sample(stage_image, spherical_grid,align_corners=True) #, mode=sampling_mode, padding_mode=padding_mode, align_corners=False) + else: + new_image = torch.nn.functional.grid_sample(image_tensor.add(1/512 - 0.0001).unsqueeze(0), offset_coords_2d, mode=sampling_mode, padding_mode=padding_mode, align_corners=False) + img_pil = torchvision.transforms.ToPILImage()(new_image.squeeze().clamp(0,1.)) torch.cuda.empty_cache() return img_pil + +def get_spherical_projection(H, W, center, magnitude,device): + xx, yy = torch.linspace(-1, 1, W,dtype=torch.float32,device=device), torch.linspace(-1, 1, H,dtype=torch.float32,device=device) + gridy, gridx = torch.meshgrid(yy, xx) + grid = torch.stack([gridx, gridy], dim=-1) + d = center - grid + d_sum = torch.sqrt((d**2).sum(axis=-1)) + grid += d * d_sum.unsqueeze(-1) * magnitude + return grid.unsqueeze(0) \ No newline at end of file From b679a5d6a2e5e0539ba74b41272d126816be2f3a Mon Sep 17 00:00:00 2001 From: Mike Howles Date: Sat, 9 Apr 2022 19:33:24 +0000 Subject: [PATCH 52/74] Add Dockerfiles --- .gitignore | 146 +++++++++++++++++++++++++++++++++++++++++ docker/README.md | 47 +++++++++++++ docker/main/Dockerfile | 40 +++++++++++ docker/prep/Dockerfile | 25 +++++++ 4 files changed, 258 insertions(+) create mode 100644 .gitignore create mode 100644 docker/README.md create mode 100644 docker/main/Dockerfile create mode 100644 docker/prep/Dockerfile diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..17f21111 --- /dev/null +++ b/.gitignore @@ -0,0 +1,146 @@ +# Disco-specfic ignores +init_images/* +images_out/* +MiDaS/ +models/ +pretrained/* +settings.json + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ diff --git a/docker/README.md b/docker/README.md new file mode 100644 index 00000000..3e3e90f0 --- /dev/null +++ b/docker/README.md @@ -0,0 +1,47 @@ +# Docker + +## Introduction + +This is a Docker build file that will preinstall dependencies, packages, Git repos, and pre-cache the large model files needed by Disco Diffusion. + +## TO-DO: + +- Make container actually accept parameters on run. Right now you'll just be seeing lighthouses. + +## Change Log + +- `1.0` + + Initial build file created based on the DD 5.1 Git repo. This initial build is deliberately meant to work touch-free of any of the existing Python code written. It does handle some of the pre-setup tasks already done in the Python code such as pip packages, Git clones, and even pre-caching the model files for faster launch speed. + +## Build the Prep Image +The prep image is broken out from the `main` folder's `Dockerfile` to help with long build context times (or wget download times after intitial build.) This prep image build contains all the large model files required by Disco Diffusion. + +From a terminal in the `docker/prep` directory, run: +```sh +docker build -t disco-diffusion-prep:5.1 . +``` +From a terminal in the `docker/main` directory, run: +## Build the Image +From a terminal, run: + +```sh +docker build -t disco-diffusion:5.1 . +``` + +## Run as a Container + +This example runs Disco Diffusion in a Docker container. It maps `images_out` and `init_images` to the container's working directory to access by the host OS. +```sh +docker run --rm -it \ + -v $(echo ~)/disco-diffusion/images_out:/workspace/code/images_out \ + -v $(echo ~)/disco-diffusion/init_images:/workspace/code/init_images \ + --gpus=all \ + --name="disco-diffusion" --ipc=host \ + --user $(id -u):$(id -g) \ +disco-diffusion:5.1 python disco-diffusion/disco.py +``` + +## Passing Parameters + +This will be added after conferring with repo authors. \ No newline at end of file diff --git a/docker/main/Dockerfile b/docker/main/Dockerfile new file mode 100644 index 00000000..63b9d65b --- /dev/null +++ b/docker/main/Dockerfile @@ -0,0 +1,40 @@ +# Model prep phase, also cuts down on build context wait time since these models files +# are large and prone to take long to copy... +FROM disco-diffusion-prep:5.1 AS modelprep + +FROM nvcr.io/nvidia/pytorch:21.08-py3 + +ENV PYTHONDONTWRITEBYTECODE 1 +ENV PYTHONUNBUFFERED 1 + +# Install a few dependencies +RUN apt update +RUN DEBIAN_FRONTEND=noninteractive TZ=Etc/UTC apt-get -y install -y tzdata imagemagick + +# Create a disco user +RUN useradd -ms /bin/bash disco +USER disco + +# Set up code directory +RUN mkdir code +WORKDIR /workspace/code + +# Copy over models used +COPY --from=modelprep /scratch/models /workspace/code/models +COPY --from=modelprep /scratch/pretrained /workspace/code/pretrained + +# Clone Git repositories +RUN git clone https://github.com/alembics/disco-diffusion.git && \ + git clone https://github.com/openai/CLIP && \ + git clone https://github.com/assafshocher/ResizeRight.git && \ + git clone https://github.com/MSFTserver/pytorch3d-lite.git && \ + git clone https://github.com/isl-org/MiDaS.git && \ + git clone https://github.com/crowsonkb/guided-diffusion.git && \ + git clone https://github.com/shariqfarooq123/AdaBins.git + +# Install Python packages +RUN pip install imageio imageio-ffmpeg==0.4.4 pyspng==0.1.0 lpips datetime timm ipywidgets omegaconf>=2.0.0 pytorch-lightning>=1.0.8 torch-fidelity einops wandb pandas ftfy + +# Precache other big files +COPY --chown=disco --from=modelprep /scratch/clip /home/disco/.cache/clip +COPY --chown=disco --from=modelprep /scratch/model-lpips/vgg16-397923af.pth /home/disco/.cache/torch/hub/checkpoints/vgg16-397923af.pth \ No newline at end of file diff --git a/docker/prep/Dockerfile b/docker/prep/Dockerfile new file mode 100644 index 00000000..414a8d22 --- /dev/null +++ b/docker/prep/Dockerfile @@ -0,0 +1,25 @@ +FROM nvcr.io/nvidia/pytorch:21.08-py3 AS prep + RUN mkdir -p /scratch/models && \ + mkdir -p /scratch/models/superres && \ + mkdir -p /scratch/models/slip && \ + mkdir -p /scratch/model-lpips && \ + mkdir -p /scratch/clip && \ + mkdir -p /scratch/pretrained + + RUN wget --progress=bar:force:noscroll -P /scratch/model-lpips https://download.pytorch.org/models/vgg16-397923af.pth + + RUN wget --no-directories --progress=bar:force:noscroll -P /scratch/models https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt + RUN wget --no-directories --progress=bar:force:noscroll -P /scratch/models https://v-diffusion.s3.us-west-2.amazonaws.com/512x512_diffusion_uncond_finetune_008100.pt + RUN wget --no-directories --progress=bar:force:noscroll -P /scratch/models https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt + RUN wget --no-directories --progress=bar:force:noscroll -P /scratch/models https://v-diffusion.s3.us-west-2.amazonaws.com/secondary_model_imagenet_2.pth + + RUN wget --no-directories --progress=bar:force:noscroll -P /scratch/pretrained https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt + + RUN wget --no-directories --progress=bar:force:noscroll -P /scratch/clip/ https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt + RUN wget --no-directories --progress=bar:force:noscroll -P /scratch/clip https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt + RUN wget --no-directories --progress=bar:force:noscroll -P /scratch/clip https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt + RUN wget --no-directories --progress=bar:force:noscroll -P /scratch/clip https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt + RUN wget --no-directories --progress=bar:force:noscroll -P /scratch/clip https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt + RUN wget --no-directories --progress=bar:force:noscroll -P /scratch/clip https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt + RUN wget --no-directories --progress=bar:force:noscroll -P /scratch/clip https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt + RUN wget --no-directories --progress=bar:force:noscroll -P /scratch/clip https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt From 9363c24b893eaf23521041278dad1ab0935e52bf Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Sat, 9 Apr 2022 22:47:40 -0400 Subject: [PATCH 53/74] Bugfixes to the VR PR. It looks like it wouldn't have run successfully. Need to look into trans_scale and a couple values that had bad syntax. Also ported the changes to disco.py --- Disco_Diffusion.ipynb | 36 ++++++++++++++------------------- disco.py | 47 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 21 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 67b41d9b..7d6e205b 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -286,7 +286,6 @@ "source": [ "**Diffusion settings (Defaults are heavily outdated)**\n", "---\n", - "\n", "Disco Diffusion is complex, and continually evolving with new features. The most current documentation on on Disco Diffusion settings can be found in the unofficial guidebook:\n", "\n", "[Zippy's Disco Diffusion Cheatsheet](https://docs.google.com/document/d/1l8s7uS2dGqjztYSjPpzlmXLjl5PM3IGkRWI3IiCuK7g/edit)\n", @@ -1423,10 +1422,12 @@ " cv2.imwrite(f'{batchFolder}/{filename}',blendedImage)\n", " else:\n", " image.save(f'{batchFolder}/{filename}')\n", - " \n", + "\n", + " # TODO(VR): trans_scale wasn't set in the PR. This needs to be set to a reasonable value!\n", + " trans_scale = 1.0\n", " if vr_mode:\n", - " generate_eye_views(trans_scale,batchFolder,filename,frame_num,midas_model, midas_transform)\n", - " \n", + " generate_eye_views(trans_scale, batchFolder, filename, frame_num, midas_model, midas_transform)\n", + "\n", " # if frame_num != args.max_frames-1:\n", " # display.clear_output()\n", " \n", @@ -1712,11 +1713,9 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "id": "ModelSettings" }, - "outputs": [], "source": [ "#@markdown ####**Models Settings:**\n", "diffusion_model = \"512x512_diffusion_uncond_finetune_008100\" #@param [\"256x256_diffusion_uncond\", \"512x512_diffusion_uncond_finetune_008100\"]\n", @@ -2028,24 +2027,25 @@ "#@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", "frames_skip_steps = '60%' #@param ['40%', '50%', '60%', '70%', '80%'] {type: 'string'}\n", "\n", - "\n", "#======= VR MODE\n", "#@markdown ---\n", "#@markdown ####**VR Mode (3D anim only):**\n", + "#@markdown EXPERIMENTAL ALPHA: Need to look into trans_scale value\n", "#@markdown Enables stereo rendering of left/right eye views (supporting Turbo) which use a different (fish-eye) camera projection matrix. \n", "#@markdown Note the images you're prompting will work better if they have some inherent wide-angle aspect\n", "#@markdown The generated images will need to be combined into left/right videos. These can then be stitched into the VR180 format.\n", "#@markdown Google made the VR180 Creator tool but subsequently stopped supporting it. It's available for download in a few places including https://www.patrickgrunwald.de/vr180-creator-download\n", "#@markdown The tool is not only good for stitching (videos and photos) but also for adding the correct metadata into existing videos, which is needed for services like YouTube to identify the format correctly.\n", "#@markdown Watching YouTube VR videos isn't necessarily the easiest depending on your headset. For instance Oculus have a dedicated media studio and store which makes the files easier to access on a Quest https://creator.oculus.com/manage/mediastudio/\n", - "#@markdown The command to get ffmpeg to concat your frames for each eye is in the form: ffmpeg -framerate 15 -i frame_%4d_l.png l.mp4 (repeat for r)", + "#@markdown The command to get ffmpeg to concat your frames for each eye is in the form: ffmpeg -framerate 15 -i frame_%4d_l.png l.mp4 (repeat for r)\n", "\n", + "# TODO(VR): vr_eye_angle and vr_ipd lines had syntax errors in initial PR. Are they OK?\n", "vr_mode = False\n", - "vr_eye_angle:0.5, #@param{type: 'number'}\n", + "vr_eye_angle = 0.5 #@param{type: 'number'}\n", "#@markdown eye_angle is the y-axis rotation of the eyes towards the center\n", - "vr_ipd:5.0,\n", + "vr_ipd = 5.0\n", "#@markdown interpupillary distance (between the eyes)\n", - " \n", + "\n", "#insist turbo be used only w 3d anim.\n", "if vr_mode and animation_mode != '3D':\n", " print('=====')\n", @@ -2387,11 +2387,9 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "id": "Prompts" }, - "outputs": [], "source": [ "text_prompts = {\n", " 0: [\"A beautiful painting of a singular lighthouse, shining its light across a tumultuous sea of blood by greg rutkowski and thomas kinkade, Trending on artstation.\", \"yellow color scheme\"],\n", @@ -2416,11 +2414,9 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "id": "DoTheRun" }, - "outputs": [], "source": [ "#@title Do the Run!\n", "#@markdown `n_batches` ignored with animation modes.\n", @@ -2616,11 +2612,9 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "id": "CreateVid" }, - "outputs": [], "source": [ "# @title ### **Create video**\n", "#@markdown Video file will save in the same folder as your images.\n", @@ -2703,8 +2697,8 @@ } ], "metadata": { - "accelerator": "GPU", "anaconda-cloud": {}, + "accelerator": "GPU", "colab": { "collapsed_sections": [ "CreditsChTop", @@ -2718,11 +2712,11 @@ "AnimSetTop", "ExtraSetTop" ], - "include_colab_link": true, "machine_shape": "hm", "name": "Disco Diffusion v5.1 [w/ Turbo]", "private_outputs": true, - "provenance": [] + "provenance": [], + "include_colab_link": true }, "kernelspec": { "display_name": "Python 3", @@ -2744,4 +2738,4 @@ }, "nbformat": 4, "nbformat_minor": 4 -} +} \ No newline at end of file diff --git a/disco.py b/disco.py index 34bc59ba..9ec4a32a 100644 --- a/disco.py +++ b/disco.py @@ -1384,11 +1384,32 @@ def cond_fn(x, t, y=None): cv2.imwrite(f'{batchFolder}/{filename}',blendedImage) else: image.save(f'{batchFolder}/{filename}') + + # TODO(VR): trans_scale wasn't set in the PR. This needs to be set to a reasonable value! + trans_scale = 1.0 + if vr_mode: + generate_eye_views(trans_scale, batchFolder, filename, frame_num, midas_model, midas_transform) + # if frame_num != args.max_frames-1: # display.clear_output() plt.plot(np.array(loss_values), 'r') +def generate_eye_views(trans_scale,batchFolder,filename,frame_num,midas_model, midas_transform): + for i in range(2): + theta = vr_eye_angle * (math.pi/180) + ray_origin = math.cos(theta) * vr_ipd / 2 * (-1.0 if i==0 else 1.0) + ray_rotation = (theta if i==0 else -theta) + translate_xyz = [-(ray_origin)*trans_scale, 0,0] + rotate_xyz = [0, (ray_rotation), 0] + rot_mat = p3dT.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), "XYZ").unsqueeze(0) + transformed_image = dxf.transform_image_3d(f'{batchFolder}/{filename}', midas_model, midas_transform, DEVICE, + rot_mat, translate_xyz, args.near_plane, args.far_plane, + args.fov, padding_mode=args.padding_mode, + sampling_mode=args.sampling_mode, midas_weight=args.midas_weight,spherical=True) + eye_file_path = batchFolder+f"/frame_{frame_num-1:04}" + ('_l' if i==0 else '_r')+'.png' + transformed_image.save(eye_file_path) + def save_settings(): setting_list = { 'text_prompts': text_prompts, @@ -1948,6 +1969,32 @@ def forward(self, input, t): #@markdown `frame_skip_steps` will blur the previous frame - higher values will flicker less but struggle to add enough new detail to zoom into. frames_skip_steps = '60%' #@param ['40%', '50%', '60%', '70%', '80%'] {type: 'string'} +#======= VR MODE +#@markdown --- +#@markdown ####**VR Mode (3D anim only):** +#@markdown EXPERIMENTAL ALPHA: Need to look into trans_scale value +#@markdown Enables stereo rendering of left/right eye views (supporting Turbo) which use a different (fish-eye) camera projection matrix. +#@markdown Note the images you're prompting will work better if they have some inherent wide-angle aspect +#@markdown The generated images will need to be combined into left/right videos. These can then be stitched into the VR180 format. +#@markdown Google made the VR180 Creator tool but subsequently stopped supporting it. It's available for download in a few places including https://www.patrickgrunwald.de/vr180-creator-download +#@markdown The tool is not only good for stitching (videos and photos) but also for adding the correct metadata into existing videos, which is needed for services like YouTube to identify the format correctly. +#@markdown Watching YouTube VR videos isn't necessarily the easiest depending on your headset. For instance Oculus have a dedicated media studio and store which makes the files easier to access on a Quest https://creator.oculus.com/manage/mediastudio/ +#@markdown The command to get ffmpeg to concat your frames for each eye is in the form: ffmpeg -framerate 15 -i frame_%4d_l.png l.mp4 (repeat for r) + +# TODO(VR): vr_eye_angle and vr_ipd lines had syntax errors in initial PR. Are they OK? +vr_mode = False +vr_eye_angle = 0.5 #@param{type: 'number'} +#@markdown eye_angle is the y-axis rotation of the eyes towards the center +vr_ipd = 5.0 +#@markdown interpupillary distance (between the eyes) + +#insist turbo be used only w 3d anim. +if vr_mode and animation_mode != '3D': + print('=====') + print('VR mode only available with 3D animations. Disabling VR.') + print('=====') + turbo_mode = False + def parse_key_frames(string, prompt_parser=None): """Given a string representing frame numbers paired with parameter values at that frame, From 78f84ecd49a8e6a0fe12a00ad76cc2503639950f Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Sun, 10 Apr 2022 09:26:36 -0400 Subject: [PATCH 54/74] Fix VR translation scale issue --- Disco_Diffusion.ipynb | 9 +++------ disco.py | 9 +++------ 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 7d6e205b..69b29e82 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -1007,6 +1007,7 @@ " return (input - input.clamp(-1, 1)).pow(2).mean([1, 2, 3])\n", "\n", "stop_on_next_loop = False # Make sure GPU memory doesn't get corrupted from cancelling the run mid-way through, allow a full frame to complete\n", + "TRANSLATION_SCALE = 1.0/200.0\n", "\n", "def do_3d_step(img_filepath, frame_num, midas_model, midas_transform):\n", " if args.key_frames:\n", @@ -1025,8 +1026,7 @@ " f'rotation_3d_z: {rotation_3d_z}',\n", " )\n", "\n", - " trans_scale = 1.0/200.0\n", - " translate_xyz = [-translation_x*trans_scale, translation_y*trans_scale, -translation_z*trans_scale]\n", + " translate_xyz = [-translation_x*TRANSLATION_SCALE, translation_y*TRANSLATION_SCALE, -translation_z*TRANSLATION_SCALE]\n", " rotate_xyz_degrees = [rotation_3d_x, rotation_3d_y, rotation_3d_z]\n", " print('translation:',translate_xyz)\n", " print('rotation:',rotate_xyz_degrees)\n", @@ -1423,10 +1423,8 @@ " else:\n", " image.save(f'{batchFolder}/{filename}')\n", "\n", - " # TODO(VR): trans_scale wasn't set in the PR. This needs to be set to a reasonable value!\n", - " trans_scale = 1.0\n", " if vr_mode:\n", - " generate_eye_views(trans_scale, batchFolder, filename, frame_num, midas_model, midas_transform)\n", + " generate_eye_views(TRANSLATION_SCALE, batchFolder, filename, frame_num, midas_model, midas_transform)\n", "\n", " # if frame_num != args.max_frames-1:\n", " # display.clear_output()\n", @@ -2030,7 +2028,6 @@ "#======= VR MODE\n", "#@markdown ---\n", "#@markdown ####**VR Mode (3D anim only):**\n", - "#@markdown EXPERIMENTAL ALPHA: Need to look into trans_scale value\n", "#@markdown Enables stereo rendering of left/right eye views (supporting Turbo) which use a different (fish-eye) camera projection matrix. \n", "#@markdown Note the images you're prompting will work better if they have some inherent wide-angle aspect\n", "#@markdown The generated images will need to be combined into left/right videos. These can then be stitched into the VR180 format.\n", diff --git a/disco.py b/disco.py index 9ec4a32a..2029b1a3 100644 --- a/disco.py +++ b/disco.py @@ -969,6 +969,7 @@ def range_loss(input): return (input - input.clamp(-1, 1)).pow(2).mean([1, 2, 3]) stop_on_next_loop = False # Make sure GPU memory doesn't get corrupted from cancelling the run mid-way through, allow a full frame to complete +TRANSLATION_SCALE = 1.0/200.0 def do_3d_step(img_filepath, frame_num, midas_model, midas_transform): if args.key_frames: @@ -987,8 +988,7 @@ def do_3d_step(img_filepath, frame_num, midas_model, midas_transform): f'rotation_3d_z: {rotation_3d_z}', ) - trans_scale = 1.0/200.0 - translate_xyz = [-translation_x*trans_scale, translation_y*trans_scale, -translation_z*trans_scale] + translate_xyz = [-translation_x*TRANSLATION_SCALE, translation_y*TRANSLATION_SCALE, -translation_z*TRANSLATION_SCALE] rotate_xyz_degrees = [rotation_3d_x, rotation_3d_y, rotation_3d_z] print('translation:',translate_xyz) print('rotation:',rotate_xyz_degrees) @@ -1385,10 +1385,8 @@ def cond_fn(x, t, y=None): else: image.save(f'{batchFolder}/{filename}') - # TODO(VR): trans_scale wasn't set in the PR. This needs to be set to a reasonable value! - trans_scale = 1.0 if vr_mode: - generate_eye_views(trans_scale, batchFolder, filename, frame_num, midas_model, midas_transform) + generate_eye_views(TRANSLATION_SCALE, batchFolder, filename, frame_num, midas_model, midas_transform) # if frame_num != args.max_frames-1: # display.clear_output() @@ -1972,7 +1970,6 @@ def forward(self, input, t): #======= VR MODE #@markdown --- #@markdown ####**VR Mode (3D anim only):** -#@markdown EXPERIMENTAL ALPHA: Need to look into trans_scale value #@markdown Enables stereo rendering of left/right eye views (supporting Turbo) which use a different (fish-eye) camera projection matrix. #@markdown Note the images you're prompting will work better if they have some inherent wide-angle aspect #@markdown The generated images will need to be combined into left/right videos. These can then be stitched into the VR180 format. From 00bb170aae738087eb99122f163a94691df7c3f7 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Sun, 10 Apr 2022 12:28:14 -0400 Subject: [PATCH 55/74] Changelog and credits updates --- Disco_Diffusion.ipynb | 12 ++++++++++-- disco.py | 11 ++++++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 69b29e82..9be35277 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -58,9 +58,13 @@ "\n", "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", "\n", - "3D animation implementation added by Adam Letts (https://twitter.com/gandamu_ml) in collaboration with Somnai.\n", + "3D animation implementation added by Adam Letts (https://twitter.com/gandamu_ml) in collaboration with Somnai. Creation of disco.py and ongoing maintenance.\n", "\n", - "Turbo feature by Chris Allen (https://twitter.com/zippy731)" + "Turbo feature by Chris Allen (https://twitter.com/zippy731)\n", + "\n", + "Improvements to ability to run on local systems, Windows support, and dependency installation by HostsServer (https://twitter.com/HostsServer)\n", + "\n", + "VR Mode by Tom Mason (https://twitter.com/nin_artificial)" ] }, { @@ -263,6 +267,10 @@ "\n", " Update for crossplatform support\n", "\n", + " v5.2 Update: Apr 10th 2022 - nin_artificial / Tom Mason\n", + "\n", + " VR Mode\n", + "\n", " '''\n", " )" ], diff --git a/disco.py b/disco.py index 2029b1a3..5823494f 100644 --- a/disco.py +++ b/disco.py @@ -52,9 +52,14 @@ Somnai (https://twitter.com/Somnai_dreams) added Diffusion Animation techniques, QoL improvements and various implementations of tech and techniques, mostly listed in the changelog below. -3D animation implementation added by Adam Letts (https://twitter.com/gandamu_ml) in collaboration with Somnai. +3D animation implementation added by Adam Letts (https://twitter.com/gandamu_ml) in collaboration with Somnai. Creation of disco.py and ongoing maintenance. Turbo feature by Chris Allen (https://twitter.com/zippy731) + +Improvements to ability to run on local systems, Windows support, and dependency installation by HostsServer (https://twitter.com/HostsServer) + +VR Mode by Tom Mason (https://twitter.com/nin_artificial) + """ # %% @@ -252,6 +257,10 @@ Update for crossplatform support + v5.2 Update: Apr 10th 2022 - nin_artificial / Tom Mason + + VR Mode + ''' ) From 366a3aa6ef5c69bd1d0a848a4b459afe7b7f7607 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Sun, 10 Apr 2022 12:34:16 -0400 Subject: [PATCH 56/74] Add Colab markup to expose VR mode settings in Colab notebook --- Disco_Diffusion.ipynb | 9 ++++----- disco.py | 9 ++++----- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 9be35277..179f64b1 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -2044,12 +2044,11 @@ "#@markdown Watching YouTube VR videos isn't necessarily the easiest depending on your headset. For instance Oculus have a dedicated media studio and store which makes the files easier to access on a Quest https://creator.oculus.com/manage/mediastudio/\n", "#@markdown The command to get ffmpeg to concat your frames for each eye is in the form: ffmpeg -framerate 15 -i frame_%4d_l.png l.mp4 (repeat for r)\n", "\n", - "# TODO(VR): vr_eye_angle and vr_ipd lines had syntax errors in initial PR. Are they OK?\n", - "vr_mode = False\n", - "vr_eye_angle = 0.5 #@param{type: 'number'}\n", - "#@markdown eye_angle is the y-axis rotation of the eyes towards the center\n", - "vr_ipd = 5.0\n", + "vr_mode = False #@param {type:\"boolean\"}\n", + "#@markdown `vr_eye_angle` is the y-axis rotation of the eyes towards the center\n", + "vr_eye_angle = 0.5 #@param{type:\"number\"}\n", "#@markdown interpupillary distance (between the eyes)\n", + "vr_ipd = 5.0 #@param{type:\"number\"}\n", "\n", "#insist turbo be used only w 3d anim.\n", "if vr_mode and animation_mode != '3D':\n", diff --git a/disco.py b/disco.py index 5823494f..b00dd5e3 100644 --- a/disco.py +++ b/disco.py @@ -1987,12 +1987,11 @@ def forward(self, input, t): #@markdown Watching YouTube VR videos isn't necessarily the easiest depending on your headset. For instance Oculus have a dedicated media studio and store which makes the files easier to access on a Quest https://creator.oculus.com/manage/mediastudio/ #@markdown The command to get ffmpeg to concat your frames for each eye is in the form: ffmpeg -framerate 15 -i frame_%4d_l.png l.mp4 (repeat for r) -# TODO(VR): vr_eye_angle and vr_ipd lines had syntax errors in initial PR. Are they OK? -vr_mode = False -vr_eye_angle = 0.5 #@param{type: 'number'} -#@markdown eye_angle is the y-axis rotation of the eyes towards the center -vr_ipd = 5.0 +vr_mode = False #@param {type:"boolean"} +#@markdown `vr_eye_angle` is the y-axis rotation of the eyes towards the center +vr_eye_angle = 0.5 #@param{type:"number"} #@markdown interpupillary distance (between the eyes) +vr_ipd = 5.0 #@param{type:"number"} #insist turbo be used only w 3d anim. if vr_mode and animation_mode != '3D': From 130e8502a3f30ddf1b4050223687e3c88dbdad37 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Sun, 10 Apr 2022 12:41:39 -0400 Subject: [PATCH 57/74] Update .ipynb title for v5.2 VR Mode --- Disco_Diffusion.ipynb | 7 ++++--- disco.py | 5 +++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 179f64b1..614a9108 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -16,7 +16,7 @@ "id": "TitleTop" }, "source": [ - "# Disco Diffusion v5.1 - Now with Turbo\n", + "# Disco Diffusion v5.2 - Now with VR Mode\n", "\n", "In case of confusion, Disco is the name of this notebook edit. The diffusion model in use is Katherine Crowson's fine-tuned 512x512 model\n", "\n", @@ -2042,7 +2042,8 @@ "#@markdown Google made the VR180 Creator tool but subsequently stopped supporting it. It's available for download in a few places including https://www.patrickgrunwald.de/vr180-creator-download\n", "#@markdown The tool is not only good for stitching (videos and photos) but also for adding the correct metadata into existing videos, which is needed for services like YouTube to identify the format correctly.\n", "#@markdown Watching YouTube VR videos isn't necessarily the easiest depending on your headset. For instance Oculus have a dedicated media studio and store which makes the files easier to access on a Quest https://creator.oculus.com/manage/mediastudio/\n", - "#@markdown The command to get ffmpeg to concat your frames for each eye is in the form: ffmpeg -framerate 15 -i frame_%4d_l.png l.mp4 (repeat for r)\n", + "#@markdown \n", + "#@markdown The command to get ffmpeg to concat your frames for each eye is in the form: `ffmpeg -framerate 15 -i frame_%4d_l.png l.mp4` (repeat for r)\n", "\n", "vr_mode = False #@param {type:\"boolean\"}\n", "#@markdown `vr_eye_angle` is the y-axis rotation of the eyes towards the center\n", @@ -2717,7 +2718,7 @@ "ExtraSetTop" ], "machine_shape": "hm", - "name": "Disco Diffusion v5.1 [w/ Turbo]", + "name": "Disco Diffusion v5.2 [w/ VR Mode]", "private_outputs": true, "provenance": [], "include_colab_link": true diff --git a/disco.py b/disco.py index b00dd5e3..9ccf510a 100644 --- a/disco.py +++ b/disco.py @@ -12,7 +12,7 @@ # !! "id": "TitleTop" # !! }} """ -# Disco Diffusion v5.1 - Now with Turbo +# Disco Diffusion v5.2 - Now with VR Mode In case of confusion, Disco is the name of this notebook edit. The diffusion model in use is Katherine Crowson's fine-tuned 512x512 model @@ -1985,7 +1985,8 @@ def forward(self, input, t): #@markdown Google made the VR180 Creator tool but subsequently stopped supporting it. It's available for download in a few places including https://www.patrickgrunwald.de/vr180-creator-download #@markdown The tool is not only good for stitching (videos and photos) but also for adding the correct metadata into existing videos, which is needed for services like YouTube to identify the format correctly. #@markdown Watching YouTube VR videos isn't necessarily the easiest depending on your headset. For instance Oculus have a dedicated media studio and store which makes the files easier to access on a Quest https://creator.oculus.com/manage/mediastudio/ -#@markdown The command to get ffmpeg to concat your frames for each eye is in the form: ffmpeg -framerate 15 -i frame_%4d_l.png l.mp4 (repeat for r) +#@markdown +#@markdown The command to get ffmpeg to concat your frames for each eye is in the form: `ffmpeg -framerate 15 -i frame_%4d_l.png l.mp4` (repeat for r) vr_mode = False #@param {type:"boolean"} #@markdown `vr_eye_angle` is the y-axis rotation of the eyes towards the center From 43fba6fca7e2795d64126c172a8392318089bb2c Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Sun, 10 Apr 2022 12:43:17 -0400 Subject: [PATCH 58/74] Update README.md for v5.2 VR Mode --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 22e34ebc..154bf15d 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,10 @@ A frankensteinian amalgamation of notebooks, models and techniques for the gener * Remove Slip Models * Update for crossplatform support +#### v5.2 Update: Apr 10th 2022 - nin_artificial / Tom Mason + +* VR Mode + ## Notebook Provenance 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. From 8ca4a973a07dccf040344a7924f130be3acec64a Mon Sep 17 00:00:00 2001 From: Tom Mason Date: Sat, 16 Apr 2022 01:32:11 +0100 Subject: [PATCH 59/74] VR Turbo missing frames fix --- disco.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/disco.py b/disco.py index 9ccf510a..2182d0b9 100644 --- a/disco.py +++ b/disco.py @@ -1109,6 +1109,8 @@ def do_run(): blendedImage = cv2.addWeighted(newWarpedImg, blend_factor, oldWarpedImg,1-blend_factor, 0.0) cv2.imwrite(f'{batchFolder}/{filename}',blendedImage) next_step_pil.save(f'{img_filepath}') # save it also as prev_frame to feed next iteration + if vr_mode: + generate_eye_views(TRANSLATION_SCALE,batchFolder,filename,frame_num,midas_model, midas_transform) continue else: #if not a skip frame, will run diffusion and need to blend. @@ -1414,7 +1416,7 @@ def generate_eye_views(trans_scale,batchFolder,filename,frame_num,midas_model, m rot_mat, translate_xyz, args.near_plane, args.far_plane, args.fov, padding_mode=args.padding_mode, sampling_mode=args.sampling_mode, midas_weight=args.midas_weight,spherical=True) - eye_file_path = batchFolder+f"/frame_{frame_num-1:04}" + ('_l' if i==0 else '_r')+'.png' + eye_file_path = batchFolder+f"/frame_{frame_num:04}" + ('_l' if i==0 else '_r')+'.png' transformed_image.save(eye_file_path) def save_settings(): From 1c52aed07313c63bf4949b04feb62eb78a8394cd Mon Sep 17 00:00:00 2001 From: Tom Mason Date: Sat, 16 Apr 2022 12:46:16 +0100 Subject: [PATCH 60/74] Fix to disable VR mode when not 3d --- disco.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/disco.py b/disco.py index 2182d0b9..9dd35984 100644 --- a/disco.py +++ b/disco.py @@ -1996,12 +1996,12 @@ def forward(self, input, t): #@markdown interpupillary distance (between the eyes) vr_ipd = 5.0 #@param{type:"number"} -#insist turbo be used only w 3d anim. +#insist VR be used only w 3d anim. if vr_mode and animation_mode != '3D': print('=====') print('VR mode only available with 3D animations. Disabling VR.') print('=====') - turbo_mode = False + vr_mode = False def parse_key_frames(string, prompt_parser=None): From 19e662a530b2d6152424bfe3fb4c0a51f7f74c29 Mon Sep 17 00:00:00 2001 From: MSFTserver Date: Wed, 20 Apr 2022 16:11:01 -0700 Subject: [PATCH 61/74] update ipynb for VR mode fixes --- Disco_Diffusion.ipynb | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 614a9108..87ead89f 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -1146,6 +1146,8 @@ " blendedImage = cv2.addWeighted(newWarpedImg, blend_factor, oldWarpedImg,1-blend_factor, 0.0)\n", " cv2.imwrite(f'{batchFolder}/{filename}',blendedImage)\n", " next_step_pil.save(f'{img_filepath}') # save it also as prev_frame to feed next iteration\n", + " if vr_mode:\n", + " generate_eye_views(TRANSLATION_SCALE,batchFolder,filename,frame_num,midas_model, midas_transform)\n", " continue\n", " else:\n", " #if not a skip frame, will run diffusion and need to blend.\n", @@ -1451,7 +1453,7 @@ " rot_mat, translate_xyz, args.near_plane, args.far_plane,\n", " args.fov, padding_mode=args.padding_mode,\n", " sampling_mode=args.sampling_mode, midas_weight=args.midas_weight,spherical=True)\n", - " eye_file_path = batchFolder+f\"/frame_{frame_num-1:04}\" + ('_l' if i==0 else '_r')+'.png'\n", + " eye_file_path = batchFolder+f\"/frame_{frame_num:04}\" + ('_l' if i==0 else '_r')+'.png'\n", " transformed_image.save(eye_file_path)\n", "\n", "def save_settings():\n", @@ -2051,12 +2053,12 @@ "#@markdown interpupillary distance (between the eyes)\n", "vr_ipd = 5.0 #@param{type:\"number\"}\n", "\n", - "#insist turbo be used only w 3d anim.\n", + "#insist VR be used only w 3d anim.\n", "if vr_mode and animation_mode != '3D':\n", " print('=====')\n", " print('VR mode only available with 3D animations. Disabling VR.')\n", " print('=====')\n", - " turbo_mode = False\n", + " vr_mode = False\n", "\n", "\n", "def parse_key_frames(string, prompt_parser=None):\n", @@ -2718,7 +2720,7 @@ "ExtraSetTop" ], "machine_shape": "hm", - "name": "Disco Diffusion v5.2 [w/ VR Mode]", + "name": "Disco Diffusion v5.1 [w/ Turbo]", "private_outputs": true, "provenance": [], "include_colab_link": true From 9e968d03cc98731149ac88567f6aeef8aef47354 Mon Sep 17 00:00:00 2001 From: MSFTserver Date: Wed, 20 Apr 2022 16:34:36 -0700 Subject: [PATCH 62/74] remove converters for future plans --- make_notebook.py | 103 ----------------------------------------------- make_py.py | 48 ---------------------- 2 files changed, 151 deletions(-) delete mode 100644 make_notebook.py delete mode 100644 make_py.py diff --git a/make_notebook.py b/make_notebook.py deleted file mode 100644 index a26d2a7d..00000000 --- a/make_notebook.py +++ /dev/null @@ -1,103 +0,0 @@ -import json -import sys -from os import path - -header_comment = '# %%\n' - -def py2nb(py_str): - # remove leading header comment - if py_str.startswith(header_comment): - py_str = py_str[len(header_comment):] - - cells = [] - chunks = py_str.split('\n\n%s' % header_comment) - - for chunk in chunks: - cell_type = 'code' - new_json = {'metadata':{}} - if chunk.startswith('# !!'): - new_json = json.loads("\n".join([x.strip() for x in chunk.splitlines() if '# !!' in x]).replace('# !!','')) - chunk = "\n".join([x for x in chunk.splitlines() if '# !!' not in x]) - if chunk.startswith("'''"): - chunk = chunk.strip("'\n") - cell_type = 'markdown' - elif chunk.startswith('"""'): - chunk = chunk.strip('"\n') - cell_type = 'markdown' - - cell = { - 'cell_type': cell_type, - 'metadata': new_json['metadata'], - 'source': chunk.splitlines(True), - } - - if cell_type == 'code': - cell.update({'outputs': [], 'execution_count': None}) - - cells.append(cell) - - notebook = { - 'cells': cells, - 'metadata': { - 'anaconda-cloud': {}, - 'accelerator': 'GPU', - 'colab': { - 'collapsed_sections': [ - 'CreditsChTop', - 'TutorialTop', - 'CheckGPU', - 'InstallDeps', - 'DefMidasFns', - 'DefFns', - 'DefSecModel', - 'DefSuperRes', - 'AnimSetTop', - 'ExtraSetTop' - ], - 'machine_shape': 'hm', - 'name': 'Disco Diffusion v5.1 [w/ Turbo]', - 'private_outputs': True, - 'provenance': [], - 'include_colab_link': True - }, - 'kernelspec': { - 'display_name': 'Python 3', - 'language': 'python', - 'name': 'python3' - }, - 'language_info': { - 'codemirror_mode': { - 'name': 'ipython', - 'version': 3 - }, - 'file_extension': '.py', - 'mimetype': 'text/x-python', - 'name': 'python', - 'nbconvert_exporter': 'python', - 'pygments_lexer': 'ipython3', - 'version': '3.6.1' - } - }, - 'nbformat': 4, - 'nbformat_minor': 4 - } - - return notebook - - -def convert(in_file, out_file): - _, in_ext = path.splitext(in_file) - _, out_ext = path.splitext(out_file) - - if in_ext == '.py' and out_ext == '.ipynb': - with open(in_file, 'r', encoding='utf-8') as f: - py_str = f.read() - notebook = py2nb(py_str) - with open(out_file, 'w', encoding='utf-8') as f: - json.dump(notebook, f, indent=2) - - else: - raise(Exception('Extensions must be .ipynb and .py or vice versa')) - - -convert('disco.py', 'Disco_Diffusion.ipynb') diff --git a/make_py.py b/make_py.py deleted file mode 100644 index b952fb09..00000000 --- a/make_py.py +++ /dev/null @@ -1,48 +0,0 @@ -import json -import sys -from os import path - -header_comment = '# %%\n' - -def nb2py(notebook): - result = [] - cells = notebook['cells'] - - for cell in cells: - cell_type = cell['cell_type'] - metadata = cell['metadata'] - format_metadata = json.dumps(metadata,indent=2).split("\n") - reformat_metadata = '# !! {"metadata":' - for key in format_metadata: - if key == '{': - reformat_metadata+=f"{key}\n" - elif key == '}': - reformat_metadata+="# !! "+key+"}\n" - else: - reformat_metadata+=f'# !! {key}\n' - - if cell_type == 'markdown': - result.append('%s"""\n%s\n"""'% - (header_comment+reformat_metadata, ''.join(cell['source']))) - - if cell_type == 'code': - result.append("%s%s" % (header_comment+reformat_metadata, ''.join(cell['source']))) - - return '\n\n'.join(result) - -def convert(in_file, out_file): - _, in_ext = path.splitext(in_file) - _, out_ext = path.splitext(out_file) - - if in_ext == '.ipynb' and out_ext == '.py': - with open(in_file, 'r', encoding='utf-8') as f: - notebook = json.load(f) - py_str = nb2py(notebook) - with open(out_file, 'w', encoding='utf-8') as f: - f.write(py_str) - - else: - raise(Exception('Extensions must be .ipynb and .py or vice versa')) - - -convert('Disco_Diffusion.ipynb', 'disco.py') From 69f5259e86707337fb47118b8d9aad99ad81de3d Mon Sep 17 00:00:00 2001 From: MSFTserver Date: Wed, 20 Apr 2022 16:40:18 -0700 Subject: [PATCH 63/74] fix version --- Disco_Diffusion.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 87ead89f..6ca2d197 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -2720,7 +2720,7 @@ "ExtraSetTop" ], "machine_shape": "hm", - "name": "Disco Diffusion v5.1 [w/ Turbo]", + "name": "Disco Diffusion v5.2 [w/ VR]", "private_outputs": true, "provenance": [], "include_colab_link": true From d84072d922bd40e014c370e051b9334bb8cb2752 Mon Sep 17 00:00:00 2001 From: MSFTserver Date: Wed, 20 Apr 2022 16:41:35 -0700 Subject: [PATCH 64/74] Update Disco_Diffusion.ipynb --- Disco_Diffusion.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 6ca2d197..8ed97d03 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -2720,7 +2720,7 @@ "ExtraSetTop" ], "machine_shape": "hm", - "name": "Disco Diffusion v5.2 [w/ VR]", + "name": "Disco Diffusion v5.2 [w/ VR Mode]", "private_outputs": true, "provenance": [], "include_colab_link": true From 458a925911ab7149bcaf089124c15fe118d789e8 Mon Sep 17 00:00:00 2001 From: MSFTserver Date: Thu, 21 Apr 2022 20:58:45 -0700 Subject: [PATCH 65/74] update init_image to take "None" --- Disco_Diffusion.ipynb | 2 +- disco.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 8ed97d03..ee4d7c8b 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -1068,7 +1068,7 @@ " \n", " # Inits if not video frames\n", " if args.animation_mode != \"Video Input\":\n", - " if args.init_image == '':\n", + " if args.init_image == '' or args.init_image.lower() == 'none':\n", " init_image = None\n", " else:\n", " init_image = args.init_image\n", diff --git a/disco.py b/disco.py index 9dd35984..dec7bea0 100644 --- a/disco.py +++ b/disco.py @@ -1031,7 +1031,7 @@ def do_run(): # Inits if not video frames if args.animation_mode != "Video Input": - if args.init_image == '': + if args.init_image == '' or args.init_image.lower() == 'none': init_image = None else: init_image = args.init_image From b40f9d2ceec83f2b710eaaf5d3416cf0a62c5119 Mon Sep 17 00:00:00 2001 From: MSFTserver Date: Thu, 21 Apr 2022 21:05:54 -0700 Subject: [PATCH 66/74] cleaner fix --- disco.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/disco.py b/disco.py index dec7bea0..1bf172e3 100644 --- a/disco.py +++ b/disco.py @@ -1031,7 +1031,7 @@ def do_run(): # Inits if not video frames if args.animation_mode != "Video Input": - if args.init_image == '' or args.init_image.lower() == 'none': + if args.init_image in ['','none', 'None', 'NONE']: init_image = None else: init_image = args.init_image From fc2720f1f782114b7e7aea1b5696ea1cbb6c1225 Mon Sep 17 00:00:00 2001 From: MSFTserver Date: Thu, 21 Apr 2022 21:14:22 -0700 Subject: [PATCH 67/74] Update Disco_Diffusion.ipynb --- Disco_Diffusion.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index ee4d7c8b..5cfa8461 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -1068,7 +1068,7 @@ " \n", " # Inits if not video frames\n", " if args.animation_mode != \"Video Input\":\n", - " if args.init_image == '' or args.init_image.lower() == 'none':\n", + " if args.init_image in ['','none', 'None', 'NONE']:\n", " init_image = None\n", " else:\n", " init_image = args.init_image\n", From 1fceed19b7d51862ce054946f13561fa17318755 Mon Sep 17 00:00:00 2001 From: MSFTserver Date: Mon, 2 May 2022 16:53:48 -0700 Subject: [PATCH 68/74] add fallback model URLS --- Disco_Diffusion.ipynb | 169 +++++++++++++++++++++++++----------------- disco.py | 169 +++++++++++++++++++++++++----------------- 2 files changed, 202 insertions(+), 136 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 5cfa8461..6963f6ca 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -478,10 +478,6 @@ " root_path = os.getcwd()\n", " model_path = f'{root_path}/models'\n", "\n", - "model_256_downloaded = False\n", - "model_512_downloaded = False\n", - "model_secondary_downloaded = False\n", - "\n", "multipip_res = subprocess.run(['pip', 'install', 'lpips', 'datetime', 'timm', 'ftfy', 'einops', 'pytorch-lightning', 'omegaconf'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", "print(multipip_res)\n", "\n", @@ -1744,76 +1740,113 @@ "#@markdown If you're having issues with model downloads, check this to compare SHA's:\n", "check_model_SHA = False #@param{type:\"boolean\"}\n", "\n", - "model_256_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a'\n", - "model_512_SHA = '9c111ab89e214862b76e1fa6a1b3f1d329b1a88281885943d2cdbe357ad57648'\n", - "model_secondary_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a'\n", - "\n", - "model_256_link = 'https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt'\n", - "model_512_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/512x512_diffusion_uncond_finetune_008100.pt'\n", - "model_secondary_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/secondary_model_imagenet_2.pth'\n", - "\n", - "model_256_path = f'{model_path}/256x256_diffusion_uncond.pt'\n", - "model_512_path = f'{model_path}/512x512_diffusion_uncond_finetune_008100.pt'\n", - "model_secondary_path = f'{model_path}/secondary_model_imagenet_2.pth'\n", - "\n", - "# Download the diffusion model\n", - "if diffusion_model == '256x256_diffusion_uncond':\n", - " if os.path.exists(model_256_path) and check_model_SHA:\n", - " print('Checking 256 Diffusion File')\n", - " with open(model_256_path,\"rb\") as f:\n", - " bytes = f.read() \n", - " hash = hashlib.sha256(bytes).hexdigest();\n", - " if hash == model_256_SHA:\n", - " print('256 Model SHA matches')\n", - " model_256_downloaded = True\n", - " else: \n", - " print(\"256 Model SHA doesn't match, redownloading...\")\n", + "def download_models(diffusion_model,use_secondary_model,fallback=False):\n", + " model_256_downloaded = False\n", + " model_512_downloaded = False\n", + " model_secondary_downloaded = False\n", + "\n", + " model_256_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a'\n", + " model_512_SHA = '9c111ab89e214862b76e1fa6a1b3f1d329b1a88281885943d2cdbe357ad57648'\n", + " model_secondary_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a'\n", + "\n", + " model_256_link = 'https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt'\n", + " model_512_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/512x512_diffusion_uncond_finetune_008100.pt'\n", + " model_secondary_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/secondary_model_imagenet_2.pth'\n", + "\n", + " model_256_link_fb = 'https://www.dropbox.com/s/9tqnqo930mpnpcn/256x256_diffusion_uncond.pt'\n", + " model_512_link_fb = 'https://www.dropbox.com/s/yjqvhu6l6l0r2eh/512x512_diffusion_uncond_finetune_008100.pt'\n", + " model_secondary_link_fb = 'https://www.dropbox.com/s/luv4fezod3r8d2n/secondary_model_imagenet_2.pth'\n", + "\n", + " model_256_path = f'{model_path}/256x256_diffusion_uncond.pt'\n", + " model_512_path = f'{model_path}/512x512_diffusion_uncond_finetune_008100.pt'\n", + " model_secondary_path = f'{model_path}/secondary_model_imagenet_2.pth'\n", + "\n", + " if fallback:\n", + " model_256_link = model_256_link_fb\n", + " model_512_link = model_512_link_fb\n", + " model_secondary_link = model_secondary_link_fb\n", + " # Download the diffusion model\n", + " if diffusion_model == '256x256_diffusion_uncond':\n", + " if os.path.exists(model_256_path) and check_model_SHA:\n", + " print('Checking 256 Diffusion File')\n", + " with open(model_256_path,\"rb\") as f:\n", + " bytes = f.read() \n", + " hash = hashlib.sha256(bytes).hexdigest();\n", + " if hash == model_256_SHA:\n", + " print('256 Model SHA matches')\n", + " model_256_downloaded = True\n", + " else: \n", + " print(\"256 Model SHA doesn't match, redownloading...\")\n", + " wget(model_256_link, model_path)\n", + " if os.path.exists(model_256_path):\n", + " model_256_downloaded = True\n", + " else:\n", + " print('First URL Failed using FallBack')\n", + " download_models(diffusion_model,use_secondary_model,True)\n", + " elif os.path.exists(model_256_path) and not check_model_SHA or model_256_downloaded == True:\n", + " print('256 Model already downloaded, check check_model_SHA if the file is corrupt')\n", + " else: \n", " wget(model_256_link, model_path)\n", - " model_256_downloaded = True\n", - " elif os.path.exists(model_256_path) and not check_model_SHA or model_256_downloaded == True:\n", - " print('256 Model already downloaded, check check_model_SHA if the file is corrupt')\n", - " else: \n", - " wget(model_256_link, model_path)\n", - " model_256_downloaded = True\n", - "elif diffusion_model == '512x512_diffusion_uncond_finetune_008100':\n", - " if os.path.exists(model_512_path) and check_model_SHA:\n", - " print('Checking 512 Diffusion File')\n", - " with open(model_512_path,\"rb\") as f:\n", - " bytes = f.read() \n", - " hash = hashlib.sha256(bytes).hexdigest();\n", - " if hash == model_512_SHA:\n", - " print('512 Model SHA matches')\n", - " model_512_downloaded = True\n", + " if os.path.exists(model_256_path):\n", + " model_256_downloaded = True\n", + " else:\n", + " print('First URL Failed using FallBack')\n", + " download_models(diffusion_model,True)\n", + " elif diffusion_model == '512x512_diffusion_uncond_finetune_008100':\n", + " if os.path.exists(model_512_path) and check_model_SHA:\n", + " print('Checking 512 Diffusion File')\n", + " with open(model_512_path,\"rb\") as f:\n", + " bytes = f.read() \n", + " hash = hashlib.sha256(bytes).hexdigest();\n", + " if hash == model_512_SHA:\n", + " print('512 Model SHA matches')\n", + " if os.path.exists(model_512_path):\n", + " model_512_downloaded = True\n", + " else:\n", + " print('First URL Failed using FallBack')\n", + " download_models(diffusion_model,use_secondary_model,True)\n", + " else: \n", + " print(\"512 Model SHA doesn't match, redownloading...\")\n", + " wget(model_512_link, model_path)\n", + " if os.path.exists(model_512_path):\n", + " model_512_downloaded = True\n", + " else:\n", + " print('First URL Failed using FallBack')\n", + " download_models(diffusion_model,use_secondary_model,True)\n", + " elif os.path.exists(model_512_path) and not check_model_SHA or model_512_downloaded == True:\n", + " print('512 Model already downloaded, check check_model_SHA if the file is corrupt')\n", " else: \n", - " print(\"512 Model SHA doesn't match, redownloading...\")\n", " wget(model_512_link, model_path)\n", " model_512_downloaded = True\n", - " elif os.path.exists(model_512_path) and not check_model_SHA or model_512_downloaded == True:\n", - " print('512 Model already downloaded, check check_model_SHA if the file is corrupt')\n", - " else: \n", - " wget(model_512_link, model_path)\n", - " model_512_downloaded = True\n", - "\n", - "\n", - "# Download the secondary diffusion model v2\n", - "if use_secondary_model == True:\n", - " if os.path.exists(model_secondary_path) and check_model_SHA:\n", - " print('Checking Secondary Diffusion File')\n", - " with open(model_secondary_path,\"rb\") as f:\n", - " bytes = f.read() \n", - " hash = hashlib.sha256(bytes).hexdigest();\n", - " if hash == model_secondary_SHA:\n", - " print('Secondary Model SHA matches')\n", - " model_secondary_downloaded = True\n", + " # Download the secondary diffusion model v2\n", + " if use_secondary_model == True:\n", + " if os.path.exists(model_secondary_path) and check_model_SHA:\n", + " print('Checking Secondary Diffusion File')\n", + " with open(model_secondary_path,\"rb\") as f:\n", + " bytes = f.read() \n", + " hash = hashlib.sha256(bytes).hexdigest();\n", + " if hash == model_secondary_SHA:\n", + " print('Secondary Model SHA matches')\n", + " model_secondary_downloaded = True\n", + " else: \n", + " print(\"Secondary Model SHA doesn't match, redownloading...\")\n", + " wget(model_secondary_link, model_path)\n", + " if os.path.exists(model_secondary_path):\n", + " model_secondary_downloaded = True\n", + " else:\n", + " print('First URL Failed using FallBack')\n", + " download_models(diffusion_model,use_secondary_model,True)\n", + " elif os.path.exists(model_secondary_path) and not check_model_SHA or model_secondary_downloaded == True:\n", + " print('Secondary Model already downloaded, check check_model_SHA if the file is corrupt')\n", " else: \n", - " print(\"Secondary Model SHA doesn't match, redownloading...\")\n", " wget(model_secondary_link, model_path)\n", - " model_secondary_downloaded = True\n", - " elif os.path.exists(model_secondary_path) and not check_model_SHA or model_secondary_downloaded == True:\n", - " print('Secondary Model already downloaded, check check_model_SHA if the file is corrupt')\n", - " else: \n", - " wget(model_secondary_link, model_path)\n", - " model_secondary_downloaded = True\n", + " if os.path.exists(model_secondary_path):\n", + " model_secondary_downloaded = True\n", + " else:\n", + " print('First URL Failed using FallBack')\n", + " download_models(diffusion_model,use_secondary_model,True)\n", + "\n", + "download_models(diffusion_model,use_secondary_model)\n", "\n", "model_config = model_and_diffusion_defaults()\n", "if diffusion_model == '512x512_diffusion_uncond_finetune_008100':\n", diff --git a/disco.py b/disco.py index 1bf172e3..0379e2e1 100644 --- a/disco.py +++ b/disco.py @@ -451,10 +451,6 @@ def createPath(filepath): root_path = os.getcwd() model_path = f'{root_path}/models' -model_256_downloaded = False -model_512_downloaded = False -model_secondary_downloaded = False - multipip_res = subprocess.run(['pip', 'install', 'lpips', 'datetime', 'timm', 'ftfy', 'einops', 'pytorch-lightning', 'omegaconf'], stdout=subprocess.PIPE).stdout.decode('utf-8') print(multipip_res) @@ -1697,76 +1693,113 @@ def forward(self, input, t): #@markdown If you're having issues with model downloads, check this to compare SHA's: check_model_SHA = False #@param{type:"boolean"} -model_256_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a' -model_512_SHA = '9c111ab89e214862b76e1fa6a1b3f1d329b1a88281885943d2cdbe357ad57648' -model_secondary_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a' - -model_256_link = 'https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt' -model_512_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/512x512_diffusion_uncond_finetune_008100.pt' -model_secondary_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/secondary_model_imagenet_2.pth' - -model_256_path = f'{model_path}/256x256_diffusion_uncond.pt' -model_512_path = f'{model_path}/512x512_diffusion_uncond_finetune_008100.pt' -model_secondary_path = f'{model_path}/secondary_model_imagenet_2.pth' - -# Download the diffusion model -if diffusion_model == '256x256_diffusion_uncond': - if os.path.exists(model_256_path) and check_model_SHA: - print('Checking 256 Diffusion File') - with open(model_256_path,"rb") as f: - bytes = f.read() - hash = hashlib.sha256(bytes).hexdigest(); - if hash == model_256_SHA: - print('256 Model SHA matches') - model_256_downloaded = True - else: - print("256 Model SHA doesn't match, redownloading...") +def download_models(diffusion_model,use_secondary_model,fallback=False): + model_256_downloaded = False + model_512_downloaded = False + model_secondary_downloaded = False + + model_256_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a' + model_512_SHA = '9c111ab89e214862b76e1fa6a1b3f1d329b1a88281885943d2cdbe357ad57648' + model_secondary_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a' + + model_256_link = 'https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt' + model_512_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/512x512_diffusion_uncond_finetune_008100.pt' + model_secondary_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/secondary_model_imagenet_2.pth' + + model_256_link_fb = 'https://www.dropbox.com/s/9tqnqo930mpnpcn/256x256_diffusion_uncond.pt' + model_512_link_fb = 'https://www.dropbox.com/s/yjqvhu6l6l0r2eh/512x512_diffusion_uncond_finetune_008100.pt' + model_secondary_link_fb = 'https://www.dropbox.com/s/luv4fezod3r8d2n/secondary_model_imagenet_2.pth' + + model_256_path = f'{model_path}/256x256_diffusion_uncond.pt' + model_512_path = f'{model_path}/512x512_diffusion_uncond_finetune_008100.pt' + model_secondary_path = f'{model_path}/secondary_model_imagenet_2.pth' + + if fallback: + model_256_link = model_256_link_fb + model_512_link = model_512_link_fb + model_secondary_link = model_secondary_link_fb + # Download the diffusion model + if diffusion_model == '256x256_diffusion_uncond': + if os.path.exists(model_256_path) and check_model_SHA: + print('Checking 256 Diffusion File') + with open(model_256_path,"rb") as f: + bytes = f.read() + hash = hashlib.sha256(bytes).hexdigest(); + if hash == model_256_SHA: + print('256 Model SHA matches') + model_256_downloaded = True + else: + print("256 Model SHA doesn't match, redownloading...") + wget(model_256_link, model_path) + if os.path.exists(model_256_path): + model_256_downloaded = True + else: + print('First URL Failed using FallBack') + download_models(diffusion_model,use_secondary_model,True) + elif os.path.exists(model_256_path) and not check_model_SHA or model_256_downloaded == True: + print('256 Model already downloaded, check check_model_SHA if the file is corrupt') + else: wget(model_256_link, model_path) - model_256_downloaded = True - elif os.path.exists(model_256_path) and not check_model_SHA or model_256_downloaded == True: - print('256 Model already downloaded, check check_model_SHA if the file is corrupt') - else: - wget(model_256_link, model_path) - model_256_downloaded = True -elif diffusion_model == '512x512_diffusion_uncond_finetune_008100': - if os.path.exists(model_512_path) and check_model_SHA: - print('Checking 512 Diffusion File') - with open(model_512_path,"rb") as f: - bytes = f.read() - hash = hashlib.sha256(bytes).hexdigest(); - if hash == model_512_SHA: - print('512 Model SHA matches') - model_512_downloaded = True + if os.path.exists(model_256_path): + model_256_downloaded = True + else: + print('First URL Failed using FallBack') + download_models(diffusion_model,True) + elif diffusion_model == '512x512_diffusion_uncond_finetune_008100': + if os.path.exists(model_512_path) and check_model_SHA: + print('Checking 512 Diffusion File') + with open(model_512_path,"rb") as f: + bytes = f.read() + hash = hashlib.sha256(bytes).hexdigest(); + if hash == model_512_SHA: + print('512 Model SHA matches') + if os.path.exists(model_512_path): + model_512_downloaded = True + else: + print('First URL Failed using FallBack') + download_models(diffusion_model,use_secondary_model,True) + else: + print("512 Model SHA doesn't match, redownloading...") + wget(model_512_link, model_path) + if os.path.exists(model_512_path): + model_512_downloaded = True + else: + print('First URL Failed using FallBack') + download_models(diffusion_model,use_secondary_model,True) + elif os.path.exists(model_512_path) and not check_model_SHA or model_512_downloaded == True: + print('512 Model already downloaded, check check_model_SHA if the file is corrupt') else: - print("512 Model SHA doesn't match, redownloading...") wget(model_512_link, model_path) model_512_downloaded = True - elif os.path.exists(model_512_path) and not check_model_SHA or model_512_downloaded == True: - print('512 Model already downloaded, check check_model_SHA if the file is corrupt') - else: - wget(model_512_link, model_path) - model_512_downloaded = True - - -# Download the secondary diffusion model v2 -if use_secondary_model == True: - if os.path.exists(model_secondary_path) and check_model_SHA: - print('Checking Secondary Diffusion File') - with open(model_secondary_path,"rb") as f: - bytes = f.read() - hash = hashlib.sha256(bytes).hexdigest(); - if hash == model_secondary_SHA: - print('Secondary Model SHA matches') - model_secondary_downloaded = True + # Download the secondary diffusion model v2 + if use_secondary_model == True: + if os.path.exists(model_secondary_path) and check_model_SHA: + print('Checking Secondary Diffusion File') + with open(model_secondary_path,"rb") as f: + bytes = f.read() + hash = hashlib.sha256(bytes).hexdigest(); + if hash == model_secondary_SHA: + print('Secondary Model SHA matches') + model_secondary_downloaded = True + else: + print("Secondary Model SHA doesn't match, redownloading...") + wget(model_secondary_link, model_path) + if os.path.exists(model_secondary_path): + model_secondary_downloaded = True + else: + print('First URL Failed using FallBack') + download_models(diffusion_model,use_secondary_model,True) + elif os.path.exists(model_secondary_path) and not check_model_SHA or model_secondary_downloaded == True: + print('Secondary Model already downloaded, check check_model_SHA if the file is corrupt') else: - print("Secondary Model SHA doesn't match, redownloading...") wget(model_secondary_link, model_path) - model_secondary_downloaded = True - elif os.path.exists(model_secondary_path) and not check_model_SHA or model_secondary_downloaded == True: - print('Secondary Model already downloaded, check check_model_SHA if the file is corrupt') - else: - wget(model_secondary_link, model_path) - model_secondary_downloaded = True + if os.path.exists(model_secondary_path): + model_secondary_downloaded = True + else: + print('First URL Failed using FallBack') + download_models(diffusion_model,use_secondary_model,True) + +download_models(diffusion_model,use_secondary_model) model_config = model_and_diffusion_defaults() if diffusion_model == '512x512_diffusion_uncond_finetune_008100': From e2906c6dce1c14bbb4d61b88295186f415f7417c Mon Sep 17 00:00:00 2001 From: MSFTserver Date: Mon, 2 May 2022 21:58:18 -0700 Subject: [PATCH 69/74] update fallback urls --- Disco_Diffusion.ipynb | 4 ++-- disco.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 6963f6ca..6e77387f 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -1754,8 +1754,8 @@ " model_secondary_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/secondary_model_imagenet_2.pth'\n", "\n", " model_256_link_fb = 'https://www.dropbox.com/s/9tqnqo930mpnpcn/256x256_diffusion_uncond.pt'\n", - " model_512_link_fb = 'https://www.dropbox.com/s/yjqvhu6l6l0r2eh/512x512_diffusion_uncond_finetune_008100.pt'\n", - " model_secondary_link_fb = 'https://www.dropbox.com/s/luv4fezod3r8d2n/secondary_model_imagenet_2.pth'\n", + " model_512_link_fb = 'https://huggingface.co/lowlevelware/512x512_diffusion_unconditional_ImageNet/resolve/main/512x512_diffusion_uncond_finetune_008100.pt'\n", + " model_secondary_link_fb = 'https://the-eye.eu/public/AI/models/v-diffusion/secondary_model_imagenet_2.pth'\n", "\n", " model_256_path = f'{model_path}/256x256_diffusion_uncond.pt'\n", " model_512_path = f'{model_path}/512x512_diffusion_uncond_finetune_008100.pt'\n", diff --git a/disco.py b/disco.py index 0379e2e1..e6db74d1 100644 --- a/disco.py +++ b/disco.py @@ -1707,8 +1707,8 @@ def download_models(diffusion_model,use_secondary_model,fallback=False): model_secondary_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/secondary_model_imagenet_2.pth' model_256_link_fb = 'https://www.dropbox.com/s/9tqnqo930mpnpcn/256x256_diffusion_uncond.pt' - model_512_link_fb = 'https://www.dropbox.com/s/yjqvhu6l6l0r2eh/512x512_diffusion_uncond_finetune_008100.pt' - model_secondary_link_fb = 'https://www.dropbox.com/s/luv4fezod3r8d2n/secondary_model_imagenet_2.pth' + model_512_link_fb = 'https://huggingface.co/lowlevelware/512x512_diffusion_unconditional_ImageNet/resolve/main/512x512_diffusion_uncond_finetune_008100.pt' + model_secondary_link_fb = 'https://the-eye.eu/public/AI/models/v-diffusion/secondary_model_imagenet_2.pth' model_256_path = f'{model_path}/256x256_diffusion_uncond.pt' model_512_path = f'{model_path}/512x512_diffusion_uncond_finetune_008100.pt' From c9821db89236178e9a90b188a44bd38b89c10c07 Mon Sep 17 00:00:00 2001 From: OodavidsinoO Date: Thu, 5 May 2022 10:12:06 +0800 Subject: [PATCH 70/74] Add option to run with CPU --- Disco_Diffusion.ipynb | 16 ++++++++++------ disco.py | 16 ++++++++++------ 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 6e77387f..17493bef 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -459,10 +459,13 @@ "id": "InstallDeps" }, "source": [ - "#@title ### 1.3 Install and import dependencies\n", + "#@title ### 1.3 Install, import dependencies and set up runtime devices\n", "\n", "import pathlib, shutil, os, sys\n", "\n", + "#@markdown Check this if you want to use CPU\n", + "useCPU = False #@param {type:\"boolean\"}\n", + "\n", "if not is_colab:\n", " # 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", " os.environ['KMP_DUPLICATE_LIB_OK']='TRUE'\n", @@ -597,9 +600,10 @@ "print('Using device:', DEVICE)\n", "device = DEVICE # At least one of the modules expects this name..\n", "\n", - "if torch.cuda.get_device_capability(DEVICE) == (8,0): ## A100 fix thanks to Emad\n", - " print('Disabling CUDNN for A100 gpu', file=sys.stderr)\n", - " torch.backends.cudnn.enabled = False" + "if not useCPU:\n", + " if torch.cuda.get_device_capability(DEVICE) == (8,0): ## A100 fix thanks to Emad\n", + " print('Disabling CUDNN for A100 gpu', file=sys.stderr)\n", + " torch.backends.cudnn.enabled = False" ], "outputs": [], "execution_count": null @@ -1864,7 +1868,7 @@ " 'num_res_blocks': 2,\n", " 'resblock_updown': True,\n", " 'use_checkpoint': use_checkpoint,\n", - " 'use_fp16': True,\n", + " 'use_fp16': not useCPU,\n", " 'use_scale_shift_norm': True,\n", " })\n", "elif diffusion_model == '256x256_diffusion_uncond':\n", @@ -1882,7 +1886,7 @@ " 'num_res_blocks': 2,\n", " 'resblock_updown': True,\n", " 'use_checkpoint': use_checkpoint,\n", - " 'use_fp16': True,\n", + " 'use_fp16': not useCPU,\n", " 'use_scale_shift_norm': True,\n", " })\n", "\n", diff --git a/disco.py b/disco.py index e6db74d1..254c57a4 100644 --- a/disco.py +++ b/disco.py @@ -432,10 +432,13 @@ def createPath(filepath): # !! "cellView": "form", # !! "id": "InstallDeps" # !! }} -#@title ### 1.3 Install and import dependencies +#@title ### 1.3 Install, import dependencies and set up runtime devices import pathlib, shutil, os, sys +# Check this if you want to use CPU +useCPU = False + if not is_colab: # If running locally, there's a good chance your env will need this in order to not crash upon np.matmul() or similar operations. os.environ['KMP_DUPLICATE_LIB_OK']='TRUE' @@ -570,9 +573,10 @@ def createPath(filepath): print('Using device:', DEVICE) device = DEVICE # At least one of the modules expects this name.. -if torch.cuda.get_device_capability(DEVICE) == (8,0): ## A100 fix thanks to Emad - print('Disabling CUDNN for A100 gpu', file=sys.stderr) - torch.backends.cudnn.enabled = False +if not useCPU: + if torch.cuda.get_device_capability(DEVICE) == (8,0): ## A100 fix thanks to Emad + print('Disabling CUDNN for A100 gpu', file=sys.stderr) + torch.backends.cudnn.enabled = False # %% # !! {"metadata": { @@ -1817,7 +1821,7 @@ def download_models(diffusion_model,use_secondary_model,fallback=False): 'num_res_blocks': 2, 'resblock_updown': True, 'use_checkpoint': use_checkpoint, - 'use_fp16': True, + 'use_fp16': not useCPU, 'use_scale_shift_norm': True, }) elif diffusion_model == '256x256_diffusion_uncond': @@ -1835,7 +1839,7 @@ def download_models(diffusion_model,use_secondary_model,fallback=False): 'num_res_blocks': 2, 'resblock_updown': True, 'use_checkpoint': use_checkpoint, - 'use_fp16': True, + 'use_fp16': not useCPU, 'use_scale_shift_norm': True, }) From a3355ca65995ba244a6ae187ca66d4841b06aa2c Mon Sep 17 00:00:00 2001 From: OodavidsinoO Date: Thu, 5 May 2022 10:24:16 +0800 Subject: [PATCH 71/74] Update torch.device() logic --- Disco_Diffusion.ipynb | 2 +- disco.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index 17493bef..b5b1f33d 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -596,7 +596,7 @@ " MAX_ADABINS_AREA = 500000\n", "\n", "import torch\n", - "DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n", + "DEVICE = torch.device('cuda:0' if (torch.cuda.is_available() and not useCPU) else 'cpu')\n", "print('Using device:', DEVICE)\n", "device = DEVICE # At least one of the modules expects this name..\n", "\n", diff --git a/disco.py b/disco.py index 254c57a4..11711c1b 100644 --- a/disco.py +++ b/disco.py @@ -569,7 +569,7 @@ def createPath(filepath): MAX_ADABINS_AREA = 500000 import torch -DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') +DEVICE = torch.device('cuda:0' if (torch.cuda.is_available() and not useCPU) else 'cpu') print('Using device:', DEVICE) device = DEVICE # At least one of the modules expects this name.. From ef39f21033cd27611e99340dc2c5b2c1bfc6295e Mon Sep 17 00:00:00 2001 From: MSFTserver Date: Sat, 14 May 2022 18:18:33 -0700 Subject: [PATCH 72/74] update for compiler align notebooks and python file also add contributing info for converter --- Disco_Diffusion.ipynb | 3 +- README.md | 9 +++ disco.py | 182 +++++++++++++++++++++++++----------------- 3 files changed, 117 insertions(+), 77 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index b5b1f33d..a8c3ca7d 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -2733,8 +2733,7 @@ " # if view_video_in_cell:\n", " # mp4 = open(filepath,'rb').read()\n", " # data_url = \"data:video/mp4;base64,\" + b64encode(mp4).decode()\n", - " # display.HTML(f'')\n", - " " + " # display.HTML(f'')" ], "outputs": [], "execution_count": null diff --git a/README.md b/README.md index 154bf15d..0bc05e35 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,16 @@ A frankensteinian amalgamation of notebooks, models and techniques for the gener [to be updated with further info soon] +## Contributing +This project uses a special conversion tool to convert the python files into notebooks for easier development. +What this means is you do not have to touch the notebook directly to make changes to it + +the tool being used is called [Colab-Convert](https://github.com/MSFTserver/colab-convert) + +- install using `pip install colab-convert` +- convert .py to .ipynb `colab-convert /path/to/file.py /path/to/file.ipynb` +- convert .ipynb to .py `colab-convert /path/to/file.ipynb /path/to/file.py` ## Changelog diff --git a/disco.py b/disco.py index 11711c1b..5e1781e8 100644 --- a/disco.py +++ b/disco.py @@ -1,5 +1,5 @@ # %% -# !! {"metadata": { +# !! {"metadata":{ # !! "id": "view-in-github", # !! "colab_type": "text" # !! }} @@ -8,8 +8,8 @@ """ # %% -# !! {"metadata": { -# !! "id": "TitleTop" +# !! {"metadata":{ +# !! "id": "TitleTop" # !! }} """ # Disco Diffusion v5.2 - Now with VR Mode @@ -20,7 +20,7 @@ """ # %% -# !! {"metadata": { +# !! {"metadata":{ # !! "id": "CreditsChTop" # !! }} """ @@ -28,7 +28,7 @@ """ # %% -# !! {"metadata": { +# !! {"metadata":{ # !! "id": "Credits" # !! }} """ @@ -59,11 +59,10 @@ Improvements to ability to run on local systems, Windows support, and dependency installation by HostsServer (https://twitter.com/HostsServer) VR Mode by Tom Mason (https://twitter.com/nin_artificial) - """ # %% -# !! {"metadata": { +# !! {"metadata":{ # !! "id": "LicenseTop" # !! }} """ @@ -71,9 +70,9 @@ """ # %% -# !! {"metadata": { -# !! "id": "License" -# !! }} +# !! {"metadata":{ +# !! "id": "License" +# !! }} """ Licensed under the MIT License @@ -149,7 +148,7 @@ """ # %% -# !! {"metadata": { +# !! {"metadata":{ # !! "id": "ChangelogTop" # !! }} """ @@ -157,9 +156,9 @@ """ # %% -# !! {"metadata": { +# !! {"metadata":{ # !! "cellView": "form", -# !! "id": "Changelog" +# !! "id": "Changelog" # !! }} #@title <- View Changelog skip_for_run_all = True #@param {type: 'boolean'} @@ -264,9 +263,8 @@ ''' ) - # %% -# !! {"metadata": { +# !! {"metadata":{ # !! "id": "TutorialTop" # !! }} """ @@ -274,8 +272,8 @@ """ # %% -# !! {"metadata": { -# !! "id": "DiffusionSet" +# !! {"metadata":{ +# !! "id": "DiffusionSet" # !! }} """ **Diffusion settings (Defaults are heavily outdated)** @@ -331,17 +329,17 @@ """ # %% -# !! {"metadata": { -# !! "id": "SetupTop" +# !! {"metadata":{ +# !! "id": "SetupTop" # !! }} """ # 1. Set Up """ # %% -# !! {"metadata": { +# !! {"metadata":{ # !! "cellView": "form", -# !! "id": "CheckGPU" +# !! "id": "CheckGPU" # !! }} #@title 1.1 Check GPU Status import subprocess @@ -358,9 +356,9 @@ print(nvidiasmi_ecc_note) # %% -# !! {"metadata": { -# !! "cellView": "form", -# !! "id": "PrepFolders" +# !! {"metadata":{ +# !! "cellView": "form", +# !! "id": "PrepFolders" # !! }} #@title 1.2 Prepare Folders import subprocess, os, sys, ipykernel @@ -428,16 +426,16 @@ def createPath(filepath): # createPath(libraries) # %% -# !! {"metadata": { -# !! "cellView": "form", -# !! "id": "InstallDeps" +# !! {"metadata":{ +# !! "cellView": "form", +# !! "id": "InstallDeps" # !! }} #@title ### 1.3 Install, import dependencies and set up runtime devices import pathlib, shutil, os, sys -# Check this if you want to use CPU -useCPU = False +#@markdown Check this if you want to use CPU +useCPU = False #@param {type:"boolean"} if not is_colab: # If running locally, there's a good chance your env will need this in order to not crash upon np.matmul() or similar operations. @@ -579,9 +577,9 @@ def createPath(filepath): torch.backends.cudnn.enabled = False # %% -# !! {"metadata": { -# !! "cellView": "form", -# !! "id": "DefMidasFns" +# !! {"metadata":{ +# !! "cellView": "form", +# !! "id": "DefMidasFns" # !! }} #@title ### 1.4 Define Midas functions @@ -686,9 +684,9 @@ def init_midas_depth_model(midas_model_type="dpt_large", optimize=True): return midas_model, midas_transform, net_w, net_h, resize_mode, normalization # %% -# !! {"metadata": { -# !! "cellView": "form", -# !! "id": "DefFns" +# !! {"metadata":{ +# !! "cellView": "form", +# !! "id": "DefFns" # !! }} #@title 1.5 Define necessary functions @@ -1497,9 +1495,9 @@ def save_settings(): json.dump(setting_list, f, ensure_ascii=False, indent=4) # %% -# !! {"metadata": { -# !! "cellView": "form", -# !! "id": "DefSecModel" +# !! {"metadata":{ +# !! "cellView": "form", +# !! "id": "DefSecModel" # !! }} #@title 1.6 Define the secondary diffusion model @@ -1665,19 +1663,18 @@ def forward(self, input, t): eps = input * sigmas + v * alphas return DiffusionOutput(v, pred, eps) - # %% -# !! {"metadata": { -# !! "id": "DiffClipSetTop" +# !! {"metadata":{ +# !! "id": "DiffClipSetTop" # !! }} """ # 2. Diffusion and CLIP model settings """ # %% -# !! {"metadata": { +# !! {"metadata":{ # !! "id": "ModelSettings" -# !! }} +# !! }} #@markdown ####**Models Settings:** diffusion_model = "512x512_diffusion_uncond_finetune_008100" #@param ["256x256_diffusion_uncond", "512x512_diffusion_uncond_finetune_008100"] use_secondary_model = True #@param {type: 'boolean'} @@ -1865,19 +1862,18 @@ def download_models(diffusion_model,use_secondary_model,fallback=False): normalize = T.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711]) lpips_model = lpips.LPIPS(net='vgg').to(device) - # %% -# !! {"metadata": { -# !! "id": "SettingsTop" +# !! {"metadata":{ +# !! "id": "SettingsTop" # !! }} """ # 3. Settings """ # %% -# !! {"metadata": { -# !! "id": "BasicSettings" -# !! }} +# !! {"metadata":{ +# !! "id": "BasicSettings" +# !! }} #@markdown ####**Basic Settings:** batch_name = 'TimeToDisco' #@param{type: 'string'} steps = 250 #@param [25,50,100,150,250,500,1000]{type: 'raw', allow-input: true} @@ -1915,18 +1911,17 @@ def download_models(diffusion_model,use_secondary_model,fallback=False): batchFolder = f'{outDirPath}/{batch_name}' createPath(batchFolder) - # %% -# !! {"metadata": { -# !! "id": "AnimSetTop" +# !! {"metadata":{ +# !! "id": "AnimSetTop" # !! }} """ ### Animation Settings """ # %% -# !! {"metadata": { -# !! "id": "AnimSettings" +# !! {"metadata":{ +# !! "id": "AnimSettings" # !! }} #@markdown ####**Animation Mode:** animation_mode = 'None' #@param ['None', '2D', '3D', 'Video Input'] {type:'string'} @@ -2281,10 +2276,9 @@ def split_prompts(prompts): rotation_3d_y = float(rotation_3d_y) rotation_3d_z = float(rotation_3d_z) - # %% -# !! {"metadata": { -# !! "id": "ExtraSetTop" +# !! {"metadata":{ +# !! "id": "ExtraSetTop" # !! }} """ ### Extra Settings @@ -2292,7 +2286,7 @@ def split_prompts(prompts): """ # %% -# !! {"metadata": { +# !! {"metadata":{ # !! "id": "ExtraSettings" # !! }} #@markdown ####**Saving:** @@ -2354,10 +2348,9 @@ def split_prompts(prompts): cut_ic_pow = 1#@param {type: 'number'} cut_icgray_p = "[0.2]*400+[0]*600"#@param {type: 'string'} - # %% -# !! {"metadata": { -# !! "id": "PromptsTop" +# !! {"metadata":{ +# !! "id": "PromptsTop" # !! }} """ ### Prompts @@ -2365,8 +2358,8 @@ def split_prompts(prompts): """ # %% -# !! {"metadata": { -# !! "id": "Prompts" +# !! {"metadata":{ +# !! "id": "Prompts" # !! }} text_prompts = { 0: ["A beautiful painting of a singular lighthouse, shining its light across a tumultuous sea of blood by greg rutkowski and thomas kinkade, Trending on artstation.", "yellow color scheme"], @@ -2377,19 +2370,18 @@ def split_prompts(prompts): # 0:['ImagePromptsWorkButArentVeryGood.png:2',], } - # %% -# !! {"metadata": { -# !! "id": "DiffuseTop" +# !! {"metadata":{ +# !! "id": "DiffuseTop" # !! }} """ # 4. Diffuse! """ # %% -# !! {"metadata": { -# !! "id": "DoTheRun" -# !! }} +# !! {"metadata":{ +# !! "id": "DoTheRun" +# !! }} #@title Do the Run! #@markdown `n_batches` ignored with animation modes. display_rate = 50 #@param{type: 'number'} @@ -2570,18 +2562,17 @@ def move_files(start_num, end_num, old_folder, new_folder): gc.collect() torch.cuda.empty_cache() - # %% -# !! {"metadata": { -# !! "id": "CreateVidTop" +# !! {"metadata":{ +# !! "id": "CreateVidTop" # !! }} """ # 5. Create the video """ # %% -# !! {"metadata": { -# !! "id": "CreateVid" +# !! {"metadata":{ +# !! "id": "CreateVid" # !! }} # @title ### **Create video** #@markdown Video file will save in the same folder as your images. @@ -2657,4 +2648,45 @@ def move_files(start_num, end_num, old_folder, new_folder): # mp4 = open(filepath,'rb').read() # data_url = "data:video/mp4;base64," + b64encode(mp4).decode() # display.HTML(f'') - + +# %% +# !! {"main_metadata":{ +# !! "anaconda-cloud": {}, +# !! "accelerator": "GPU", +# !! "colab": { +# !! "collapsed_sections": [ +# !! "CreditsChTop", +# !! "TutorialTop", +# !! "CheckGPU", +# !! "InstallDeps", +# !! "DefMidasFns", +# !! "DefFns", +# !! "DefSecModel", +# !! "DefSuperRes", +# !! "AnimSetTop", +# !! "ExtraSetTop" +# !! ], +# !! "machine_shape": "hm", +# !! "name": "Disco Diffusion v5.2 [w/ VR Mode]", +# !! "private_outputs": true, +# !! "provenance": [], +# !! "include_colab_link": true +# !! }, +# !! "kernelspec": { +# !! "display_name": "Python 3", +# !! "language": "python", +# !! "name": "python3" +# !! }, +# !! "language_info": { +# !! "codemirror_mode": { +# !! "name": "ipython", +# !! "version": 3 +# !! }, +# !! "file_extension": ".py", +# !! "mimetype": "text/x-python", +# !! "name": "python", +# !! "nbconvert_exporter": "python", +# !! "pygments_lexer": "ipython3", +# !! "version": "3.6.1" +# !! } +# !! }} From c5a3b24f7b8d757ed0517061ac19e6a5a4bf1ef6 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Tue, 17 May 2022 15:27:05 -0400 Subject: [PATCH 73/74] Downgrade torch for T4 and V100 --- Disco_Diffusion.ipynb | 7 +++++++ disco.py | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index a8c3ca7d..e6bffa65 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -463,6 +463,13 @@ "\n", "import pathlib, shutil, os, sys\n", "\n", + "nvidiasmi_output = subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + "cards_requiring_downgrade = [\"Tesla T4\", \"V100\"]\n", + "if any(cardstr in nvidiasmi_output for cardstr in cards_requiring_downgrade):\n", + " print(\"Downgrading pytorch. This can take a couple minutes ...\")\n", + " downgrade_pytorch_result = subprocess.run(['pip', 'install', 'torch==1.10.2', 'torchvision==0.11.3', '-q'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " print(\"pytorch downgraded.\")\n", + "\n", "#@markdown Check this if you want to use CPU\n", "useCPU = False #@param {type:\"boolean\"}\n", "\n", diff --git a/disco.py b/disco.py index 5e1781e8..36fd0609 100644 --- a/disco.py +++ b/disco.py @@ -434,6 +434,13 @@ def createPath(filepath): import pathlib, shutil, os, sys +nvidiasmi_output = subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE).stdout.decode('utf-8') +cards_requiring_downgrade = ["Tesla T4", "V100"] +if any(cardstr in nvidiasmi_output for cardstr in cards_requiring_downgrade): + print("Downgrading pytorch. This can take a couple minutes ...") + downgrade_pytorch_result = subprocess.run(['pip', 'install', 'torch==1.10.2', 'torchvision==0.11.3', '-q'], stdout=subprocess.PIPE).stdout.decode('utf-8') + print("pytorch downgraded.") + #@markdown Check this if you want to use CPU useCPU = False #@param {type:"boolean"} From 789990d4d5bc44e2bc8b8ca3fac804e0b6e7f241 Mon Sep 17 00:00:00 2001 From: Adam Letts Date: Tue, 17 May 2022 16:59:15 -0400 Subject: [PATCH 74/74] Only do the T4 or V100 torch downgrade if on Colab. Indentation changes across all of disco.py and corresponding notebook (standardizing on 4 spaces). --- Disco_Diffusion.ipynb | 605 +++++++++++++++++++++--------------------- disco.py | 605 +++++++++++++++++++++--------------------- 2 files changed, 606 insertions(+), 604 deletions(-) diff --git a/Disco_Diffusion.ipynb b/Disco_Diffusion.ipynb index e6bffa65..30d8caa2 100644 --- a/Disco_Diffusion.ipynb +++ b/Disco_Diffusion.ipynb @@ -364,15 +364,15 @@ "import subprocess\n", "simple_nvidia_smi_display = False#@param {type:\"boolean\"}\n", "if simple_nvidia_smi_display:\n", - " #!nvidia-smi\n", - " nvidiasmi_output = subprocess.run(['nvidia-smi', '-L'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", - " print(nvidiasmi_output)\n", + " #!nvidia-smi\n", + " nvidiasmi_output = subprocess.run(['nvidia-smi', '-L'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " print(nvidiasmi_output)\n", "else:\n", - " #!nvidia-smi -i 0 -e 0\n", - " nvidiasmi_output = subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", - " print(nvidiasmi_output)\n", - " nvidiasmi_ecc_note = subprocess.run(['nvidia-smi', '-i', '0', '-e', '0'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", - " print(nvidiasmi_ecc_note)" + " #!nvidia-smi -i 0 -e 0\n", + " nvidiasmi_output = subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " print(nvidiasmi_output)\n", + " nvidiasmi_ecc_note = subprocess.run(['nvidia-smi', '-i', '0', '-e', '0'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " print(nvidiasmi_ecc_note)" ], "outputs": [], "execution_count": null @@ -388,20 +388,20 @@ "import subprocess, os, sys, ipykernel\n", "\n", "def gitclone(url):\n", - " res = subprocess.run(['git', 'clone', url], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", - " print(res)\n", + " res = subprocess.run(['git', 'clone', url], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " print(res)\n", "\n", "def pipi(modulestr):\n", - " res = subprocess.run(['pip', 'install', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", - " print(res)\n", + " res = subprocess.run(['pip', 'install', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " print(res)\n", "\n", "def pipie(modulestr):\n", - " res = subprocess.run(['git', 'install', '-e', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", - " print(res)\n", + " res = subprocess.run(['git', 'install', '-e', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " print(res)\n", "\n", "def wget(url, outputdir):\n", - " res = subprocess.run(['wget', url, '-P', f'{outputdir}'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", - " print(res)\n", + " res = subprocess.run(['wget', url, '-P', f'{outputdir}'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " print(res)\n", "\n", "try:\n", " from google.colab import drive\n", @@ -465,83 +465,84 @@ "\n", "nvidiasmi_output = subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", "cards_requiring_downgrade = [\"Tesla T4\", \"V100\"]\n", - "if any(cardstr in nvidiasmi_output for cardstr in cards_requiring_downgrade):\n", - " print(\"Downgrading pytorch. This can take a couple minutes ...\")\n", - " downgrade_pytorch_result = subprocess.run(['pip', 'install', 'torch==1.10.2', 'torchvision==0.11.3', '-q'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", - " print(\"pytorch downgraded.\")\n", + "if is_colab:\n", + " if any(cardstr in nvidiasmi_output for cardstr in cards_requiring_downgrade):\n", + " print(\"Downgrading pytorch. This can take a couple minutes ...\")\n", + " downgrade_pytorch_result = subprocess.run(['pip', 'install', 'torch==1.10.2', 'torchvision==0.11.3', '-q'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " print(\"pytorch downgraded.\")\n", "\n", "#@markdown Check this if you want to use CPU\n", "useCPU = False #@param {type:\"boolean\"}\n", "\n", "if not is_colab:\n", - " # 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", - " os.environ['KMP_DUPLICATE_LIB_OK']='TRUE'\n", + " # 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", + " os.environ['KMP_DUPLICATE_LIB_OK']='TRUE'\n", "\n", "PROJECT_DIR = os.path.abspath(os.getcwd())\n", "USE_ADABINS = True\n", "\n", "if is_colab:\n", - " if google_drive is not True:\n", - " root_path = f'/content'\n", - " model_path = '/content/models' \n", + " if not google_drive:\n", + " root_path = f'/content'\n", + " model_path = '/content/models' \n", "else:\n", - " root_path = os.getcwd()\n", - " model_path = f'{root_path}/models'\n", + " root_path = os.getcwd()\n", + " model_path = f'{root_path}/models'\n", "\n", "multipip_res = subprocess.run(['pip', 'install', 'lpips', 'datetime', 'timm', 'ftfy', 'einops', 'pytorch-lightning', 'omegaconf'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", "print(multipip_res)\n", "\n", "if is_colab:\n", - " subprocess.run(['apt', 'install', 'imagemagick'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", + " subprocess.run(['apt', 'install', 'imagemagick'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", "\n", "try:\n", - " from CLIP import clip\n", + " from CLIP import clip\n", "except:\n", - " if not os.path.exists(\"CLIP\"):\n", - " gitclone(\"https://github.com/openai/CLIP\")\n", - " sys.path.append(f'{PROJECT_DIR}/CLIP')\n", + " if not os.path.exists(\"CLIP\"):\n", + " gitclone(\"https://github.com/openai/CLIP\")\n", + " sys.path.append(f'{PROJECT_DIR}/CLIP')\n", "\n", "try:\n", - " from guided_diffusion.script_util import create_model_and_diffusion\n", + " from guided_diffusion.script_util import create_model_and_diffusion\n", "except:\n", - " if not os.path.exists(\"guided-diffusion\"):\n", - " gitclone(\"https://github.com/crowsonkb/guided-diffusion\")\n", - " sys.path.append(f'{PROJECT_DIR}/guided-diffusion')\n", + " if not os.path.exists(\"guided-diffusion\"):\n", + " gitclone(\"https://github.com/crowsonkb/guided-diffusion\")\n", + " sys.path.append(f'{PROJECT_DIR}/guided-diffusion')\n", "\n", "try:\n", - " from resize_right import resize\n", + " from resize_right import resize\n", "except:\n", - " if not os.path.exists(\"ResizeRight\"):\n", - " gitclone(\"https://github.com/assafshocher/ResizeRight.git\")\n", - " sys.path.append(f'{PROJECT_DIR}/ResizeRight')\n", + " if not os.path.exists(\"ResizeRight\"):\n", + " gitclone(\"https://github.com/assafshocher/ResizeRight.git\")\n", + " sys.path.append(f'{PROJECT_DIR}/ResizeRight')\n", "\n", "try:\n", - " import py3d_tools\n", + " import py3d_tools\n", "except:\n", - " if not os.path.exists('pytorch3d-lite'):\n", - " gitclone(\"https://github.com/MSFTserver/pytorch3d-lite.git\")\n", - " sys.path.append(f'{PROJECT_DIR}/pytorch3d-lite')\n", + " if not os.path.exists('pytorch3d-lite'):\n", + " gitclone(\"https://github.com/MSFTserver/pytorch3d-lite.git\")\n", + " sys.path.append(f'{PROJECT_DIR}/pytorch3d-lite')\n", "\n", "try:\n", - " from midas.dpt_depth import DPTDepthModel\n", + " from midas.dpt_depth import DPTDepthModel\n", "except:\n", - " if not os.path.exists('MiDaS'):\n", - " gitclone(\"https://github.com/isl-org/MiDaS.git\")\n", - " if not os.path.exists('MiDaS/midas_utils.py'):\n", - " shutil.move('MiDaS/utils.py', 'MiDaS/midas_utils.py')\n", - " if not os.path.exists(f'{model_path}/dpt_large-midas-2f21e586.pt'):\n", - " wget(\"https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt\", model_path)\n", - " sys.path.append(f'{PROJECT_DIR}/MiDaS')\n", + " if not os.path.exists('MiDaS'):\n", + " gitclone(\"https://github.com/isl-org/MiDaS.git\")\n", + " if not os.path.exists('MiDaS/midas_utils.py'):\n", + " shutil.move('MiDaS/utils.py', 'MiDaS/midas_utils.py')\n", + " if not os.path.exists(f'{model_path}/dpt_large-midas-2f21e586.pt'):\n", + " wget(\"https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt\", model_path)\n", + " sys.path.append(f'{PROJECT_DIR}/MiDaS')\n", "\n", "try:\n", - " sys.path.append(PROJECT_DIR)\n", - " import disco_xform_utils as dxf\n", + " sys.path.append(PROJECT_DIR)\n", + " import disco_xform_utils as dxf\n", "except:\n", - " if not os.path.exists(\"disco-diffusion\"):\n", - " gitclone(\"https://github.com/alembics/disco-diffusion.git\")\n", - " if os.path.exists('disco_xform_utils.py') is not True:\n", - " shutil.move('disco-diffusion/disco_xform_utils.py', 'disco_xform_utils.py')\n", - " sys.path.append(PROJECT_DIR)\n", + " if not os.path.exists(\"disco-diffusion\"):\n", + " gitclone(\"https://github.com/alembics/disco-diffusion.git\")\n", + " if not os.path.exists('disco_xform_utils.py'):\n", + " shutil.move('disco-diffusion/disco_xform_utils.py', 'disco_xform_utils.py')\n", + " sys.path.append(PROJECT_DIR)\n", "\n", "import torch\n", "from dataclasses import dataclass\n", @@ -575,10 +576,10 @@ "import hashlib\n", "from functools import partial\n", "if is_colab:\n", - " os.chdir('/content')\n", - " from google.colab import files\n", + " os.chdir('/content')\n", + " from google.colab import files\n", "else:\n", - " os.chdir(f'{PROJECT_DIR}')\n", + " os.chdir(f'{PROJECT_DIR}')\n", "from IPython.display import Image as ipyimg\n", "from numpy import asarray\n", "from einops import rearrange, repeat\n", @@ -590,17 +591,17 @@ "\n", "# AdaBins stuff\n", "if USE_ADABINS:\n", - " try:\n", + " try:\n", + " from infer import InferenceHelper\n", + " except:\n", + " if not os.path.exists(\"AdaBins\"):\n", + " gitclone(\"https://github.com/shariqfarooq123/AdaBins.git\")\n", + " if not os.path.exists(f'{PROJECT_DIR}/pretrained/AdaBins_nyu.pt'):\n", + " createPath(f'{PROJECT_DIR}/pretrained')\n", + " wget(\"https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt\", f'{PROJECT_DIR}/pretrained')\n", + " sys.path.append(f'{PROJECT_DIR}/AdaBins')\n", " from infer import InferenceHelper\n", - " except:\n", - " if os.path.exists(\"AdaBins\") is not True:\n", - " gitclone(\"https://github.com/shariqfarooq123/AdaBins.git\")\n", - " if not os.path.exists(f'{PROJECT_DIR}/pretrained/AdaBins_nyu.pt'):\n", - " createPath(f'{PROJECT_DIR}/pretrained')\n", - " wget(\"https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt\", f'{PROJECT_DIR}/pretrained')\n", - " sys.path.append(f'{PROJECT_DIR}/AdaBins')\n", - " from infer import InferenceHelper\n", - " MAX_ADABINS_AREA = 500000\n", + " MAX_ADABINS_AREA = 500000\n", "\n", "import torch\n", "DEVICE = torch.device('cuda:0' if (torch.cuda.is_available() and not useCPU) else 'cpu')\n", @@ -608,9 +609,9 @@ "device = DEVICE # At least one of the modules expects this name..\n", "\n", "if not useCPU:\n", - " if torch.cuda.get_device_capability(DEVICE) == (8,0): ## A100 fix thanks to Emad\n", - " print('Disabling CUDNN for A100 gpu', file=sys.stderr)\n", - " torch.backends.cudnn.enabled = False" + " if torch.cuda.get_device_capability(DEVICE) == (8,0): ## A100 fix thanks to Emad\n", + " print('Disabling CUDNN for A100 gpu', file=sys.stderr)\n", + " torch.backends.cudnn.enabled = False" ], "outputs": [], "execution_count": null @@ -1752,110 +1753,110 @@ "check_model_SHA = False #@param{type:\"boolean\"}\n", "\n", "def download_models(diffusion_model,use_secondary_model,fallback=False):\n", - " model_256_downloaded = False\n", - " model_512_downloaded = False\n", - " model_secondary_downloaded = False\n", - "\n", - " model_256_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a'\n", - " model_512_SHA = '9c111ab89e214862b76e1fa6a1b3f1d329b1a88281885943d2cdbe357ad57648'\n", - " model_secondary_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a'\n", - "\n", - " model_256_link = 'https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt'\n", - " model_512_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/512x512_diffusion_uncond_finetune_008100.pt'\n", - " model_secondary_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/secondary_model_imagenet_2.pth'\n", - "\n", - " model_256_link_fb = 'https://www.dropbox.com/s/9tqnqo930mpnpcn/256x256_diffusion_uncond.pt'\n", - " model_512_link_fb = 'https://huggingface.co/lowlevelware/512x512_diffusion_unconditional_ImageNet/resolve/main/512x512_diffusion_uncond_finetune_008100.pt'\n", - " model_secondary_link_fb = 'https://the-eye.eu/public/AI/models/v-diffusion/secondary_model_imagenet_2.pth'\n", - "\n", - " model_256_path = f'{model_path}/256x256_diffusion_uncond.pt'\n", - " model_512_path = f'{model_path}/512x512_diffusion_uncond_finetune_008100.pt'\n", - " model_secondary_path = f'{model_path}/secondary_model_imagenet_2.pth'\n", - "\n", - " if fallback:\n", - " model_256_link = model_256_link_fb\n", - " model_512_link = model_512_link_fb\n", - " model_secondary_link = model_secondary_link_fb\n", - " # Download the diffusion model\n", - " if diffusion_model == '256x256_diffusion_uncond':\n", - " if os.path.exists(model_256_path) and check_model_SHA:\n", - " print('Checking 256 Diffusion File')\n", - " with open(model_256_path,\"rb\") as f:\n", - " bytes = f.read() \n", - " hash = hashlib.sha256(bytes).hexdigest();\n", - " if hash == model_256_SHA:\n", - " print('256 Model SHA matches')\n", - " model_256_downloaded = True\n", - " else: \n", - " print(\"256 Model SHA doesn't match, redownloading...\")\n", - " wget(model_256_link, model_path)\n", - " if os.path.exists(model_256_path):\n", - " model_256_downloaded = True\n", - " else:\n", - " print('First URL Failed using FallBack')\n", - " download_models(diffusion_model,use_secondary_model,True)\n", - " elif os.path.exists(model_256_path) and not check_model_SHA or model_256_downloaded == True:\n", - " print('256 Model already downloaded, check check_model_SHA if the file is corrupt')\n", - " else: \n", - " wget(model_256_link, model_path)\n", - " if os.path.exists(model_256_path):\n", - " model_256_downloaded = True\n", - " else:\n", - " print('First URL Failed using FallBack')\n", - " download_models(diffusion_model,True)\n", - " elif diffusion_model == '512x512_diffusion_uncond_finetune_008100':\n", - " if os.path.exists(model_512_path) and check_model_SHA:\n", - " print('Checking 512 Diffusion File')\n", - " with open(model_512_path,\"rb\") as f:\n", - " bytes = f.read() \n", - " hash = hashlib.sha256(bytes).hexdigest();\n", - " if hash == model_512_SHA:\n", - " print('512 Model SHA matches')\n", - " if os.path.exists(model_512_path):\n", - " model_512_downloaded = True\n", - " else:\n", - " print('First URL Failed using FallBack')\n", - " download_models(diffusion_model,use_secondary_model,True)\n", - " else: \n", - " print(\"512 Model SHA doesn't match, redownloading...\")\n", - " wget(model_512_link, model_path)\n", - " if os.path.exists(model_512_path):\n", - " model_512_downloaded = True\n", - " else:\n", - " print('First URL Failed using FallBack')\n", - " download_models(diffusion_model,use_secondary_model,True)\n", - " elif os.path.exists(model_512_path) and not check_model_SHA or model_512_downloaded == True:\n", - " print('512 Model already downloaded, check check_model_SHA if the file is corrupt')\n", - " else: \n", - " wget(model_512_link, model_path)\n", - " model_512_downloaded = True\n", - " # Download the secondary diffusion model v2\n", - " if use_secondary_model == True:\n", - " if os.path.exists(model_secondary_path) and check_model_SHA:\n", - " print('Checking Secondary Diffusion File')\n", - " with open(model_secondary_path,\"rb\") as f:\n", - " bytes = f.read() \n", - " hash = hashlib.sha256(bytes).hexdigest();\n", - " if hash == model_secondary_SHA:\n", - " print('Secondary Model SHA matches')\n", - " model_secondary_downloaded = True\n", - " else: \n", - " print(\"Secondary Model SHA doesn't match, redownloading...\")\n", - " wget(model_secondary_link, model_path)\n", - " if os.path.exists(model_secondary_path):\n", - " model_secondary_downloaded = True\n", - " else:\n", - " print('First URL Failed using FallBack')\n", - " download_models(diffusion_model,use_secondary_model,True)\n", - " elif os.path.exists(model_secondary_path) and not check_model_SHA or model_secondary_downloaded == True:\n", - " print('Secondary Model already downloaded, check check_model_SHA if the file is corrupt')\n", - " else: \n", - " wget(model_secondary_link, model_path)\n", - " if os.path.exists(model_secondary_path):\n", - " model_secondary_downloaded = True\n", - " else:\n", - " print('First URL Failed using FallBack')\n", - " download_models(diffusion_model,use_secondary_model,True)\n", + " model_256_downloaded = False\n", + " model_512_downloaded = False\n", + " model_secondary_downloaded = False\n", + "\n", + " model_256_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a'\n", + " model_512_SHA = '9c111ab89e214862b76e1fa6a1b3f1d329b1a88281885943d2cdbe357ad57648'\n", + " model_secondary_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a'\n", + "\n", + " model_256_link = 'https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt'\n", + " model_512_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/512x512_diffusion_uncond_finetune_008100.pt'\n", + " model_secondary_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/secondary_model_imagenet_2.pth'\n", + "\n", + " model_256_link_fb = 'https://www.dropbox.com/s/9tqnqo930mpnpcn/256x256_diffusion_uncond.pt'\n", + " model_512_link_fb = 'https://huggingface.co/lowlevelware/512x512_diffusion_unconditional_ImageNet/resolve/main/512x512_diffusion_uncond_finetune_008100.pt'\n", + " model_secondary_link_fb = 'https://the-eye.eu/public/AI/models/v-diffusion/secondary_model_imagenet_2.pth'\n", + "\n", + " model_256_path = f'{model_path}/256x256_diffusion_uncond.pt'\n", + " model_512_path = f'{model_path}/512x512_diffusion_uncond_finetune_008100.pt'\n", + " model_secondary_path = f'{model_path}/secondary_model_imagenet_2.pth'\n", + "\n", + " if fallback:\n", + " model_256_link = model_256_link_fb\n", + " model_512_link = model_512_link_fb\n", + " model_secondary_link = model_secondary_link_fb\n", + " # Download the diffusion model\n", + " if diffusion_model == '256x256_diffusion_uncond':\n", + " if os.path.exists(model_256_path) and check_model_SHA:\n", + " print('Checking 256 Diffusion File')\n", + " with open(model_256_path,\"rb\") as f:\n", + " bytes = f.read() \n", + " hash = hashlib.sha256(bytes).hexdigest();\n", + " if hash == model_256_SHA:\n", + " print('256 Model SHA matches')\n", + " model_256_downloaded = True\n", + " else:\n", + " print(\"256 Model SHA doesn't match, redownloading...\")\n", + " wget(model_256_link, model_path)\n", + " if os.path.exists(model_256_path):\n", + " model_256_downloaded = True\n", + " else:\n", + " print('First URL Failed using FallBack')\n", + " download_models(diffusion_model,use_secondary_model,True)\n", + " elif os.path.exists(model_256_path) and not check_model_SHA or model_256_downloaded == True:\n", + " print('256 Model already downloaded, check check_model_SHA if the file is corrupt')\n", + " else: \n", + " wget(model_256_link, model_path)\n", + " if os.path.exists(model_256_path):\n", + " model_256_downloaded = True\n", + " else:\n", + " print('First URL Failed using FallBack')\n", + " download_models(diffusion_model,True)\n", + " elif diffusion_model == '512x512_diffusion_uncond_finetune_008100':\n", + " if os.path.exists(model_512_path) and check_model_SHA:\n", + " print('Checking 512 Diffusion File')\n", + " with open(model_512_path,\"rb\") as f:\n", + " bytes = f.read() \n", + " hash = hashlib.sha256(bytes).hexdigest();\n", + " if hash == model_512_SHA:\n", + " print('512 Model SHA matches')\n", + " if os.path.exists(model_512_path):\n", + " model_512_downloaded = True\n", + " else:\n", + " print('First URL Failed using FallBack')\n", + " download_models(diffusion_model,use_secondary_model,True)\n", + " else: \n", + " print(\"512 Model SHA doesn't match, redownloading...\")\n", + " wget(model_512_link, model_path)\n", + " if os.path.exists(model_512_path):\n", + " model_512_downloaded = True\n", + " else:\n", + " print('First URL Failed using FallBack')\n", + " download_models(diffusion_model,use_secondary_model,True)\n", + " elif os.path.exists(model_512_path) and not check_model_SHA or model_512_downloaded:\n", + " print('512 Model already downloaded, check check_model_SHA if the file is corrupt')\n", + " else: \n", + " wget(model_512_link, model_path)\n", + " model_512_downloaded = True\n", + " # Download the secondary diffusion model v2\n", + " if use_secondary_model:\n", + " if os.path.exists(model_secondary_path) and check_model_SHA:\n", + " print('Checking Secondary Diffusion File')\n", + " with open(model_secondary_path,\"rb\") as f:\n", + " bytes = f.read() \n", + " hash = hashlib.sha256(bytes).hexdigest();\n", + " if hash == model_secondary_SHA:\n", + " print('Secondary Model SHA matches')\n", + " model_secondary_downloaded = True\n", + " else: \n", + " print(\"Secondary Model SHA doesn't match, redownloading...\")\n", + " wget(model_secondary_link, model_path)\n", + " if os.path.exists(model_secondary_path):\n", + " model_secondary_downloaded = True\n", + " else:\n", + " print('First URL Failed using FallBack')\n", + " download_models(diffusion_model,use_secondary_model,True)\n", + " elif os.path.exists(model_secondary_path) and not check_model_SHA or model_secondary_downloaded:\n", + " print('Secondary Model already downloaded, check check_model_SHA if the file is corrupt')\n", + " else: \n", + " wget(model_secondary_link, model_path)\n", + " if os.path.exists(model_secondary_path):\n", + " model_secondary_downloaded = True\n", + " else:\n", + " print('First URL Failed using FallBack')\n", + " download_models(diffusion_model,use_secondary_model,True)\n", "\n", "download_models(diffusion_model,use_secondary_model)\n", "\n", @@ -1960,7 +1961,7 @@ "side_x = (width_height[0]//64)*64;\n", "side_y = (width_height[1]//64)*64;\n", "if side_x != width_height[0] or side_y != width_height[1]:\n", - " print(f'Changing output size to {side_x}x{side_y}. Dimensions must by multiples of 64.')\n", + " print(f'Changing output size to {side_x}x{side_y}. Dimensions must by multiples of 64.')\n", "\n", "#Update Model Settings\n", "timestep_respacing = f'ddim{steps}'\n", @@ -2015,10 +2016,10 @@ " createPath(videoFramesFolder)\n", " print(f\"Exporting Video Frames (1 every {extract_nth_frame})...\")\n", " try:\n", - " for f in pathlib.Path(f'{videoFramesFolder}').glob('*.jpg'):\n", - " f.unlink()\n", + " for f in pathlib.Path(f'{videoFramesFolder}').glob('*.jpg'):\n", + " f.unlink()\n", " except:\n", - " print('')\n", + " print('')\n", " vf = f'select=not(mod(n\\,{extract_nth_frame}))'\n", " subprocess.run(['ffmpeg', '-i', f'{video_init_path}', '-vf', f'{vf}', '-vsync', 'vfr', '-q:v', '2', '-loglevel', 'error', '-stats', f'{videoFramesFolder}/%04d.jpg'], stdout=subprocess.PIPE).stdout.decode('utf-8')\n", " #!ffmpeg -i {video_init_path} -vf {vf} -vsync vfr -q:v 2 -loglevel error -stats {videoFramesFolder}/%04d.jpg\n", @@ -2034,7 +2035,7 @@ "max_frames = 10000#@param {type:\"number\"}\n", "\n", "if animation_mode == \"Video Input\":\n", - " max_frames = len(glob(f'{videoFramesFolder}/*.jpg'))\n", + " max_frames = len(glob(f'{videoFramesFolder}/*.jpg'))\n", "\n", "interp_spline = 'Linear' #Do not change, currently will not look good. param ['Linear','Quadratic','Cubic']{type:\"string\"}\n", "angle = \"0:(0)\"#@param {type:\"string\"}\n", @@ -2066,10 +2067,10 @@ "\n", "#insist turbo be used only w 3d anim.\n", "if turbo_mode and animation_mode != '3D':\n", - " print('=====')\n", - " print('Turbo mode only available with 3D animations. Disabling Turbo.')\n", - " print('=====')\n", - " turbo_mode = False\n", + " print('=====')\n", + " print('Turbo mode only available with 3D animations. Disabling Turbo.')\n", + " print('=====')\n", + " turbo_mode = False\n", "\n", "#@markdown ---\n", "\n", @@ -2099,10 +2100,10 @@ "\n", "#insist VR be used only w 3d anim.\n", "if vr_mode and animation_mode != '3D':\n", - " print('=====')\n", - " print('VR mode only available with 3D animations. Disabling VR.')\n", - " print('=====')\n", - " vr_mode = False\n", + " print('=====')\n", + " print('VR mode only available with 3D animations. Disabling VR.')\n", + " print('=====')\n", + " vr_mode = False\n", "\n", "\n", "def parse_key_frames(string, prompt_parser=None):\n", @@ -2215,12 +2216,12 @@ " return key_frame_series\n", "\n", "def split_prompts(prompts):\n", - " prompt_series = pd.Series([np.nan for a in range(max_frames)])\n", - " for i, prompt in prompts.items():\n", - " prompt_series[i] = prompt\n", - " # prompt_series = prompt_series.astype(str)\n", - " prompt_series = prompt_series.ffill().bfill()\n", - " return prompt_series\n", + " prompt_series = pd.Series([np.nan for a in range(max_frames)])\n", + " for i, prompt in prompts.items():\n", + " prompt_series[i] = prompt\n", + " # prompt_series = prompt_series.astype(str)\n", + " prompt_series = prompt_series.ffill().bfill()\n", + " return prompt_series\n", "\n", "if key_frames:\n", " try:\n", @@ -2376,20 +2377,20 @@ "\n", "\n", "if type(intermediate_saves) is not list:\n", - " if intermediate_saves:\n", - " steps_per_checkpoint = math.floor((steps - skip_steps - 1) // (intermediate_saves+1))\n", - " steps_per_checkpoint = steps_per_checkpoint if steps_per_checkpoint > 0 else 1\n", - " print(f'Will save every {steps_per_checkpoint} steps')\n", - " else:\n", - " steps_per_checkpoint = steps+10\n", + " if intermediate_saves:\n", + " steps_per_checkpoint = math.floor((steps - skip_steps - 1) // (intermediate_saves+1))\n", + " steps_per_checkpoint = steps_per_checkpoint if steps_per_checkpoint > 0 else 1\n", + " print(f'Will save every {steps_per_checkpoint} steps')\n", + " else:\n", + " steps_per_checkpoint = steps+10\n", "else:\n", - " steps_per_checkpoint = None\n", + " steps_per_checkpoint = None\n", "\n", "if intermediate_saves and intermediates_in_subfolder is True:\n", - " partialFolder = f'{batchFolder}/partials'\n", - " createPath(partialFolder)\n", + " partialFolder = f'{batchFolder}/partials'\n", + " createPath(partialFolder)\n", "\n", - " #@markdown ---\n", + "#@markdown ---\n", "\n", "#@markdown ####**Advanced Settings:**\n", "#@markdown *There are a few extra advanced settings available if you double click this cell.*\n", @@ -2411,7 +2412,7 @@ "rand_mag = 0.05\n", "\n", "\n", - " #@markdown ---\n", + "#@markdown ---\n", "\n", "#@markdown ####**Cutn Scheduling:**\n", "#@markdown Format: `[40]*400+[20]*600` = 40 cuts for the first 400 /1000 steps, then 20 for the last 600/1000\n", @@ -2497,9 +2498,9 @@ "run_to_resume = 'latest' #@param{type: 'string'}\n", "resume_from_frame = 'latest' #@param{type: 'string'}\n", "retain_overwritten_frames = False #@param{type: 'boolean'}\n", - "if retain_overwritten_frames is True:\n", - " retainFolder = f'{batchFolder}/retained'\n", - " createPath(retainFolder)\n", + "if retain_overwritten_frames:\n", + " retainFolder = f'{batchFolder}/retained'\n", + " createPath(retainFolder)\n", "\n", "\n", "skip_step_ratio = int(frames_skip_steps.rstrip(\"%\")) / 100\n", @@ -2510,31 +2511,31 @@ " sys.exit(\"ERROR: You can't skip more steps than your total steps\")\n", "\n", "if resume_run:\n", - " if run_to_resume == 'latest':\n", - " try:\n", - " batchNum\n", - " except:\n", - " batchNum = len(glob(f\"{batchFolder}/{batch_name}(*)_settings.txt\"))-1\n", - " else:\n", - " batchNum = int(run_to_resume)\n", - " if resume_from_frame == 'latest':\n", - " start_frame = len(glob(batchFolder+f\"/{batch_name}({batchNum})_*.png\"))\n", - " if animation_mode != '3D' and turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0:\n", - " start_frame = start_frame - (start_frame % int(turbo_steps))\n", - " else:\n", - " start_frame = int(resume_from_frame)+1\n", - " if animation_mode != '3D' and turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0:\n", - " start_frame = start_frame - (start_frame % int(turbo_steps))\n", - " if retain_overwritten_frames is True:\n", - " existing_frames = len(glob(batchFolder+f\"/{batch_name}({batchNum})_*.png\"))\n", - " frames_to_save = existing_frames - start_frame\n", - " print(f'Moving {frames_to_save} frames to the Retained folder')\n", - " move_files(start_frame, existing_frames, batchFolder, retainFolder)\n", + " if run_to_resume == 'latest':\n", + " try:\n", + " batchNum\n", + " except:\n", + " batchNum = len(glob(f\"{batchFolder}/{batch_name}(*)_settings.txt\"))-1\n", + " else:\n", + " batchNum = int(run_to_resume)\n", + " if resume_from_frame == 'latest':\n", + " start_frame = len(glob(batchFolder+f\"/{batch_name}({batchNum})_*.png\"))\n", + " if animation_mode != '3D' and turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0:\n", + " start_frame = start_frame - (start_frame % int(turbo_steps))\n", + " else:\n", + " start_frame = int(resume_from_frame)+1\n", + " if animation_mode != '3D' and turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0:\n", + " start_frame = start_frame - (start_frame % int(turbo_steps))\n", + " if retain_overwritten_frames is True:\n", + " existing_frames = len(glob(batchFolder+f\"/{batch_name}({batchNum})_*.png\"))\n", + " frames_to_save = existing_frames - start_frame\n", + " print(f'Moving {frames_to_save} frames to the Retained folder')\n", + " move_files(start_frame, existing_frames, batchFolder, retainFolder)\n", "else:\n", - " start_frame = 0\n", - " batchNum = len(glob(batchFolder+\"/*.txt\"))\n", - " while os.path.isfile(f\"{batchFolder}/{batch_name}({batchNum})_settings.txt\") is True or os.path.isfile(f\"{batchFolder}/{batch_name}-{batchNum}_settings.txt\") is True:\n", - " batchNum += 1\n", + " start_frame = 0\n", + " batchNum = len(glob(batchFolder+\"/*.txt\"))\n", + " while os.path.isfile(f\"{batchFolder}/{batch_name}({batchNum})_settings.txt\") or os.path.isfile(f\"{batchFolder}/{batch_name}-{batchNum}_settings.txt\"):\n", + " batchNum += 1\n", "\n", "print(f'Starting Run: {batch_name}({batchNum}) at frame {start_frame}')\n", "\n", @@ -2641,7 +2642,7 @@ "gc.collect()\n", "torch.cuda.empty_cache()\n", "try:\n", - " do_run()\n", + " do_run()\n", "except KeyboardInterrupt:\n", " pass\n", "finally:\n", @@ -2673,74 +2674,74 @@ "skip_video_for_run_all = True #@param {type: 'boolean'}\n", "\n", "if skip_video_for_run_all == True:\n", - " print('Skipping video creation, uncheck skip_video_for_run_all if you want to run it')\n", + " print('Skipping video creation, uncheck skip_video_for_run_all if you want to run it')\n", "\n", "else:\n", - " # import subprocess in case this cell is run without the above cells\n", - " import subprocess\n", - " from base64 import b64encode\n", - "\n", - " latest_run = batchNum\n", - "\n", - " folder = batch_name #@param\n", - " run = latest_run #@param\n", - " final_frame = 'final_frame'\n", - "\n", - "\n", - " init_frame = 1#@param {type:\"number\"} This is the frame where the video will start\n", - " 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", - " fps = 12#@param {type:\"number\"}\n", - " # view_video_in_cell = True #@param {type: 'boolean'}\n", - "\n", - " frames = []\n", - " # tqdm.write('Generating video...')\n", - "\n", - " if last_frame == 'final_frame':\n", - " last_frame = len(glob(batchFolder+f\"/{folder}({run})_*.png\"))\n", - " print(f'Total frames: {last_frame}')\n", - "\n", - " image_path = f\"{outDirPath}/{folder}/{folder}({run})_%04d.png\"\n", - " filepath = f\"{outDirPath}/{folder}/{folder}({run}).mp4\"\n", - "\n", - "\n", - " cmd = [\n", - " 'ffmpeg',\n", - " '-y',\n", - " '-vcodec',\n", - " 'png',\n", - " '-r',\n", - " str(fps),\n", - " '-start_number',\n", - " str(init_frame),\n", - " '-i',\n", - " image_path,\n", - " '-frames:v',\n", - " str(last_frame+1),\n", - " '-c:v',\n", - " 'libx264',\n", - " '-vf',\n", - " f'fps={fps}',\n", - " '-pix_fmt',\n", - " 'yuv420p',\n", - " '-crf',\n", - " '17',\n", - " '-preset',\n", - " 'veryslow',\n", - " filepath\n", - " ]\n", - "\n", - " process = subprocess.Popen(cmd, cwd=f'{batchFolder}', stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n", - " stdout, stderr = process.communicate()\n", - " if process.returncode != 0:\n", - " print(stderr)\n", - " raise RuntimeError(stderr)\n", - " else:\n", - " print(\"The video is ready and saved to the images folder\")\n", + " # import subprocess in case this cell is run without the above cells\n", + " import subprocess\n", + " from base64 import b64encode\n", + "\n", + " latest_run = batchNum\n", + "\n", + " folder = batch_name #@param\n", + " run = latest_run #@param\n", + " final_frame = 'final_frame'\n", + "\n", + "\n", + " init_frame = 1#@param {type:\"number\"} This is the frame where the video will start\n", + " 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", + " fps = 12#@param {type:\"number\"}\n", + " # view_video_in_cell = True #@param {type: 'boolean'}\n", + "\n", + " frames = []\n", + " # tqdm.write('Generating video...')\n", + "\n", + " if last_frame == 'final_frame':\n", + " last_frame = len(glob(batchFolder+f\"/{folder}({run})_*.png\"))\n", + " print(f'Total frames: {last_frame}')\n", + "\n", + " image_path = f\"{outDirPath}/{folder}/{folder}({run})_%04d.png\"\n", + " filepath = f\"{outDirPath}/{folder}/{folder}({run}).mp4\"\n", + "\n", + "\n", + " cmd = [\n", + " 'ffmpeg',\n", + " '-y',\n", + " '-vcodec',\n", + " 'png',\n", + " '-r',\n", + " str(fps),\n", + " '-start_number',\n", + " str(init_frame),\n", + " '-i',\n", + " image_path,\n", + " '-frames:v',\n", + " str(last_frame+1),\n", + " '-c:v',\n", + " 'libx264',\n", + " '-vf',\n", + " f'fps={fps}',\n", + " '-pix_fmt',\n", + " 'yuv420p',\n", + " '-crf',\n", + " '17',\n", + " '-preset',\n", + " 'veryslow',\n", + " filepath\n", + " ]\n", + "\n", + " process = subprocess.Popen(cmd, cwd=f'{batchFolder}', stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n", + " stdout, stderr = process.communicate()\n", + " if process.returncode != 0:\n", + " print(stderr)\n", + " raise RuntimeError(stderr)\n", + " else:\n", + " print(\"The video is ready and saved to the images folder\")\n", "\n", - " # if view_video_in_cell:\n", - " # mp4 = open(filepath,'rb').read()\n", - " # data_url = \"data:video/mp4;base64,\" + b64encode(mp4).decode()\n", - " # display.HTML(f'')" + " # if view_video_in_cell:\n", + " # mp4 = open(filepath,'rb').read()\n", + " # data_url = \"data:video/mp4;base64,\" + b64encode(mp4).decode()\n", + " # display.HTML(f'')" ], "outputs": [], "execution_count": null diff --git a/disco.py b/disco.py index 36fd0609..74356a66 100644 --- a/disco.py +++ b/disco.py @@ -345,15 +345,15 @@ import subprocess simple_nvidia_smi_display = False#@param {type:"boolean"} if simple_nvidia_smi_display: - #!nvidia-smi - nvidiasmi_output = subprocess.run(['nvidia-smi', '-L'], stdout=subprocess.PIPE).stdout.decode('utf-8') - print(nvidiasmi_output) + #!nvidia-smi + nvidiasmi_output = subprocess.run(['nvidia-smi', '-L'], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(nvidiasmi_output) else: - #!nvidia-smi -i 0 -e 0 - nvidiasmi_output = subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE).stdout.decode('utf-8') - print(nvidiasmi_output) - nvidiasmi_ecc_note = subprocess.run(['nvidia-smi', '-i', '0', '-e', '0'], stdout=subprocess.PIPE).stdout.decode('utf-8') - print(nvidiasmi_ecc_note) + #!nvidia-smi -i 0 -e 0 + nvidiasmi_output = subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(nvidiasmi_output) + nvidiasmi_ecc_note = subprocess.run(['nvidia-smi', '-i', '0', '-e', '0'], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(nvidiasmi_ecc_note) # %% # !! {"metadata":{ @@ -364,20 +364,20 @@ import subprocess, os, sys, ipykernel def gitclone(url): - res = subprocess.run(['git', 'clone', url], stdout=subprocess.PIPE).stdout.decode('utf-8') - print(res) + res = subprocess.run(['git', 'clone', url], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(res) def pipi(modulestr): - res = subprocess.run(['pip', 'install', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8') - print(res) + res = subprocess.run(['pip', 'install', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(res) def pipie(modulestr): - res = subprocess.run(['git', 'install', '-e', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8') - print(res) + res = subprocess.run(['git', 'install', '-e', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(res) def wget(url, outputdir): - res = subprocess.run(['wget', url, '-P', f'{outputdir}'], stdout=subprocess.PIPE).stdout.decode('utf-8') - print(res) + res = subprocess.run(['wget', url, '-P', f'{outputdir}'], stdout=subprocess.PIPE).stdout.decode('utf-8') + print(res) try: from google.colab import drive @@ -436,83 +436,84 @@ def createPath(filepath): nvidiasmi_output = subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE).stdout.decode('utf-8') cards_requiring_downgrade = ["Tesla T4", "V100"] -if any(cardstr in nvidiasmi_output for cardstr in cards_requiring_downgrade): - print("Downgrading pytorch. This can take a couple minutes ...") - downgrade_pytorch_result = subprocess.run(['pip', 'install', 'torch==1.10.2', 'torchvision==0.11.3', '-q'], stdout=subprocess.PIPE).stdout.decode('utf-8') - print("pytorch downgraded.") +if is_colab: + if any(cardstr in nvidiasmi_output for cardstr in cards_requiring_downgrade): + print("Downgrading pytorch. This can take a couple minutes ...") + downgrade_pytorch_result = subprocess.run(['pip', 'install', 'torch==1.10.2', 'torchvision==0.11.3', '-q'], stdout=subprocess.PIPE).stdout.decode('utf-8') + print("pytorch downgraded.") #@markdown Check this if you want to use CPU useCPU = False #@param {type:"boolean"} if not is_colab: - # If running locally, there's a good chance your env will need this in order to not crash upon np.matmul() or similar operations. - os.environ['KMP_DUPLICATE_LIB_OK']='TRUE' + # If running locally, there's a good chance your env will need this in order to not crash upon np.matmul() or similar operations. + os.environ['KMP_DUPLICATE_LIB_OK']='TRUE' PROJECT_DIR = os.path.abspath(os.getcwd()) USE_ADABINS = True if is_colab: - if google_drive is not True: - root_path = f'/content' - model_path = '/content/models' + if not google_drive: + root_path = f'/content' + model_path = '/content/models' else: - root_path = os.getcwd() - model_path = f'{root_path}/models' + root_path = os.getcwd() + model_path = f'{root_path}/models' multipip_res = subprocess.run(['pip', 'install', 'lpips', 'datetime', 'timm', 'ftfy', 'einops', 'pytorch-lightning', 'omegaconf'], stdout=subprocess.PIPE).stdout.decode('utf-8') print(multipip_res) if is_colab: - subprocess.run(['apt', 'install', 'imagemagick'], stdout=subprocess.PIPE).stdout.decode('utf-8') + subprocess.run(['apt', 'install', 'imagemagick'], stdout=subprocess.PIPE).stdout.decode('utf-8') try: - from CLIP import clip + from CLIP import clip except: - if not os.path.exists("CLIP"): - gitclone("https://github.com/openai/CLIP") - sys.path.append(f'{PROJECT_DIR}/CLIP') + if not os.path.exists("CLIP"): + gitclone("https://github.com/openai/CLIP") + sys.path.append(f'{PROJECT_DIR}/CLIP') try: - from guided_diffusion.script_util import create_model_and_diffusion + from guided_diffusion.script_util import create_model_and_diffusion except: - if not os.path.exists("guided-diffusion"): - gitclone("https://github.com/crowsonkb/guided-diffusion") - sys.path.append(f'{PROJECT_DIR}/guided-diffusion') + if not os.path.exists("guided-diffusion"): + gitclone("https://github.com/crowsonkb/guided-diffusion") + sys.path.append(f'{PROJECT_DIR}/guided-diffusion') try: - from resize_right import resize + from resize_right import resize except: - if not os.path.exists("ResizeRight"): - gitclone("https://github.com/assafshocher/ResizeRight.git") - sys.path.append(f'{PROJECT_DIR}/ResizeRight') + if not os.path.exists("ResizeRight"): + gitclone("https://github.com/assafshocher/ResizeRight.git") + sys.path.append(f'{PROJECT_DIR}/ResizeRight') try: - import py3d_tools + import py3d_tools except: - if not os.path.exists('pytorch3d-lite'): - gitclone("https://github.com/MSFTserver/pytorch3d-lite.git") - sys.path.append(f'{PROJECT_DIR}/pytorch3d-lite') + if not os.path.exists('pytorch3d-lite'): + gitclone("https://github.com/MSFTserver/pytorch3d-lite.git") + sys.path.append(f'{PROJECT_DIR}/pytorch3d-lite') try: - from midas.dpt_depth import DPTDepthModel + from midas.dpt_depth import DPTDepthModel except: - if not os.path.exists('MiDaS'): - gitclone("https://github.com/isl-org/MiDaS.git") - if not os.path.exists('MiDaS/midas_utils.py'): - shutil.move('MiDaS/utils.py', 'MiDaS/midas_utils.py') - if not os.path.exists(f'{model_path}/dpt_large-midas-2f21e586.pt'): - wget("https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", model_path) - sys.path.append(f'{PROJECT_DIR}/MiDaS') + if not os.path.exists('MiDaS'): + gitclone("https://github.com/isl-org/MiDaS.git") + if not os.path.exists('MiDaS/midas_utils.py'): + shutil.move('MiDaS/utils.py', 'MiDaS/midas_utils.py') + if not os.path.exists(f'{model_path}/dpt_large-midas-2f21e586.pt'): + wget("https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", model_path) + sys.path.append(f'{PROJECT_DIR}/MiDaS') try: - sys.path.append(PROJECT_DIR) - import disco_xform_utils as dxf + sys.path.append(PROJECT_DIR) + import disco_xform_utils as dxf except: - if not os.path.exists("disco-diffusion"): - gitclone("https://github.com/alembics/disco-diffusion.git") - if os.path.exists('disco_xform_utils.py') is not True: - shutil.move('disco-diffusion/disco_xform_utils.py', 'disco_xform_utils.py') - sys.path.append(PROJECT_DIR) + if not os.path.exists("disco-diffusion"): + gitclone("https://github.com/alembics/disco-diffusion.git") + if not os.path.exists('disco_xform_utils.py'): + shutil.move('disco-diffusion/disco_xform_utils.py', 'disco_xform_utils.py') + sys.path.append(PROJECT_DIR) import torch from dataclasses import dataclass @@ -546,10 +547,10 @@ def createPath(filepath): import hashlib from functools import partial if is_colab: - os.chdir('/content') - from google.colab import files + os.chdir('/content') + from google.colab import files else: - os.chdir(f'{PROJECT_DIR}') + os.chdir(f'{PROJECT_DIR}') from IPython.display import Image as ipyimg from numpy import asarray from einops import rearrange, repeat @@ -561,17 +562,17 @@ def createPath(filepath): # AdaBins stuff if USE_ADABINS: - try: + try: + from infer import InferenceHelper + except: + if not os.path.exists("AdaBins"): + gitclone("https://github.com/shariqfarooq123/AdaBins.git") + if not os.path.exists(f'{PROJECT_DIR}/pretrained/AdaBins_nyu.pt'): + createPath(f'{PROJECT_DIR}/pretrained') + wget("https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt", f'{PROJECT_DIR}/pretrained') + sys.path.append(f'{PROJECT_DIR}/AdaBins') from infer import InferenceHelper - except: - if os.path.exists("AdaBins") is not True: - gitclone("https://github.com/shariqfarooq123/AdaBins.git") - if not os.path.exists(f'{PROJECT_DIR}/pretrained/AdaBins_nyu.pt'): - createPath(f'{PROJECT_DIR}/pretrained') - wget("https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt", f'{PROJECT_DIR}/pretrained') - sys.path.append(f'{PROJECT_DIR}/AdaBins') - from infer import InferenceHelper - MAX_ADABINS_AREA = 500000 + MAX_ADABINS_AREA = 500000 import torch DEVICE = torch.device('cuda:0' if (torch.cuda.is_available() and not useCPU) else 'cpu') @@ -579,9 +580,9 @@ def createPath(filepath): device = DEVICE # At least one of the modules expects this name.. if not useCPU: - if torch.cuda.get_device_capability(DEVICE) == (8,0): ## A100 fix thanks to Emad - print('Disabling CUDNN for A100 gpu', file=sys.stderr) - torch.backends.cudnn.enabled = False + if torch.cuda.get_device_capability(DEVICE) == (8,0): ## A100 fix thanks to Emad + print('Disabling CUDNN for A100 gpu', file=sys.stderr) + torch.backends.cudnn.enabled = False # %% # !! {"metadata":{ @@ -1702,110 +1703,110 @@ def forward(self, input, t): check_model_SHA = False #@param{type:"boolean"} def download_models(diffusion_model,use_secondary_model,fallback=False): - model_256_downloaded = False - model_512_downloaded = False - model_secondary_downloaded = False - - model_256_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a' - model_512_SHA = '9c111ab89e214862b76e1fa6a1b3f1d329b1a88281885943d2cdbe357ad57648' - model_secondary_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a' - - model_256_link = 'https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt' - model_512_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/512x512_diffusion_uncond_finetune_008100.pt' - model_secondary_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/secondary_model_imagenet_2.pth' - - model_256_link_fb = 'https://www.dropbox.com/s/9tqnqo930mpnpcn/256x256_diffusion_uncond.pt' - model_512_link_fb = 'https://huggingface.co/lowlevelware/512x512_diffusion_unconditional_ImageNet/resolve/main/512x512_diffusion_uncond_finetune_008100.pt' - model_secondary_link_fb = 'https://the-eye.eu/public/AI/models/v-diffusion/secondary_model_imagenet_2.pth' - - model_256_path = f'{model_path}/256x256_diffusion_uncond.pt' - model_512_path = f'{model_path}/512x512_diffusion_uncond_finetune_008100.pt' - model_secondary_path = f'{model_path}/secondary_model_imagenet_2.pth' - - if fallback: - model_256_link = model_256_link_fb - model_512_link = model_512_link_fb - model_secondary_link = model_secondary_link_fb - # Download the diffusion model - if diffusion_model == '256x256_diffusion_uncond': - if os.path.exists(model_256_path) and check_model_SHA: - print('Checking 256 Diffusion File') - with open(model_256_path,"rb") as f: - bytes = f.read() - hash = hashlib.sha256(bytes).hexdigest(); - if hash == model_256_SHA: - print('256 Model SHA matches') - model_256_downloaded = True - else: - print("256 Model SHA doesn't match, redownloading...") - wget(model_256_link, model_path) - if os.path.exists(model_256_path): - model_256_downloaded = True - else: - print('First URL Failed using FallBack') - download_models(diffusion_model,use_secondary_model,True) - elif os.path.exists(model_256_path) and not check_model_SHA or model_256_downloaded == True: - print('256 Model already downloaded, check check_model_SHA if the file is corrupt') - else: - wget(model_256_link, model_path) - if os.path.exists(model_256_path): - model_256_downloaded = True - else: - print('First URL Failed using FallBack') - download_models(diffusion_model,True) - elif diffusion_model == '512x512_diffusion_uncond_finetune_008100': - if os.path.exists(model_512_path) and check_model_SHA: - print('Checking 512 Diffusion File') - with open(model_512_path,"rb") as f: - bytes = f.read() - hash = hashlib.sha256(bytes).hexdigest(); - if hash == model_512_SHA: - print('512 Model SHA matches') - if os.path.exists(model_512_path): - model_512_downloaded = True - else: - print('First URL Failed using FallBack') - download_models(diffusion_model,use_secondary_model,True) - else: - print("512 Model SHA doesn't match, redownloading...") - wget(model_512_link, model_path) - if os.path.exists(model_512_path): - model_512_downloaded = True - else: - print('First URL Failed using FallBack') - download_models(diffusion_model,use_secondary_model,True) - elif os.path.exists(model_512_path) and not check_model_SHA or model_512_downloaded == True: - print('512 Model already downloaded, check check_model_SHA if the file is corrupt') - else: - wget(model_512_link, model_path) - model_512_downloaded = True - # Download the secondary diffusion model v2 - if use_secondary_model == True: - if os.path.exists(model_secondary_path) and check_model_SHA: - print('Checking Secondary Diffusion File') - with open(model_secondary_path,"rb") as f: - bytes = f.read() - hash = hashlib.sha256(bytes).hexdigest(); - if hash == model_secondary_SHA: - print('Secondary Model SHA matches') - model_secondary_downloaded = True - else: - print("Secondary Model SHA doesn't match, redownloading...") - wget(model_secondary_link, model_path) - if os.path.exists(model_secondary_path): - model_secondary_downloaded = True - else: - print('First URL Failed using FallBack') - download_models(diffusion_model,use_secondary_model,True) - elif os.path.exists(model_secondary_path) and not check_model_SHA or model_secondary_downloaded == True: - print('Secondary Model already downloaded, check check_model_SHA if the file is corrupt') - else: - wget(model_secondary_link, model_path) - if os.path.exists(model_secondary_path): - model_secondary_downloaded = True - else: - print('First URL Failed using FallBack') - download_models(diffusion_model,use_secondary_model,True) + model_256_downloaded = False + model_512_downloaded = False + model_secondary_downloaded = False + + model_256_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a' + model_512_SHA = '9c111ab89e214862b76e1fa6a1b3f1d329b1a88281885943d2cdbe357ad57648' + model_secondary_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a' + + model_256_link = 'https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt' + model_512_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/512x512_diffusion_uncond_finetune_008100.pt' + model_secondary_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/secondary_model_imagenet_2.pth' + + model_256_link_fb = 'https://www.dropbox.com/s/9tqnqo930mpnpcn/256x256_diffusion_uncond.pt' + model_512_link_fb = 'https://huggingface.co/lowlevelware/512x512_diffusion_unconditional_ImageNet/resolve/main/512x512_diffusion_uncond_finetune_008100.pt' + model_secondary_link_fb = 'https://the-eye.eu/public/AI/models/v-diffusion/secondary_model_imagenet_2.pth' + + model_256_path = f'{model_path}/256x256_diffusion_uncond.pt' + model_512_path = f'{model_path}/512x512_diffusion_uncond_finetune_008100.pt' + model_secondary_path = f'{model_path}/secondary_model_imagenet_2.pth' + + if fallback: + model_256_link = model_256_link_fb + model_512_link = model_512_link_fb + model_secondary_link = model_secondary_link_fb + # Download the diffusion model + if diffusion_model == '256x256_diffusion_uncond': + if os.path.exists(model_256_path) and check_model_SHA: + print('Checking 256 Diffusion File') + with open(model_256_path,"rb") as f: + bytes = f.read() + hash = hashlib.sha256(bytes).hexdigest(); + if hash == model_256_SHA: + print('256 Model SHA matches') + model_256_downloaded = True + else: + print("256 Model SHA doesn't match, redownloading...") + wget(model_256_link, model_path) + if os.path.exists(model_256_path): + model_256_downloaded = True + else: + print('First URL Failed using FallBack') + download_models(diffusion_model,use_secondary_model,True) + elif os.path.exists(model_256_path) and not check_model_SHA or model_256_downloaded == True: + print('256 Model already downloaded, check check_model_SHA if the file is corrupt') + else: + wget(model_256_link, model_path) + if os.path.exists(model_256_path): + model_256_downloaded = True + else: + print('First URL Failed using FallBack') + download_models(diffusion_model,True) + elif diffusion_model == '512x512_diffusion_uncond_finetune_008100': + if os.path.exists(model_512_path) and check_model_SHA: + print('Checking 512 Diffusion File') + with open(model_512_path,"rb") as f: + bytes = f.read() + hash = hashlib.sha256(bytes).hexdigest(); + if hash == model_512_SHA: + print('512 Model SHA matches') + if os.path.exists(model_512_path): + model_512_downloaded = True + else: + print('First URL Failed using FallBack') + download_models(diffusion_model,use_secondary_model,True) + else: + print("512 Model SHA doesn't match, redownloading...") + wget(model_512_link, model_path) + if os.path.exists(model_512_path): + model_512_downloaded = True + else: + print('First URL Failed using FallBack') + download_models(diffusion_model,use_secondary_model,True) + elif os.path.exists(model_512_path) and not check_model_SHA or model_512_downloaded: + print('512 Model already downloaded, check check_model_SHA if the file is corrupt') + else: + wget(model_512_link, model_path) + model_512_downloaded = True + # Download the secondary diffusion model v2 + if use_secondary_model: + if os.path.exists(model_secondary_path) and check_model_SHA: + print('Checking Secondary Diffusion File') + with open(model_secondary_path,"rb") as f: + bytes = f.read() + hash = hashlib.sha256(bytes).hexdigest(); + if hash == model_secondary_SHA: + print('Secondary Model SHA matches') + model_secondary_downloaded = True + else: + print("Secondary Model SHA doesn't match, redownloading...") + wget(model_secondary_link, model_path) + if os.path.exists(model_secondary_path): + model_secondary_downloaded = True + else: + print('First URL Failed using FallBack') + download_models(diffusion_model,use_secondary_model,True) + elif os.path.exists(model_secondary_path) and not check_model_SHA or model_secondary_downloaded: + print('Secondary Model already downloaded, check check_model_SHA if the file is corrupt') + else: + wget(model_secondary_link, model_path) + if os.path.exists(model_secondary_path): + model_secondary_downloaded = True + else: + print('First URL Failed using FallBack') + download_models(diffusion_model,use_secondary_model,True) download_models(diffusion_model,use_secondary_model) @@ -1904,7 +1905,7 @@ def download_models(diffusion_model,use_secondary_model,fallback=False): side_x = (width_height[0]//64)*64; side_y = (width_height[1]//64)*64; if side_x != width_height[0] or side_y != width_height[1]: - print(f'Changing output size to {side_x}x{side_y}. Dimensions must by multiples of 64.') + print(f'Changing output size to {side_x}x{side_y}. Dimensions must by multiples of 64.') #Update Model Settings timestep_respacing = f'ddim{steps}' @@ -1953,10 +1954,10 @@ def download_models(diffusion_model,use_secondary_model,fallback=False): createPath(videoFramesFolder) print(f"Exporting Video Frames (1 every {extract_nth_frame})...") try: - for f in pathlib.Path(f'{videoFramesFolder}').glob('*.jpg'): - f.unlink() + for f in pathlib.Path(f'{videoFramesFolder}').glob('*.jpg'): + f.unlink() except: - print('') + print('') vf = f'select=not(mod(n\,{extract_nth_frame}))' subprocess.run(['ffmpeg', '-i', f'{video_init_path}', '-vf', f'{vf}', '-vsync', 'vfr', '-q:v', '2', '-loglevel', 'error', '-stats', f'{videoFramesFolder}/%04d.jpg'], stdout=subprocess.PIPE).stdout.decode('utf-8') #!ffmpeg -i {video_init_path} -vf {vf} -vsync vfr -q:v 2 -loglevel error -stats {videoFramesFolder}/%04d.jpg @@ -1972,7 +1973,7 @@ def download_models(diffusion_model,use_secondary_model,fallback=False): max_frames = 10000#@param {type:"number"} if animation_mode == "Video Input": - max_frames = len(glob(f'{videoFramesFolder}/*.jpg')) + max_frames = len(glob(f'{videoFramesFolder}/*.jpg')) interp_spline = 'Linear' #Do not change, currently will not look good. param ['Linear','Quadratic','Cubic']{type:"string"} angle = "0:(0)"#@param {type:"string"} @@ -2004,10 +2005,10 @@ def download_models(diffusion_model,use_secondary_model,fallback=False): #insist turbo be used only w 3d anim. if turbo_mode and animation_mode != '3D': - print('=====') - print('Turbo mode only available with 3D animations. Disabling Turbo.') - print('=====') - turbo_mode = False + print('=====') + print('Turbo mode only available with 3D animations. Disabling Turbo.') + print('=====') + turbo_mode = False #@markdown --- @@ -2037,10 +2038,10 @@ def download_models(diffusion_model,use_secondary_model,fallback=False): #insist VR be used only w 3d anim. if vr_mode and animation_mode != '3D': - print('=====') - print('VR mode only available with 3D animations. Disabling VR.') - print('=====') - vr_mode = False + print('=====') + print('VR mode only available with 3D animations. Disabling VR.') + print('=====') + vr_mode = False def parse_key_frames(string, prompt_parser=None): @@ -2153,12 +2154,12 @@ def get_inbetweens(key_frames, integer=False): return key_frame_series def split_prompts(prompts): - prompt_series = pd.Series([np.nan for a in range(max_frames)]) - for i, prompt in prompts.items(): - prompt_series[i] = prompt - # prompt_series = prompt_series.astype(str) - prompt_series = prompt_series.ffill().bfill() - return prompt_series + prompt_series = pd.Series([np.nan for a in range(max_frames)]) + for i, prompt in prompts.items(): + prompt_series[i] = prompt + # prompt_series = prompt_series.astype(str) + prompt_series = prompt_series.ffill().bfill() + return prompt_series if key_frames: try: @@ -2308,20 +2309,20 @@ def split_prompts(prompts): if type(intermediate_saves) is not list: - if intermediate_saves: - steps_per_checkpoint = math.floor((steps - skip_steps - 1) // (intermediate_saves+1)) - steps_per_checkpoint = steps_per_checkpoint if steps_per_checkpoint > 0 else 1 - print(f'Will save every {steps_per_checkpoint} steps') - else: - steps_per_checkpoint = steps+10 + if intermediate_saves: + steps_per_checkpoint = math.floor((steps - skip_steps - 1) // (intermediate_saves+1)) + steps_per_checkpoint = steps_per_checkpoint if steps_per_checkpoint > 0 else 1 + print(f'Will save every {steps_per_checkpoint} steps') + else: + steps_per_checkpoint = steps+10 else: - steps_per_checkpoint = None + steps_per_checkpoint = None if intermediate_saves and intermediates_in_subfolder is True: - partialFolder = f'{batchFolder}/partials' - createPath(partialFolder) + partialFolder = f'{batchFolder}/partials' + createPath(partialFolder) - #@markdown --- +#@markdown --- #@markdown ####**Advanced Settings:** #@markdown *There are a few extra advanced settings available if you double click this cell.* @@ -2343,7 +2344,7 @@ def split_prompts(prompts): rand_mag = 0.05 - #@markdown --- +#@markdown --- #@markdown ####**Cutn Scheduling:** #@markdown Format: `[40]*400+[20]*600` = 40 cuts for the first 400 /1000 steps, then 20 for the last 600/1000 @@ -2417,9 +2418,9 @@ def move_files(start_num, end_num, old_folder, new_folder): run_to_resume = 'latest' #@param{type: 'string'} resume_from_frame = 'latest' #@param{type: 'string'} retain_overwritten_frames = False #@param{type: 'boolean'} -if retain_overwritten_frames is True: - retainFolder = f'{batchFolder}/retained' - createPath(retainFolder) +if retain_overwritten_frames: + retainFolder = f'{batchFolder}/retained' + createPath(retainFolder) skip_step_ratio = int(frames_skip_steps.rstrip("%")) / 100 @@ -2430,31 +2431,31 @@ def move_files(start_num, end_num, old_folder, new_folder): sys.exit("ERROR: You can't skip more steps than your total steps") if resume_run: - if run_to_resume == 'latest': - try: - batchNum - except: - batchNum = len(glob(f"{batchFolder}/{batch_name}(*)_settings.txt"))-1 - else: - batchNum = int(run_to_resume) - if resume_from_frame == 'latest': - start_frame = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png")) - if animation_mode != '3D' and turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0: - start_frame = start_frame - (start_frame % int(turbo_steps)) - else: - start_frame = int(resume_from_frame)+1 - if animation_mode != '3D' and turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0: - start_frame = start_frame - (start_frame % int(turbo_steps)) - if retain_overwritten_frames is True: - existing_frames = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png")) - frames_to_save = existing_frames - start_frame - print(f'Moving {frames_to_save} frames to the Retained folder') - move_files(start_frame, existing_frames, batchFolder, retainFolder) + if run_to_resume == 'latest': + try: + batchNum + except: + batchNum = len(glob(f"{batchFolder}/{batch_name}(*)_settings.txt"))-1 + else: + batchNum = int(run_to_resume) + if resume_from_frame == 'latest': + start_frame = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png")) + if animation_mode != '3D' and turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0: + start_frame = start_frame - (start_frame % int(turbo_steps)) + else: + start_frame = int(resume_from_frame)+1 + if animation_mode != '3D' and turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0: + start_frame = start_frame - (start_frame % int(turbo_steps)) + if retain_overwritten_frames is True: + existing_frames = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png")) + frames_to_save = existing_frames - start_frame + print(f'Moving {frames_to_save} frames to the Retained folder') + move_files(start_frame, existing_frames, batchFolder, retainFolder) else: - start_frame = 0 - batchNum = len(glob(batchFolder+"/*.txt")) - while os.path.isfile(f"{batchFolder}/{batch_name}({batchNum})_settings.txt") is True or os.path.isfile(f"{batchFolder}/{batch_name}-{batchNum}_settings.txt") is True: - batchNum += 1 + start_frame = 0 + batchNum = len(glob(batchFolder+"/*.txt")) + while os.path.isfile(f"{batchFolder}/{batch_name}({batchNum})_settings.txt") or os.path.isfile(f"{batchFolder}/{batch_name}-{batchNum}_settings.txt"): + batchNum += 1 print(f'Starting Run: {batch_name}({batchNum}) at frame {start_frame}') @@ -2561,7 +2562,7 @@ def move_files(start_num, end_num, old_folder, new_folder): gc.collect() torch.cuda.empty_cache() try: - do_run() + do_run() except KeyboardInterrupt: pass finally: @@ -2587,74 +2588,74 @@ def move_files(start_num, end_num, old_folder, new_folder): skip_video_for_run_all = True #@param {type: 'boolean'} if skip_video_for_run_all == True: - print('Skipping video creation, uncheck skip_video_for_run_all if you want to run it') + print('Skipping video creation, uncheck skip_video_for_run_all if you want to run it') else: - # import subprocess in case this cell is run without the above cells - import subprocess - from base64 import b64encode - - latest_run = batchNum - - folder = batch_name #@param - run = latest_run #@param - final_frame = 'final_frame' - - - init_frame = 1#@param {type:"number"} This is the frame where the video will start - 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. - fps = 12#@param {type:"number"} - # view_video_in_cell = True #@param {type: 'boolean'} - - frames = [] - # tqdm.write('Generating video...') - - if last_frame == 'final_frame': - last_frame = len(glob(batchFolder+f"/{folder}({run})_*.png")) - print(f'Total frames: {last_frame}') - - image_path = f"{outDirPath}/{folder}/{folder}({run})_%04d.png" - filepath = f"{outDirPath}/{folder}/{folder}({run}).mp4" - - - cmd = [ - 'ffmpeg', - '-y', - '-vcodec', - 'png', - '-r', - str(fps), - '-start_number', - str(init_frame), - '-i', - image_path, - '-frames:v', - str(last_frame+1), - '-c:v', - 'libx264', - '-vf', - f'fps={fps}', - '-pix_fmt', - 'yuv420p', - '-crf', - '17', - '-preset', - 'veryslow', - filepath - ] - - process = subprocess.Popen(cmd, cwd=f'{batchFolder}', stdout=subprocess.PIPE, stderr=subprocess.PIPE) - stdout, stderr = process.communicate() - if process.returncode != 0: - print(stderr) - raise RuntimeError(stderr) - else: - print("The video is ready and saved to the images folder") + # import subprocess in case this cell is run without the above cells + import subprocess + from base64 import b64encode + + latest_run = batchNum + + folder = batch_name #@param + run = latest_run #@param + final_frame = 'final_frame' + + + init_frame = 1#@param {type:"number"} This is the frame where the video will start + 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. + fps = 12#@param {type:"number"} + # view_video_in_cell = True #@param {type: 'boolean'} + + frames = [] + # tqdm.write('Generating video...') + + if last_frame == 'final_frame': + last_frame = len(glob(batchFolder+f"/{folder}({run})_*.png")) + print(f'Total frames: {last_frame}') + + image_path = f"{outDirPath}/{folder}/{folder}({run})_%04d.png" + filepath = f"{outDirPath}/{folder}/{folder}({run}).mp4" + + + cmd = [ + 'ffmpeg', + '-y', + '-vcodec', + 'png', + '-r', + str(fps), + '-start_number', + str(init_frame), + '-i', + image_path, + '-frames:v', + str(last_frame+1), + '-c:v', + 'libx264', + '-vf', + f'fps={fps}', + '-pix_fmt', + 'yuv420p', + '-crf', + '17', + '-preset', + 'veryslow', + filepath + ] + + process = subprocess.Popen(cmd, cwd=f'{batchFolder}', stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = process.communicate() + if process.returncode != 0: + print(stderr) + raise RuntimeError(stderr) + else: + print("The video is ready and saved to the images folder") - # if view_video_in_cell: - # mp4 = open(filepath,'rb').read() - # data_url = "data:video/mp4;base64," + b64encode(mp4).decode() - # display.HTML(f'') + # if view_video_in_cell: + # mp4 = open(filepath,'rb').read() + # data_url = "data:video/mp4;base64," + b64encode(mp4).decode() + # display.HTML(f'') # %% # !! {"main_metadata":{