diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..aa11c43cacb478618e90fd991ef104f07f252099 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +assets/001_with_eval.png filter=lfs diff=lfs merge=lfs -text +assets/tile.gif filter=lfs diff=lfs merge=lfs -text +outputs/000004.mp4 filter=lfs diff=lfs merge=lfs -text diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..ae8a7a268ba3c7622545b570bfce221c5aa921c4 --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1 @@ +.github @Stability-AI/infrastructure \ No newline at end of file diff --git a/LICENSE-CODE b/LICENSE-CODE new file mode 100644 index 0000000000000000000000000000000000000000..8855a41d3f4238ee6939af58b8fc278e108b9af7 --- /dev/null +++ b/LICENSE-CODE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Stability AI + +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. \ No newline at end of file diff --git a/README.md b/README.md index 7079157919534b75b81b941a9a012498523c555d..61fa687b8c3446cec0d37bdd0510398d7acac4c8 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,292 @@ ---- -title: Stable Video Diffusion -emoji: 📺 -colorFrom: purple -colorTo: purple -sdk: gradio -sdk_version: 4.4.0 -app_file: app.py -pinned: false -license: other ---- \ No newline at end of file +# Generative Models by Stability AI + +![sample1](assets/000.jpg) + +## News + +**November 21, 2023** + +- We are releasing Stable Video Diffusion, an image-to-video model, for research purposes: + - [SVD](https://huggingface.co/stabilityai/stable-video-diffusion-img2vid): This model was trained to generate 14 + frames at resolution 576x1024 given a context frame of the same size. + We use the standard image encoder from SD 2.1, but replace the decoder with a temporally-aware `deflickering decoder`. + - [SVD-XT](https://huggingface.co/stabilityai/stable-video-diffusion-img2vid-xt): Same architecture as `SVD` but finetuned + for 25 frame generation. + - We provide a streamlit demo `scripts/demo/video_sampling.py` and a standalone python script `scripts/sampling/simple_video_sample.py` for inference of both models. + - Alongside the model, we release a [technical report](https://stability.ai/research/stable-video-diffusion-scaling-latent-video-diffusion-models-to-large-datasets). + + ![tile](assets/tile.gif) + +**July 26, 2023** + +- We are releasing two new open models with a + permissive [`CreativeML Open RAIL++-M` license](model_licenses/LICENSE-SDXL1.0) (see [Inference](#inference) for file + hashes): + - [SDXL-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0): An improved version + over `SDXL-base-0.9`. + - [SDXL-refiner-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-refiner-1.0): An improved version + over `SDXL-refiner-0.9`. + +![sample2](assets/001_with_eval.png) + +**July 4, 2023** + +- A technical report on SDXL is now available [here](https://arxiv.org/abs/2307.01952). + +**June 22, 2023** + +- We are releasing two new diffusion models for research purposes: + - `SDXL-base-0.9`: The base model was trained on a variety of aspect ratios on images with resolution 1024^2. The + base model uses [OpenCLIP-ViT/G](https://github.com/mlfoundations/open_clip) + and [CLIP-ViT/L](https://github.com/openai/CLIP/tree/main) for text encoding whereas the refiner model only uses + the OpenCLIP model. + - `SDXL-refiner-0.9`: The refiner has been trained to denoise small noise levels of high quality data and as such is + not expected to work as a text-to-image model; instead, it should only be used as an image-to-image model. + +If you would like to access these models for your research, please apply using one of the following links: +[SDXL-0.9-Base model](https://huggingface.co/stabilityai/stable-diffusion-xl-base-0.9), +and [SDXL-0.9-Refiner](https://huggingface.co/stabilityai/stable-diffusion-xl-refiner-0.9). +This means that you can apply for any of the two links - and if you are granted - you can access both. +Please log in to your Hugging Face Account with your organization email to request access. +**We plan to do a full release soon (July).** + +## The codebase + +### General Philosophy + +Modularity is king. This repo implements a config-driven approach where we build and combine submodules by +calling `instantiate_from_config()` on objects defined in yaml configs. See `configs/` for many examples. + +### Changelog from the old `ldm` codebase + +For training, we use [PyTorch Lightning](https://lightning.ai/docs/pytorch/stable/), but it should be easy to use other +training wrappers around the base modules. The core diffusion model class (formerly `LatentDiffusion`, +now `DiffusionEngine`) has been cleaned up: + +- No more extensive subclassing! We now handle all types of conditioning inputs (vectors, sequences and spatial + conditionings, and all combinations thereof) in a single class: `GeneralConditioner`, + see `sgm/modules/encoders/modules.py`. +- We separate guiders (such as classifier-free guidance, see `sgm/modules/diffusionmodules/guiders.py`) from the + samplers (`sgm/modules/diffusionmodules/sampling.py`), and the samplers are independent of the model. +- We adopt the ["denoiser framework"](https://arxiv.org/abs/2206.00364) for both training and inference (most notable + change is probably now the option to train continuous time models): + * Discrete times models (denoisers) are simply a special case of continuous time models (denoisers); + see `sgm/modules/diffusionmodules/denoiser.py`. + * The following features are now independent: weighting of the diffusion loss + function (`sgm/modules/diffusionmodules/denoiser_weighting.py`), preconditioning of the + network (`sgm/modules/diffusionmodules/denoiser_scaling.py`), and sampling of noise levels during + training (`sgm/modules/diffusionmodules/sigma_sampling.py`). +- Autoencoding models have also been cleaned up. + +## Installation: + + + +#### 1. Clone the repo + +```shell +git clone git@github.com:Stability-AI/generative-models.git +cd generative-models +``` + +#### 2. Setting up the virtualenv + +This is assuming you have navigated to the `generative-models` root after cloning it. + +**NOTE:** This is tested under `python3.10`. For other python versions, you might encounter version conflicts. + +**PyTorch 2.0** + +```shell +# install required packages from pypi +python3 -m venv .pt2 +source .pt2/bin/activate +pip3 install -r requirements/pt2.txt +``` + +#### 3. Install `sgm` + +```shell +pip3 install . +``` + +#### 4. Install `sdata` for training + +```shell +pip3 install -e git+https://github.com/Stability-AI/datapipelines.git@main#egg=sdata +``` + +## Packaging + +This repository uses PEP 517 compliant packaging using [Hatch](https://hatch.pypa.io/latest/). + +To build a distributable wheel, install `hatch` and run `hatch build` +(specifying `-t wheel` will skip building a sdist, which is not necessary). + +``` +pip install hatch +hatch build -t wheel +``` + +You will find the built package in `dist/`. You can install the wheel with `pip install dist/*.whl`. + +Note that the package does **not** currently specify dependencies; you will need to install the required packages, +depending on your use case and PyTorch version, manually. + +## Inference + +We provide a [streamlit](https://streamlit.io/) demo for text-to-image and image-to-image sampling +in `scripts/demo/sampling.py`. +We provide file hashes for the complete file as well as for only the saved tensors in the file ( +see [Model Spec](https://github.com/Stability-AI/ModelSpec) for a script to evaluate that). +The following models are currently supported: + +- [SDXL-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) + ``` + File Hash (sha256): 31e35c80fc4829d14f90153f4c74cd59c90b779f6afe05a74cd6120b893f7e5b + Tensordata Hash (sha256): 0xd7a9105a900fd52748f20725fe52fe52b507fd36bee4fc107b1550a26e6ee1d7 + ``` +- [SDXL-refiner-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-refiner-1.0) + ``` + File Hash (sha256): 7440042bbdc8a24813002c09b6b69b64dc90fded4472613437b7f55f9b7d9c5f + Tensordata Hash (sha256): 0x1a77d21bebc4b4de78c474a90cb74dc0d2217caf4061971dbfa75ad406b75d81 + ``` +- [SDXL-base-0.9](https://huggingface.co/stabilityai/stable-diffusion-xl-base-0.9) +- [SDXL-refiner-0.9](https://huggingface.co/stabilityai/stable-diffusion-xl-refiner-0.9) +- [SD-2.1-512](https://huggingface.co/stabilityai/stable-diffusion-2-1-base/blob/main/v2-1_512-ema-pruned.safetensors) +- [SD-2.1-768](https://huggingface.co/stabilityai/stable-diffusion-2-1/blob/main/v2-1_768-ema-pruned.safetensors) + +**Weights for SDXL**: + +**SDXL-1.0:** +The weights of SDXL-1.0 are available (subject to +a [`CreativeML Open RAIL++-M` license](model_licenses/LICENSE-SDXL1.0)) here: + +- base model: https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/ +- refiner model: https://huggingface.co/stabilityai/stable-diffusion-xl-refiner-1.0/ + +**SDXL-0.9:** +The weights of SDXL-0.9 are available and subject to a [research license](model_licenses/LICENSE-SDXL0.9). +If you would like to access these models for your research, please apply using one of the following links: +[SDXL-base-0.9 model](https://huggingface.co/stabilityai/stable-diffusion-xl-base-0.9), +and [SDXL-refiner-0.9](https://huggingface.co/stabilityai/stable-diffusion-xl-refiner-0.9). +This means that you can apply for any of the two links - and if you are granted - you can access both. +Please log in to your Hugging Face Account with your organization email to request access. + +After obtaining the weights, place them into `checkpoints/`. +Next, start the demo using + +``` +streamlit run scripts/demo/sampling.py --server.port +``` + +### Invisible Watermark Detection + +Images generated with our code use the +[invisible-watermark](https://github.com/ShieldMnt/invisible-watermark/) +library to embed an invisible watermark into the model output. We also provide +a script to easily detect that watermark. Please note that this watermark is +not the same as in previous Stable Diffusion 1.x/2.x versions. + +To run the script you need to either have a working installation as above or +try an _experimental_ import using only a minimal amount of packages: + +```bash +python -m venv .detect +source .detect/bin/activate + +pip install "numpy>=1.17" "PyWavelets>=1.1.1" "opencv-python>=4.1.0.25" +pip install --no-deps invisible-watermark +``` + +To run the script you need to have a working installation as above. The script +is then useable in the following ways (don't forget to activate your +virtual environment beforehand, e.g. `source .pt1/bin/activate`): + +```bash +# test a single file +python scripts/demo/detect.py +# test multiple files at once +python scripts/demo/detect.py ... +# test all files in a specific folder +python scripts/demo/detect.py /* +``` + +## Training: + +We are providing example training configs in `configs/example_training`. To launch a training, run + +``` +python main.py --base configs/ configs/ +``` + +where configs are merged from left to right (later configs overwrite the same values). +This can be used to combine model, training and data configs. However, all of them can also be +defined in a single config. For example, to run a class-conditional pixel-based diffusion model training on MNIST, +run + +```bash +python main.py --base configs/example_training/toy/mnist_cond.yaml +``` + +**NOTE 1:** Using the non-toy-dataset +configs `configs/example_training/imagenet-f8_cond.yaml`, `configs/example_training/txt2img-clipl.yaml` +and `configs/example_training/txt2img-clipl-legacy-ucg-training.yaml` for training will require edits depending on the +used dataset (which is expected to stored in tar-file in +the [webdataset-format](https://github.com/webdataset/webdataset)). To find the parts which have to be adapted, search +for comments containing `USER:` in the respective config. + +**NOTE 2:** This repository supports both `pytorch1.13` and `pytorch2`for training generative models. However for +autoencoder training as e.g. in `configs/example_training/autoencoder/kl-f4/imagenet-attnfree-logvar.yaml`, +only `pytorch1.13` is supported. + +**NOTE 3:** Training latent generative models (as e.g. in `configs/example_training/imagenet-f8_cond.yaml`) requires +retrieving the checkpoint from [Hugging Face](https://huggingface.co/stabilityai/sdxl-vae/tree/main) and replacing +the `CKPT_PATH` placeholder in [this line](configs/example_training/imagenet-f8_cond.yaml#81). The same is to be done +for the provided text-to-image configs. + +### Building New Diffusion Models + +#### Conditioner + +The `GeneralConditioner` is configured through the `conditioner_config`. Its only attribute is `emb_models`, a list of +different embedders (all inherited from `AbstractEmbModel`) that are used to condition the generative model. +All embedders should define whether or not they are trainable (`is_trainable`, default `False`), a classifier-free +guidance dropout rate is used (`ucg_rate`, default `0`), and an input key (`input_key`), for example, `txt` for +text-conditioning or `cls` for class-conditioning. +When computing conditionings, the embedder will get `batch[input_key]` as input. +We currently support two to four dimensional conditionings and conditionings of different embedders are concatenated +appropriately. +Note that the order of the embedders in the `conditioner_config` is important. + +#### Network + +The neural network is set through the `network_config`. This used to be called `unet_config`, which is not general +enough as we plan to experiment with transformer-based diffusion backbones. + +#### Loss + +The loss is configured through `loss_config`. For standard diffusion model training, you will have to +set `sigma_sampler_config`. + +#### Sampler config + +As discussed above, the sampler is independent of the model. In the `sampler_config`, we set the type of numerical +solver, number of steps, type of discretization, as well as, for example, guidance wrappers for classifier-free +guidance. + +### Dataset Handling + +For large scale training we recommend using the data pipelines from +our [data pipelines](https://github.com/Stability-AI/datapipelines) project. The project is contained in the requirement +and automatically included when following the steps from the [Installation section](#installation). +Small map-style datasets should be defined here in the repository (e.g., MNIST, CIFAR-10, ...), and return a dict of +data keys/values, +e.g., + +```python +example = {"jpg": x, # this is a tensor -1...1 chw + "txt": "a beautiful image"} +``` + +where we expect images in -1...1, channel-first format. diff --git a/assets/000.jpg b/assets/000.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e93d6c1b6e07edcb9b5efa946fc3092fe8b4e9b7 Binary files /dev/null and b/assets/000.jpg differ diff --git a/assets/001_with_eval.png b/assets/001_with_eval.png new file mode 100644 index 0000000000000000000000000000000000000000..ac5d5009ccf0079c2d002014ac84e002491a9fe5 --- /dev/null +++ b/assets/001_with_eval.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:026fa14e30098729064a00fb7fcec41bb57dcddb33b36b548d553f601bc53634 +size 4186270 diff --git a/assets/test_image.png b/assets/test_image.png new file mode 100644 index 0000000000000000000000000000000000000000..3f6fef6fafe7a32cef32bcf01f9493bb9441c379 Binary files /dev/null and b/assets/test_image.png differ diff --git a/assets/tile.gif b/assets/tile.gif new file mode 100644 index 0000000000000000000000000000000000000000..5adcd559625989ca53a08d1b0d317f0071a2f8b0 --- /dev/null +++ b/assets/tile.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2340a9809e36fa9634633c7cc5fd256737c620ba47151726c85173512dc5c8ff +size 18630497 diff --git a/data/DejaVuSans.ttf b/data/DejaVuSans.ttf new file mode 100644 index 0000000000000000000000000000000000000000..e5f7eecce43be41ff0703ed99e1553029b849f14 Binary files /dev/null and b/data/DejaVuSans.ttf differ diff --git a/main.py b/main.py new file mode 100644 index 0000000000000000000000000000000000000000..5e03c1c5b617b5efc9590a6815fcbb01202026f9 --- /dev/null +++ b/main.py @@ -0,0 +1,943 @@ +import argparse +import datetime +import glob +import inspect +import os +import sys +from inspect import Parameter +from typing import Union + +import numpy as np +import pytorch_lightning as pl +import torch +import torchvision +import wandb +from matplotlib import pyplot as plt +from natsort import natsorted +from omegaconf import OmegaConf +from packaging import version +from PIL import Image +from pytorch_lightning import seed_everything +from pytorch_lightning.callbacks import Callback +from pytorch_lightning.loggers import WandbLogger +from pytorch_lightning.trainer import Trainer +from pytorch_lightning.utilities import rank_zero_only + +from sgm.util import exists, instantiate_from_config, isheatmap + +MULTINODE_HACKS = True + + +def default_trainer_args(): + argspec = dict(inspect.signature(Trainer.__init__).parameters) + argspec.pop("self") + default_args = { + param: argspec[param].default + for param in argspec + if argspec[param] != Parameter.empty + } + return default_args + + +def get_parser(**parser_kwargs): + def str2bool(v): + if isinstance(v, bool): + return v + if v.lower() in ("yes", "true", "t", "y", "1"): + return True + elif v.lower() in ("no", "false", "f", "n", "0"): + return False + else: + raise argparse.ArgumentTypeError("Boolean value expected.") + + parser = argparse.ArgumentParser(**parser_kwargs) + parser.add_argument( + "-n", + "--name", + type=str, + const=True, + default="", + nargs="?", + help="postfix for logdir", + ) + parser.add_argument( + "--no_date", + type=str2bool, + nargs="?", + const=True, + default=False, + help="if True, skip date generation for logdir and only use naming via opt.base or opt.name (+ opt.postfix, optionally)", + ) + parser.add_argument( + "-r", + "--resume", + type=str, + const=True, + default="", + nargs="?", + help="resume from logdir or checkpoint in logdir", + ) + parser.add_argument( + "-b", + "--base", + nargs="*", + metavar="base_config.yaml", + help="paths to base configs. Loaded from left-to-right. " + "Parameters can be overwritten or added with command-line options of the form `--key value`.", + default=list(), + ) + parser.add_argument( + "-t", + "--train", + type=str2bool, + const=True, + default=True, + nargs="?", + help="train", + ) + parser.add_argument( + "--no-test", + type=str2bool, + const=True, + default=False, + nargs="?", + help="disable test", + ) + parser.add_argument( + "-p", "--project", help="name of new or path to existing project" + ) + parser.add_argument( + "-d", + "--debug", + type=str2bool, + nargs="?", + const=True, + default=False, + help="enable post-mortem debugging", + ) + parser.add_argument( + "-s", + "--seed", + type=int, + default=23, + help="seed for seed_everything", + ) + parser.add_argument( + "-f", + "--postfix", + type=str, + default="", + help="post-postfix for default name", + ) + parser.add_argument( + "--projectname", + type=str, + default="stablediffusion", + ) + parser.add_argument( + "-l", + "--logdir", + type=str, + default="logs", + help="directory for logging dat shit", + ) + parser.add_argument( + "--scale_lr", + type=str2bool, + nargs="?", + const=True, + default=False, + help="scale base-lr by ngpu * batch_size * n_accumulate", + ) + parser.add_argument( + "--legacy_naming", + type=str2bool, + nargs="?", + const=True, + default=False, + help="name run based on config file name if true, else by whole path", + ) + parser.add_argument( + "--enable_tf32", + type=str2bool, + nargs="?", + const=True, + default=False, + help="enables the TensorFloat32 format both for matmuls and cuDNN for pytorch 1.12", + ) + parser.add_argument( + "--startup", + type=str, + default=None, + help="Startuptime from distributed script", + ) + parser.add_argument( + "--wandb", + type=str2bool, + nargs="?", + const=True, + default=False, # TODO: later default to True + help="log to wandb", + ) + parser.add_argument( + "--no_base_name", + type=str2bool, + nargs="?", + const=True, + default=False, # TODO: later default to True + help="log to wandb", + ) + if version.parse(torch.__version__) >= version.parse("2.0.0"): + parser.add_argument( + "--resume_from_checkpoint", + type=str, + default=None, + help="single checkpoint file to resume from", + ) + default_args = default_trainer_args() + for key in default_args: + parser.add_argument("--" + key, default=default_args[key]) + return parser + + +def get_checkpoint_name(logdir): + ckpt = os.path.join(logdir, "checkpoints", "last**.ckpt") + ckpt = natsorted(glob.glob(ckpt)) + print('available "last" checkpoints:') + print(ckpt) + if len(ckpt) > 1: + print("got most recent checkpoint") + ckpt = sorted(ckpt, key=lambda x: os.path.getmtime(x))[-1] + print(f"Most recent ckpt is {ckpt}") + with open(os.path.join(logdir, "most_recent_ckpt.txt"), "w") as f: + f.write(ckpt + "\n") + try: + version = int(ckpt.split("/")[-1].split("-v")[-1].split(".")[0]) + except Exception as e: + print("version confusion but not bad") + print(e) + version = 1 + # version = last_version + 1 + else: + # in this case, we only have one "last.ckpt" + ckpt = ckpt[0] + version = 1 + melk_ckpt_name = f"last-v{version}.ckpt" + print(f"Current melk ckpt name: {melk_ckpt_name}") + return ckpt, melk_ckpt_name + + +class SetupCallback(Callback): + def __init__( + self, + resume, + now, + logdir, + ckptdir, + cfgdir, + config, + lightning_config, + debug, + ckpt_name=None, + ): + super().__init__() + self.resume = resume + self.now = now + self.logdir = logdir + self.ckptdir = ckptdir + self.cfgdir = cfgdir + self.config = config + self.lightning_config = lightning_config + self.debug = debug + self.ckpt_name = ckpt_name + + def on_exception(self, trainer: pl.Trainer, pl_module, exception): + if not self.debug and trainer.global_rank == 0: + print("Summoning checkpoint.") + if self.ckpt_name is None: + ckpt_path = os.path.join(self.ckptdir, "last.ckpt") + else: + ckpt_path = os.path.join(self.ckptdir, self.ckpt_name) + trainer.save_checkpoint(ckpt_path) + + def on_fit_start(self, trainer, pl_module): + if trainer.global_rank == 0: + # Create logdirs and save configs + os.makedirs(self.logdir, exist_ok=True) + os.makedirs(self.ckptdir, exist_ok=True) + os.makedirs(self.cfgdir, exist_ok=True) + + if "callbacks" in self.lightning_config: + if ( + "metrics_over_trainsteps_checkpoint" + in self.lightning_config["callbacks"] + ): + os.makedirs( + os.path.join(self.ckptdir, "trainstep_checkpoints"), + exist_ok=True, + ) + print("Project config") + print(OmegaConf.to_yaml(self.config)) + if MULTINODE_HACKS: + import time + + time.sleep(5) + OmegaConf.save( + self.config, + os.path.join(self.cfgdir, "{}-project.yaml".format(self.now)), + ) + + print("Lightning config") + print(OmegaConf.to_yaml(self.lightning_config)) + OmegaConf.save( + OmegaConf.create({"lightning": self.lightning_config}), + os.path.join(self.cfgdir, "{}-lightning.yaml".format(self.now)), + ) + + else: + # ModelCheckpoint callback created log directory --- remove it + if not MULTINODE_HACKS and not self.resume and os.path.exists(self.logdir): + dst, name = os.path.split(self.logdir) + dst = os.path.join(dst, "child_runs", name) + os.makedirs(os.path.split(dst)[0], exist_ok=True) + try: + os.rename(self.logdir, dst) + except FileNotFoundError: + pass + + +class ImageLogger(Callback): + def __init__( + self, + batch_frequency, + max_images, + clamp=True, + increase_log_steps=True, + rescale=True, + disabled=False, + log_on_batch_idx=False, + log_first_step=False, + log_images_kwargs=None, + log_before_first_step=False, + enable_autocast=True, + ): + super().__init__() + self.enable_autocast = enable_autocast + self.rescale = rescale + self.batch_freq = batch_frequency + self.max_images = max_images + self.log_steps = [2**n for n in range(int(np.log2(self.batch_freq)) + 1)] + if not increase_log_steps: + self.log_steps = [self.batch_freq] + self.clamp = clamp + self.disabled = disabled + self.log_on_batch_idx = log_on_batch_idx + self.log_images_kwargs = log_images_kwargs if log_images_kwargs else {} + self.log_first_step = log_first_step + self.log_before_first_step = log_before_first_step + + @rank_zero_only + def log_local( + self, + save_dir, + split, + images, + global_step, + current_epoch, + batch_idx, + pl_module: Union[None, pl.LightningModule] = None, + ): + root = os.path.join(save_dir, "images", split) + for k in images: + if isheatmap(images[k]): + fig, ax = plt.subplots() + ax = ax.matshow( + images[k].cpu().numpy(), cmap="hot", interpolation="lanczos" + ) + plt.colorbar(ax) + plt.axis("off") + + filename = "{}_gs-{:06}_e-{:06}_b-{:06}.png".format( + k, global_step, current_epoch, batch_idx + ) + os.makedirs(root, exist_ok=True) + path = os.path.join(root, filename) + plt.savefig(path) + plt.close() + # TODO: support wandb + else: + grid = torchvision.utils.make_grid(images[k], nrow=4) + if self.rescale: + grid = (grid + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w + grid = grid.transpose(0, 1).transpose(1, 2).squeeze(-1) + grid = grid.numpy() + grid = (grid * 255).astype(np.uint8) + filename = "{}_gs-{:06}_e-{:06}_b-{:06}.png".format( + k, global_step, current_epoch, batch_idx + ) + path = os.path.join(root, filename) + os.makedirs(os.path.split(path)[0], exist_ok=True) + img = Image.fromarray(grid) + img.save(path) + if exists(pl_module): + assert isinstance( + pl_module.logger, WandbLogger + ), "logger_log_image only supports WandbLogger currently" + pl_module.logger.log_image( + key=f"{split}/{k}", + images=[ + img, + ], + step=pl_module.global_step, + ) + + @rank_zero_only + def log_img(self, pl_module, batch, batch_idx, split="train"): + check_idx = batch_idx if self.log_on_batch_idx else pl_module.global_step + if ( + self.check_frequency(check_idx) + and hasattr(pl_module, "log_images") # batch_idx % self.batch_freq == 0 + and callable(pl_module.log_images) + and + # batch_idx > 5 and + self.max_images > 0 + ): + logger = type(pl_module.logger) + is_train = pl_module.training + if is_train: + pl_module.eval() + + gpu_autocast_kwargs = { + "enabled": self.enable_autocast, # torch.is_autocast_enabled(), + "dtype": torch.get_autocast_gpu_dtype(), + "cache_enabled": torch.is_autocast_cache_enabled(), + } + with torch.no_grad(), torch.cuda.amp.autocast(**gpu_autocast_kwargs): + images = pl_module.log_images( + batch, split=split, **self.log_images_kwargs + ) + + for k in images: + N = min(images[k].shape[0], self.max_images) + if not isheatmap(images[k]): + images[k] = images[k][:N] + if isinstance(images[k], torch.Tensor): + images[k] = images[k].detach().float().cpu() + if self.clamp and not isheatmap(images[k]): + images[k] = torch.clamp(images[k], -1.0, 1.0) + + self.log_local( + pl_module.logger.save_dir, + split, + images, + pl_module.global_step, + pl_module.current_epoch, + batch_idx, + pl_module=pl_module + if isinstance(pl_module.logger, WandbLogger) + else None, + ) + + if is_train: + pl_module.train() + + def check_frequency(self, check_idx): + if ((check_idx % self.batch_freq) == 0 or (check_idx in self.log_steps)) and ( + check_idx > 0 or self.log_first_step + ): + try: + self.log_steps.pop(0) + except IndexError as e: + print(e) + pass + return True + return False + + @rank_zero_only + def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx): + if not self.disabled and (pl_module.global_step > 0 or self.log_first_step): + self.log_img(pl_module, batch, batch_idx, split="train") + + @rank_zero_only + def on_train_batch_start(self, trainer, pl_module, batch, batch_idx): + if self.log_before_first_step and pl_module.global_step == 0: + print(f"{self.__class__.__name__}: logging before training") + self.log_img(pl_module, batch, batch_idx, split="train") + + @rank_zero_only + def on_validation_batch_end( + self, trainer, pl_module, outputs, batch, batch_idx, *args, **kwargs + ): + if not self.disabled and pl_module.global_step > 0: + self.log_img(pl_module, batch, batch_idx, split="val") + if hasattr(pl_module, "calibrate_grad_norm"): + if ( + pl_module.calibrate_grad_norm and batch_idx % 25 == 0 + ) and batch_idx > 0: + self.log_gradients(trainer, pl_module, batch_idx=batch_idx) + + +@rank_zero_only +def init_wandb(save_dir, opt, config, group_name, name_str): + print(f"setting WANDB_DIR to {save_dir}") + os.makedirs(save_dir, exist_ok=True) + + os.environ["WANDB_DIR"] = save_dir + if opt.debug: + wandb.init(project=opt.projectname, mode="offline", group=group_name) + else: + wandb.init( + project=opt.projectname, + config=config, + settings=wandb.Settings(code_dir="./sgm"), + group=group_name, + name=name_str, + ) + + +if __name__ == "__main__": + # custom parser to specify config files, train, test and debug mode, + # postfix, resume. + # `--key value` arguments are interpreted as arguments to the trainer. + # `nested.key=value` arguments are interpreted as config parameters. + # configs are merged from left-to-right followed by command line parameters. + + # model: + # base_learning_rate: float + # target: path to lightning module + # params: + # key: value + # data: + # target: main.DataModuleFromConfig + # params: + # batch_size: int + # wrap: bool + # train: + # target: path to train dataset + # params: + # key: value + # validation: + # target: path to validation dataset + # params: + # key: value + # test: + # target: path to test dataset + # params: + # key: value + # lightning: (optional, has sane defaults and can be specified on cmdline) + # trainer: + # additional arguments to trainer + # logger: + # logger to instantiate + # modelcheckpoint: + # modelcheckpoint to instantiate + # callbacks: + # callback1: + # target: importpath + # params: + # key: value + + now = datetime.datetime.now().strftime("%Y-%m-%dT%H-%M-%S") + + # add cwd for convenience and to make classes in this file available when + # running as `python main.py` + # (in particular `main.DataModuleFromConfig`) + sys.path.append(os.getcwd()) + + parser = get_parser() + + opt, unknown = parser.parse_known_args() + + if opt.name and opt.resume: + raise ValueError( + "-n/--name and -r/--resume cannot be specified both." + "If you want to resume training in a new log folder, " + "use -n/--name in combination with --resume_from_checkpoint" + ) + melk_ckpt_name = None + name = None + if opt.resume: + if not os.path.exists(opt.resume): + raise ValueError("Cannot find {}".format(opt.resume)) + if os.path.isfile(opt.resume): + paths = opt.resume.split("/") + # idx = len(paths)-paths[::-1].index("logs")+1 + # logdir = "/".join(paths[:idx]) + logdir = "/".join(paths[:-2]) + ckpt = opt.resume + _, melk_ckpt_name = get_checkpoint_name(logdir) + else: + assert os.path.isdir(opt.resume), opt.resume + logdir = opt.resume.rstrip("/") + ckpt, melk_ckpt_name = get_checkpoint_name(logdir) + + print("#" * 100) + print(f'Resuming from checkpoint "{ckpt}"') + print("#" * 100) + + opt.resume_from_checkpoint = ckpt + base_configs = sorted(glob.glob(os.path.join(logdir, "configs/*.yaml"))) + opt.base = base_configs + opt.base + _tmp = logdir.split("/") + nowname = _tmp[-1] + else: + if opt.name: + name = "_" + opt.name + elif opt.base: + if opt.no_base_name: + name = "" + else: + if opt.legacy_naming: + cfg_fname = os.path.split(opt.base[0])[-1] + cfg_name = os.path.splitext(cfg_fname)[0] + else: + assert "configs" in os.path.split(opt.base[0])[0], os.path.split( + opt.base[0] + )[0] + cfg_path = os.path.split(opt.base[0])[0].split(os.sep)[ + os.path.split(opt.base[0])[0].split(os.sep).index("configs") + + 1 : + ] # cut away the first one (we assert all configs are in "configs") + cfg_name = os.path.splitext(os.path.split(opt.base[0])[-1])[0] + cfg_name = "-".join(cfg_path) + f"-{cfg_name}" + name = "_" + cfg_name + else: + name = "" + if not opt.no_date: + nowname = now + name + opt.postfix + else: + nowname = name + opt.postfix + if nowname.startswith("_"): + nowname = nowname[1:] + logdir = os.path.join(opt.logdir, nowname) + print(f"LOGDIR: {logdir}") + + ckptdir = os.path.join(logdir, "checkpoints") + cfgdir = os.path.join(logdir, "configs") + seed_everything(opt.seed, workers=True) + + # move before model init, in case a torch.compile(...) is called somewhere + if opt.enable_tf32: + # pt_version = version.parse(torch.__version__) + torch.backends.cuda.matmul.allow_tf32 = True + torch.backends.cudnn.allow_tf32 = True + print(f"Enabling TF32 for PyTorch {torch.__version__}") + else: + print(f"Using default TF32 settings for PyTorch {torch.__version__}:") + print( + f"torch.backends.cuda.matmul.allow_tf32={torch.backends.cuda.matmul.allow_tf32}" + ) + print(f"torch.backends.cudnn.allow_tf32={torch.backends.cudnn.allow_tf32}") + + try: + # init and save configs + configs = [OmegaConf.load(cfg) for cfg in opt.base] + cli = OmegaConf.from_dotlist(unknown) + config = OmegaConf.merge(*configs, cli) + lightning_config = config.pop("lightning", OmegaConf.create()) + # merge trainer cli with config + trainer_config = lightning_config.get("trainer", OmegaConf.create()) + + # default to gpu + trainer_config["accelerator"] = "gpu" + # + standard_args = default_trainer_args() + for k in standard_args: + if getattr(opt, k) != standard_args[k]: + trainer_config[k] = getattr(opt, k) + + ckpt_resume_path = opt.resume_from_checkpoint + + if not "devices" in trainer_config and trainer_config["accelerator"] != "gpu": + del trainer_config["accelerator"] + cpu = True + else: + gpuinfo = trainer_config["devices"] + print(f"Running on GPUs {gpuinfo}") + cpu = False + trainer_opt = argparse.Namespace(**trainer_config) + lightning_config.trainer = trainer_config + + # model + model = instantiate_from_config(config.model) + + # trainer and callbacks + trainer_kwargs = dict() + + # default logger configs + default_logger_cfgs = { + "wandb": { + "target": "pytorch_lightning.loggers.WandbLogger", + "params": { + "name": nowname, + # "save_dir": logdir, + "offline": opt.debug, + "id": nowname, + "project": opt.projectname, + "log_model": False, + # "dir": logdir, + }, + }, + "csv": { + "target": "pytorch_lightning.loggers.CSVLogger", + "params": { + "name": "testtube", # hack for sbord fanatics + "save_dir": logdir, + }, + }, + } + default_logger_cfg = default_logger_cfgs["wandb" if opt.wandb else "csv"] + if opt.wandb: + # TODO change once leaving "swiffer" config directory + try: + group_name = nowname.split(now)[-1].split("-")[1] + except: + group_name = nowname + default_logger_cfg["params"]["group"] = group_name + init_wandb( + os.path.join(os.getcwd(), logdir), + opt=opt, + group_name=group_name, + config=config, + name_str=nowname, + ) + if "logger" in lightning_config: + logger_cfg = lightning_config.logger + else: + logger_cfg = OmegaConf.create() + logger_cfg = OmegaConf.merge(default_logger_cfg, logger_cfg) + trainer_kwargs["logger"] = instantiate_from_config(logger_cfg) + + # modelcheckpoint - use TrainResult/EvalResult(checkpoint_on=metric) to + # specify which metric is used to determine best models + default_modelckpt_cfg = { + "target": "pytorch_lightning.callbacks.ModelCheckpoint", + "params": { + "dirpath": ckptdir, + "filename": "{epoch:06}", + "verbose": True, + "save_last": True, + }, + } + if hasattr(model, "monitor"): + print(f"Monitoring {model.monitor} as checkpoint metric.") + default_modelckpt_cfg["params"]["monitor"] = model.monitor + default_modelckpt_cfg["params"]["save_top_k"] = 3 + + if "modelcheckpoint" in lightning_config: + modelckpt_cfg = lightning_config.modelcheckpoint + else: + modelckpt_cfg = OmegaConf.create() + modelckpt_cfg = OmegaConf.merge(default_modelckpt_cfg, modelckpt_cfg) + print(f"Merged modelckpt-cfg: \n{modelckpt_cfg}") + + # https://pytorch-lightning.readthedocs.io/en/stable/extensions/strategy.html + # default to ddp if not further specified + default_strategy_config = {"target": "pytorch_lightning.strategies.DDPStrategy"} + + if "strategy" in lightning_config: + strategy_cfg = lightning_config.strategy + else: + strategy_cfg = OmegaConf.create() + default_strategy_config["params"] = { + "find_unused_parameters": False, + # "static_graph": True, + # "ddp_comm_hook": default.fp16_compress_hook # TODO: experiment with this, also for DDPSharded + } + strategy_cfg = OmegaConf.merge(default_strategy_config, strategy_cfg) + print( + f"strategy config: \n ++++++++++++++ \n {strategy_cfg} \n ++++++++++++++ " + ) + trainer_kwargs["strategy"] = instantiate_from_config(strategy_cfg) + + # add callback which sets up log directory + default_callbacks_cfg = { + "setup_callback": { + "target": "main.SetupCallback", + "params": { + "resume": opt.resume, + "now": now, + "logdir": logdir, + "ckptdir": ckptdir, + "cfgdir": cfgdir, + "config": config, + "lightning_config": lightning_config, + "debug": opt.debug, + "ckpt_name": melk_ckpt_name, + }, + }, + "image_logger": { + "target": "main.ImageLogger", + "params": {"batch_frequency": 1000, "max_images": 4, "clamp": True}, + }, + "learning_rate_logger": { + "target": "pytorch_lightning.callbacks.LearningRateMonitor", + "params": { + "logging_interval": "step", + # "log_momentum": True + }, + }, + } + if version.parse(pl.__version__) >= version.parse("1.4.0"): + default_callbacks_cfg.update({"checkpoint_callback": modelckpt_cfg}) + + if "callbacks" in lightning_config: + callbacks_cfg = lightning_config.callbacks + else: + callbacks_cfg = OmegaConf.create() + + if "metrics_over_trainsteps_checkpoint" in callbacks_cfg: + print( + "Caution: Saving checkpoints every n train steps without deleting. This might require some free space." + ) + default_metrics_over_trainsteps_ckpt_dict = { + "metrics_over_trainsteps_checkpoint": { + "target": "pytorch_lightning.callbacks.ModelCheckpoint", + "params": { + "dirpath": os.path.join(ckptdir, "trainstep_checkpoints"), + "filename": "{epoch:06}-{step:09}", + "verbose": True, + "save_top_k": -1, + "every_n_train_steps": 10000, + "save_weights_only": True, + }, + } + } + default_callbacks_cfg.update(default_metrics_over_trainsteps_ckpt_dict) + + callbacks_cfg = OmegaConf.merge(default_callbacks_cfg, callbacks_cfg) + if "ignore_keys_callback" in callbacks_cfg and ckpt_resume_path is not None: + callbacks_cfg.ignore_keys_callback.params["ckpt_path"] = ckpt_resume_path + elif "ignore_keys_callback" in callbacks_cfg: + del callbacks_cfg["ignore_keys_callback"] + + trainer_kwargs["callbacks"] = [ + instantiate_from_config(callbacks_cfg[k]) for k in callbacks_cfg + ] + if not "plugins" in trainer_kwargs: + trainer_kwargs["plugins"] = list() + + # cmd line trainer args (which are in trainer_opt) have always priority over config-trainer-args (which are in trainer_kwargs) + trainer_opt = vars(trainer_opt) + trainer_kwargs = { + key: val for key, val in trainer_kwargs.items() if key not in trainer_opt + } + trainer = Trainer(**trainer_opt, **trainer_kwargs) + + trainer.logdir = logdir ### + + # data + data = instantiate_from_config(config.data) + # NOTE according to https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html + # calling these ourselves should not be necessary but it is. + # lightning still takes care of proper multiprocessing though + data.prepare_data() + # data.setup() + print("#### Data #####") + try: + for k in data.datasets: + print( + f"{k}, {data.datasets[k].__class__.__name__}, {len(data.datasets[k])}" + ) + except: + print("datasets not yet initialized.") + + # configure learning rate + if "batch_size" in config.data.params: + bs, base_lr = config.data.params.batch_size, config.model.base_learning_rate + else: + bs, base_lr = ( + config.data.params.train.loader.batch_size, + config.model.base_learning_rate, + ) + if not cpu: + ngpu = len(lightning_config.trainer.devices.strip(",").split(",")) + else: + ngpu = 1 + if "accumulate_grad_batches" in lightning_config.trainer: + accumulate_grad_batches = lightning_config.trainer.accumulate_grad_batches + else: + accumulate_grad_batches = 1 + print(f"accumulate_grad_batches = {accumulate_grad_batches}") + lightning_config.trainer.accumulate_grad_batches = accumulate_grad_batches + if opt.scale_lr: + model.learning_rate = accumulate_grad_batches * ngpu * bs * base_lr + print( + "Setting learning rate to {:.2e} = {} (accumulate_grad_batches) * {} (num_gpus) * {} (batchsize) * {:.2e} (base_lr)".format( + model.learning_rate, accumulate_grad_batches, ngpu, bs, base_lr + ) + ) + else: + model.learning_rate = base_lr + print("++++ NOT USING LR SCALING ++++") + print(f"Setting learning rate to {model.learning_rate:.2e}") + + # allow checkpointing via USR1 + def melk(*args, **kwargs): + # run all checkpoint hooks + if trainer.global_rank == 0: + print("Summoning checkpoint.") + if melk_ckpt_name is None: + ckpt_path = os.path.join(ckptdir, "last.ckpt") + else: + ckpt_path = os.path.join(ckptdir, melk_ckpt_name) + trainer.save_checkpoint(ckpt_path) + + def divein(*args, **kwargs): + if trainer.global_rank == 0: + import pudb + + pudb.set_trace() + + import signal + + signal.signal(signal.SIGUSR1, melk) + signal.signal(signal.SIGUSR2, divein) + + # run + if opt.train: + try: + trainer.fit(model, data, ckpt_path=ckpt_resume_path) + except Exception: + if not opt.debug: + melk() + raise + if not opt.no_test and not trainer.interrupted: + trainer.test(model, data) + except RuntimeError as err: + if MULTINODE_HACKS: + import datetime + import os + import socket + + import requests + + device = os.environ.get("CUDA_VISIBLE_DEVICES", "?") + hostname = socket.gethostname() + ts = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") + resp = requests.get("http://169.254.169.254/latest/meta-data/instance-id") + print( + f"ERROR at {ts} on {hostname}/{resp.text} (CUDA_VISIBLE_DEVICES={device}): {type(err).__name__}: {err}", + flush=True, + ) + raise err + except Exception: + if opt.debug and trainer.global_rank == 0: + try: + import pudb as debugger + except ImportError: + import pdb as debugger + debugger.post_mortem() + raise + finally: + # move newly created debug project to debug_runs + if opt.debug and not opt.resume and trainer.global_rank == 0: + dst, name = os.path.split(logdir) + dst = os.path.join(dst, "debug_runs", name) + os.makedirs(os.path.split(dst)[0], exist_ok=True) + os.rename(logdir, dst) + + if opt.wandb: + wandb.finish() + # if trainer.global_rank == 0: + # print(trainer.profiler.summary()) diff --git a/model_licenses/LICENSE-SDV b/model_licenses/LICENSE-SDV new file mode 100644 index 0000000000000000000000000000000000000000..22090ebb9f69d0fc8e1087ddcc4e9f908e78936f --- /dev/null +++ b/model_licenses/LICENSE-SDV @@ -0,0 +1,31 @@ +STABLE VIDEO DIFFUSION NON-COMMERCIAL COMMUNITY LICENSE AGREEMENT +Dated: November 21, 2023 + +“AUP” means the Stability AI Acceptable Use Policy available at https://stability.ai/use-policy, as may be updated from time to time. + +"Agreement" means the terms and conditions for use, reproduction, distribution and modification of the Software Products set forth herein. +"Derivative Work(s)” means (a) any derivative work of the Software Products as recognized by U.S. copyright laws and (b) any modifications to a Model, and any other model created which is based on or derived from the Model or the Model’s output. For clarity, Derivative Works do not include the output of any Model. +“Documentation” means any specifications, manuals, documentation, and other written information provided by Stability AI related to the Software. + +"Licensee" or "you" means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity's behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf. + +"Stability AI" or "we" means Stability AI Ltd. + +"Software" means, collectively, Stability AI’s proprietary StableCode made available under this Agreement. + +“Software Products” means Software and Documentation. + +By using or distributing any portion or element of the Software Products, you agree to be bound by this Agreement. + + + +License Rights and Redistribution. +Subject to your compliance with this Agreement, the AUP (which is hereby incorporated herein by reference), and the Documentation, Stability AI grants you a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable, royalty free and limited license under Stability AI’s intellectual property or other rights owned by Stability AI embodied in the Software Products to reproduce, distribute, and create Derivative Works of the Software Products for purposes other than commercial or production use. +b. If you distribute or make the Software Products, or any Derivative Works thereof, available to a third party, the Software Products, Derivative Works, or any portion thereof, respectively, will remain subject to this Agreement and you must (i) provide a copy of this Agreement to such third party, and (ii) retain the following attribution notice within a "Notice" text file distributed as a part of such copies: "Stable Video Diffusion is licensed under the Stable Video Diffusion Research License, Copyright (c) Stability AI Ltd. All Rights Reserved.” If you create a Derivative Work of a Software Product, you may add your own attribution notices to the Notice file included with the Software Product, provided that you clearly indicate which attributions apply to the Software Product and you must state in the NOTICE file that you changed the Software Product and how it was modified. +2. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE SOFTWARE PRODUCTS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE SOFTWARE PRODUCTS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE SOFTWARE PRODUCTS AND ANY OUTPUT AND RESULTS. +3. Limitation of Liability. IN NO EVENT WILL STABILITY AI OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF STABILITY AI OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING. +3. Intellectual Property. +a. No trademark licenses are granted under this Agreement, and in connection with the Software Products, neither Stability AI nor Licensee may use any name or mark owned by or associated with the other or any of its affiliates, except as required for reasonable and customary use in describing and redistributing the Software Products. +Subject to Stability AI’s ownership of the Software Products and Derivative Works made by or for Stability AI, with respect to any Derivative Works that are made by you, as between you and Stability AI, you are and will be the owner of such Derivative Works. +If you institute litigation or other proceedings against Stability AI (including a cross-claim or counterclaim in a lawsuit) alleging that the Software Products or associated outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Stability AI from and against any claim by any third party arising out of or related to your use or distribution of the Software Products in violation of this Agreement. +4. Term and Termination. The term of this Agreement will commence upon your acceptance of this Agreement or access to the Software Products and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Stability AI may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of the Software Products. Sections 2-4 shall survive the termination of this Agreement. diff --git a/model_licenses/LICENSE-SDXL0.9 b/model_licenses/LICENSE-SDXL0.9 new file mode 100644 index 0000000000000000000000000000000000000000..b01c5a6838f0c01a347aaf83e2fde3b59a36006d --- /dev/null +++ b/model_licenses/LICENSE-SDXL0.9 @@ -0,0 +1,75 @@ +SDXL 0.9 RESEARCH LICENSE AGREEMENT +Copyright (c) Stability AI Ltd. +This License Agreement (as may be amended in accordance with this License Agreement, “License”), between you, or your employer or other entity (if you are entering into this agreement on behalf of your employer or other entity) (“Licensee” or “you”) and Stability AI Ltd. (“Stability AI” or “we”) applies to your use of any computer program, algorithm, source code, object code, or software that is made available by Stability AI under this License (“Software”) and any specifications, manuals, documentation, and other written information provided by Stability AI related to the Software (“Documentation”). +By clicking “I Accept” below or by using the Software, you agree to the terms of this License. If you do not agree to this License, then you do not have any rights to use the Software or Documentation (collectively, the “Software Products”), and you must immediately cease using the Software Products. If you are agreeing to be bound by the terms of this License on behalf of your employer or other entity, you represent and warrant to Stability AI that you have full legal authority to bind your employer or such entity to this License. If you do not have the requisite authority, you may not accept the License or access the Software Products on behalf of your employer or other entity. +1. LICENSE GRANT + +a. Subject to your compliance with the Documentation and Sections 2, 3, and 5, Stability AI grants you a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable, royalty free and limited license under Stability AI’s copyright interests to reproduce, distribute, and create derivative works of the Software solely for your non-commercial research purposes. The foregoing license is personal to you, and you may not assign or sublicense this License or any other rights or obligations under this License without Stability AI’s prior written consent; any such assignment or sublicense will be void and will automatically and immediately terminate this License. + +b. You may make a reasonable number of copies of the Documentation solely for use in connection with the license to the Software granted above. + +c. The grant of rights expressly set forth in this Section 1 (License Grant) are the complete grant of rights to you in the Software Products, and no other licenses are granted, whether by waiver, estoppel, implication, equity or otherwise. Stability AI and its licensors reserve all rights not expressly granted by this License. + + +2. RESTRICTIONS + +You will not, and will not permit, assist or cause any third party to: + +a. use, modify, copy, reproduce, create derivative works of, or distribute the Software Products (or any derivative works thereof, works incorporating the Software Products, or any data produced by the Software), in whole or in part, for (i) any commercial or production purposes, (ii) military purposes or in the service of nuclear technology, (iii) purposes of surveillance, including any research or development relating to surveillance, (iv) biometric processing, (v) in any manner that infringes, misappropriates, or otherwise violates any third-party rights, or (vi) in any manner that violates any applicable law and violating any privacy or security laws, rules, regulations, directives, or governmental requirements (including the General Data Privacy Regulation (Regulation (EU) 2016/679), the California Consumer Privacy Act, and any and all laws governing the processing of biometric information), as well as all amendments and successor laws to any of the foregoing; + +b. alter or remove copyright and other proprietary notices which appear on or in the Software Products; + +c. utilize any equipment, device, software, or other means to circumvent or remove any security or protection used by Stability AI in connection with the Software, or to circumvent or remove any usage restrictions, or to enable functionality disabled by Stability AI; or + +d. offer or impose any terms on the Software Products that alter, restrict, or are inconsistent with the terms of this License. + +e. 1) violate any applicable U.S. and non-U.S. export control and trade sanctions laws (“Export Laws”); 2) directly or indirectly export, re-export, provide, or otherwise transfer Software Products: (a) to any individual, entity, or country prohibited by Export Laws; (b) to anyone on U.S. or non-U.S. government restricted parties lists; or (c) for any purpose prohibited by Export Laws, including nuclear, chemical or biological weapons, or missile technology applications; 3) use or download Software Products if you or they are: (a) located in a comprehensively sanctioned jurisdiction, (b) currently listed on any U.S. or non-U.S. restricted parties list, or (c) for any purpose prohibited by Export Laws; and (4) will not disguise your location through IP proxying or other methods. + + +3. ATTRIBUTION + +Together with any copies of the Software Products (as well as derivative works thereof or works incorporating the Software Products) that you distribute, you must provide (i) a copy of this License, and (ii) the following attribution notice: “SDXL 0.9 is licensed under the SDXL Research License, Copyright (c) Stability AI Ltd. All Rights Reserved.” + + +4. DISCLAIMERS + +THE SOFTWARE PRODUCTS ARE PROVIDED “AS IS” AND “WITH ALL FAULTS” WITH NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. STABILITY AIEXPRESSLY DISCLAIMS ALL REPRESENTATIONS AND WARRANTIES, EXPRESS OR IMPLIED, WHETHER BY STATUTE, CUSTOM, USAGE OR OTHERWISE AS TO ANY MATTERS RELATED TO THE SOFTWARE PRODUCTS, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, SATISFACTORY QUALITY, OR NON-INFRINGEMENT. STABILITY AI MAKES NO WARRANTIES OR REPRESENTATIONS THAT THE SOFTWARE PRODUCTS WILL BE ERROR FREE OR FREE OF VIRUSES OR OTHER HARMFUL COMPONENTS, OR PRODUCE ANY PARTICULAR RESULTS. + + +5. LIMITATION OF LIABILITY + +TO THE FULLEST EXTENT PERMITTED BY LAW, IN NO EVENT WILL STABILITY AI BE LIABLE TO YOU (A) UNDER ANY THEORY OF LIABILITY, WHETHER BASED IN CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY, WARRANTY, OR OTHERWISE UNDER THIS LICENSE, OR (B) FOR ANY INDIRECT, CONSEQUENTIAL, EXEMPLARY, INCIDENTAL, PUNITIVE OR SPECIAL DAMAGES OR LOST PROFITS, EVEN IF STABILITY AI HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. THE SOFTWARE PRODUCTS, THEIR CONSTITUENT COMPONENTS, AND ANY OUTPUT (COLLECTIVELY, “SOFTWARE MATERIALS”) ARE NOT DESIGNED OR INTENDED FOR USE IN ANY APPLICATION OR SITUATION WHERE FAILURE OR FAULT OF THE SOFTWARE MATERIALS COULD REASONABLY BE ANTICIPATED TO LEAD TO SERIOUS INJURY OF ANY PERSON, INCLUDING POTENTIAL DISCRIMINATION OR VIOLATION OF AN INDIVIDUAL’S PRIVACY RIGHTS, OR TO SEVERE PHYSICAL, PROPERTY, OR ENVIRONMENTAL DAMAGE (EACH, A “HIGH-RISK USE”). IF YOU ELECT TO USE ANY OF THE SOFTWARE MATERIALS FOR A HIGH-RISK USE, YOU DO SO AT YOUR OWN RISK. YOU AGREE TO DESIGN AND IMPLEMENT APPROPRIATE DECISION-MAKING AND RISK-MITIGATION PROCEDURES AND POLICIES IN CONNECTION WITH A HIGH-RISK USE SUCH THAT EVEN IF THERE IS A FAILURE OR FAULT IN ANY OF THE SOFTWARE MATERIALS, THE SAFETY OF PERSONS OR PROPERTY AFFECTED BY THE ACTIVITY STAYS AT A LEVEL THAT IS REASONABLE, APPROPRIATE, AND LAWFUL FOR THE FIELD OF THE HIGH-RISK USE. + + +6. INDEMNIFICATION + +You will indemnify, defend and hold harmless Stability AI and our subsidiaries and affiliates, and each of our respective shareholders, directors, officers, employees, agents, successors, and assigns (collectively, the “Stability AI Parties”) from and against any losses, liabilities, damages, fines, penalties, and expenses (including reasonable attorneys’ fees) incurred by any Stability AI Party in connection with any claim, demand, allegation, lawsuit, proceeding, or investigation (collectively, “Claims”) arising out of or related to: (a) your access to or use of the Software Products (as well as any results or data generated from such access or use), including any High-Risk Use (defined below); (b) your violation of this License; or (c) your violation, misappropriation or infringement of any rights of another (including intellectual property or other proprietary rights and privacy rights). You will promptly notify the Stability AI Parties of any such Claims, and cooperate with Stability AI Parties in defending such Claims. You will also grant the Stability AI Parties sole control of the defense or settlement, at Stability AI’s sole option, of any Claims. This indemnity is in addition to, and not in lieu of, any other indemnities or remedies set forth in a written agreement between you and Stability AI or the other Stability AI Parties. + + +7. TERMINATION; SURVIVAL + +a. This License will automatically terminate upon any breach by you of the terms of this License. + +b. We may terminate this License, in whole or in part, at any time upon notice (including electronic) to you. + +c. The following sections survive termination of this License: 2 (Restrictions), 3 (Attribution), 4 (Disclaimers), 5 (Limitation on Liability), 6 (Indemnification) 7 (Termination; Survival), 8 (Third Party Materials), 9 (Trademarks), 10 (Applicable Law; Dispute Resolution), and 11 (Miscellaneous). + + +8. THIRD PARTY MATERIALS + +The Software Products may contain third-party software or other components (including free and open source software) (all of the foregoing, “Third Party Materials”), which are subject to the license terms of the respective third-party licensors. Your dealings or correspondence with third parties and your use of or interaction with any Third Party Materials are solely between you and the third party. Stability AI does not control or endorse, and makes no representations or warranties regarding, any Third Party Materials, and your access to and use of such Third Party Materials are at your own risk. + + +9. TRADEMARKS + +Licensee has not been granted any trademark license as part of this License and may not use any name or mark associated with Stability AI without the prior written permission of Stability AI, except to the extent necessary to make the reference required by the “ATTRIBUTION” section of this Agreement. + + +10. APPLICABLE LAW; DISPUTE RESOLUTION + +This License will be governed and construed under the laws of the State of California without regard to conflicts of law provisions. Any suit or proceeding arising out of or relating to this License will be brought in the federal or state courts, as applicable, in San Mateo County, California, and each party irrevocably submits to the jurisdiction and venue of such courts. + + +11. MISCELLANEOUS + +If any provision or part of a provision of this License is unlawful, void or unenforceable, that provision or part of the provision is deemed severed from this License, and will not affect the validity and enforceability of any remaining provisions. The failure of Stability AI to exercise or enforce any right or provision of this License will not operate as a waiver of such right or provision. This License does not confer any third-party beneficiary rights upon any other person or entity. This License, together with the Documentation, contains the entire understanding between you and Stability AI regarding the subject matter of this License, and supersedes all other written or oral agreements and understandings between you and Stability AI regarding such subject matter. No change or addition to any provision of this License will be binding unless it is in writing and signed by an authorized representative of both you and Stability AI. \ No newline at end of file diff --git a/model_licenses/LICENSE-SDXL1.0 b/model_licenses/LICENSE-SDXL1.0 new file mode 100644 index 0000000000000000000000000000000000000000..741e30e1d609b6c864c5d86f8f827e7a4e82ac82 --- /dev/null +++ b/model_licenses/LICENSE-SDXL1.0 @@ -0,0 +1,175 @@ +Copyright (c) 2023 Stability AI CreativeML Open RAIL++-M License dated July 26, 2023 + +Section I: PREAMBLE Multimodal generative models are being widely adopted and used, and +have the potential to transform the way artists, among other individuals, conceive and +benefit from AI or ML technologies as a tool for content creation. Notwithstanding the +current and potential benefits that these artifacts can bring to society at large, there +are also concerns about potential misuses of them, either due to their technical +limitations or ethical considerations. In short, this license strives for both the open +and responsible downstream use of the accompanying model. When it comes to the open +character, we took inspiration from open source permissive licenses regarding the grant +of IP rights. Referring to the downstream responsible use, we added use-based +restrictions not permitting the use of the model in very specific scenarios, in order +for the licensor to be able to enforce the license in case potential misuses of the +Model may occur. At the same time, we strive to promote open and responsible research on +generative models for art and content generation. Even though downstream derivative +versions of the model could be released under different licensing terms, the latter will +always have to include - at minimum - the same use-based restrictions as the ones in the +original license (this license). We believe in the intersection between open and +responsible AI development; thus, this agreement aims to strike a balance between both +in order to enable responsible open-science in the field of AI. This CreativeML Open +RAIL++-M License governs the use of the model (and its derivatives) and is informed by +the model card associated with the model. NOW THEREFORE, You and Licensor agree as +follows: Definitions "License" means the terms and conditions for use, reproduction, and +Distribution as defined in this document. "Data" means a collection of information +and/or content extracted from the dataset used with the Model, including to train, +pretrain, or otherwise evaluate the Model. The Data is not licensed under this License. +"Output" means the results of operating a Model as embodied in informational content +resulting therefrom. "Model" means any accompanying machine-learning based assemblies +(including checkpoints), consisting of learnt weights, parameters (including optimizer +states), corresponding to the model architecture as embodied in the Complementary +Material, that have been trained or tuned, in whole or in part on the Data, using the +Complementary Material. "Derivatives of the Model" means all modifications to the Model, +works based on the Model, or any other model which is created or initialized by transfer +of patterns of the weights, parameters, activations or output of the Model, to the other +model, in order to cause the other model to perform similarly to the Model, including - +but not limited to - distillation methods entailing the use of intermediate data +representations or methods based on the generation of synthetic data by the Model for +training the other model. "Complementary Material" means the accompanying source code +and scripts used to define, run, load, benchmark or evaluate the Model, and used to +prepare data for training or evaluation, if any. This includes any accompanying +documentation, tutorials, examples, etc, if any. "Distribution" means any transmission, +reproduction, publication or other sharing of the Model or Derivatives of the Model to a +third party, including providing the Model as a hosted service made available by +electronic or other remote means - e.g. API-based or web access. "Licensor" means the +copyright owner or entity authorized by the copyright owner that is granting the +License, including the persons or entities that may have rights in the Model and/or +distributing the Model. "You" (or "Your") means an individual or Legal Entity exercising +permissions granted by this License and/or making use of the Model for whichever purpose +and in any field of use, including usage of the Model in an end-use application - e.g. +chatbot, translator, image generator. "Third Parties" means individuals or legal +entities that are not under common control with Licensor or You. "Contribution" means +any work of authorship, including the original version of the Model and any +modifications or additions to that Model or Derivatives of the Model thereof, that is +intentionally submitted to Licensor for inclusion in the Model by the copyright owner or +by an individual or Legal Entity authorized to submit on behalf of the copyright owner. +For the purposes of this definition, "submitted" means any form of electronic, verbal, +or written communication sent to the Licensor or its representatives, including but not +limited to communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for the +purpose of discussing and improving the Model, but excluding communication that is +conspicuously marked or otherwise designated in writing by the copyright owner as "Not a +Contribution." "Contributor" means Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently incorporated +within the Model. + +Section II: INTELLECTUAL PROPERTY RIGHTS Both copyright and patent grants apply to the +Model, Derivatives of the Model and Complementary Material. The Model and Derivatives of +the Model are subject to additional terms as described in + +Section III. Grant of Copyright License. Subject to the terms and conditions of this +License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable copyright license to reproduce, prepare, publicly +display, publicly perform, sublicense, and distribute the Complementary Material, the +Model, and Derivatives of the Model. Grant of Patent License. Subject to the terms and +conditions of this License and where and as applicable, each Contributor hereby grants +to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable +(except as stated in this paragraph) patent license to make, have made, use, offer to +sell, sell, import, and otherwise transfer the Model and the Complementary Material, +where such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination of their +Contribution(s) with the Model to which such Contribution(s) was submitted. If You +institute patent litigation against any entity (including a cross-claim or counterclaim +in a lawsuit) alleging that the Model and/or Complementary Material or a Contribution +incorporated within the Model and/or Complementary Material constitutes direct or +contributory patent infringement, then any patent licenses granted to You under this +License for the Model and/or Work shall terminate as of the date such litigation is +asserted or filed. Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION +Distribution and Redistribution. You may host for Third Party remote access purposes +(e.g. software-as-a-service), reproduce and distribute copies of the Model or +Derivatives of the Model thereof in any medium, with or without modifications, provided +that You meet the following conditions: Use-based restrictions as referenced in +paragraph 5 MUST be included as an enforceable provision by You in any type of legal +agreement (e.g. a license) governing the use and/or distribution of the Model or +Derivatives of the Model, and You shall give notice to subsequent users You Distribute +to, that the Model or Derivatives of the Model are subject to paragraph 5. This +provision does not apply to the use of Complementary Material. You must give any Third +Party recipients of the Model or Derivatives of the Model a copy of this License; You +must cause any modified files to carry prominent notices stating that You changed the +files; You must retain all copyright, patent, trademark, and attribution notices +excluding those notices that do not pertain to any part of the Model, Derivatives of the +Model. You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions - respecting paragraph 4.a. - for +use, reproduction, or Distribution of Your modifications, or for any such Derivatives of +the Model as a whole, provided Your use, reproduction, and Distribution of the Model +otherwise complies with the conditions stated in this License. Use-based restrictions. +The restrictions set forth in Attachment A are considered Use-based restrictions. +Therefore You cannot use the Model and the Derivatives of the Model for the specified +restricted uses. You may use the Model subject to this License, including only for +lawful purposes and in accordance with the License. Use may include creating any content +with, finetuning, updating, running, training, evaluating and/or reparametrizing the +Model. You shall require all of Your users who use the Model or a Derivative of the +Model to comply with the terms of this paragraph (paragraph 5). The Output You Generate. +Except as set forth herein, Licensor claims no rights in the Output You generate using +the Model. You are accountable for the Output you generate and its subsequent uses. No +use of the output can contravene any provision as stated in the License. + +Section IV: OTHER PROVISIONS Updates and Runtime Restrictions. To the maximum extent +permitted by law, Licensor reserves the right to restrict (remotely or otherwise) usage +of the Model in violation of this License. Trademarks and related. Nothing in this +License permits You to make use of Licensors’ trademarks, trade names, logos or to +otherwise suggest endorsement or misrepresent the relationship between the parties; and +any rights not expressly granted herein are reserved by the Licensors. Disclaimer of +Warranty. Unless required by applicable law or agreed to in writing, Licensor provides +the Model and the Complementary Material (and each Contributor provides its +Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +express or implied, including, without limitation, any warranties or conditions of +TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or redistributing the +Model, Derivatives of the Model, and the Complementary Material and assume any risks +associated with Your exercise of permissions under this License. Limitation of +Liability. In no event and under no legal theory, whether in tort (including +negligence), contract, or otherwise, unless required by applicable law (such as +deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, or +consequential damages of any character arising as a result of this License or out of the +use or inability to use the Model and the Complementary Material (including but not +limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, +or any and all other commercial damages or losses), even if such Contributor has been +advised of the possibility of such damages. Accepting Warranty or Additional Liability. +While redistributing the Model, Derivatives of the Model and the Complementary Material +thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, +indemnity, or other liability obligations and/or rights consistent with this License. +However, in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You agree to +indemnify, defend, and hold each Contributor harmless for any liability incurred by, or +claims asserted against, such Contributor by reason of your accepting any such warranty +or additional liability. If any provision of this License is held to be invalid, illegal +or unenforceable, the remaining provisions shall be unaffected thereby and remain valid +as if such provision had not been set forth herein. + +END OF TERMS AND CONDITIONS + +Attachment A Use Restrictions +You agree not to use the Model or Derivatives of the Model: +In any way that violates any applicable national, federal, state, local or +international law or regulation; For the purpose of exploiting, harming or attempting to +exploit or harm minors in any way; To generate or disseminate verifiably false +information and/or content with the purpose of harming others; To generate or +disseminate personal identifiable information that can be used to harm an individual; To +defame, disparage or otherwise harass others; For fully automated decision making that +adversely impacts an individual’s legal rights or otherwise creates or modifies a +binding, enforceable obligation; For any use intended to or which has the effect of +discriminating against or harming individuals or groups based on online or offline +social behavior or known or predicted personal or personality characteristics; To +exploit any of the vulnerabilities of a specific group of persons based on their age, +social, physical or mental characteristics, in order to materially distort the behavior +of a person pertaining to that group in a manner that causes or is likely to cause that +person or another person physical or psychological harm; For any use intended to or +which has the effect of discriminating against individuals or groups based on legally +protected characteristics or categories; To provide medical advice and medical results +interpretation; To generate or disseminate information for the purpose to be used for +administration of justice, law enforcement, immigration or asylum processes, such as +predicting an individual will commit fraud/crime commitment (e.g. by text profiling, +drawing causal relationships between assertions made in documents, indiscriminate and +arbitrarily-targeted use). diff --git a/outputs/000000.mp4 b/outputs/000000.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..60273d7ab35f65eff280667485893c387439d471 Binary files /dev/null and b/outputs/000000.mp4 differ diff --git a/outputs/000001.mp4 b/outputs/000001.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..926f48af33fed3f2ee7290da1fe92e2c07486e2e Binary files /dev/null and b/outputs/000001.mp4 differ diff --git a/outputs/000002.mp4 b/outputs/000002.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..a8edaa90b4faff9ead28cef3f37276cd4aa941c8 Binary files /dev/null and b/outputs/000002.mp4 differ diff --git a/outputs/000003.mp4 b/outputs/000003.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..0daa7ad304bacaf8831b88fc47420f0f6ea711c8 Binary files /dev/null and b/outputs/000003.mp4 differ diff --git a/outputs/000004.mp4 b/outputs/000004.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..ddb1f2e00ff984dfc52b1dbf8deb5a80fbf871a4 --- /dev/null +++ b/outputs/000004.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2cc34e39dd8c5d2022de56d1d83936ac2b7a286ab0351895f1b83e00a9e2fa7 +size 1574414 diff --git a/outputs/000005.mp4 b/outputs/000005.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..94985012377359aa733f9a62704d76a2bbda4caf Binary files /dev/null and b/outputs/000005.mp4 differ diff --git a/outputs/simple_video_sample/svd_xt/000000.mp4 b/outputs/simple_video_sample/svd_xt/000000.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..64c2eb54d9dcfafaf8545f79fa1e4c4fe18cf74d Binary files /dev/null and b/outputs/simple_video_sample/svd_xt/000000.mp4 differ diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..2cc5021682b58914f28e686eb8d2904a4f3e636e --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,48 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "sgm" +dynamic = ["version"] +description = "Stability Generative Models" +readme = "README.md" +license-files = { paths = ["LICENSE-CODE"] } +requires-python = ">=3.8" + +[project.urls] +Homepage = "https://github.com/Stability-AI/generative-models" + +[tool.hatch.version] +path = "sgm/__init__.py" + +[tool.hatch.build] +# This needs to be explicitly set so the configuration files +# grafted into the `sgm` directory get included in the wheel's +# RECORD file. +include = [ + "sgm", +] +# The force-include configurations below make Hatch copy +# the configs/ directory (containing the various YAML files required +# to generatively model) into the source distribution and the wheel. + +[tool.hatch.build.targets.sdist.force-include] +"./configs" = "sgm/configs" + +[tool.hatch.build.targets.wheel.force-include] +"./configs" = "sgm/configs" + +[tool.hatch.envs.ci] +skip-install = false + +dependencies = [ + "pytest" +] + +[tool.hatch.envs.ci.scripts] +test-inference = [ + "pip install torch==2.0.1+cu118 torchvision==0.15.2+cu118 torchaudio==2.0.2+cu118 --index-url https://download.pytorch.org/whl/cu118", + "pip install -r requirements/pt2.txt", + "pytest -v tests/inference/test_inference.py {args}", +] diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..d79bd9b2efec0bcf3d4594b6261ca6bfc68b170c --- /dev/null +++ b/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +markers = + inference: mark as inference test (deselect with '-m "not inference"') \ No newline at end of file diff --git a/requirements/pt13.txt b/requirements/pt13.txt new file mode 100644 index 0000000000000000000000000000000000000000..b4f1272d89961ed8492084e0389224f44df53f32 --- /dev/null +++ b/requirements/pt13.txt @@ -0,0 +1,40 @@ +black==23.7.0 +chardet>=5.1.0 +clip @ git+https://github.com/openai/CLIP.git +einops>=0.6.1 +fairscale>=0.4.13 +fire>=0.5.0 +fsspec>=2023.6.0 +invisible-watermark>=0.2.0 +kornia==0.6.9 +matplotlib>=3.7.2 +natsort>=8.4.0 +numpy>=1.24.4 +omegaconf>=2.3.0 +onnx<=1.12.0 +open-clip-torch>=2.20.0 +opencv-python==4.6.0.66 +pandas>=2.0.3 +pillow>=9.5.0 +pudb>=2022.1.3 +pytorch-lightning==1.8.5 +pyyaml>=6.0.1 +scipy>=1.10.1 +streamlit>=1.25.0 +tensorboardx==2.5.1 +timm>=0.9.2 +tokenizers==0.12.1 +--extra-index-url https://download.pytorch.org/whl/cu117 +torch==1.13.1+cu117 +torchaudio==0.13.1 +torchdata==0.5.1 +torchmetrics>=1.0.1 +torchvision==0.14.1+cu117 +tqdm>=4.65.0 +transformers==4.19.1 +triton==2.0.0.post1 +urllib3<1.27,>=1.25.4 +wandb>=0.15.6 +webdataset>=0.2.33 +wheel>=0.41.0 +xformers==0.0.16 \ No newline at end of file diff --git a/scripts/__pycache__/__init__.cpython-310.pyc b/scripts/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f3987017c3b034ec9035c88a49c920ccbc56e78 Binary files /dev/null and b/scripts/__pycache__/__init__.cpython-310.pyc differ diff --git a/scripts/util/__pycache__/__init__.cpython-310.pyc b/scripts/util/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2e8da3e1d80d81a530aa041edf5ef6eac3ef156 Binary files /dev/null and b/scripts/util/__pycache__/__init__.cpython-310.pyc differ diff --git a/scripts/util/detection/__pycache__/__init__.cpython-310.pyc b/scripts/util/detection/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a14a90dda9c6b981a0214a498644a1b5f505846 Binary files /dev/null and b/scripts/util/detection/__pycache__/__init__.cpython-310.pyc differ diff --git a/scripts/util/detection/__pycache__/nsfw_and_watermark_dectection.cpython-310.pyc b/scripts/util/detection/__pycache__/nsfw_and_watermark_dectection.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69c32407a5b8c81c72b3c01126f969d0561e5ea9 Binary files /dev/null and b/scripts/util/detection/__pycache__/nsfw_and_watermark_dectection.cpython-310.pyc differ diff --git a/sgm/__pycache__/__init__.cpython-310.pyc b/sgm/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a5bafe34449f9384b9ca2252ae841fe3b76d938 Binary files /dev/null and b/sgm/__pycache__/__init__.cpython-310.pyc differ diff --git a/sgm/__pycache__/util.cpython-310.pyc b/sgm/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51aacb35a2f99f5291971c48dfd405899975184e Binary files /dev/null and b/sgm/__pycache__/util.cpython-310.pyc differ diff --git a/sgm/inference/__pycache__/helpers.cpython-310.pyc b/sgm/inference/__pycache__/helpers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b2e76a0e7316517c70bb47547a3675dde4b84c1 Binary files /dev/null and b/sgm/inference/__pycache__/helpers.cpython-310.pyc differ diff --git a/sgm/inference/api.py b/sgm/inference/api.py index 051950cce1f6a7db02a4f3eff59e3368cf2825e5..7171ff4abb774556b638c98ad809e195082bdccf 100644 --- a/sgm/inference/api.py +++ b/sgm/inference/api.py @@ -5,15 +5,14 @@ from typing import Optional from omegaconf import OmegaConf -from sgm.inference.helpers import Img2ImgDiscretizationWrapper, do_img2img, do_sample -from sgm.modules.diffusionmodules.sampling import ( - DPMPP2MSampler, - DPMPP2SAncestralSampler, - EulerAncestralSampler, - EulerEDMSampler, - HeunEDMSampler, - LinearMultistepSampler, -) +from sgm.inference.helpers import (Img2ImgDiscretizationWrapper, do_img2img, + do_sample) +from sgm.modules.diffusionmodules.sampling import (DPMPP2MSampler, + DPMPP2SAncestralSampler, + EulerAncestralSampler, + EulerEDMSampler, + HeunEDMSampler, + LinearMultistepSampler) from sgm.util import load_model_from_config diff --git a/sgm/models/__pycache__/__init__.cpython-310.pyc b/sgm/models/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b70e9673947bec87dfcbb9f989be104a57236440 Binary files /dev/null and b/sgm/models/__pycache__/__init__.cpython-310.pyc differ diff --git a/sgm/models/__pycache__/autoencoder.cpython-310.pyc b/sgm/models/__pycache__/autoencoder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1a772db5c3113b1ebe6efe7cbb0aa430397893d Binary files /dev/null and b/sgm/models/__pycache__/autoencoder.cpython-310.pyc differ diff --git a/sgm/models/__pycache__/diffusion.cpython-310.pyc b/sgm/models/__pycache__/diffusion.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e62ef1c4d9e4be45e440fff2d7eaa3a873b18fd Binary files /dev/null and b/sgm/models/__pycache__/diffusion.cpython-310.pyc differ diff --git a/sgm/models/autoencoder.py b/sgm/models/autoencoder.py index 17e86e72c2b50e8fdd5516fa0f1bd9c92a0a06e9..2949b91011a2be7a6b8ca17ce260812f20ce8b75 100644 --- a/sgm/models/autoencoder.py +++ b/sgm/models/autoencoder.py @@ -13,12 +13,8 @@ from packaging import version from ..modules.autoencoding.regularizers import AbstractRegularizer from ..modules.ema import LitEma -from ..util import ( - default, - get_nested_attribute, - get_obj_from_str, - instantiate_from_config, -) +from ..util import (default, get_nested_attribute, get_obj_from_str, + instantiate_from_config) logpy = logging.getLogger(__name__) diff --git a/sgm/models/diffusion.py b/sgm/models/diffusion.py index 261a4812b87cf0762ca48dc42c4c92535ab12803..2f3efd3c7e1e37bf4f78673ae72021f1f968e116 100644 --- a/sgm/models/diffusion.py +++ b/sgm/models/diffusion.py @@ -12,13 +12,8 @@ from ..modules import UNCONDITIONAL_CONFIG from ..modules.autoencoding.temporal_ae import VideoDecoder from ..modules.diffusionmodules.wrappers import OPENAIUNETWRAPPER from ..modules.ema import LitEma -from ..util import ( - default, - disabled_train, - get_obj_from_str, - instantiate_from_config, - log_txt_as_img, -) +from ..util import (default, disabled_train, get_obj_from_str, + instantiate_from_config, log_txt_as_img) class DiffusionEngine(pl.LightningModule): diff --git a/sgm/modules/__pycache__/__init__.cpython-310.pyc b/sgm/modules/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64bf4bc128d480bdfe6d23825638aef5d2706a56 Binary files /dev/null and b/sgm/modules/__pycache__/__init__.cpython-310.pyc differ diff --git a/sgm/modules/__pycache__/attention.cpython-310.pyc b/sgm/modules/__pycache__/attention.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70674211bea5664f2db28d9d085225f0825c764f Binary files /dev/null and b/sgm/modules/__pycache__/attention.cpython-310.pyc differ diff --git a/sgm/modules/__pycache__/ema.cpython-310.pyc b/sgm/modules/__pycache__/ema.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ab79ed4352457fb7f3a14e5f554845406a80bc2 Binary files /dev/null and b/sgm/modules/__pycache__/ema.cpython-310.pyc differ diff --git a/sgm/modules/__pycache__/video_attention.cpython-310.pyc b/sgm/modules/__pycache__/video_attention.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aba67cb7d0bd56ca370f9178da896f5529c9e163 Binary files /dev/null and b/sgm/modules/__pycache__/video_attention.cpython-310.pyc differ diff --git a/sgm/modules/autoencoding/__pycache__/__init__.cpython-310.pyc b/sgm/modules/autoencoding/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32ff974258e69fdea7c26c2d79976f59c13a71a7 Binary files /dev/null and b/sgm/modules/autoencoding/__pycache__/__init__.cpython-310.pyc differ diff --git a/sgm/modules/autoencoding/__pycache__/temporal_ae.cpython-310.pyc b/sgm/modules/autoencoding/__pycache__/temporal_ae.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c2a7af8f7d230af30e5ee98e74bf6b92cf59e0a Binary files /dev/null and b/sgm/modules/autoencoding/__pycache__/temporal_ae.cpython-310.pyc differ diff --git a/sgm/modules/autoencoding/regularizers/__init__.py b/sgm/modules/autoencoding/regularizers/__init__.py index 6065fb209b6cb6fb4e0cb601c895c2a35e0044e9..ff2b1815a5ba88892375e8ec9bedacea49024113 100644 --- a/sgm/modules/autoencoding/regularizers/__init__.py +++ b/sgm/modules/autoencoding/regularizers/__init__.py @@ -5,7 +5,8 @@ import torch import torch.nn as nn import torch.nn.functional as F -from ....modules.distributions.distributions import DiagonalGaussianDistribution +from ....modules.distributions.distributions import \ + DiagonalGaussianDistribution from .base import AbstractRegularizer diff --git a/sgm/modules/autoencoding/regularizers/__pycache__/__init__.cpython-310.pyc b/sgm/modules/autoencoding/regularizers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f28a6eb5275cc8fca4eaf28d4a5f32c01a0fbc9c Binary files /dev/null and b/sgm/modules/autoencoding/regularizers/__pycache__/__init__.cpython-310.pyc differ diff --git a/sgm/modules/autoencoding/regularizers/__pycache__/base.cpython-310.pyc b/sgm/modules/autoencoding/regularizers/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4cf67ba9304b4e0c65e06893839408e95eebaa1 Binary files /dev/null and b/sgm/modules/autoencoding/regularizers/__pycache__/base.cpython-310.pyc differ diff --git a/sgm/modules/autoencoding/temporal_ae.py b/sgm/modules/autoencoding/temporal_ae.py index d5b3944f109e5114c5068d549207bcc8f6a4cdbe..374373e2e4330846ffef28d9061dcc64f70d2722 100644 --- a/sgm/modules/autoencoding/temporal_ae.py +++ b/sgm/modules/autoencoding/temporal_ae.py @@ -29,7 +29,7 @@ class VideoResBlock(ResnetBlock): super().__init__(out_channels=out_channels, dropout=dropout, *args, **kwargs) if video_kernel_size is None: video_kernel_size = [3, 1, 1] - self.time_mix_blocks = ResBlock( + self.time_stack = ResBlock( channels=out_channels, emb_channels=0, dropout=dropout, @@ -74,7 +74,7 @@ class VideoResBlock(ResnetBlock): x = rearrange(x, "(b t) c h w -> b c t h w", t=timesteps) - x = self.time_mix_blocks(x, temb) + x = self.time_stack(x, temb) alpha = self.get_alpha(bs=b // timesteps) x = alpha * x + (1.0 - alpha) * x_mix @@ -83,7 +83,7 @@ class VideoResBlock(ResnetBlock): return x -class PostHocConv2WithTime(torch.nn.Conv2d): +class AE3DConv(torch.nn.Conv2d): def __init__(self, in_channels, out_channels, video_kernel_size=3, *args, **kwargs): super().__init__(in_channels, out_channels, *args, **kwargs) if isinstance(video_kernel_size, Iterable): @@ -333,9 +333,7 @@ class VideoDecoder(Decoder): def _make_conv(self) -> Callable: if self.time_mode != "attn-only": - return partialclass( - PostHocConv2WithTime, video_kernel_size=self.video_kernel_size - ) + return partialclass(AE3DConv, video_kernel_size=self.video_kernel_size) else: return Conv2DWrapper diff --git a/sgm/modules/diffusionmodules/__pycache__/__init__.cpython-310.pyc b/sgm/modules/diffusionmodules/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..180152d8be6ff466fc91e176cab78bc7c8f1f7d3 Binary files /dev/null and b/sgm/modules/diffusionmodules/__pycache__/__init__.cpython-310.pyc differ diff --git a/sgm/modules/diffusionmodules/__pycache__/denoiser.cpython-310.pyc b/sgm/modules/diffusionmodules/__pycache__/denoiser.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69b23bc54662b54e70f4b163b366db31b062b3df Binary files /dev/null and b/sgm/modules/diffusionmodules/__pycache__/denoiser.cpython-310.pyc differ diff --git a/sgm/modules/diffusionmodules/__pycache__/denoiser_scaling.cpython-310.pyc b/sgm/modules/diffusionmodules/__pycache__/denoiser_scaling.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea5312ebf639733a630ccf99572a2c287043abe7 Binary files /dev/null and b/sgm/modules/diffusionmodules/__pycache__/denoiser_scaling.cpython-310.pyc differ diff --git a/sgm/modules/diffusionmodules/__pycache__/discretizer.cpython-310.pyc b/sgm/modules/diffusionmodules/__pycache__/discretizer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7776cbb5ab5f46d9cf24d78fda50cd8a7d2ab171 Binary files /dev/null and b/sgm/modules/diffusionmodules/__pycache__/discretizer.cpython-310.pyc differ diff --git a/sgm/modules/diffusionmodules/__pycache__/guiders.cpython-310.pyc b/sgm/modules/diffusionmodules/__pycache__/guiders.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7a1ad89c0da9ef5fdb5f8b68f96b46d7eeb0fdd Binary files /dev/null and b/sgm/modules/diffusionmodules/__pycache__/guiders.cpython-310.pyc differ diff --git a/sgm/modules/diffusionmodules/__pycache__/model.cpython-310.pyc b/sgm/modules/diffusionmodules/__pycache__/model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33be3a7eaff6b085f1f7b16d3a724c09d4a61e05 Binary files /dev/null and b/sgm/modules/diffusionmodules/__pycache__/model.cpython-310.pyc differ diff --git a/sgm/modules/diffusionmodules/__pycache__/openaimodel.cpython-310.pyc b/sgm/modules/diffusionmodules/__pycache__/openaimodel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c03af92f0ec7751ef9c555cfeeaee486e98c301 Binary files /dev/null and b/sgm/modules/diffusionmodules/__pycache__/openaimodel.cpython-310.pyc differ diff --git a/sgm/modules/diffusionmodules/__pycache__/sampling.cpython-310.pyc b/sgm/modules/diffusionmodules/__pycache__/sampling.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebbf1c7a1c73bb0e00641b6218ab5d98d8b8dc1b Binary files /dev/null and b/sgm/modules/diffusionmodules/__pycache__/sampling.cpython-310.pyc differ diff --git a/sgm/modules/diffusionmodules/__pycache__/sampling_utils.cpython-310.pyc b/sgm/modules/diffusionmodules/__pycache__/sampling_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9258cb5de5fff48578e353e94752fd45cb7e747 Binary files /dev/null and b/sgm/modules/diffusionmodules/__pycache__/sampling_utils.cpython-310.pyc differ diff --git a/sgm/modules/diffusionmodules/__pycache__/util.cpython-310.pyc b/sgm/modules/diffusionmodules/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..066a373f7ff843071cea88ddbebe2949ee933392 Binary files /dev/null and b/sgm/modules/diffusionmodules/__pycache__/util.cpython-310.pyc differ diff --git a/sgm/modules/diffusionmodules/__pycache__/video_model.cpython-310.pyc b/sgm/modules/diffusionmodules/__pycache__/video_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..229a412d026b9925aafc357457acce46d5150381 Binary files /dev/null and b/sgm/modules/diffusionmodules/__pycache__/video_model.cpython-310.pyc differ diff --git a/sgm/modules/diffusionmodules/__pycache__/wrappers.cpython-310.pyc b/sgm/modules/diffusionmodules/__pycache__/wrappers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6fe8ea509d07cd2ab0642ecaae1ef9faedfe1ae Binary files /dev/null and b/sgm/modules/diffusionmodules/__pycache__/wrappers.cpython-310.pyc differ diff --git a/sgm/modules/diffusionmodules/denoiser_weighting.py b/sgm/modules/diffusionmodules/denoiser_weighting.py new file mode 100644 index 0000000000000000000000000000000000000000..b8b03ca58f17ea3d7374f4bbb7bf1d2994755e00 --- /dev/null +++ b/sgm/modules/diffusionmodules/denoiser_weighting.py @@ -0,0 +1,24 @@ +import torch + + +class UnitWeighting: + def __call__(self, sigma): + return torch.ones_like(sigma, device=sigma.device) + + +class EDMWeighting: + def __init__(self, sigma_data=0.5): + self.sigma_data = sigma_data + + def __call__(self, sigma): + return (sigma**2 + self.sigma_data**2) / (sigma * self.sigma_data) ** 2 + + +class VWeighting(EDMWeighting): + def __init__(self): + super().__init__(sigma_data=1.0) + + +class EpsWeighting: + def __call__(self, sigma): + return sigma**-2.0 diff --git a/sgm/modules/diffusionmodules/openaimodel.py b/sgm/modules/diffusionmodules/openaimodel.py index 5874fdd696eae8da5822a2e19831577a62fe0aa4..b58e1b0e9be031cd09803d451fc59f2a5ce88eea 100644 --- a/sgm/modules/diffusionmodules/openaimodel.py +++ b/sgm/modules/diffusionmodules/openaimodel.py @@ -10,14 +10,9 @@ from einops import rearrange from torch.utils.checkpoint import checkpoint from ...modules.attention import SpatialTransformer -from ...modules.diffusionmodules.util import ( - avg_pool_nd, - conv_nd, - linear, - normalization, - timestep_embedding, - zero_module, -) +from ...modules.diffusionmodules.util import (avg_pool_nd, conv_nd, linear, + normalization, + timestep_embedding, zero_module) from ...modules.video_attention import SpatialVideoTransformer from ...util import exists diff --git a/sgm/modules/diffusionmodules/sampling.py b/sgm/modules/diffusionmodules/sampling.py index 6346829c86a76ab549ed69431f1704e01379535a..af07566d599fdd6f255f8b9fd4592a962b0d2ace 100644 --- a/sgm/modules/diffusionmodules/sampling.py +++ b/sgm/modules/diffusionmodules/sampling.py @@ -9,13 +9,10 @@ import torch from omegaconf import ListConfig, OmegaConf from tqdm import tqdm -from ...modules.diffusionmodules.sampling_utils import ( - get_ancestral_step, - linear_multistep_coeff, - to_d, - to_neg_log_sigma, - to_sigma, -) +from ...modules.diffusionmodules.sampling_utils import (get_ancestral_step, + linear_multistep_coeff, + to_d, to_neg_log_sigma, + to_sigma) from ...util import append_dims, default, instantiate_from_config DEFAULT_GUIDER = {"target": "sgm.modules.diffusionmodules.guiders.IdentityGuider"} diff --git a/sgm/modules/diffusionmodules/video_model.py b/sgm/modules/diffusionmodules/video_model.py index fd794c0dc8d2482c5ba0227c9fa8d8a926078886..ff2d077c7d0c7ed1c4a2c21f14105c266abc4926 100644 --- a/sgm/modules/diffusionmodules/video_model.py +++ b/sgm/modules/diffusionmodules/video_model.py @@ -16,7 +16,7 @@ class VideoResBlock(ResBlock): emb_channels: int, dropout: float, video_kernel_size: Union[int, List[int]] = 3, - merge_strategy: bool = "fixed", + merge_strategy: str = "fixed", merge_factor: float = 0.5, out_channels: Optional[int] = None, use_conv: bool = False, @@ -39,7 +39,7 @@ class VideoResBlock(ResBlock): down=down, ) - self.time_mix_blocks = ResBlock( + self.time_stack = ResBlock( default(out_channels, channels), emb_channels, dropout=dropout, @@ -71,7 +71,7 @@ class VideoResBlock(ResBlock): x_mix = rearrange(x, "(b t) c h w -> b c t h w", t=num_video_frames) x = rearrange(x, "(b t) c h w -> b c t h w", t=num_video_frames) - x = self.time_mix_blocks( + x = self.time_stack( x, rearrange(emb, "(b t) ... -> b t ...", t=num_video_frames) ) x = self.time_mixer( diff --git a/sgm/modules/distributions/__pycache__/__init__.cpython-310.pyc b/sgm/modules/distributions/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0d6dec4b8c9929b420bf1c0e1a8ec1914cd4071 Binary files /dev/null and b/sgm/modules/distributions/__pycache__/__init__.cpython-310.pyc differ diff --git a/sgm/modules/distributions/__pycache__/distributions.cpython-310.pyc b/sgm/modules/distributions/__pycache__/distributions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..853a461c38d0a917de4b6f68383ce84732f15ed4 Binary files /dev/null and b/sgm/modules/distributions/__pycache__/distributions.cpython-310.pyc differ diff --git a/sgm/modules/encoders/__pycache__/__init__.cpython-310.pyc b/sgm/modules/encoders/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cd2d5aa953650c688d6192424856953e790a446 Binary files /dev/null and b/sgm/modules/encoders/__pycache__/__init__.cpython-310.pyc differ diff --git a/sgm/modules/encoders/__pycache__/modules.cpython-310.pyc b/sgm/modules/encoders/__pycache__/modules.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d02623ff71f2b53dbeb8d6d277948ce1cb7792e Binary files /dev/null and b/sgm/modules/encoders/__pycache__/modules.cpython-310.pyc differ diff --git a/sgm/modules/encoders/modules.py b/sgm/modules/encoders/modules.py index 0faa9b4669cd702a2aceeda601cc2aa5a56c14f5..d77b8ed706552a449a7df2a3febf1172ea28f4ee 100644 --- a/sgm/modules/encoders/modules.py +++ b/sgm/modules/encoders/modules.py @@ -11,28 +11,17 @@ import torch.nn as nn from einops import rearrange, repeat from omegaconf import ListConfig from torch.utils.checkpoint import checkpoint -from transformers import ( - ByT5Tokenizer, - CLIPTextModel, - CLIPTokenizer, - T5EncoderModel, - T5Tokenizer, -) +from transformers import (ByT5Tokenizer, CLIPTextModel, CLIPTokenizer, + T5EncoderModel, T5Tokenizer) from ...modules.autoencoding.regularizers import DiagonalGaussianRegularizer from ...modules.diffusionmodules.model import Encoder from ...modules.diffusionmodules.openaimodel import Timestep -from ...modules.diffusionmodules.util import extract_into_tensor, make_beta_schedule +from ...modules.diffusionmodules.util import (extract_into_tensor, + make_beta_schedule) from ...modules.distributions.distributions import DiagonalGaussianDistribution -from ...util import ( - append_dims, - autocast, - count_params, - default, - disabled_train, - expand_dims_like, - instantiate_from_config, -) +from ...util import (append_dims, autocast, count_params, default, + disabled_train, expand_dims_like, instantiate_from_config) class AbstractEmbModel(nn.Module): diff --git a/sgm/modules/video_attention.py b/sgm/modules/video_attention.py index 197863af4d5bb8b6ab4910700ec162993c62ce8e..783395aa554144936766b57380f35dab29c093c3 100644 --- a/sgm/modules/video_attention.py +++ b/sgm/modules/video_attention.py @@ -191,7 +191,7 @@ class SpatialVideoTransformer(SpatialTransformer): if use_spatial_context: time_context_dim = context_dim - self.time_mix_blocks = nn.ModuleList( + self.time_stack = nn.ModuleList( [ VideoTransformerBlock( inner_dim, @@ -211,13 +211,13 @@ class SpatialVideoTransformer(SpatialTransformer): ] ) - assert len(self.time_mix_blocks) == len(self.transformer_blocks) + assert len(self.time_stack) == len(self.transformer_blocks) self.use_spatial_context = use_spatial_context self.in_channels = in_channels time_embed_dim = self.in_channels * 4 - self.time_mix_time_embed = nn.Sequential( + self.time_pos_embed = nn.Sequential( linear(self.in_channels, time_embed_dim), nn.SiLU(), linear(time_embed_dim, self.in_channels), @@ -272,11 +272,11 @@ class SpatialVideoTransformer(SpatialTransformer): repeat_only=False, max_period=self.max_time_embed_period, ) - emb = self.time_mix_time_embed(t_emb) + emb = self.time_pos_embed(t_emb) emb = emb[:, None, :] for it_, (block, mix_block) in enumerate( - zip(self.transformer_blocks, self.time_mix_blocks) + zip(self.transformer_blocks, self.time_stack) ): x = block( x, diff --git a/tests/inference/test_inference.py b/tests/inference/test_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..2b2af11e44775f7835514b26627b1cee44cb3c79 --- /dev/null +++ b/tests/inference/test_inference.py @@ -0,0 +1,111 @@ +import numpy +from PIL import Image +import pytest +from pytest import fixture +import torch +from typing import Tuple + +from sgm.inference.api import ( + model_specs, + SamplingParams, + SamplingPipeline, + Sampler, + ModelArchitecture, +) +import sgm.inference.helpers as helpers + + +@pytest.mark.inference +class TestInference: + @fixture(scope="class", params=model_specs.keys()) + def pipeline(self, request) -> SamplingPipeline: + pipeline = SamplingPipeline(request.param) + yield pipeline + del pipeline + torch.cuda.empty_cache() + + @fixture( + scope="class", + params=[ + [ModelArchitecture.SDXL_V1_BASE, ModelArchitecture.SDXL_V1_REFINER], + [ModelArchitecture.SDXL_V0_9_BASE, ModelArchitecture.SDXL_V0_9_REFINER], + ], + ids=["SDXL_V1", "SDXL_V0_9"], + ) + def sdxl_pipelines(self, request) -> Tuple[SamplingPipeline, SamplingPipeline]: + base_pipeline = SamplingPipeline(request.param[0]) + refiner_pipeline = SamplingPipeline(request.param[1]) + yield base_pipeline, refiner_pipeline + del base_pipeline + del refiner_pipeline + torch.cuda.empty_cache() + + def create_init_image(self, h, w): + image_array = numpy.random.rand(h, w, 3) * 255 + image = Image.fromarray(image_array.astype("uint8")).convert("RGB") + return helpers.get_input_image_tensor(image) + + @pytest.mark.parametrize("sampler_enum", Sampler) + def test_txt2img(self, pipeline: SamplingPipeline, sampler_enum): + output = pipeline.text_to_image( + params=SamplingParams(sampler=sampler_enum.value, steps=10), + prompt="A professional photograph of an astronaut riding a pig", + negative_prompt="", + samples=1, + ) + + assert output is not None + + @pytest.mark.parametrize("sampler_enum", Sampler) + def test_img2img(self, pipeline: SamplingPipeline, sampler_enum): + output = pipeline.image_to_image( + params=SamplingParams(sampler=sampler_enum.value, steps=10), + image=self.create_init_image(pipeline.specs.height, pipeline.specs.width), + prompt="A professional photograph of an astronaut riding a pig", + negative_prompt="", + samples=1, + ) + assert output is not None + + @pytest.mark.parametrize("sampler_enum", Sampler) + @pytest.mark.parametrize( + "use_init_image", [True, False], ids=["img2img", "txt2img"] + ) + def test_sdxl_with_refiner( + self, + sdxl_pipelines: Tuple[SamplingPipeline, SamplingPipeline], + sampler_enum, + use_init_image, + ): + base_pipeline, refiner_pipeline = sdxl_pipelines + if use_init_image: + output = base_pipeline.image_to_image( + params=SamplingParams(sampler=sampler_enum.value, steps=10), + image=self.create_init_image( + base_pipeline.specs.height, base_pipeline.specs.width + ), + prompt="A professional photograph of an astronaut riding a pig", + negative_prompt="", + samples=1, + return_latents=True, + ) + else: + output = base_pipeline.text_to_image( + params=SamplingParams(sampler=sampler_enum.value, steps=10), + prompt="A professional photograph of an astronaut riding a pig", + negative_prompt="", + samples=1, + return_latents=True, + ) + + assert isinstance(output, (tuple, list)) + samples, samples_z = output + assert samples is not None + assert samples_z is not None + refiner_pipeline.refiner( + params=SamplingParams(sampler=sampler_enum.value, steps=10), + image=samples_z, + prompt="A professional photograph of an astronaut riding a pig", + negative_prompt="", + samples=1, + )