Spaces:
Paused
Paused
Commit ·
a3f8f46
1
Parent(s): e3d310b
Upload 147 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+3
- CODEOWNERSAdded+1
- LICENSE-CODEAdded+21
- README.md+292-11
- assets/000.jpgAdded
- assets/001_with_eval.pngAdded
- assets/test_image.pngAdded
- assets/tile.gifAdded
- data/DejaVuSans.ttfAdded
- main.pyAdded+943
- model_licenses/LICENSE-SDVAdded+31
- model_licenses/LICENSE-SDXL0.9Added+75
- model_licenses/LICENSE-SDXL1.0Added+175
- outputs/000000.mp4Added
- outputs/000001.mp4Added
- outputs/000002.mp4Added
- outputs/000003.mp4Added
- outputs/000004.mp4Added+3
- outputs/000005.mp4Added
- outputs/simple_video_sample/svd_xt/000000.mp4Added
- pyproject.tomlAdded+48
- pytest.iniAdded+3
- requirements/pt13.txtAdded+40
- scripts/__pycache__/__init__.cpython-310.pycAdded
- scripts/util/__pycache__/__init__.cpython-310.pycAdded
- scripts/util/detection/__pycache__/__init__.cpython-310.pycAdded
- scripts/util/detection/__pycache__/nsfw_and_watermark_dectection.cpython-310.pycAdded
- sgm/__pycache__/__init__.cpython-310.pycAdded
- sgm/__pycache__/util.cpython-310.pycAdded
- sgm/inference/__pycache__/helpers.cpython-310.pycAdded
- sgm/inference/api.py+8-9
- sgm/models/__pycache__/__init__.cpython-310.pycAdded
- sgm/models/__pycache__/autoencoder.cpython-310.pycAdded
- sgm/models/__pycache__/diffusion.cpython-310.pycAdded
- sgm/models/autoencoder.py+2-6
- sgm/models/diffusion.py+2-7
- sgm/modules/__pycache__/__init__.cpython-310.pycAdded
- sgm/modules/__pycache__/attention.cpython-310.pycAdded
- sgm/modules/__pycache__/ema.cpython-310.pycAdded
- sgm/modules/__pycache__/video_attention.cpython-310.pycAdded
- sgm/modules/autoencoding/__pycache__/__init__.cpython-310.pycAdded
- sgm/modules/autoencoding/__pycache__/temporal_ae.cpython-310.pycAdded
- sgm/modules/autoencoding/regularizers/__init__.py+2-1
- sgm/modules/autoencoding/regularizers/__pycache__/__init__.cpython-310.pycAdded
- sgm/modules/autoencoding/regularizers/__pycache__/base.cpython-310.pycAdded
- sgm/modules/autoencoding/temporal_ae.py+4-6
- sgm/modules/diffusionmodules/__pycache__/__init__.cpython-310.pycAdded
- sgm/modules/diffusionmodules/__pycache__/denoiser.cpython-310.pycAdded
- sgm/modules/diffusionmodules/__pycache__/denoiser_scaling.cpython-310.pycAdded
- sgm/modules/diffusionmodules/__pycache__/discretizer.cpython-310.pycAdded
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines33343536373832 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textassets/001_with_eval.png filter=lfs diff=lfs merge=lfs -textassets/tile.gif filter=lfs diff=lfs merge=lfs -textoutputs/000004.mp4 filter=lfs diff=lfs merge=lfs -text
1.github @Stability-AI/infrastructure123456789101112131415161718192021MIT License
Copyright (c) 2023 Stability AI
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 THESOFTWARE.1234567891011---title: Stable Video Diffusionemoji: 📺colorFrom: purplecolorTo: purplesdk: gradiosdk_version: 4.4.0app_file: app.pypinned: falselicense: other---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292# Generative Models by Stability AI## 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 14frames 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 finetunedfor 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).**July 26, 2023**- We are releasing two new open models with apermissive [`CreativeML Open RAIL++-M` license](model_licenses/LICENSE-SDXL1.0) (see [Inference](#inference) for filehashes):- [SDXL-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0): An improved versionover `SDXL-base-0.9`.- [SDXL-refiner-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-refiner-1.0): An improved versionover `SDXL-refiner-0.9`.**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. Thebase 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 usesthe OpenCLIP model.- `SDXL-refiner-0.9`: The refiner has been trained to denoise small noise levels of high quality data and as such isnot 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 PhilosophyModularity is king. This repo implements a config-driven approach where we build and combine submodules bycalling `instantiate_from_config()` on objects defined in yaml configs. See `configs/` for many examples.### Changelog from the old `ldm` codebaseFor training, we use [PyTorch Lightning](https://lightning.ai/docs/pytorch/stable/), but it should be easy to use othertraining 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 spatialconditionings, 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 thesamplers (`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 notablechange 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 lossfunction (`sgm/modules/diffusionmodules/denoiser_weighting.py`), preconditioning of thenetwork (`sgm/modules/diffusionmodules/denoiser_scaling.py`), and sampling of noise levels duringtraining (`sgm/modules/diffusionmodules/sigma_sampling.py`).- Autoencoding models have also been cleaned up.## Installation:<a name="installation"></a>#### 1. Clone the repo```shellgit clone git@github.com:Stability-AI/generative-models.gitcd generative-models```#### 2. Setting up the virtualenvThis 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 pypipython3 -m venv .pt2source .pt2/bin/activatepip3 install -r requirements/pt2.txt```#### 3. Install `sgm````shellpip3 install .```#### 4. Install `sdata` for training```shellpip3 install -e git+https://github.com/Stability-AI/datapipelines.git@main#egg=sdata```## PackagingThis 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 hatchhatch 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.## InferenceWe provide a [streamlit](https://streamlit.io/) demo for text-to-image and image-to-image samplingin `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): 31e35c80fc4829d14f90153f4c74cd59c90b779f6afe05a74cd6120b893f7e5bTensordata Hash (sha256): 0xd7a9105a900fd52748f20725fe52fe52b507fd36bee4fc107b1550a26e6ee1d7```- [SDXL-refiner-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-refiner-1.0)```File Hash (sha256): 7440042bbdc8a24813002c09b6b69b64dc90fded4472613437b7f55f9b7d9c5fTensordata 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 toa [`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 <your_port>```### Invisible Watermark DetectionImages 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 providea script to easily detect that watermark. Please note that this watermark isnot 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 ortry an _experimental_ import using only a minimal amount of packages:```bashpython -m venv .detectsource .detect/bin/activatepip 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 scriptis then useable in the following ways (don't forget to activate yourvirtual environment beforehand, e.g. `source .pt1/bin/activate`):```bash# test a single filepython scripts/demo/detect.py <your filename here># test multiple files at oncepython scripts/demo/detect.py <filename 1> <filename 2> ... <filename n># test all files in a specific folderpython scripts/demo/detect.py <your folder name here>/*```## Training:We are providing example training configs in `configs/example_training`. To launch a training, run```python main.py --base configs/<config1.yaml> configs/<config2.yaml>```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 bedefined in a single config. For example, to run a class-conditional pixel-based diffusion model training on MNIST,run```bashpython main.py --base configs/example_training/toy/mnist_cond.yaml```**NOTE 1:** Using the non-toy-datasetconfigs `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 theused dataset (which is expected to stored in tar-file inthe [webdataset-format](https://github.com/webdataset/webdataset)). To find the parts which have to be adapted, searchfor comments containing `USER:` in the respective config.**NOTE 2:** This repository supports both `pytorch1.13` and `pytorch2`for training generative models. However forautoencoder 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`) requiresretrieving the checkpoint from [Hugging Face](https://huggingface.co/stabilityai/sdxl-vae/tree/main) and replacingthe `CKPT_PATH` placeholder in [this line](configs/example_training/imagenet-f8_cond.yaml#81). The same is to be donefor the provided text-to-image configs.### Building New Diffusion Models#### ConditionerThe `GeneralConditioner` is configured through the `conditioner_config`. Its only attribute is `emb_models`, a list ofdifferent 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-freeguidance dropout rate is used (`ucg_rate`, default `0`), and an input key (`input_key`), for example, `txt` fortext-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 concatenatedappropriately.Note that the order of the embedders in the `conditioner_config` is important.#### NetworkThe neural network is set through the `network_config`. This used to be called `unet_config`, which is not generalenough as we plan to experiment with transformer-based diffusion backbones.#### LossThe loss is configured through `loss_config`. For standard diffusion model training, you will have toset `sigma_sampler_config`.#### Sampler configAs discussed above, the sampler is independent of the model. In the `sampler_config`, we set the type of numericalsolver, number of steps, type of discretization, as well as, for example, guidance wrappers for classifier-freeguidance.### Dataset HandlingFor large scale training we recommend using the data pipelines fromour [data pipelines](https://github.com/Stability-AI/datapipelines) project. The project is contained in the requirementand 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 ofdata keys/values,e.g.,```pythonexample = {"jpg": x, # this is a tensor -1...1 chw"txt": "a beautiful image"}```where we expect images in -1...1, channel-first format.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943import argparseimport datetimeimport globimport inspectimport osimport sysfrom inspect import Parameterfrom typing import Union
import numpy as npimport pytorch_lightning as plimport torchimport torchvisionimport wandbfrom matplotlib import pyplot as pltfrom natsort import natsortedfrom omegaconf import OmegaConffrom packaging import versionfrom PIL import Imagefrom pytorch_lightning import seed_everythingfrom pytorch_lightning.callbacks import Callbackfrom pytorch_lightning.loggers import WandbLoggerfrom pytorch_lightning.trainer import Trainerfrom 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_onlydef 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())12345678910111213141516171819202122232425262728293031STABLE 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. 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475SDXL 0.9 RESEARCH LICENSE AGREEMENTCopyright (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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175Copyright (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, andhave the potential to transform the way artists, among other individuals, conceive andbenefit from AI or ML technologies as a tool for content creation. Notwithstanding thecurrent and potential benefits that these artifacts can bring to society at large, thereare also concerns about potential misuses of them, either due to their technicallimitations or ethical considerations. In short, this license strives for both the openand responsible downstream use of the accompanying model. When it comes to the opencharacter, we took inspiration from open source permissive licenses regarding the grantof IP rights. Referring to the downstream responsible use, we added use-basedrestrictions not permitting the use of the model in very specific scenarios, in orderfor the licensor to be able to enforce the license in case potential misuses of theModel may occur. At the same time, we strive to promote open and responsible research ongenerative models for art and content generation. Even though downstream derivativeversions of the model could be released under different licensing terms, the latter willalways have to include - at minimum - the same use-based restrictions as the ones in theoriginal license (this license). We believe in the intersection between open andresponsible AI development; thus, this agreement aims to strike a balance between bothin order to enable responsible open-science in the field of AI. This CreativeML OpenRAIL++-M License governs the use of the model (and its derivatives) and is informed bythe model card associated with the model. NOW THEREFORE, You and Licensor agree asfollows: Definitions "License" means the terms and conditions for use, reproduction, andDistribution as defined in this document. "Data" means a collection of informationand/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 contentresulting therefrom. "Model" means any accompanying machine-learning based assemblies(including checkpoints), consisting of learnt weights, parameters (including optimizerstates), corresponding to the model architecture as embodied in the ComplementaryMaterial, that have been trained or tuned, in whole or in part on the Data, using theComplementary 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 transferof patterns of the weights, parameters, activations or output of the Model, to the othermodel, 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 datarepresentations or methods based on the generation of synthetic data by the Model fortraining the other model. "Complementary Material" means the accompanying source codeand scripts used to define, run, load, benchmark or evaluate the Model, and used toprepare data for training or evaluation, if any. This includes any accompanyingdocumentation, tutorials, examples, etc, if any. "Distribution" means any transmission,reproduction, publication or other sharing of the Model or Derivatives of the Model to athird party, including providing the Model as a hosted service made available byelectronic or other remote means - e.g. API-based or web access. "Licensor" means thecopyright owner or entity authorized by the copyright owner that is granting theLicense, including the persons or entities that may have rights in the Model and/ordistributing the Model. "You" (or "Your") means an individual or Legal Entity exercisingpermissions granted by this License and/or making use of the Model for whichever purposeand 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 legalentities that are not under common control with Licensor or You. "Contribution" meansany work of authorship, including the original version of the Model and anymodifications or additions to that Model or Derivatives of the Model thereof, that isintentionally submitted to Licensor for inclusion in the Model by the copyright owner orby 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 notlimited to communication on electronic mailing lists, source code control systems, andissue tracking systems that are managed by, or on behalf of, the Licensor for thepurpose of discussing and improving the Model, but excluding communication that isconspicuously marked or otherwise designated in writing by the copyright owner as "Not aContribution." "Contributor" means Licensor and any individual or Legal Entity on behalfof whom a Contribution has been received by Licensor and subsequently incorporatedwithin the Model.
Section II: INTELLECTUAL PROPERTY RIGHTS Both copyright and patent grants apply to theModel, Derivatives of the Model and Complementary Material. The Model and Derivatives ofthe Model are subject to additional terms as described in
Section III. Grant of Copyright License. Subject to the terms and conditions of thisLicense, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,no-charge, royalty-free, irrevocable copyright license to reproduce, prepare, publiclydisplay, publicly perform, sublicense, and distribute the Complementary Material, theModel, and Derivatives of the Model. Grant of Patent License. Subject to the terms andconditions of this License and where and as applicable, each Contributor hereby grantsto 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 tosell, sell, import, and otherwise transfer the Model and the Complementary Material,where such license applies only to those patent claims licensable by such Contributorthat are necessarily infringed by their Contribution(s) alone or by combination of theirContribution(s) with the Model to which such Contribution(s) was submitted. If Youinstitute patent litigation against any entity (including a cross-claim or counterclaimin a lawsuit) alleging that the Model and/or Complementary Material or a Contributionincorporated within the Model and/or Complementary Material constitutes direct orcontributory patent infringement, then any patent licenses granted to You under thisLicense for the Model and/or Work shall terminate as of the date such litigation isasserted or filed. Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTIONDistribution and Redistribution. You may host for Third Party remote access purposes(e.g. software-as-a-service), reproduce and distribute copies of the Model orDerivatives of the Model thereof in any medium, with or without modifications, providedthat You meet the following conditions: Use-based restrictions as referenced inparagraph 5 MUST be included as an enforceable provision by You in any type of legalagreement (e.g. a license) governing the use and/or distribution of the Model orDerivatives of the Model, and You shall give notice to subsequent users You Distributeto, that the Model or Derivatives of the Model are subject to paragraph 5. Thisprovision does not apply to the use of Complementary Material. You must give any ThirdParty recipients of the Model or Derivatives of the Model a copy of this License; Youmust cause any modified files to carry prominent notices stating that You changed thefiles; You must retain all copyright, patent, trademark, and attribution noticesexcluding those notices that do not pertain to any part of the Model, Derivatives of theModel. You may add Your own copyright statement to Your modifications and may provideadditional or different license terms and conditions - respecting paragraph 4.a. - foruse, reproduction, or Distribution of Your modifications, or for any such Derivatives ofthe Model as a whole, provided Your use, reproduction, and Distribution of the Modelotherwise 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 specifiedrestricted uses. You may use the Model subject to this License, including only forlawful purposes and in accordance with the License. Use may include creating any contentwith, finetuning, updating, running, training, evaluating and/or reparametrizing theModel. You shall require all of Your users who use the Model or a Derivative of theModel 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 usingthe Model. You are accountable for the Output you generate and its subsequent uses. Nouse of the output can contravene any provision as stated in the License.
Section IV: OTHER PROVISIONS Updates and Runtime Restrictions. To the maximum extentpermitted by law, Licensor reserves the right to restrict (remotely or otherwise) usageof the Model in violation of this License. Trademarks and related. Nothing in thisLicense permits You to make use of Licensors’ trademarks, trade names, logos or tootherwise suggest endorsement or misrepresent the relationship between the parties; andany rights not expressly granted herein are reserved by the Licensors. Disclaimer ofWarranty. Unless required by applicable law or agreed to in writing, Licensor providesthe Model and the Complementary Material (and each Contributor provides itsContributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, eitherexpress or implied, including, without limitation, any warranties or conditions ofTITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You aresolely responsible for determining the appropriateness of using or redistributing theModel, Derivatives of the Model, and the Complementary Material and assume any risksassociated with Your exercise of permissions under this License. Limitation ofLiability. In no event and under no legal theory, whether in tort (includingnegligence), contract, or otherwise, unless required by applicable law (such asdeliberate and grossly negligent acts) or agreed to in writing, shall any Contributor beliable to You for damages, including any direct, indirect, special, incidental, orconsequential damages of any character arising as a result of this License or out of theuse or inability to use the Model and the Complementary Material (including but notlimited 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 beenadvised of the possibility of such damages. Accepting Warranty or Additional Liability.While redistributing the Model, Derivatives of the Model and the Complementary Materialthereof, 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 Yoursole responsibility, not on behalf of any other Contributor, and only if You agree toindemnify, defend, and hold each Contributor harmless for any liability incurred by, orclaims asserted against, such Contributor by reason of your accepting any such warrantyor additional liability. If any provision of this License is held to be invalid, illegalor unenforceable, the remaining provisions shall be unaffected thereby and remain validas if such provision had not been set forth herein.
END OF TERMS AND CONDITIONS
Attachment A Use RestrictionsYou agree not to use the Model or Derivatives of the Model:In any way that violates any applicable national, federal, state, local orinternational law or regulation; For the purpose of exploiting, harming or attempting toexploit or harm minors in any way; To generate or disseminate verifiably falseinformation and/or content with the purpose of harming others; To generate ordisseminate personal identifiable information that can be used to harm an individual; Todefame, disparage or otherwise harass others; For fully automated decision making thatadversely impacts an individual’s legal rights or otherwise creates or modifies abinding, enforceable obligation; For any use intended to or which has the effect ofdiscriminating against or harming individuals or groups based on online or offlinesocial behavior or known or predicted personal or personality characteristics; Toexploit 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 behaviorof a person pertaining to that group in a manner that causes or is likely to cause thatperson or another person physical or psychological harm; For any use intended to orwhich has the effect of discriminating against individuals or groups based on legallyprotected characteristics or categories; To provide medical advice and medical resultsinterpretation; To generate or disseminate information for the purpose to be used foradministration of justice, law enforcement, immigration or asylum processes, such aspredicting an individual will commit fraud/crime commitment (e.g. by text profiling,drawing causal relationships between assertions made in documents, indiscriminate andarbitrarily-targeted use).123version https://git-lfs.github.com/spec/v1oid sha256:c2cc34e39dd8c5d2022de56d1d83936ac2b7a286ab0351895f1b83e00a9e2fa7size 1574414123456789101112131415161718192021222324252627282930313233343536373839404142434445464748[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}",]123[pytest]markers = inference: mark as inference test (deselect with '-m "not inference"')12345678910111213141516171819202122232425262728293031323334353637383940black==23.7.0chardet>=5.1.0clip @ git+https://github.com/openai/CLIP.giteinops>=0.6.1fairscale>=0.4.13fire>=0.5.0fsspec>=2023.6.0invisible-watermark>=0.2.0kornia==0.6.9matplotlib>=3.7.2natsort>=8.4.0numpy>=1.24.4omegaconf>=2.3.0onnx<=1.12.0open-clip-torch>=2.20.0opencv-python==4.6.0.66pandas>=2.0.3pillow>=9.5.0pudb>=2022.1.3pytorch-lightning==1.8.5pyyaml>=6.0.1scipy>=1.10.1streamlit>=1.25.0tensorboardx==2.5.1timm>=0.9.2tokenizers==0.12.1--extra-index-url https://download.pytorch.org/whl/cu117torch==1.13.1+cu117torchaudio==0.13.1torchdata==0.5.1torchmetrics>=1.0.1torchvision==0.14.1+cu117tqdm>=4.65.0transformers==4.19.1triton==2.0.0.post1urllib3<1.27,>=1.25.4wandb>=0.15.6webdataset>=0.2.33wheel>=0.41.0xformers==0.0.164 unmodified lines56789101112131415161718194 unmodified linesfrom omegaconf import OmegaConffrom sgm.inference.helpers import Img2ImgDiscretizationWrapper, do_img2img, do_samplefrom sgm.modules.diffusionmodules.sampling import (DPMPP2MSampler,DPMPP2SAncestralSampler,EulerAncestralSampler,EulerEDMSampler,HeunEDMSampler,LinearMultistepSampler,)from sgm.util import load_model_from_config4 unmodified lines567891011121314151617184 unmodified linesfrom omegaconf import OmegaConffrom 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
12 unmodified lines13141516171819202122232412 unmodified linesfrom ..modules.autoencoding.regularizers import AbstractRegularizerfrom ..modules.ema import LitEmafrom ..util import (default,get_nested_attribute,get_obj_from_str,instantiate_from_config,)logpy = logging.getLogger(__name__)12 unmodified lines131415161718192012 unmodified linesfrom ..modules.autoencoding.regularizers import AbstractRegularizerfrom ..modules.ema import LitEmafrom ..util import (default, get_nested_attribute, get_obj_from_str,instantiate_from_config)logpy = logging.getLogger(__name__)
11 unmodified lines1213141516171819202122232411 unmodified linesfrom ..modules.autoencoding.temporal_ae import VideoDecoderfrom ..modules.diffusionmodules.wrappers import OPENAIUNETWRAPPERfrom ..modules.ema import LitEmafrom ..util import (default,disabled_train,get_obj_from_str,instantiate_from_config,log_txt_as_img,)class DiffusionEngine(pl.LightningModule):11 unmodified lines121314151617181911 unmodified linesfrom ..modules.autoencoding.temporal_ae import VideoDecoderfrom ..modules.diffusionmodules.wrappers import OPENAIUNETWRAPPERfrom ..modules.ema import LitEmafrom ..util import (default, disabled_train, get_obj_from_str,instantiate_from_config, log_txt_as_img)class DiffusionEngine(pl.LightningModule):
4 unmodified lines5678910114 unmodified linesimport torch.nn as nnimport torch.nn.functional as Ffrom ....modules.distributions.distributions import DiagonalGaussianDistributionfrom .base import AbstractRegularizer4 unmodified lines567891011124 unmodified linesimport torch.nn as nnimport torch.nn.functional as Ffrom ....modules.distributions.distributions import \DiagonalGaussianDistributionfrom .base import AbstractRegularizer
28 unmodified lines2930313233343538 unmodified lines747576777879802 unmodified lines83848586878889243 unmodified lines33333433533633733833934034128 unmodified linessuper().__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(channels=out_channels,emb_channels=0,dropout=dropout,38 unmodified linesx = rearrange(x, "(b t) c h w -> b c t h w", t=timesteps)x = self.time_mix_blocks(x, temb)alpha = self.get_alpha(bs=b // timesteps)x = alpha * x + (1.0 - alpha) * x_mix2 unmodified linesreturn xclass PostHocConv2WithTime(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):243 unmodified linesdef _make_conv(self) -> Callable:if self.time_mode != "attn-only":return partialclass(PostHocConv2WithTime, video_kernel_size=self.video_kernel_size)else:return Conv2DWrapper28 unmodified lines2930313233343538 unmodified lines747576777879802 unmodified lines83848586878889243 unmodified lines33333433533633733833928 unmodified linessuper().__init__(out_channels=out_channels, dropout=dropout, *args, **kwargs)if video_kernel_size is None:video_kernel_size = [3, 1, 1]self.time_stack = ResBlock(channels=out_channels,emb_channels=0,dropout=dropout,38 unmodified linesx = rearrange(x, "(b t) c h w -> b c t h w", t=timesteps)x = self.time_stack(x, temb)alpha = self.get_alpha(bs=b // timesteps)x = alpha * x + (1.0 - alpha) * x_mix2 unmodified linesreturn xclass 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):243 unmodified linesdef _make_conv(self) -> Callable:if self.time_mode != "attn-only":return partialclass(AE3DConv, video_kernel_size=self.video_kernel_size)else:return Conv2DWrapper
.gitattributes+3
CODEOWNERSAdded+1
LICENSE-CODEAdded+21
README.md+292-11
assets/000.jpgAdded

assets/001_with_eval.pngAdded

Large File Pointer Details
- SHA256: 026fa14e30098729064a00fb7fcec41bb57dcddb33b36b548d553f601bc53634
- Pointer size: 132 Bytes
- Size of remote file: 4.19 MB
assets/test_image.pngAdded

assets/tile.gifAdded

Large File Pointer Details
- SHA256: 2340a9809e36fa9634633c7cc5fd256737c620ba47151726c85173512dc5c8ff
- Pointer size: 133 Bytes
- Size of remote file: 18.6 MB
data/DejaVuSans.ttfAdded
main.pyAdded+943
model_licenses/LICENSE-SDVAdded+31
model_licenses/LICENSE-SDXL0.9Added+75
model_licenses/LICENSE-SDXL1.0Added+175
outputs/000000.mp4Added
outputs/000001.mp4Added
outputs/000002.mp4Added
outputs/000003.mp4Added
outputs/000004.mp4Added+3
outputs/000005.mp4Added
outputs/simple_video_sample/svd_xt/000000.mp4Added
pyproject.tomlAdded+48
pytest.iniAdded+3
requirements/pt13.txtAdded+40
scripts/__pycache__/__init__.cpython-310.pycAdded
scripts/util/__pycache__/__init__.cpython-310.pycAdded
scripts/util/detection/__pycache__/__init__.cpython-310.pycAdded
scripts/util/detection/__pycache__/nsfw_and_watermark_dectection.cpython-310.pycAdded
sgm/__pycache__/__init__.cpython-310.pycAdded
sgm/__pycache__/util.cpython-310.pycAdded
sgm/inference/__pycache__/helpers.cpython-310.pycAdded
sgm/inference/api.py+8-9
sgm/models/__pycache__/__init__.cpython-310.pycAdded
sgm/models/__pycache__/autoencoder.cpython-310.pycAdded
sgm/models/__pycache__/diffusion.cpython-310.pycAdded
sgm/models/autoencoder.py+2-6
sgm/models/diffusion.py+2-7
sgm/modules/__pycache__/__init__.cpython-310.pycAdded
sgm/modules/__pycache__/attention.cpython-310.pycAdded
sgm/modules/__pycache__/ema.cpython-310.pycAdded
sgm/modules/__pycache__/video_attention.cpython-310.pycAdded
sgm/modules/autoencoding/__pycache__/__init__.cpython-310.pycAdded
sgm/modules/autoencoding/__pycache__/temporal_ae.cpython-310.pycAdded
sgm/modules/autoencoding/regularizers/__init__.py+2-1
sgm/modules/autoencoding/regularizers/__pycache__/__init__.cpython-310.pycAdded
sgm/modules/autoencoding/regularizers/__pycache__/base.cpython-310.pycAdded
sgm/modules/autoencoding/temporal_ae.py+4-6
sgm/modules/diffusionmodules/__pycache__/__init__.cpython-310.pycAdded
sgm/modules/diffusionmodules/__pycache__/denoiser.cpython-310.pycAdded
sgm/modules/diffusionmodules/__pycache__/denoiser_scaling.cpython-310.pycAdded
sgm/modules/diffusionmodules/__pycache__/discretizer.cpython-310.pycAdded