Spaces:
Configuration error
Configuration error
scribbyotx
commited on
Commit
•
610ead1
1
Parent(s):
6128574
Upload 160 files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- LICENSE +9 -0
- README.md +255 -12
- configs/generate.yaml +99 -0
- configs/train.yaml +113 -0
- dataset_creation/generate_img_dataset.py +315 -0
- dataset_creation/generate_txt_dataset.py +113 -0
- dataset_creation/prepare_dataset.py +29 -0
- dataset_creation/prepare_for_gpt.py +25 -0
- edit_app.py +268 -0
- edit_cli.py +128 -0
- edit_dataset.py +121 -0
- environment.yaml +38 -0
- imgs/dataset.jpg +0 -0
- imgs/edit_app.jpg +0 -0
- imgs/example.jpg +0 -0
- imgs/prompt_app.jpg +0 -0
- main.py +799 -0
- metrics/clip_similarity.py +47 -0
- metrics/compute_metrics.py +235 -0
- prompt_app.py +55 -0
- scripts/download_checkpoints.sh +7 -0
- scripts/download_data.sh +27 -0
- scripts/download_pretrained_sd.sh +7 -0
- stable_diffusion/LICENSE +82 -0
- stable_diffusion/README.md +215 -0
- stable_diffusion/Stable_Diffusion_v1_Model_Card.md +144 -0
- stable_diffusion/assets/a-painting-of-a-fire.png +0 -0
- stable_diffusion/assets/a-photograph-of-a-fire.png +0 -0
- stable_diffusion/assets/a-shirt-with-a-fire-printed-on-it.png +0 -0
- stable_diffusion/assets/a-shirt-with-the-inscription-'fire'.png +0 -0
- stable_diffusion/assets/a-watercolor-painting-of-a-fire.png +0 -0
- stable_diffusion/assets/birdhouse.png +0 -0
- stable_diffusion/assets/fire.png +0 -0
- stable_diffusion/assets/inpainting.png +0 -0
- stable_diffusion/assets/modelfigure.png +0 -0
- stable_diffusion/assets/rdm-preview.jpg +0 -0
- stable_diffusion/assets/reconstruction1.png +0 -0
- stable_diffusion/assets/reconstruction2.png +0 -0
- stable_diffusion/assets/results.gif.REMOVED.git-id +1 -0
- stable_diffusion/assets/rick.jpeg +0 -0
- stable_diffusion/assets/stable-samples/img2img/mountains-1.png +0 -0
- stable_diffusion/assets/stable-samples/img2img/mountains-2.png +0 -0
- stable_diffusion/assets/stable-samples/img2img/mountains-3.png +0 -0
- stable_diffusion/assets/stable-samples/img2img/sketch-mountains-input.jpg +0 -0
- stable_diffusion/assets/stable-samples/img2img/upscaling-in.png.REMOVED.git-id +1 -0
- stable_diffusion/assets/stable-samples/img2img/upscaling-out.png.REMOVED.git-id +1 -0
- stable_diffusion/assets/stable-samples/txt2img/000002025.png +0 -0
- stable_diffusion/assets/stable-samples/txt2img/000002035.png +0 -0
- stable_diffusion/assets/stable-samples/txt2img/merged-0005.png.REMOVED.git-id +1 -0
- stable_diffusion/assets/stable-samples/txt2img/merged-0006.png.REMOVED.git-id +1 -0
LICENSE
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Copyright 2023 Timothy Brooks, Aleksander Holynski, Alexei A. Efros
|
2 |
+
|
3 |
+
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:
|
4 |
+
|
5 |
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
6 |
+
|
7 |
+
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.
|
8 |
+
|
9 |
+
Portions of code and models (such as pretrained checkpoints, which are fine-tuned starting from released Stable Diffusion checkpoints) are derived from the Stable Diffusion codebase (https://github.com/CompVis/stable-diffusion). Further restrictions may apply. Please consult the Stable Diffusion license `stable_diffusion/LICENSE`. Modified code is denoted as such in comments at the start of each file.
|
README.md
CHANGED
@@ -1,12 +1,255 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# InstructPix2Pix: Learning to Follow Image Editing Instructions
|
2 |
+
### [Project Page](https://www.timothybrooks.com/instruct-pix2pix/) | [Paper](https://arxiv.org/abs/2211.09800) | [Data](http://instruct-pix2pix.eecs.berkeley.edu/)
|
3 |
+
PyTorch implementation of InstructPix2Pix, an instruction-based image editing model, based on the original [CompVis/stable_diffusion](https://github.com/CompVis/stable-diffusion) repo. <br>
|
4 |
+
|
5 |
+
[InstructPix2Pix: Learning to Follow Image Editing Instructions](https://www.timothybrooks.com/instruct-pix2pix/)
|
6 |
+
[Tim Brooks](https://www.timothybrooks.com/)\*,
|
7 |
+
[Aleksander Holynski](https://holynski.org/)\*,
|
8 |
+
[Alexei A. Efros](https://people.eecs.berkeley.edu/~efros/) <br>
|
9 |
+
UC Berkeley <br>
|
10 |
+
\*denotes equal contribution
|
11 |
+
|
12 |
+
<img src='https://instruct-pix2pix.timothybrooks.com/teaser.jpg'/>
|
13 |
+
|
14 |
+
## TL;DR: quickstart
|
15 |
+
|
16 |
+
Follow the instructions below to download and run InstructPix2Pix on your own images. These instructions have been tested on a GPU with >18GB VRAM. If you don't have a GPU, you may need to change the default configuration, or check out [other ways of using the model](https://github.com/timothybrooks/instruct-pix2pix#other-ways-of-using-instructpix2pix).
|
17 |
+
|
18 |
+
### Set up a conda environment, and download a pretrained model:
|
19 |
+
```
|
20 |
+
conda env create -f environment.yaml
|
21 |
+
conda activate ip2p
|
22 |
+
bash scripts/download_checkpoints.sh
|
23 |
+
```
|
24 |
+
|
25 |
+
### Edit a single image:
|
26 |
+
```
|
27 |
+
python edit_cli.py --input imgs/example.jpg --output imgs/output.jpg --edit "turn him into a cyborg"
|
28 |
+
|
29 |
+
# Optionally, you can specify parameters to tune your result:
|
30 |
+
# python edit_cli.py --steps 100 --resolution 512 --seed 1371 --cfg-text 7.5 --cfg-image 1.2 --input imgs/example.jpg --output imgs/output.jpg --edit "turn him into a cyborg"
|
31 |
+
```
|
32 |
+
|
33 |
+
### Or launch your own interactive editing Gradio app:
|
34 |
+
```
|
35 |
+
python edit_app.py
|
36 |
+
```
|
37 |
+
![Edit app](https://github.com/timothybrooks/instruct-pix2pix/blob/main/imgs/edit_app.jpg?raw=true)
|
38 |
+
|
39 |
+
_(For advice on how to get the best results by tuning parameters, see the [Tips](https://github.com/timothybrooks/instruct-pix2pix#tips) section)._
|
40 |
+
|
41 |
+
## Setup
|
42 |
+
|
43 |
+
Install all dependencies with:
|
44 |
+
```
|
45 |
+
conda env create -f environment.yaml
|
46 |
+
```
|
47 |
+
|
48 |
+
Download the pretrained models by running:
|
49 |
+
```
|
50 |
+
bash scripts/download_checkpoints.sh
|
51 |
+
```
|
52 |
+
|
53 |
+
## Generated Dataset
|
54 |
+
|
55 |
+
Our image editing model is trained on a generated dataset consisting of 454,445 examples. Each example contains (1) an input image, (2) an editing instruction, and (3) an output edited image. We provide two versions of the dataset, one in which each pair of edited images is generated 100 times, and the best examples are chosen based on CLIP metrics (Section 3.1.2 in the paper) (`clip-filtered-dataset`), and one in which examples are randomly chosen (`random-sample-dataset`).
|
56 |
+
|
57 |
+
For the released version of this dataset, we've additionally filtered prompts and images for NSFW content. After NSFW filtering, the GPT-3 generated dataset contains 451,990 examples. The final image-pair datasets contain:
|
58 |
+
|
59 |
+
| | # of image editing examples | Dataset size |
|
60 |
+
|--|-----------------------|----------------------- |
|
61 |
+
| `random-sample-dataset` |451990|727GB|
|
62 |
+
| `clip-filtered-dataset` |313010|436GB|
|
63 |
+
|
64 |
+
To download one of these datasets, along with the entire NSFW-filtered text data, run the following command with the appropriate dataset name:
|
65 |
+
|
66 |
+
```
|
67 |
+
bash scripts/download_data.sh clip-filtered-dataset
|
68 |
+
```
|
69 |
+
|
70 |
+
|
71 |
+
## Training InstructPix2Pix
|
72 |
+
|
73 |
+
InstructPix2Pix is trained by fine-tuning from an initial StableDiffusion checkpoint. The first step is to download a Stable Diffusion checkpoint. For our trained models, we used the v1.5 checkpoint as the starting point. To download the same ones we used, you can run the following script:
|
74 |
+
```
|
75 |
+
bash scripts/download_pretrained_sd.sh
|
76 |
+
```
|
77 |
+
If you'd like to use a different checkpoint, point to it in the config file `configs/train.yaml`, on line 8, after `ckpt_path:`.
|
78 |
+
|
79 |
+
Next, we need to change the config to point to our downloaded (or generated) dataset. If you're using the `clip-filtered-dataset` from above, you can skip this. Otherwise, you may need to edit lines 85 and 94 of the config (`data.params.train.params.path`, `data.params.validation.params.path`).
|
80 |
+
|
81 |
+
Finally, start a training job with the following command:
|
82 |
+
|
83 |
+
```
|
84 |
+
python main.py --name default --base configs/train.yaml --train --gpus 0,1,2,3,4,5,6,7
|
85 |
+
```
|
86 |
+
|
87 |
+
|
88 |
+
## Creating your own dataset
|
89 |
+
|
90 |
+
Our generated dataset of paired images and editing instructions is made in two phases: First, we use GPT-3 to generate text triplets: (a) a caption describing an image, (b) an edit instruction, (c) a caption describing the image after the edit. Then, we turn pairs of captions (before/after the edit) into pairs of images using Stable Diffusion and Prompt-to-Prompt.
|
91 |
+
|
92 |
+
### (1) Generate a dataset of captions and instructions
|
93 |
+
|
94 |
+
We provide our generated dataset of captions and edit instructions [here](https://instruct-pix2pix.eecs.berkeley.edu/gpt-generated-prompts.jsonl). If you plan to use our captions+instructions, skip to step (2). Otherwise, if you would like to create your own text dataset, please follow steps (1.1-1.3) below. Note that generating very large datasets using GPT-3 can be expensive.
|
95 |
+
|
96 |
+
#### (1.1) Manually write a dataset of instructions and captions
|
97 |
+
|
98 |
+
The first step of the process is fine-tuning GPT-3. To do this, we made a dataset of 700 examples broadly covering of edits that we might want our model to be able to perform. Our examples are available [here](https://instruct-pix2pix.eecs.berkeley.edu/human-written-prompts.jsonl). These should be diverse and cover a wide range of possible captions and types of edits. Ideally, they should avoid duplication or significant overlap of captions and instructions. It is also important to be mindful of limitations of Stable Diffusion and Prompt-to-Prompt in writing these examples, such as inability to perform large spatial transformations (e.g., moving the camera, zooming in, swapping object locations).
|
99 |
+
|
100 |
+
Input prompts should closely match the distribution of input prompts used to generate the larger dataset. We sampled the 700 input prompts from the _LAION Improved Aesthetics 6.5+_ dataset and also use this dataset for generating examples. We found this dataset is quite noisy (many of the captions are overly long and contain irrelevant text). For this reason, we also considered MSCOCO and LAION-COCO datasets, but ultimately chose _LAION Improved Aesthetics 6.5+_ due to its diversity of content, proper nouns, and artistic mediums. If you choose to use another dataset or combination of datasets as input to GPT-3 when generating examples, we recommend you sample the input prompts from the same distribution when manually writing training examples.
|
101 |
+
|
102 |
+
#### (1.2) Finetune GPT-3
|
103 |
+
|
104 |
+
The next step is to finetune a large language model on the manually written instructions/outputs to generate edit instructions and edited caption from a new input caption. For this, we finetune GPT-3's Davinci model via the OpenAI API, although other language models could be used.
|
105 |
+
|
106 |
+
To prepare training data for GPT-3, one must first create an OpenAI developer account to access the needed APIs, and [set up the API keys on your local device](https://beta.openai.com/docs/api-reference/introduction). Also, run the `prompts/prepare_for_gpt.py` script, which forms the prompts into the correct format by concatenating instructions and captions and adding delimiters and stop sequences.
|
107 |
+
|
108 |
+
```bash
|
109 |
+
python dataset_creation/prepare_for_gpt.py --input-path data/human-written-prompts.jsonl --output-path data/human-written-prompts-for-gpt.jsonl
|
110 |
+
```
|
111 |
+
|
112 |
+
Next, finetune GPT-3 via the OpenAI CLI. We provide an example below, although please refer to OpenAI's official documentation for this, as best practices may change. We trained the Davinci model for a single epoch. You can experiment with smaller less expensive GPT-3 variants or with open source language models, although this may negatively affect performance.
|
113 |
+
|
114 |
+
```bash
|
115 |
+
openai api fine_tunes.create -t data/human-written-prompts-for-gpt.jsonl -m davinci --n_epochs 1 --suffix "instruct-pix2pix"
|
116 |
+
```
|
117 |
+
|
118 |
+
You can test out the finetuned GPT-3 model by launching the provided Gradio app:
|
119 |
+
|
120 |
+
```bash
|
121 |
+
python prompt_app.py --openai-api-key OPENAI_KEY --openai-model OPENAI_MODEL_NAME
|
122 |
+
```
|
123 |
+
|
124 |
+
![Prompt app](https://github.com/timothybrooks/instruct-pix2pix/blob/main/imgs/prompt_app.jpg?raw=true)
|
125 |
+
|
126 |
+
#### (1.3) Generate a large dataset of captions and instructions
|
127 |
+
|
128 |
+
We now use the finetuned GPT-3 model to generate a large dataset. Our dataset cost thousands of dollars to create. See `prompts/gen_instructions_and_captions.py` for the script which generates these examples. We recommend first generating a small number of examples (by setting a low value of `--num-samples`) and gradually increasing the scale to ensure the results are working as desired before increasing scale.
|
129 |
+
|
130 |
+
```bash
|
131 |
+
python dataset_creation/generate_txt_dataset.py --openai-api-key OPENAI_KEY --openai-model OPENAI_MODEL_NAME
|
132 |
+
```
|
133 |
+
|
134 |
+
If you are generating at a very large scale (e.g., 100K+), it will be noteably faster to generate the dataset with multiple processes running in parallel. This can be accomplished by setting `--partitions=N` to a higher number and running multiple processes, setting each `--partition` to the corresponding value.
|
135 |
+
|
136 |
+
```bash
|
137 |
+
python dataset_creation/generate_txt_dataset.py --openai-api-key OPENAI_KEY --openai-model OPENAI_MODEL_NAME --partitions=10 --partition=0
|
138 |
+
```
|
139 |
+
|
140 |
+
### (2) Turn paired captions into paired images
|
141 |
+
|
142 |
+
The next step is to turn pairs of text captions into pairs of images. For this, we need to copy some pre-trained Stable Diffusion checkpoints to `stable_diffusion/models/ldm/stable-diffusion-v1/`. You may have already done this if you followed the instructions above for training with our provided data, but if not, you can do this by running:
|
143 |
+
|
144 |
+
```bash
|
145 |
+
bash scripts/download_pretrained_sd.sh
|
146 |
+
```
|
147 |
+
|
148 |
+
For our model, we used [checkpoint v1.5](https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned.ckpt), and the [new autoencoder](https://huggingface.co/stabilityai/sd-vae-ft-mse-original/resolve/main/vae-ft-mse-840000-ema-pruned.ckpt), but other models may work as well. If you choose to use other models, make sure to change point to the corresponding checkpoints by passing in the `--ckpt` and `--vae-ckpt` arguments. Once all checkpoints have been downloaded, we can generate the dataset with the following command:
|
149 |
+
|
150 |
+
```
|
151 |
+
python dataset_creation/generate_img_dataset.py --out_dir data/instruct-pix2pix-dataset-000 --prompts_file path/to/generated_prompts.jsonl
|
152 |
+
```
|
153 |
+
|
154 |
+
This command operates on a single GPU (typically a V100 or A100). To parallelize over many GPUs/machines, set `--n-partitions` to the total number of parallel jobs and `--partition` to the index of each job.
|
155 |
+
|
156 |
+
```
|
157 |
+
python dataset_creation/generate_img_dataset.py --out_dir data/instruct-pix2pix-dataset-000 --prompts_file path/to/generated_prompts.jsonl --n-partitions 100 --partition 0
|
158 |
+
```
|
159 |
+
|
160 |
+
The default parameters match that of our dataset, although in practice you can use a smaller number of steps (e.g., `--steps=25`) to generate high quality data faster. By default, we generate 100 samples per prompt and use CLIP filtering to keep a max of 4 per prompt. You can experiment with fewer samples by setting `--n-samples`. The command below turns off CLIP filtering entirely and is therefore faster:
|
161 |
+
|
162 |
+
```
|
163 |
+
python dataset_creation/generate_img_dataset.py --out_dir data/instruct-pix2pix-dataset-000 --prompts_file path/to/generated_prompts.jsonl --n-samples 4 --clip-threshold 0 --clip-dir-threshold 0 --clip-img-threshold 0 --n-partitions 100 --partition 0
|
164 |
+
```
|
165 |
+
|
166 |
+
After generating all of the dataset examples, run the following command below to create a list of the examples. This is needed for the dataset onject to efficiently be able to sample examples without needing to iterate over the entire dataset directory at the start of each training run.
|
167 |
+
|
168 |
+
```
|
169 |
+
python dataset_creation/prepare_dataset.py data/instruct-pix2pix-dataset-000
|
170 |
+
```
|
171 |
+
|
172 |
+
## Evaluation
|
173 |
+
|
174 |
+
To generate plots like the ones in Figures 8 and 10 in the paper, run the following command:
|
175 |
+
|
176 |
+
```
|
177 |
+
python metrics/compute_metrics.py --ckpt /path/to/your/model.ckpt
|
178 |
+
```
|
179 |
+
|
180 |
+
## Tips
|
181 |
+
|
182 |
+
If you're not getting the quality result you want, there may be a few reasons:
|
183 |
+
1. **Is the image not changing enough?** Your Image CFG weight may be too high. This value dictates how similar the output should be to the input. It's possible your edit requires larger changes from the original image, and your Image CFG weight isn't allowing that. Alternatively, your Text CFG weight may be too low. This value dictates how much to listen to the text instruction. The default Image CFG of 1.5 and Text CFG of 7.5 are a good starting point, but aren't necessarily optimal for each edit. Try:
|
184 |
+
* Decreasing the Image CFG weight, or
|
185 |
+
* Increasing the Text CFG weight, or
|
186 |
+
2. Conversely, **is the image changing too much**, such that the details in the original image aren't preserved? Try:
|
187 |
+
* Increasing the Image CFG weight, or
|
188 |
+
* Decreasing the Text CFG weight
|
189 |
+
3. Try generating results with different random seeds by setting "Randomize Seed" and running generation multiple times. You can also try setting "Randomize CFG" to sample new Text CFG and Image CFG values each time.
|
190 |
+
4. Rephrasing the instruction sometimes improves results (e.g., "turn him into a dog" vs. "make him a dog" vs. "as a dog").
|
191 |
+
5. Increasing the number of steps sometimes improves results.
|
192 |
+
6. Do faces look weird? The Stable Diffusion autoencoder has a hard time with faces that are small in the image. Try cropping the image so the face takes up a larger portion of the frame.
|
193 |
+
|
194 |
+
## Comments
|
195 |
+
|
196 |
+
- Our codebase is based on the [Stable Diffusion codebase](https://github.com/CompVis/stable-diffusion).
|
197 |
+
|
198 |
+
## BibTeX
|
199 |
+
|
200 |
+
```
|
201 |
+
@article{brooks2022instructpix2pix,
|
202 |
+
title={InstructPix2Pix: Learning to Follow Image Editing Instructions},
|
203 |
+
author={Brooks, Tim and Holynski, Aleksander and Efros, Alexei A},
|
204 |
+
journal={arXiv preprint arXiv:2211.09800},
|
205 |
+
year={2022}
|
206 |
+
}
|
207 |
+
```
|
208 |
+
## Other ways of using InstructPix2Pix
|
209 |
+
|
210 |
+
### InstructPix2Pix on [HuggingFace](https://huggingface.co/spaces/timbrooks/instruct-pix2pix):
|
211 |
+
> A browser-based version of the demo is available as a [HuggingFace space](https://huggingface.co/spaces/timbrooks/instruct-pix2pix). For this version, you only need a browser, a picture you want to edit, and an instruction! Note that this is a shared online demo, and processing time may be slower during peak utilization.
|
212 |
+
|
213 |
+
### InstructPix2Pix on [Replicate](https://replicate.com/timothybrooks/instruct-pix2pix):
|
214 |
+
> Replicate provides a production-ready cloud API for running the InstructPix2Pix model. You can run the model from any environment using a simple API call with cURL, Python, JavaScript, or your language of choice. Replicate also provides a web interface for running the model and sharing predictions.
|
215 |
+
|
216 |
+
### InstructPix2Pix in [Imaginairy](https://github.com/brycedrennan/imaginAIry#-edit-images-with-instructions-alone-by-instructpix2pix):
|
217 |
+
> Imaginairy offers another way of easily installing InstructPix2Pix with a single command. It can run on devices without GPUs (like a Macbook!).
|
218 |
+
> ```bash
|
219 |
+
> pip install imaginairy --upgrade
|
220 |
+
> aimg edit any-image.jpg --gif "turn him into a cyborg"
|
221 |
+
> ```
|
222 |
+
> It also offers an easy way to perform a bunch of edits on an image, and can save edits out to an animated GIF:
|
223 |
+
> ```
|
224 |
+
> aimg edit --gif --surprise-me pearl-earring.jpg
|
225 |
+
> ```
|
226 |
+
> <img src="https://raw.githubusercontent.com/brycedrennan/imaginAIry/7c05c3aae2740278978c5e84962b826e58201bac/assets/girl_with_a_pearl_earring_suprise.gif" width="512">
|
227 |
+
|
228 |
+
### InstructPix2Pix in [🧨 Diffusers](https://github.com/huggingface/diffusers):
|
229 |
+
|
230 |
+
> InstructPix2Pix in Diffusers is a bit more optimized, so it may be faster and more suitable for GPUs with less memory. Below are instructions for installing the library and editing an image:
|
231 |
+
> 1. Install diffusers and relevant dependencies:
|
232 |
+
>
|
233 |
+
> ```bash
|
234 |
+
> pip install transformers accelerate torch
|
235 |
+
>
|
236 |
+
> pip install git+https://github.com/huggingface/diffusers.git
|
237 |
+
> ```
|
238 |
+
>
|
239 |
+
> 2. Load the model and edit the image:
|
240 |
+
>
|
241 |
+
> ```python
|
242 |
+
>
|
243 |
+
> import torch
|
244 |
+
> from diffusers import StableDiffusionInstructPix2PixPipeline, EulerAncestralDiscreteScheduler
|
245 |
+
>
|
246 |
+
> model_id = "timbrooks/instruct-pix2pix"
|
247 |
+
> pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(model_id, torch_dtype=torch.float16, safety_checker=None)
|
248 |
+
> pipe.to("cuda")
|
249 |
+
> pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
|
250 |
+
> # `image` is an RGB PIL.Image
|
251 |
+
> images = pipe("turn him into cyborg", image=image).images
|
252 |
+
> images[0]
|
253 |
+
> ```
|
254 |
+
>
|
255 |
+
> For more information, check the docs [here](https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/pix2pix).
|
configs/generate.yaml
ADDED
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# File modified by authors of InstructPix2Pix from original (https://github.com/CompVis/stable-diffusion).
|
2 |
+
# See more details in LICENSE.
|
3 |
+
|
4 |
+
model:
|
5 |
+
base_learning_rate: 1.0e-04
|
6 |
+
target: ldm.models.diffusion.ddpm_edit.LatentDiffusion
|
7 |
+
params:
|
8 |
+
linear_start: 0.00085
|
9 |
+
linear_end: 0.0120
|
10 |
+
num_timesteps_cond: 1
|
11 |
+
log_every_t: 200
|
12 |
+
timesteps: 1000
|
13 |
+
first_stage_key: edited
|
14 |
+
cond_stage_key: edit
|
15 |
+
# image_size: 64
|
16 |
+
# image_size: 32
|
17 |
+
image_size: 16
|
18 |
+
channels: 4
|
19 |
+
cond_stage_trainable: false # Note: different from the one we trained before
|
20 |
+
conditioning_key: hybrid
|
21 |
+
monitor: val/loss_simple_ema
|
22 |
+
scale_factor: 0.18215
|
23 |
+
use_ema: true
|
24 |
+
load_ema: true
|
25 |
+
|
26 |
+
scheduler_config: # 10000 warmup steps
|
27 |
+
target: ldm.lr_scheduler.LambdaLinearScheduler
|
28 |
+
params:
|
29 |
+
warm_up_steps: [ 0 ]
|
30 |
+
cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
|
31 |
+
f_start: [ 1.e-6 ]
|
32 |
+
f_max: [ 1. ]
|
33 |
+
f_min: [ 1. ]
|
34 |
+
|
35 |
+
unet_config:
|
36 |
+
target: ldm.modules.diffusionmodules.openaimodel.UNetModel
|
37 |
+
params:
|
38 |
+
image_size: 32 # unused
|
39 |
+
in_channels: 8
|
40 |
+
out_channels: 4
|
41 |
+
model_channels: 320
|
42 |
+
attention_resolutions: [ 4, 2, 1 ]
|
43 |
+
num_res_blocks: 2
|
44 |
+
channel_mult: [ 1, 2, 4, 4 ]
|
45 |
+
num_heads: 8
|
46 |
+
use_spatial_transformer: True
|
47 |
+
transformer_depth: 1
|
48 |
+
context_dim: 768
|
49 |
+
use_checkpoint: True
|
50 |
+
legacy: False
|
51 |
+
|
52 |
+
first_stage_config:
|
53 |
+
target: ldm.models.autoencoder.AutoencoderKL
|
54 |
+
params:
|
55 |
+
embed_dim: 4
|
56 |
+
monitor: val/rec_loss
|
57 |
+
ddconfig:
|
58 |
+
double_z: true
|
59 |
+
z_channels: 4
|
60 |
+
resolution: 256
|
61 |
+
in_channels: 3
|
62 |
+
out_ch: 3
|
63 |
+
ch: 128
|
64 |
+
ch_mult:
|
65 |
+
- 1
|
66 |
+
- 2
|
67 |
+
- 4
|
68 |
+
- 4
|
69 |
+
num_res_blocks: 2
|
70 |
+
attn_resolutions: []
|
71 |
+
dropout: 0.0
|
72 |
+
lossconfig:
|
73 |
+
target: torch.nn.Identity
|
74 |
+
|
75 |
+
cond_stage_config:
|
76 |
+
target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
|
77 |
+
|
78 |
+
data:
|
79 |
+
target: main.DataModuleFromConfig
|
80 |
+
params:
|
81 |
+
batch_size: 128
|
82 |
+
num_workers: 1
|
83 |
+
wrap: false
|
84 |
+
validation:
|
85 |
+
target: edit_dataset.EditDataset
|
86 |
+
params:
|
87 |
+
path: data/clip-filtered-dataset
|
88 |
+
cache_dir: data/
|
89 |
+
cache_name: data_10k
|
90 |
+
split: val
|
91 |
+
min_text_sim: 0.2
|
92 |
+
min_image_sim: 0.75
|
93 |
+
min_direction_sim: 0.2
|
94 |
+
max_samples_per_prompt: 1
|
95 |
+
min_resize_res: 512
|
96 |
+
max_resize_res: 512
|
97 |
+
crop_res: 512
|
98 |
+
output_as_edit: False
|
99 |
+
real_input: True
|
configs/train.yaml
ADDED
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# File modified by authors of InstructPix2Pix from original (https://github.com/CompVis/stable-diffusion).
|
2 |
+
# See more details in LICENSE.
|
3 |
+
|
4 |
+
model:
|
5 |
+
base_learning_rate: 1.0e-04
|
6 |
+
target: ldm.models.diffusion.ddpm_edit.LatentDiffusion
|
7 |
+
params:
|
8 |
+
ckpt_path: stable_diffusion/models/ldm/stable-diffusion-v1/v1-5-pruned-emaonly.ckpt
|
9 |
+
linear_start: 0.00085
|
10 |
+
linear_end: 0.0120
|
11 |
+
num_timesteps_cond: 1
|
12 |
+
log_every_t: 200
|
13 |
+
timesteps: 1000
|
14 |
+
first_stage_key: edited
|
15 |
+
cond_stage_key: edit
|
16 |
+
image_size: 32
|
17 |
+
channels: 4
|
18 |
+
cond_stage_trainable: false # Note: different from the one we trained before
|
19 |
+
conditioning_key: hybrid
|
20 |
+
monitor: val/loss_simple_ema
|
21 |
+
scale_factor: 0.18215
|
22 |
+
use_ema: true
|
23 |
+
load_ema: false
|
24 |
+
|
25 |
+
scheduler_config: # 10000 warmup steps
|
26 |
+
target: ldm.lr_scheduler.LambdaLinearScheduler
|
27 |
+
params:
|
28 |
+
warm_up_steps: [ 0 ]
|
29 |
+
cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
|
30 |
+
f_start: [ 1.e-6 ]
|
31 |
+
f_max: [ 1. ]
|
32 |
+
f_min: [ 1. ]
|
33 |
+
|
34 |
+
unet_config:
|
35 |
+
target: ldm.modules.diffusionmodules.openaimodel.UNetModel
|
36 |
+
params:
|
37 |
+
image_size: 32 # unused
|
38 |
+
in_channels: 8
|
39 |
+
out_channels: 4
|
40 |
+
model_channels: 320
|
41 |
+
attention_resolutions: [ 4, 2, 1 ]
|
42 |
+
num_res_blocks: 2
|
43 |
+
channel_mult: [ 1, 2, 4, 4 ]
|
44 |
+
num_heads: 8
|
45 |
+
use_spatial_transformer: True
|
46 |
+
transformer_depth: 1
|
47 |
+
context_dim: 768
|
48 |
+
use_checkpoint: True
|
49 |
+
legacy: False
|
50 |
+
|
51 |
+
first_stage_config:
|
52 |
+
target: ldm.models.autoencoder.AutoencoderKL
|
53 |
+
params:
|
54 |
+
embed_dim: 4
|
55 |
+
monitor: val/rec_loss
|
56 |
+
ddconfig:
|
57 |
+
double_z: true
|
58 |
+
z_channels: 4
|
59 |
+
resolution: 256
|
60 |
+
in_channels: 3
|
61 |
+
out_ch: 3
|
62 |
+
ch: 128
|
63 |
+
ch_mult:
|
64 |
+
- 1
|
65 |
+
- 2
|
66 |
+
- 4
|
67 |
+
- 4
|
68 |
+
num_res_blocks: 2
|
69 |
+
attn_resolutions: []
|
70 |
+
dropout: 0.0
|
71 |
+
lossconfig:
|
72 |
+
target: torch.nn.Identity
|
73 |
+
|
74 |
+
cond_stage_config:
|
75 |
+
target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
|
76 |
+
|
77 |
+
data:
|
78 |
+
target: main.DataModuleFromConfig
|
79 |
+
params:
|
80 |
+
batch_size: 32
|
81 |
+
num_workers: 2
|
82 |
+
train:
|
83 |
+
target: edit_dataset.EditDataset
|
84 |
+
params:
|
85 |
+
path: data/clip-filtered-dataset
|
86 |
+
split: train
|
87 |
+
min_resize_res: 256
|
88 |
+
max_resize_res: 256
|
89 |
+
crop_res: 256
|
90 |
+
flip_prob: 0.5
|
91 |
+
validation:
|
92 |
+
target: edit_dataset.EditDataset
|
93 |
+
params:
|
94 |
+
path: data/clip-filtered-dataset
|
95 |
+
split: val
|
96 |
+
min_resize_res: 256
|
97 |
+
max_resize_res: 256
|
98 |
+
crop_res: 256
|
99 |
+
|
100 |
+
lightning:
|
101 |
+
callbacks:
|
102 |
+
image_logger:
|
103 |
+
target: main.ImageLogger
|
104 |
+
params:
|
105 |
+
batch_frequency: 2000
|
106 |
+
max_images: 2
|
107 |
+
increase_log_steps: False
|
108 |
+
|
109 |
+
trainer:
|
110 |
+
max_epochs: 2000
|
111 |
+
benchmark: True
|
112 |
+
accumulate_grad_batches: 4
|
113 |
+
check_val_every_n_epoch: 4
|
dataset_creation/generate_img_dataset.py
ADDED
@@ -0,0 +1,315 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import json
|
3 |
+
import sys
|
4 |
+
from pathlib import Path
|
5 |
+
|
6 |
+
import k_diffusion
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import torch.nn as nn
|
10 |
+
from einops import rearrange, repeat
|
11 |
+
from omegaconf import OmegaConf
|
12 |
+
from PIL import Image
|
13 |
+
from pytorch_lightning import seed_everything
|
14 |
+
from tqdm import tqdm
|
15 |
+
|
16 |
+
sys.path.append("./")
|
17 |
+
sys.path.append("./stable_diffusion")
|
18 |
+
|
19 |
+
from ldm.modules.attention import CrossAttention
|
20 |
+
from ldm.util import instantiate_from_config
|
21 |
+
from metrics.clip_similarity import ClipSimilarity
|
22 |
+
|
23 |
+
|
24 |
+
################################################################################
|
25 |
+
# Modified K-diffusion Euler ancestral sampler with prompt-to-prompt.
|
26 |
+
# https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/sampling.py
|
27 |
+
|
28 |
+
|
29 |
+
def append_dims(x, target_dims):
|
30 |
+
"""Appends dimensions to the end of a tensor until it has target_dims dimensions."""
|
31 |
+
dims_to_append = target_dims - x.ndim
|
32 |
+
if dims_to_append < 0:
|
33 |
+
raise ValueError(f"input has {x.ndim} dims but target_dims is {target_dims}, which is less")
|
34 |
+
return x[(...,) + (None,) * dims_to_append]
|
35 |
+
|
36 |
+
|
37 |
+
def to_d(x, sigma, denoised):
|
38 |
+
"""Converts a denoiser output to a Karras ODE derivative."""
|
39 |
+
return (x - denoised) / append_dims(sigma, x.ndim)
|
40 |
+
|
41 |
+
|
42 |
+
def get_ancestral_step(sigma_from, sigma_to):
|
43 |
+
"""Calculates the noise level (sigma_down) to step down to and the amount
|
44 |
+
of noise to add (sigma_up) when doing an ancestral sampling step."""
|
45 |
+
sigma_up = min(sigma_to, (sigma_to**2 * (sigma_from**2 - sigma_to**2) / sigma_from**2) ** 0.5)
|
46 |
+
sigma_down = (sigma_to**2 - sigma_up**2) ** 0.5
|
47 |
+
return sigma_down, sigma_up
|
48 |
+
|
49 |
+
|
50 |
+
def sample_euler_ancestral(model, x, sigmas, prompt2prompt_threshold=0.0, **extra_args):
|
51 |
+
"""Ancestral sampling with Euler method steps."""
|
52 |
+
s_in = x.new_ones([x.shape[0]])
|
53 |
+
for i in range(len(sigmas) - 1):
|
54 |
+
prompt_to_prompt = prompt2prompt_threshold > i / (len(sigmas) - 2)
|
55 |
+
for m in model.modules():
|
56 |
+
if isinstance(m, CrossAttention):
|
57 |
+
m.prompt_to_prompt = prompt_to_prompt
|
58 |
+
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
59 |
+
sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1])
|
60 |
+
d = to_d(x, sigmas[i], denoised)
|
61 |
+
# Euler method
|
62 |
+
dt = sigma_down - sigmas[i]
|
63 |
+
x = x + d * dt
|
64 |
+
if sigmas[i + 1] > 0:
|
65 |
+
# Make noise the same across all samples in batch.
|
66 |
+
x = x + torch.randn_like(x[:1]) * sigma_up
|
67 |
+
return x
|
68 |
+
|
69 |
+
|
70 |
+
################################################################################
|
71 |
+
|
72 |
+
|
73 |
+
def load_model_from_config(config, ckpt, vae_ckpt=None, verbose=False):
|
74 |
+
print(f"Loading model from {ckpt}")
|
75 |
+
pl_sd = torch.load(ckpt, map_location="cpu")
|
76 |
+
if "global_step" in pl_sd:
|
77 |
+
print(f"Global Step: {pl_sd['global_step']}")
|
78 |
+
sd = pl_sd["state_dict"]
|
79 |
+
if vae_ckpt is not None:
|
80 |
+
print(f"Loading VAE from {vae_ckpt}")
|
81 |
+
vae_sd = torch.load(vae_ckpt, map_location="cpu")["state_dict"]
|
82 |
+
sd = {
|
83 |
+
k: vae_sd[k[len("first_stage_model.") :]] if k.startswith("first_stage_model.") else v
|
84 |
+
for k, v in sd.items()
|
85 |
+
}
|
86 |
+
model = instantiate_from_config(config.model)
|
87 |
+
m, u = model.load_state_dict(sd, strict=False)
|
88 |
+
if len(m) > 0 and verbose:
|
89 |
+
print("missing keys:")
|
90 |
+
print(m)
|
91 |
+
if len(u) > 0 and verbose:
|
92 |
+
print("unexpected keys:")
|
93 |
+
print(u)
|
94 |
+
return model
|
95 |
+
|
96 |
+
|
97 |
+
class CFGDenoiser(nn.Module):
|
98 |
+
def __init__(self, model):
|
99 |
+
super().__init__()
|
100 |
+
self.inner_model = model
|
101 |
+
|
102 |
+
def forward(self, x, sigma, uncond, cond, cfg_scale):
|
103 |
+
x_in = torch.cat([x] * 2)
|
104 |
+
sigma_in = torch.cat([sigma] * 2)
|
105 |
+
cond_in = torch.cat([uncond, cond])
|
106 |
+
uncond, cond = self.inner_model(x_in, sigma_in, cond=cond_in).chunk(2)
|
107 |
+
return uncond + (cond - uncond) * cfg_scale
|
108 |
+
|
109 |
+
|
110 |
+
def to_pil(image: torch.Tensor) -> Image.Image:
|
111 |
+
image = 255.0 * rearrange(image.cpu().numpy(), "c h w -> h w c")
|
112 |
+
image = Image.fromarray(image.astype(np.uint8))
|
113 |
+
return image
|
114 |
+
|
115 |
+
|
116 |
+
def main():
|
117 |
+
parser = argparse.ArgumentParser()
|
118 |
+
parser.add_argument(
|
119 |
+
"--out_dir",
|
120 |
+
type=str,
|
121 |
+
required=True,
|
122 |
+
help="Path to output dataset directory.",
|
123 |
+
)
|
124 |
+
parser.add_argument(
|
125 |
+
"--prompts_file",
|
126 |
+
type=str,
|
127 |
+
required=True,
|
128 |
+
help="Path to prompts .jsonl file.",
|
129 |
+
)
|
130 |
+
parser.add_argument(
|
131 |
+
"--ckpt",
|
132 |
+
type=str,
|
133 |
+
default="stable_diffusion/models/ldm/stable-diffusion-v1/v1-5-pruned-emaonly.ckpt",
|
134 |
+
help="Path to stable diffusion checkpoint.",
|
135 |
+
)
|
136 |
+
parser.add_argument(
|
137 |
+
"--vae-ckpt",
|
138 |
+
type=str,
|
139 |
+
default="stable_diffusion/models/ldm/stable-diffusion-v1/vae-ft-mse-840000-ema-pruned.ckpt",
|
140 |
+
help="Path to vae checkpoint.",
|
141 |
+
)
|
142 |
+
parser.add_argument(
|
143 |
+
"--steps",
|
144 |
+
type=int,
|
145 |
+
default=100,
|
146 |
+
help="Number of sampling steps.",
|
147 |
+
)
|
148 |
+
parser.add_argument(
|
149 |
+
"--n-samples",
|
150 |
+
type=int,
|
151 |
+
default=100,
|
152 |
+
help="Number of samples to generate per prompt (before CLIP filtering).",
|
153 |
+
)
|
154 |
+
parser.add_argument(
|
155 |
+
"--max-out-samples",
|
156 |
+
type=int,
|
157 |
+
default=4,
|
158 |
+
help="Max number of output samples to save per prompt (after CLIP filtering).",
|
159 |
+
)
|
160 |
+
parser.add_argument(
|
161 |
+
"--n-partitions",
|
162 |
+
type=int,
|
163 |
+
default=1,
|
164 |
+
help="Number of total partitions.",
|
165 |
+
)
|
166 |
+
parser.add_argument(
|
167 |
+
"--partition",
|
168 |
+
type=int,
|
169 |
+
default=0,
|
170 |
+
help="Partition index.",
|
171 |
+
)
|
172 |
+
parser.add_argument(
|
173 |
+
"--min-p2p",
|
174 |
+
type=float,
|
175 |
+
default=0.1,
|
176 |
+
help="Min prompt2prompt threshold (portion of denoising for which to fix self attention maps).",
|
177 |
+
)
|
178 |
+
parser.add_argument(
|
179 |
+
"--max-p2p",
|
180 |
+
type=float,
|
181 |
+
default=0.9,
|
182 |
+
help="Max prompt2prompt threshold (portion of denoising for which to fix self attention maps).",
|
183 |
+
)
|
184 |
+
parser.add_argument(
|
185 |
+
"--min-cfg",
|
186 |
+
type=float,
|
187 |
+
default=7.5,
|
188 |
+
help="Min classifier free guidance scale.",
|
189 |
+
)
|
190 |
+
parser.add_argument(
|
191 |
+
"--max-cfg",
|
192 |
+
type=float,
|
193 |
+
default=15,
|
194 |
+
help="Max classifier free guidance scale.",
|
195 |
+
)
|
196 |
+
parser.add_argument(
|
197 |
+
"--clip-threshold",
|
198 |
+
type=float,
|
199 |
+
default=0.2,
|
200 |
+
help="CLIP threshold for text-image similarity of each image.",
|
201 |
+
)
|
202 |
+
parser.add_argument(
|
203 |
+
"--clip-dir-threshold",
|
204 |
+
type=float,
|
205 |
+
default=0.2,
|
206 |
+
help="Directional CLIP threshold for similarity of change between pairs of text and pairs of images.",
|
207 |
+
)
|
208 |
+
parser.add_argument(
|
209 |
+
"--clip-img-threshold",
|
210 |
+
type=float,
|
211 |
+
default=0.7,
|
212 |
+
help="CLIP threshold for image-image similarity.",
|
213 |
+
)
|
214 |
+
opt = parser.parse_args()
|
215 |
+
|
216 |
+
global_seed = torch.randint(1 << 32, ()).item()
|
217 |
+
print(f"Global seed: {global_seed}")
|
218 |
+
seed_everything(global_seed)
|
219 |
+
|
220 |
+
model = load_model_from_config(
|
221 |
+
OmegaConf.load("stable_diffusion/configs/stable-diffusion/v1-inference.yaml"),
|
222 |
+
ckpt=opt.ckpt,
|
223 |
+
vae_ckpt=opt.vae_ckpt,
|
224 |
+
)
|
225 |
+
model.cuda().eval()
|
226 |
+
model_wrap = k_diffusion.external.CompVisDenoiser(model)
|
227 |
+
|
228 |
+
clip_similarity = ClipSimilarity().cuda()
|
229 |
+
|
230 |
+
out_dir = Path(opt.out_dir)
|
231 |
+
out_dir.mkdir(exist_ok=True, parents=True)
|
232 |
+
|
233 |
+
with open(opt.prompts_file) as fp:
|
234 |
+
prompts = [json.loads(line) for line in fp]
|
235 |
+
|
236 |
+
print(f"Partition index {opt.partition} ({opt.partition + 1} / {opt.n_partitions})")
|
237 |
+
prompts = np.array_split(list(enumerate(prompts)), opt.n_partitions)[opt.partition]
|
238 |
+
|
239 |
+
with torch.no_grad(), torch.autocast("cuda"), model.ema_scope():
|
240 |
+
uncond = model.get_learned_conditioning(2 * [""])
|
241 |
+
sigmas = model_wrap.get_sigmas(opt.steps)
|
242 |
+
|
243 |
+
for i, prompt in tqdm(prompts, desc="Prompts"):
|
244 |
+
prompt_dir = out_dir.joinpath(f"{i:07d}")
|
245 |
+
prompt_dir.mkdir(exist_ok=True)
|
246 |
+
|
247 |
+
with open(prompt_dir.joinpath("prompt.json"), "w") as fp:
|
248 |
+
json.dump(prompt, fp)
|
249 |
+
|
250 |
+
cond = model.get_learned_conditioning([prompt["caption"], prompt["output"]])
|
251 |
+
results = {}
|
252 |
+
|
253 |
+
with tqdm(total=opt.n_samples, desc="Samples") as progress_bar:
|
254 |
+
|
255 |
+
while len(results) < opt.n_samples:
|
256 |
+
seed = torch.randint(1 << 32, ()).item()
|
257 |
+
if seed in results:
|
258 |
+
continue
|
259 |
+
torch.manual_seed(seed)
|
260 |
+
|
261 |
+
x = torch.randn(1, 4, 512 // 8, 512 // 8, device="cuda") * sigmas[0]
|
262 |
+
x = repeat(x, "1 ... -> n ...", n=2)
|
263 |
+
|
264 |
+
model_wrap_cfg = CFGDenoiser(model_wrap)
|
265 |
+
p2p_threshold = opt.min_p2p + torch.rand(()).item() * (opt.max_p2p - opt.min_p2p)
|
266 |
+
cfg_scale = opt.min_cfg + torch.rand(()).item() * (opt.max_cfg - opt.min_cfg)
|
267 |
+
extra_args = {"cond": cond, "uncond": uncond, "cfg_scale": cfg_scale}
|
268 |
+
samples_ddim = sample_euler_ancestral(model_wrap_cfg, x, sigmas, p2p_threshold, **extra_args)
|
269 |
+
x_samples_ddim = model.decode_first_stage(samples_ddim)
|
270 |
+
x_samples_ddim = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0)
|
271 |
+
|
272 |
+
x0 = x_samples_ddim[0]
|
273 |
+
x1 = x_samples_ddim[1]
|
274 |
+
|
275 |
+
clip_sim_0, clip_sim_1, clip_sim_dir, clip_sim_image = clip_similarity(
|
276 |
+
x0[None], x1[None], [prompt["caption"]], [prompt["output"]]
|
277 |
+
)
|
278 |
+
|
279 |
+
results[seed] = dict(
|
280 |
+
image_0=to_pil(x0),
|
281 |
+
image_1=to_pil(x1),
|
282 |
+
p2p_threshold=p2p_threshold,
|
283 |
+
cfg_scale=cfg_scale,
|
284 |
+
clip_sim_0=clip_sim_0[0].item(),
|
285 |
+
clip_sim_1=clip_sim_1[0].item(),
|
286 |
+
clip_sim_dir=clip_sim_dir[0].item(),
|
287 |
+
clip_sim_image=clip_sim_image[0].item(),
|
288 |
+
)
|
289 |
+
|
290 |
+
progress_bar.update()
|
291 |
+
|
292 |
+
# CLIP filter to get best samples for each prompt.
|
293 |
+
metadata = [
|
294 |
+
(result["clip_sim_dir"], seed)
|
295 |
+
for seed, result in results.items()
|
296 |
+
if result["clip_sim_image"] >= opt.clip_img_threshold
|
297 |
+
and result["clip_sim_dir"] >= opt.clip_dir_threshold
|
298 |
+
and result["clip_sim_0"] >= opt.clip_threshold
|
299 |
+
and result["clip_sim_1"] >= opt.clip_threshold
|
300 |
+
]
|
301 |
+
metadata.sort(reverse=True)
|
302 |
+
for _, seed in metadata[: opt.max_out_samples]:
|
303 |
+
result = results[seed]
|
304 |
+
image_0 = result.pop("image_0")
|
305 |
+
image_1 = result.pop("image_1")
|
306 |
+
image_0.save(prompt_dir.joinpath(f"{seed}_0.jpg"), quality=100)
|
307 |
+
image_1.save(prompt_dir.joinpath(f"{seed}_1.jpg"), quality=100)
|
308 |
+
with open(prompt_dir.joinpath(f"metadata.jsonl"), "a") as fp:
|
309 |
+
fp.write(f"{json.dumps(dict(seed=seed, **result))}\n")
|
310 |
+
|
311 |
+
print("Done.")
|
312 |
+
|
313 |
+
|
314 |
+
if __name__ == "__main__":
|
315 |
+
main()
|
dataset_creation/generate_txt_dataset.py
ADDED
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import json
|
4 |
+
import time
|
5 |
+
from argparse import ArgumentParser
|
6 |
+
from pathlib import Path
|
7 |
+
from typing import Optional
|
8 |
+
|
9 |
+
import datasets
|
10 |
+
import numpy as np
|
11 |
+
import openai
|
12 |
+
from tqdm.auto import tqdm
|
13 |
+
|
14 |
+
|
15 |
+
DELIMITER_0 = "\n##\n"
|
16 |
+
DELIMITER_1 = "\n%%\n"
|
17 |
+
STOP = "\nEND"
|
18 |
+
|
19 |
+
|
20 |
+
def generate(
|
21 |
+
openai_model: str,
|
22 |
+
caption: str,
|
23 |
+
num_retries: int = 3,
|
24 |
+
max_tokens: int = 256,
|
25 |
+
temperature: float = 0.7,
|
26 |
+
top_p: float = 1.0,
|
27 |
+
frequency_penalty: float = 0.1,
|
28 |
+
presence_penalty: float = 0.0,
|
29 |
+
sleep_on_error: float = 1.0,
|
30 |
+
) -> Optional[tuple[str, str]]:
|
31 |
+
for _ in range(1 + num_retries):
|
32 |
+
try:
|
33 |
+
response = openai.Completion.create(
|
34 |
+
model=openai_model,
|
35 |
+
prompt=caption + DELIMITER_0,
|
36 |
+
temperature=temperature,
|
37 |
+
max_tokens=max_tokens,
|
38 |
+
top_p=top_p,
|
39 |
+
frequency_penalty=frequency_penalty,
|
40 |
+
presence_penalty=presence_penalty,
|
41 |
+
stop=[STOP],
|
42 |
+
)
|
43 |
+
except Exception as e:
|
44 |
+
print(e)
|
45 |
+
time.sleep(sleep_on_error)
|
46 |
+
continue
|
47 |
+
output = response["choices"][0]["text"].split(DELIMITER_1)
|
48 |
+
if len(output) == 2:
|
49 |
+
instruction, edited_caption = output
|
50 |
+
results = openai.Moderation.create([instruction, edited_caption])["results"]
|
51 |
+
if results[0]["flagged"] or results[1]["flagged"]:
|
52 |
+
continue
|
53 |
+
if caption.strip().strip(".!?").lower() != edited_caption.strip().strip(".!?").lower():
|
54 |
+
return instruction, edited_caption
|
55 |
+
|
56 |
+
|
57 |
+
def main(openai_model: str, num_samples: int, num_partitions: int, partition: int, seed: int):
|
58 |
+
dataset = datasets.load_dataset("ChristophSchuhmann/improved_aesthetics_6.5plus", split="train")
|
59 |
+
# Other datasets we considered that may be worth trying:
|
60 |
+
# dataset = datasets.load_dataset("ChristophSchuhmann/MS_COCO_2017_URL_TEXT", split="train")
|
61 |
+
# dataset = datasets.load_dataset("laion/laion-coco", split="train")
|
62 |
+
|
63 |
+
np.random.seed(seed)
|
64 |
+
permutation = np.array_split(np.random.permutation(len(dataset)), num_partitions)[partition]
|
65 |
+
dataset = dataset[permutation]
|
66 |
+
captions = dataset["TEXT"]
|
67 |
+
urls = dataset["URL"]
|
68 |
+
output_path = f"data/dataset=laion-aesthetics-6.5_model={openai_model}_samples={num_samples}_partition={partition}.jsonl" # fmt: skip
|
69 |
+
print(f"Prompt file path: {output_path}")
|
70 |
+
|
71 |
+
count = 0
|
72 |
+
caption_set = set()
|
73 |
+
url_set = set()
|
74 |
+
|
75 |
+
if Path(output_path).exists():
|
76 |
+
with open(output_path, "r") as f:
|
77 |
+
for line in tqdm(f, desc="Resuming from existing prompts"):
|
78 |
+
prompt = json.loads(line)
|
79 |
+
if prompt["caption"] not in caption_set and prompt["url"] not in url_set:
|
80 |
+
caption_set.add(prompt["caption"])
|
81 |
+
url_set.add(prompt["url"])
|
82 |
+
count += 1
|
83 |
+
|
84 |
+
with open(output_path, "a") as fp:
|
85 |
+
with tqdm(total=num_samples - count, desc="Generating instructions and edited captions") as progress_bar:
|
86 |
+
for caption, url in zip(captions, urls):
|
87 |
+
if caption in caption_set or url in url_set:
|
88 |
+
continue
|
89 |
+
if openai.Moderation.create(caption)["results"][0]["flagged"]:
|
90 |
+
continue
|
91 |
+
edit_output = generate(openai_model, caption)
|
92 |
+
if edit_output is not None:
|
93 |
+
edit, output = edit_output
|
94 |
+
fp.write(f"{json.dumps(dict(caption=caption, edit=edit, output=output, url=url))}\n")
|
95 |
+
count += 1
|
96 |
+
progress_bar.update()
|
97 |
+
caption_set.add(caption)
|
98 |
+
url_set.add(url)
|
99 |
+
if count == num_samples:
|
100 |
+
break
|
101 |
+
|
102 |
+
|
103 |
+
if __name__ == "__main__":
|
104 |
+
parser = ArgumentParser()
|
105 |
+
parser.add_argument("--openai-api-key", required=True, type=str)
|
106 |
+
parser.add_argument("--openai-model", required=True, type=str)
|
107 |
+
parser.add_argument("--num-samples", default=10000, type=int)
|
108 |
+
parser.add_argument("--num-partitions", default=1, type=int)
|
109 |
+
parser.add_argument("--partition", default=0, type=int)
|
110 |
+
parser.add_argument("--seed", default=0, type=int)
|
111 |
+
args = parser.parse_args()
|
112 |
+
openai.api_key = args.openai_api_key
|
113 |
+
main(args.openai_model, args.num_samples, args.num_partitions, args.partition, args.seed)
|
dataset_creation/prepare_dataset.py
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
from argparse import ArgumentParser
|
3 |
+
from pathlib import Path
|
4 |
+
|
5 |
+
from tqdm.auto import tqdm
|
6 |
+
|
7 |
+
|
8 |
+
def main():
|
9 |
+
parser = ArgumentParser()
|
10 |
+
parser.add_argument("dataset_dir")
|
11 |
+
args = parser.parse_args()
|
12 |
+
dataset_dir = Path(args.dataset_dir)
|
13 |
+
|
14 |
+
seeds = []
|
15 |
+
with tqdm(desc="Listing dataset image seeds") as progress_bar:
|
16 |
+
for prompt_dir in dataset_dir.iterdir():
|
17 |
+
if prompt_dir.is_dir():
|
18 |
+
prompt_seeds = [image_path.name.split("_")[0] for image_path in sorted(prompt_dir.glob("*_0.jpg"))]
|
19 |
+
if len(prompt_seeds) > 0:
|
20 |
+
seeds.append((prompt_dir.name, prompt_seeds))
|
21 |
+
progress_bar.update()
|
22 |
+
seeds.sort()
|
23 |
+
|
24 |
+
with open(dataset_dir.joinpath("seeds.json"), "w") as f:
|
25 |
+
json.dump(seeds, f)
|
26 |
+
|
27 |
+
|
28 |
+
if __name__ == "__main__":
|
29 |
+
main()
|
dataset_creation/prepare_for_gpt.py
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
from argparse import ArgumentParser
|
3 |
+
|
4 |
+
from generate_txt_dataset import DELIMITER_0, DELIMITER_1, STOP
|
5 |
+
|
6 |
+
|
7 |
+
def main(input_path: str, output_path: str):
|
8 |
+
with open(input_path) as f:
|
9 |
+
prompts = [json.loads(l) for l in f]
|
10 |
+
|
11 |
+
with open(output_path, "w") as f:
|
12 |
+
for prompt in prompts:
|
13 |
+
prompt_for_gpt = {
|
14 |
+
"prompt": f"{prompt['input']}{DELIMITER_0}",
|
15 |
+
"completion": f"{prompt['edit']}{DELIMITER_1}{prompt['output']}{STOP}",
|
16 |
+
}
|
17 |
+
f.write(f"{json.dumps(prompt_for_gpt)}\n")
|
18 |
+
|
19 |
+
|
20 |
+
if __name__ == "__main__":
|
21 |
+
parser = ArgumentParser()
|
22 |
+
parser.add_argument("--input-path", required=True, type=str)
|
23 |
+
parser.add_argument("--output-path", required=True, type=str)
|
24 |
+
args = parser.parse_args()
|
25 |
+
main(args.input_path, args.output_path)
|
edit_app.py
ADDED
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import math
|
4 |
+
import random
|
5 |
+
import sys
|
6 |
+
from argparse import ArgumentParser
|
7 |
+
|
8 |
+
import einops
|
9 |
+
import gradio as gr
|
10 |
+
import k_diffusion as K
|
11 |
+
import numpy as np
|
12 |
+
import torch
|
13 |
+
import torch.nn as nn
|
14 |
+
from einops import rearrange
|
15 |
+
from omegaconf import OmegaConf
|
16 |
+
from PIL import Image, ImageOps
|
17 |
+
from torch import autocast
|
18 |
+
|
19 |
+
sys.path.append("./stable_diffusion")
|
20 |
+
|
21 |
+
from stable_diffusion.ldm.util import instantiate_from_config
|
22 |
+
|
23 |
+
|
24 |
+
help_text = """
|
25 |
+
If you're not getting what you want, there may be a few reasons:
|
26 |
+
1. Is the image not changing enough? Your Image CFG weight may be too high. This value dictates how similar the output should be to the input. It's possible your edit requires larger changes from the original image, and your Image CFG weight isn't allowing that. Alternatively, your Text CFG weight may be too low. This value dictates how much to listen to the text instruction. The default Image CFG of 1.5 and Text CFG of 7.5 are a good starting point, but aren't necessarily optimal for each edit. Try:
|
27 |
+
* Decreasing the Image CFG weight, or
|
28 |
+
* Incerasing the Text CFG weight, or
|
29 |
+
2. Conversely, is the image changing too much, such that the details in the original image aren't preserved? Try:
|
30 |
+
* Increasing the Image CFG weight, or
|
31 |
+
* Decreasing the Text CFG weight
|
32 |
+
3. Try generating results with different random seeds by setting "Randomize Seed" and running generation multiple times. You can also try setting "Randomize CFG" to sample new Text CFG and Image CFG values each time.
|
33 |
+
4. Rephrasing the instruction sometimes improves results (e.g., "turn him into a dog" vs. "make him a dog" vs. "as a dog").
|
34 |
+
5. Increasing the number of steps sometimes improves results.
|
35 |
+
6. Do faces look weird? The Stable Diffusion autoencoder has a hard time with faces that are small in the image. Try:
|
36 |
+
* Cropping the image so the face takes up a larger portion of the frame.
|
37 |
+
"""
|
38 |
+
|
39 |
+
|
40 |
+
example_instructions = [
|
41 |
+
"Make it a picasso painting",
|
42 |
+
"as if it were by modigliani",
|
43 |
+
"convert to a bronze statue",
|
44 |
+
"Turn it into an anime.",
|
45 |
+
"have it look like a graphic novel",
|
46 |
+
"make him gain weight",
|
47 |
+
"what would he look like bald?",
|
48 |
+
"Have him smile",
|
49 |
+
"Put him in a cocktail party.",
|
50 |
+
"move him at the beach.",
|
51 |
+
"add dramatic lighting",
|
52 |
+
"Convert to black and white",
|
53 |
+
"What if it were snowing?",
|
54 |
+
"Give him a leather jacket",
|
55 |
+
"Turn him into a cyborg!",
|
56 |
+
"make him wear a beanie",
|
57 |
+
]
|
58 |
+
|
59 |
+
|
60 |
+
class CFGDenoiser(nn.Module):
|
61 |
+
def __init__(self, model):
|
62 |
+
super().__init__()
|
63 |
+
self.inner_model = model
|
64 |
+
|
65 |
+
def forward(self, z, sigma, cond, uncond, text_cfg_scale, image_cfg_scale):
|
66 |
+
cfg_z = einops.repeat(z, "1 ... -> n ...", n=3)
|
67 |
+
cfg_sigma = einops.repeat(sigma, "1 ... -> n ...", n=3)
|
68 |
+
cfg_cond = {
|
69 |
+
"c_crossattn": [torch.cat([cond["c_crossattn"][0], uncond["c_crossattn"][0], uncond["c_crossattn"][0]])],
|
70 |
+
"c_concat": [torch.cat([cond["c_concat"][0], cond["c_concat"][0], uncond["c_concat"][0]])],
|
71 |
+
}
|
72 |
+
out_cond, out_img_cond, out_uncond = self.inner_model(cfg_z, cfg_sigma, cond=cfg_cond).chunk(3)
|
73 |
+
return out_uncond + text_cfg_scale * (out_cond - out_img_cond) + image_cfg_scale * (out_img_cond - out_uncond)
|
74 |
+
|
75 |
+
|
76 |
+
def load_model_from_config(config, ckpt, vae_ckpt=None, verbose=False):
|
77 |
+
print(f"Loading model from {ckpt}")
|
78 |
+
pl_sd = torch.load(ckpt, map_location="cpu")
|
79 |
+
if "global_step" in pl_sd:
|
80 |
+
print(f"Global Step: {pl_sd['global_step']}")
|
81 |
+
sd = pl_sd["state_dict"]
|
82 |
+
if vae_ckpt is not None:
|
83 |
+
print(f"Loading VAE from {vae_ckpt}")
|
84 |
+
vae_sd = torch.load(vae_ckpt, map_location="cpu")["state_dict"]
|
85 |
+
sd = {
|
86 |
+
k: vae_sd[k[len("first_stage_model.") :]] if k.startswith("first_stage_model.") else v
|
87 |
+
for k, v in sd.items()
|
88 |
+
}
|
89 |
+
model = instantiate_from_config(config.model)
|
90 |
+
m, u = model.load_state_dict(sd, strict=False)
|
91 |
+
if len(m) > 0 and verbose:
|
92 |
+
print("missing keys:")
|
93 |
+
print(m)
|
94 |
+
if len(u) > 0 and verbose:
|
95 |
+
print("unexpected keys:")
|
96 |
+
print(u)
|
97 |
+
return model
|
98 |
+
|
99 |
+
|
100 |
+
def main():
|
101 |
+
parser = ArgumentParser()
|
102 |
+
parser.add_argument("--resolution", default=512, type=int)
|
103 |
+
parser.add_argument("--config", default="configs/generate.yaml", type=str)
|
104 |
+
parser.add_argument("--ckpt", default="checkpoints/instruct-pix2pix-00-22000.ckpt", type=str)
|
105 |
+
parser.add_argument("--vae-ckpt", default=None, type=str)
|
106 |
+
args = parser.parse_args()
|
107 |
+
|
108 |
+
config = OmegaConf.load(args.config)
|
109 |
+
model = load_model_from_config(config, args.ckpt, args.vae_ckpt)
|
110 |
+
model.eval().cuda()
|
111 |
+
model_wrap = K.external.CompVisDenoiser(model)
|
112 |
+
model_wrap_cfg = CFGDenoiser(model_wrap)
|
113 |
+
null_token = model.get_learned_conditioning([""])
|
114 |
+
example_image = Image.open("imgs/example.jpg").convert("RGB")
|
115 |
+
|
116 |
+
def load_example(
|
117 |
+
steps: int,
|
118 |
+
randomize_seed: bool,
|
119 |
+
seed: int,
|
120 |
+
randomize_cfg: bool,
|
121 |
+
text_cfg_scale: float,
|
122 |
+
image_cfg_scale: float,
|
123 |
+
):
|
124 |
+
example_instruction = random.choice(example_instructions)
|
125 |
+
return [example_image, example_instruction] + generate(
|
126 |
+
example_image,
|
127 |
+
example_instruction,
|
128 |
+
steps,
|
129 |
+
randomize_seed,
|
130 |
+
seed,
|
131 |
+
randomize_cfg,
|
132 |
+
text_cfg_scale,
|
133 |
+
image_cfg_scale,
|
134 |
+
)
|
135 |
+
|
136 |
+
def generate(
|
137 |
+
input_image: Image.Image,
|
138 |
+
instruction: str,
|
139 |
+
steps: int,
|
140 |
+
randomize_seed: bool,
|
141 |
+
seed: int,
|
142 |
+
randomize_cfg: bool,
|
143 |
+
text_cfg_scale: float,
|
144 |
+
image_cfg_scale: float,
|
145 |
+
):
|
146 |
+
seed = random.randint(0, 100000) if randomize_seed else seed
|
147 |
+
text_cfg_scale = round(random.uniform(6.0, 9.0), ndigits=2) if randomize_cfg else text_cfg_scale
|
148 |
+
image_cfg_scale = round(random.uniform(1.2, 1.8), ndigits=2) if randomize_cfg else image_cfg_scale
|
149 |
+
|
150 |
+
width, height = input_image.size
|
151 |
+
factor = args.resolution / max(width, height)
|
152 |
+
factor = math.ceil(min(width, height) * factor / 64) * 64 / min(width, height)
|
153 |
+
width = int((width * factor) // 64) * 64
|
154 |
+
height = int((height * factor) // 64) * 64
|
155 |
+
input_image = ImageOps.fit(input_image, (width, height), method=Image.Resampling.LANCZOS)
|
156 |
+
|
157 |
+
if instruction == "":
|
158 |
+
return [input_image, seed]
|
159 |
+
|
160 |
+
with torch.no_grad(), autocast("cuda"), model.ema_scope():
|
161 |
+
cond = {}
|
162 |
+
cond["c_crossattn"] = [model.get_learned_conditioning([instruction])]
|
163 |
+
input_image = 2 * torch.tensor(np.array(input_image)).float() / 255 - 1
|
164 |
+
input_image = rearrange(input_image, "h w c -> 1 c h w").to(model.device)
|
165 |
+
cond["c_concat"] = [model.encode_first_stage(input_image).mode()]
|
166 |
+
|
167 |
+
uncond = {}
|
168 |
+
uncond["c_crossattn"] = [null_token]
|
169 |
+
uncond["c_concat"] = [torch.zeros_like(cond["c_concat"][0])]
|
170 |
+
|
171 |
+
sigmas = model_wrap.get_sigmas(steps)
|
172 |
+
|
173 |
+
extra_args = {
|
174 |
+
"cond": cond,
|
175 |
+
"uncond": uncond,
|
176 |
+
"text_cfg_scale": text_cfg_scale,
|
177 |
+
"image_cfg_scale": image_cfg_scale,
|
178 |
+
}
|
179 |
+
torch.manual_seed(seed)
|
180 |
+
z = torch.randn_like(cond["c_concat"][0]) * sigmas[0]
|
181 |
+
z = K.sampling.sample_euler_ancestral(model_wrap_cfg, z, sigmas, extra_args=extra_args)
|
182 |
+
x = model.decode_first_stage(z)
|
183 |
+
x = torch.clamp((x + 1.0) / 2.0, min=0.0, max=1.0)
|
184 |
+
x = 255.0 * rearrange(x, "1 c h w -> h w c")
|
185 |
+
edited_image = Image.fromarray(x.type(torch.uint8).cpu().numpy())
|
186 |
+
|
187 |
+
return [seed, text_cfg_scale, image_cfg_scale, edited_image]
|
188 |
+
|
189 |
+
def reset():
|
190 |
+
return [0, "Randomize Seed", 1371, "Fix CFG", 7.5, 1.5, None]
|
191 |
+
|
192 |
+
with gr.Blocks(css="footer {visibility: hidden}") as demo:
|
193 |
+
with gr.Row():
|
194 |
+
with gr.Column(scale=1, min_width=100):
|
195 |
+
generate_button = gr.Button("Generate")
|
196 |
+
with gr.Column(scale=1, min_width=100):
|
197 |
+
load_button = gr.Button("Load Example")
|
198 |
+
with gr.Column(scale=1, min_width=100):
|
199 |
+
reset_button = gr.Button("Reset")
|
200 |
+
with gr.Column(scale=3):
|
201 |
+
instruction = gr.Textbox(lines=1, label="Edit Instruction", interactive=True)
|
202 |
+
|
203 |
+
with gr.Row():
|
204 |
+
input_image = gr.Image(label="Input Image", type="pil", interactive=True)
|
205 |
+
edited_image = gr.Image(label=f"Edited Image", type="pil", interactive=False)
|
206 |
+
input_image.style(height=512, width=512)
|
207 |
+
edited_image.style(height=512, width=512)
|
208 |
+
|
209 |
+
with gr.Row():
|
210 |
+
steps = gr.Number(value=100, precision=0, label="Steps", interactive=True)
|
211 |
+
randomize_seed = gr.Radio(
|
212 |
+
["Fix Seed", "Randomize Seed"],
|
213 |
+
value="Randomize Seed",
|
214 |
+
type="index",
|
215 |
+
show_label=False,
|
216 |
+
interactive=True,
|
217 |
+
)
|
218 |
+
seed = gr.Number(value=1371, precision=0, label="Seed", interactive=True)
|
219 |
+
randomize_cfg = gr.Radio(
|
220 |
+
["Fix CFG", "Randomize CFG"],
|
221 |
+
value="Fix CFG",
|
222 |
+
type="index",
|
223 |
+
show_label=False,
|
224 |
+
interactive=True,
|
225 |
+
)
|
226 |
+
text_cfg_scale = gr.Number(value=7.5, label=f"Text CFG", interactive=True)
|
227 |
+
image_cfg_scale = gr.Number(value=1.5, label=f"Image CFG", interactive=True)
|
228 |
+
|
229 |
+
gr.Markdown(help_text)
|
230 |
+
|
231 |
+
load_button.click(
|
232 |
+
fn=load_example,
|
233 |
+
inputs=[
|
234 |
+
steps,
|
235 |
+
randomize_seed,
|
236 |
+
seed,
|
237 |
+
randomize_cfg,
|
238 |
+
text_cfg_scale,
|
239 |
+
image_cfg_scale,
|
240 |
+
],
|
241 |
+
outputs=[input_image, instruction, seed, text_cfg_scale, image_cfg_scale, edited_image],
|
242 |
+
)
|
243 |
+
generate_button.click(
|
244 |
+
fn=generate,
|
245 |
+
inputs=[
|
246 |
+
input_image,
|
247 |
+
instruction,
|
248 |
+
steps,
|
249 |
+
randomize_seed,
|
250 |
+
seed,
|
251 |
+
randomize_cfg,
|
252 |
+
text_cfg_scale,
|
253 |
+
image_cfg_scale,
|
254 |
+
],
|
255 |
+
outputs=[seed, text_cfg_scale, image_cfg_scale, edited_image],
|
256 |
+
)
|
257 |
+
reset_button.click(
|
258 |
+
fn=reset,
|
259 |
+
inputs=[],
|
260 |
+
outputs=[steps, randomize_seed, seed, randomize_cfg, text_cfg_scale, image_cfg_scale, edited_image],
|
261 |
+
)
|
262 |
+
|
263 |
+
demo.queue(concurrency_count=1)
|
264 |
+
demo.launch(share=True)
|
265 |
+
|
266 |
+
|
267 |
+
if __name__ == "__main__":
|
268 |
+
main()
|
edit_cli.py
ADDED
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import math
|
4 |
+
import random
|
5 |
+
import sys
|
6 |
+
from argparse import ArgumentParser
|
7 |
+
|
8 |
+
import einops
|
9 |
+
import k_diffusion as K
|
10 |
+
import numpy as np
|
11 |
+
import torch
|
12 |
+
import torch.nn as nn
|
13 |
+
from einops import rearrange
|
14 |
+
from omegaconf import OmegaConf
|
15 |
+
from PIL import Image, ImageOps
|
16 |
+
from torch import autocast
|
17 |
+
|
18 |
+
sys.path.append("./stable_diffusion")
|
19 |
+
|
20 |
+
from stable_diffusion.ldm.util import instantiate_from_config
|
21 |
+
|
22 |
+
|
23 |
+
class CFGDenoiser(nn.Module):
|
24 |
+
def __init__(self, model):
|
25 |
+
super().__init__()
|
26 |
+
self.inner_model = model
|
27 |
+
|
28 |
+
def forward(self, z, sigma, cond, uncond, text_cfg_scale, image_cfg_scale):
|
29 |
+
cfg_z = einops.repeat(z, "1 ... -> n ...", n=3)
|
30 |
+
cfg_sigma = einops.repeat(sigma, "1 ... -> n ...", n=3)
|
31 |
+
cfg_cond = {
|
32 |
+
"c_crossattn": [torch.cat([cond["c_crossattn"][0], uncond["c_crossattn"][0], uncond["c_crossattn"][0]])],
|
33 |
+
"c_concat": [torch.cat([cond["c_concat"][0], cond["c_concat"][0], uncond["c_concat"][0]])],
|
34 |
+
}
|
35 |
+
out_cond, out_img_cond, out_uncond = self.inner_model(cfg_z, cfg_sigma, cond=cfg_cond).chunk(3)
|
36 |
+
return out_uncond + text_cfg_scale * (out_cond - out_img_cond) + image_cfg_scale * (out_img_cond - out_uncond)
|
37 |
+
|
38 |
+
|
39 |
+
def load_model_from_config(config, ckpt, vae_ckpt=None, verbose=False):
|
40 |
+
print(f"Loading model from {ckpt}")
|
41 |
+
pl_sd = torch.load(ckpt, map_location="cpu")
|
42 |
+
if "global_step" in pl_sd:
|
43 |
+
print(f"Global Step: {pl_sd['global_step']}")
|
44 |
+
sd = pl_sd["state_dict"]
|
45 |
+
if vae_ckpt is not None:
|
46 |
+
print(f"Loading VAE from {vae_ckpt}")
|
47 |
+
vae_sd = torch.load(vae_ckpt, map_location="cpu")["state_dict"]
|
48 |
+
sd = {
|
49 |
+
k: vae_sd[k[len("first_stage_model.") :]] if k.startswith("first_stage_model.") else v
|
50 |
+
for k, v in sd.items()
|
51 |
+
}
|
52 |
+
model = instantiate_from_config(config.model)
|
53 |
+
m, u = model.load_state_dict(sd, strict=False)
|
54 |
+
if len(m) > 0 and verbose:
|
55 |
+
print("missing keys:")
|
56 |
+
print(m)
|
57 |
+
if len(u) > 0 and verbose:
|
58 |
+
print("unexpected keys:")
|
59 |
+
print(u)
|
60 |
+
return model
|
61 |
+
|
62 |
+
|
63 |
+
def main():
|
64 |
+
parser = ArgumentParser()
|
65 |
+
parser.add_argument("--resolution", default=512, type=int)
|
66 |
+
parser.add_argument("--steps", default=100, type=int)
|
67 |
+
parser.add_argument("--config", default="configs/generate.yaml", type=str)
|
68 |
+
parser.add_argument("--ckpt", default="checkpoints/instruct-pix2pix-00-22000.ckpt", type=str)
|
69 |
+
parser.add_argument("--vae-ckpt", default=None, type=str)
|
70 |
+
parser.add_argument("--input", required=True, type=str)
|
71 |
+
parser.add_argument("--output", required=True, type=str)
|
72 |
+
parser.add_argument("--edit", required=True, type=str)
|
73 |
+
parser.add_argument("--cfg-text", default=7.5, type=float)
|
74 |
+
parser.add_argument("--cfg-image", default=1.5, type=float)
|
75 |
+
parser.add_argument("--seed", type=int)
|
76 |
+
args = parser.parse_args()
|
77 |
+
|
78 |
+
config = OmegaConf.load(args.config)
|
79 |
+
model = load_model_from_config(config, args.ckpt, args.vae_ckpt)
|
80 |
+
model.eval().cuda()
|
81 |
+
model_wrap = K.external.CompVisDenoiser(model)
|
82 |
+
model_wrap_cfg = CFGDenoiser(model_wrap)
|
83 |
+
null_token = model.get_learned_conditioning([""])
|
84 |
+
|
85 |
+
seed = random.randint(0, 100000) if args.seed is None else args.seed
|
86 |
+
input_image = Image.open(args.input).convert("RGB")
|
87 |
+
width, height = input_image.size
|
88 |
+
factor = args.resolution / max(width, height)
|
89 |
+
factor = math.ceil(min(width, height) * factor / 64) * 64 / min(width, height)
|
90 |
+
width = int((width * factor) // 64) * 64
|
91 |
+
height = int((height * factor) // 64) * 64
|
92 |
+
input_image = ImageOps.fit(input_image, (width, height), method=Image.Resampling.LANCZOS)
|
93 |
+
|
94 |
+
if args.edit == "":
|
95 |
+
input_image.save(args.output)
|
96 |
+
return
|
97 |
+
|
98 |
+
with torch.no_grad(), autocast("cuda"), model.ema_scope():
|
99 |
+
cond = {}
|
100 |
+
cond["c_crossattn"] = [model.get_learned_conditioning([args.edit])]
|
101 |
+
input_image = 2 * torch.tensor(np.array(input_image)).float() / 255 - 1
|
102 |
+
input_image = rearrange(input_image, "h w c -> 1 c h w").to(model.device)
|
103 |
+
cond["c_concat"] = [model.encode_first_stage(input_image).mode()]
|
104 |
+
|
105 |
+
uncond = {}
|
106 |
+
uncond["c_crossattn"] = [null_token]
|
107 |
+
uncond["c_concat"] = [torch.zeros_like(cond["c_concat"][0])]
|
108 |
+
|
109 |
+
sigmas = model_wrap.get_sigmas(args.steps)
|
110 |
+
|
111 |
+
extra_args = {
|
112 |
+
"cond": cond,
|
113 |
+
"uncond": uncond,
|
114 |
+
"text_cfg_scale": args.cfg_text,
|
115 |
+
"image_cfg_scale": args.cfg_image,
|
116 |
+
}
|
117 |
+
torch.manual_seed(seed)
|
118 |
+
z = torch.randn_like(cond["c_concat"][0]) * sigmas[0]
|
119 |
+
z = K.sampling.sample_euler_ancestral(model_wrap_cfg, z, sigmas, extra_args=extra_args)
|
120 |
+
x = model.decode_first_stage(z)
|
121 |
+
x = torch.clamp((x + 1.0) / 2.0, min=0.0, max=1.0)
|
122 |
+
x = 255.0 * rearrange(x, "1 c h w -> h w c")
|
123 |
+
edited_image = Image.fromarray(x.type(torch.uint8).cpu().numpy())
|
124 |
+
edited_image.save(args.output)
|
125 |
+
|
126 |
+
|
127 |
+
if __name__ == "__main__":
|
128 |
+
main()
|
edit_dataset.py
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import json
|
4 |
+
import math
|
5 |
+
from pathlib import Path
|
6 |
+
from typing import Any
|
7 |
+
|
8 |
+
import numpy as np
|
9 |
+
import torch
|
10 |
+
import torchvision
|
11 |
+
from einops import rearrange
|
12 |
+
from PIL import Image
|
13 |
+
from torch.utils.data import Dataset
|
14 |
+
|
15 |
+
|
16 |
+
class EditDataset(Dataset):
|
17 |
+
def __init__(
|
18 |
+
self,
|
19 |
+
path: str,
|
20 |
+
split: str = "train",
|
21 |
+
splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
|
22 |
+
min_resize_res: int = 256,
|
23 |
+
max_resize_res: int = 256,
|
24 |
+
crop_res: int = 256,
|
25 |
+
flip_prob: float = 0.0,
|
26 |
+
):
|
27 |
+
assert split in ("train", "val", "test")
|
28 |
+
assert sum(splits) == 1
|
29 |
+
self.path = path
|
30 |
+
self.min_resize_res = min_resize_res
|
31 |
+
self.max_resize_res = max_resize_res
|
32 |
+
self.crop_res = crop_res
|
33 |
+
self.flip_prob = flip_prob
|
34 |
+
|
35 |
+
with open(Path(self.path, "seeds.json")) as f:
|
36 |
+
self.seeds = json.load(f)
|
37 |
+
|
38 |
+
split_0, split_1 = {
|
39 |
+
"train": (0.0, splits[0]),
|
40 |
+
"val": (splits[0], splits[0] + splits[1]),
|
41 |
+
"test": (splits[0] + splits[1], 1.0),
|
42 |
+
}[split]
|
43 |
+
|
44 |
+
idx_0 = math.floor(split_0 * len(self.seeds))
|
45 |
+
idx_1 = math.floor(split_1 * len(self.seeds))
|
46 |
+
self.seeds = self.seeds[idx_0:idx_1]
|
47 |
+
|
48 |
+
def __len__(self) -> int:
|
49 |
+
return len(self.seeds)
|
50 |
+
|
51 |
+
def __getitem__(self, i: int) -> dict[str, Any]:
|
52 |
+
name, seeds = self.seeds[i]
|
53 |
+
propt_dir = Path(self.path, name)
|
54 |
+
seed = seeds[torch.randint(0, len(seeds), ()).item()]
|
55 |
+
with open(propt_dir.joinpath("prompt.json")) as fp:
|
56 |
+
prompt = json.load(fp)["edit"]
|
57 |
+
|
58 |
+
image_0 = Image.open(propt_dir.joinpath(f"{seed}_0.jpg"))
|
59 |
+
image_1 = Image.open(propt_dir.joinpath(f"{seed}_1.jpg"))
|
60 |
+
|
61 |
+
reize_res = torch.randint(self.min_resize_res, self.max_resize_res + 1, ()).item()
|
62 |
+
image_0 = image_0.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
|
63 |
+
image_1 = image_1.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
|
64 |
+
|
65 |
+
image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
|
66 |
+
image_1 = rearrange(2 * torch.tensor(np.array(image_1)).float() / 255 - 1, "h w c -> c h w")
|
67 |
+
|
68 |
+
crop = torchvision.transforms.RandomCrop(self.crop_res)
|
69 |
+
flip = torchvision.transforms.RandomHorizontalFlip(float(self.flip_prob))
|
70 |
+
image_0, image_1 = flip(crop(torch.cat((image_0, image_1)))).chunk(2)
|
71 |
+
|
72 |
+
return dict(edited=image_1, edit=dict(c_concat=image_0, c_crossattn=prompt))
|
73 |
+
|
74 |
+
|
75 |
+
class EditDatasetEval(Dataset):
|
76 |
+
def __init__(
|
77 |
+
self,
|
78 |
+
path: str,
|
79 |
+
split: str = "train",
|
80 |
+
splits: tuple[float, float, float] = (0.9, 0.05, 0.05),
|
81 |
+
res: int = 256,
|
82 |
+
):
|
83 |
+
assert split in ("train", "val", "test")
|
84 |
+
assert sum(splits) == 1
|
85 |
+
self.path = path
|
86 |
+
self.res = res
|
87 |
+
|
88 |
+
with open(Path(self.path, "seeds.json")) as f:
|
89 |
+
self.seeds = json.load(f)
|
90 |
+
|
91 |
+
split_0, split_1 = {
|
92 |
+
"train": (0.0, splits[0]),
|
93 |
+
"val": (splits[0], splits[0] + splits[1]),
|
94 |
+
"test": (splits[0] + splits[1], 1.0),
|
95 |
+
}[split]
|
96 |
+
|
97 |
+
idx_0 = math.floor(split_0 * len(self.seeds))
|
98 |
+
idx_1 = math.floor(split_1 * len(self.seeds))
|
99 |
+
self.seeds = self.seeds[idx_0:idx_1]
|
100 |
+
|
101 |
+
def __len__(self) -> int:
|
102 |
+
return len(self.seeds)
|
103 |
+
|
104 |
+
def __getitem__(self, i: int) -> dict[str, Any]:
|
105 |
+
name, seeds = self.seeds[i]
|
106 |
+
propt_dir = Path(self.path, name)
|
107 |
+
seed = seeds[torch.randint(0, len(seeds), ()).item()]
|
108 |
+
with open(propt_dir.joinpath("prompt.json")) as fp:
|
109 |
+
prompt = json.load(fp)
|
110 |
+
edit = prompt["edit"]
|
111 |
+
input_prompt = prompt["input"]
|
112 |
+
output_prompt = prompt["output"]
|
113 |
+
|
114 |
+
image_0 = Image.open(propt_dir.joinpath(f"{seed}_0.jpg"))
|
115 |
+
|
116 |
+
reize_res = torch.randint(self.res, self.res + 1, ()).item()
|
117 |
+
image_0 = image_0.resize((reize_res, reize_res), Image.Resampling.LANCZOS)
|
118 |
+
|
119 |
+
image_0 = rearrange(2 * torch.tensor(np.array(image_0)).float() / 255 - 1, "h w c -> c h w")
|
120 |
+
|
121 |
+
return dict(image_0=image_0, input_prompt=input_prompt, edit=edit, output_prompt=output_prompt)
|
environment.yaml
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# File modified by authors of InstructPix2Pix from original (https://github.com/CompVis/stable-diffusion).
|
2 |
+
# See more details in LICENSE.
|
3 |
+
|
4 |
+
name: ip2p
|
5 |
+
channels:
|
6 |
+
- pytorch
|
7 |
+
- defaults
|
8 |
+
dependencies:
|
9 |
+
- python=3.8.5
|
10 |
+
- pip=20.3
|
11 |
+
- cudatoolkit=11.3
|
12 |
+
- pytorch=1.11.0
|
13 |
+
- torchvision=0.12.0
|
14 |
+
- numpy=1.19.2
|
15 |
+
- pip:
|
16 |
+
- albumentations==0.4.3
|
17 |
+
- datasets==2.8.0
|
18 |
+
- diffusers
|
19 |
+
- opencv-python==4.1.2.30
|
20 |
+
- pudb==2019.2
|
21 |
+
- invisible-watermark
|
22 |
+
- imageio==2.9.0
|
23 |
+
- imageio-ffmpeg==0.4.2
|
24 |
+
- pytorch-lightning==1.4.2
|
25 |
+
- omegaconf==2.1.1
|
26 |
+
- test-tube>=0.7.5
|
27 |
+
- streamlit>=0.73.1
|
28 |
+
- einops==0.3.0
|
29 |
+
- torch-fidelity==0.3.0
|
30 |
+
- transformers==4.19.2
|
31 |
+
- torchmetrics==0.6.0
|
32 |
+
- kornia==0.6
|
33 |
+
- -e git+https://github.com/CompVis/taming-transformers.git@master#egg=taming-transformers
|
34 |
+
- -e git+https://github.com/openai/CLIP.git@main#egg=clip
|
35 |
+
- openai
|
36 |
+
- gradio
|
37 |
+
- seaborn
|
38 |
+
- git+https://github.com/crowsonkb/k-diffusion.git
|
imgs/dataset.jpg
ADDED
imgs/edit_app.jpg
ADDED
imgs/example.jpg
ADDED
imgs/prompt_app.jpg
ADDED
main.py
ADDED
@@ -0,0 +1,799 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse, os, sys, datetime, glob
|
2 |
+
import numpy as np
|
3 |
+
import time
|
4 |
+
import torch
|
5 |
+
import torchvision
|
6 |
+
import pytorch_lightning as pl
|
7 |
+
import json
|
8 |
+
import pickle
|
9 |
+
|
10 |
+
from packaging import version
|
11 |
+
from omegaconf import OmegaConf
|
12 |
+
from torch.utils.data import DataLoader, Dataset
|
13 |
+
from functools import partial
|
14 |
+
from PIL import Image
|
15 |
+
|
16 |
+
import torch.distributed as dist
|
17 |
+
from pytorch_lightning import seed_everything
|
18 |
+
from pytorch_lightning.trainer import Trainer
|
19 |
+
from pytorch_lightning.callbacks import ModelCheckpoint, Callback, LearningRateMonitor
|
20 |
+
from pytorch_lightning.utilities.distributed import rank_zero_only
|
21 |
+
from pytorch_lightning.utilities import rank_zero_info
|
22 |
+
from pytorch_lightning.plugins import DDPPlugin
|
23 |
+
|
24 |
+
sys.path.append("./stable_diffusion")
|
25 |
+
|
26 |
+
from ldm.data.base import Txt2ImgIterableBaseDataset
|
27 |
+
from ldm.util import instantiate_from_config
|
28 |
+
|
29 |
+
|
30 |
+
def get_parser(**parser_kwargs):
|
31 |
+
def str2bool(v):
|
32 |
+
if isinstance(v, bool):
|
33 |
+
return v
|
34 |
+
if v.lower() in ("yes", "true", "t", "y", "1"):
|
35 |
+
return True
|
36 |
+
elif v.lower() in ("no", "false", "f", "n", "0"):
|
37 |
+
return False
|
38 |
+
else:
|
39 |
+
raise argparse.ArgumentTypeError("Boolean value expected.")
|
40 |
+
|
41 |
+
parser = argparse.ArgumentParser(**parser_kwargs)
|
42 |
+
parser.add_argument(
|
43 |
+
"-n",
|
44 |
+
"--name",
|
45 |
+
type=str,
|
46 |
+
const=True,
|
47 |
+
default="",
|
48 |
+
nargs="?",
|
49 |
+
help="postfix for logdir",
|
50 |
+
)
|
51 |
+
parser.add_argument(
|
52 |
+
"-r",
|
53 |
+
"--resume",
|
54 |
+
type=str,
|
55 |
+
const=True,
|
56 |
+
default="",
|
57 |
+
nargs="?",
|
58 |
+
help="resume from logdir or checkpoint in logdir",
|
59 |
+
)
|
60 |
+
parser.add_argument(
|
61 |
+
"-b",
|
62 |
+
"--base",
|
63 |
+
nargs="*",
|
64 |
+
metavar="base_config.yaml",
|
65 |
+
help="paths to base configs. Loaded from left-to-right. "
|
66 |
+
"Parameters can be overwritten or added with command-line options of the form `--key value`.",
|
67 |
+
default=list(),
|
68 |
+
)
|
69 |
+
parser.add_argument(
|
70 |
+
"-t",
|
71 |
+
"--train",
|
72 |
+
type=str2bool,
|
73 |
+
const=True,
|
74 |
+
default=False,
|
75 |
+
nargs="?",
|
76 |
+
help="train",
|
77 |
+
)
|
78 |
+
parser.add_argument(
|
79 |
+
"--no-test",
|
80 |
+
type=str2bool,
|
81 |
+
const=True,
|
82 |
+
default=False,
|
83 |
+
nargs="?",
|
84 |
+
help="disable test",
|
85 |
+
)
|
86 |
+
parser.add_argument(
|
87 |
+
"-p",
|
88 |
+
"--project",
|
89 |
+
help="name of new or path to existing project"
|
90 |
+
)
|
91 |
+
parser.add_argument(
|
92 |
+
"-d",
|
93 |
+
"--debug",
|
94 |
+
type=str2bool,
|
95 |
+
nargs="?",
|
96 |
+
const=True,
|
97 |
+
default=False,
|
98 |
+
help="enable post-mortem debugging",
|
99 |
+
)
|
100 |
+
parser.add_argument(
|
101 |
+
"-s",
|
102 |
+
"--seed",
|
103 |
+
type=int,
|
104 |
+
default=23,
|
105 |
+
help="seed for seed_everything",
|
106 |
+
)
|
107 |
+
parser.add_argument(
|
108 |
+
"-f",
|
109 |
+
"--postfix",
|
110 |
+
type=str,
|
111 |
+
default="",
|
112 |
+
help="post-postfix for default name",
|
113 |
+
)
|
114 |
+
parser.add_argument(
|
115 |
+
"-l",
|
116 |
+
"--logdir",
|
117 |
+
type=str,
|
118 |
+
default="logs",
|
119 |
+
help="directory for logging dat shit",
|
120 |
+
)
|
121 |
+
parser.add_argument(
|
122 |
+
"--scale_lr",
|
123 |
+
action="store_true",
|
124 |
+
default=False,
|
125 |
+
help="scale base-lr by ngpu * batch_size * n_accumulate",
|
126 |
+
)
|
127 |
+
return parser
|
128 |
+
|
129 |
+
|
130 |
+
def nondefault_trainer_args(opt):
|
131 |
+
parser = argparse.ArgumentParser()
|
132 |
+
parser = Trainer.add_argparse_args(parser)
|
133 |
+
args = parser.parse_args([])
|
134 |
+
return sorted(k for k in vars(args) if getattr(opt, k) != getattr(args, k))
|
135 |
+
|
136 |
+
|
137 |
+
class WrappedDataset(Dataset):
|
138 |
+
"""Wraps an arbitrary object with __len__ and __getitem__ into a pytorch dataset"""
|
139 |
+
|
140 |
+
def __init__(self, dataset):
|
141 |
+
self.data = dataset
|
142 |
+
|
143 |
+
def __len__(self):
|
144 |
+
return len(self.data)
|
145 |
+
|
146 |
+
def __getitem__(self, idx):
|
147 |
+
return self.data[idx]
|
148 |
+
|
149 |
+
|
150 |
+
def worker_init_fn(_):
|
151 |
+
worker_info = torch.utils.data.get_worker_info()
|
152 |
+
|
153 |
+
dataset = worker_info.dataset
|
154 |
+
worker_id = worker_info.id
|
155 |
+
|
156 |
+
if isinstance(dataset, Txt2ImgIterableBaseDataset):
|
157 |
+
split_size = dataset.num_records // worker_info.num_workers
|
158 |
+
# reset num_records to the true number to retain reliable length information
|
159 |
+
dataset.sample_ids = dataset.valid_ids[worker_id * split_size:(worker_id + 1) * split_size]
|
160 |
+
current_id = np.random.choice(len(np.random.get_state()[1]), 1)
|
161 |
+
return np.random.seed(np.random.get_state()[1][current_id] + worker_id)
|
162 |
+
else:
|
163 |
+
return np.random.seed(np.random.get_state()[1][0] + worker_id)
|
164 |
+
|
165 |
+
|
166 |
+
class DataModuleFromConfig(pl.LightningDataModule):
|
167 |
+
def __init__(self, batch_size, train=None, validation=None, test=None, predict=None,
|
168 |
+
wrap=False, num_workers=None, shuffle_test_loader=False, use_worker_init_fn=False,
|
169 |
+
shuffle_val_dataloader=False):
|
170 |
+
super().__init__()
|
171 |
+
self.batch_size = batch_size
|
172 |
+
self.dataset_configs = dict()
|
173 |
+
self.num_workers = num_workers if num_workers is not None else batch_size * 2
|
174 |
+
self.use_worker_init_fn = use_worker_init_fn
|
175 |
+
if train is not None:
|
176 |
+
self.dataset_configs["train"] = train
|
177 |
+
self.train_dataloader = self._train_dataloader
|
178 |
+
if validation is not None:
|
179 |
+
self.dataset_configs["validation"] = validation
|
180 |
+
self.val_dataloader = partial(self._val_dataloader, shuffle=shuffle_val_dataloader)
|
181 |
+
if test is not None:
|
182 |
+
self.dataset_configs["test"] = test
|
183 |
+
self.test_dataloader = partial(self._test_dataloader, shuffle=shuffle_test_loader)
|
184 |
+
if predict is not None:
|
185 |
+
self.dataset_configs["predict"] = predict
|
186 |
+
self.predict_dataloader = self._predict_dataloader
|
187 |
+
self.wrap = wrap
|
188 |
+
|
189 |
+
def prepare_data(self):
|
190 |
+
for data_cfg in self.dataset_configs.values():
|
191 |
+
instantiate_from_config(data_cfg)
|
192 |
+
|
193 |
+
def setup(self, stage=None):
|
194 |
+
self.datasets = dict(
|
195 |
+
(k, instantiate_from_config(self.dataset_configs[k]))
|
196 |
+
for k in self.dataset_configs)
|
197 |
+
if self.wrap:
|
198 |
+
for k in self.datasets:
|
199 |
+
self.datasets[k] = WrappedDataset(self.datasets[k])
|
200 |
+
|
201 |
+
def _train_dataloader(self):
|
202 |
+
is_iterable_dataset = isinstance(self.datasets['train'], Txt2ImgIterableBaseDataset)
|
203 |
+
if is_iterable_dataset or self.use_worker_init_fn:
|
204 |
+
init_fn = worker_init_fn
|
205 |
+
else:
|
206 |
+
init_fn = None
|
207 |
+
return DataLoader(self.datasets["train"], batch_size=self.batch_size,
|
208 |
+
num_workers=self.num_workers, shuffle=False if is_iterable_dataset else True,
|
209 |
+
worker_init_fn=init_fn, persistent_workers=True)
|
210 |
+
|
211 |
+
def _val_dataloader(self, shuffle=False):
|
212 |
+
if isinstance(self.datasets['validation'], Txt2ImgIterableBaseDataset) or self.use_worker_init_fn:
|
213 |
+
init_fn = worker_init_fn
|
214 |
+
else:
|
215 |
+
init_fn = None
|
216 |
+
return DataLoader(self.datasets["validation"],
|
217 |
+
batch_size=self.batch_size,
|
218 |
+
num_workers=self.num_workers,
|
219 |
+
worker_init_fn=init_fn,
|
220 |
+
shuffle=shuffle, persistent_workers=True)
|
221 |
+
|
222 |
+
def _test_dataloader(self, shuffle=False):
|
223 |
+
is_iterable_dataset = isinstance(self.datasets['train'], Txt2ImgIterableBaseDataset)
|
224 |
+
if is_iterable_dataset or self.use_worker_init_fn:
|
225 |
+
init_fn = worker_init_fn
|
226 |
+
else:
|
227 |
+
init_fn = None
|
228 |
+
|
229 |
+
# do not shuffle dataloader for iterable dataset
|
230 |
+
shuffle = shuffle and (not is_iterable_dataset)
|
231 |
+
|
232 |
+
return DataLoader(self.datasets["test"], batch_size=self.batch_size,
|
233 |
+
num_workers=self.num_workers, worker_init_fn=init_fn, shuffle=shuffle, persistent_workers=True)
|
234 |
+
|
235 |
+
def _predict_dataloader(self, shuffle=False):
|
236 |
+
if isinstance(self.datasets['predict'], Txt2ImgIterableBaseDataset) or self.use_worker_init_fn:
|
237 |
+
init_fn = worker_init_fn
|
238 |
+
else:
|
239 |
+
init_fn = None
|
240 |
+
return DataLoader(self.datasets["predict"], batch_size=self.batch_size,
|
241 |
+
num_workers=self.num_workers, worker_init_fn=init_fn, persistent_workers=True)
|
242 |
+
|
243 |
+
|
244 |
+
class SetupCallback(Callback):
|
245 |
+
def __init__(self, resume, now, logdir, ckptdir, cfgdir, config, lightning_config):
|
246 |
+
super().__init__()
|
247 |
+
self.resume = resume
|
248 |
+
self.now = now
|
249 |
+
self.logdir = logdir
|
250 |
+
self.ckptdir = ckptdir
|
251 |
+
self.cfgdir = cfgdir
|
252 |
+
self.config = config
|
253 |
+
self.lightning_config = lightning_config
|
254 |
+
|
255 |
+
def on_keyboard_interrupt(self, trainer, pl_module):
|
256 |
+
if trainer.global_rank == 0:
|
257 |
+
print("Summoning checkpoint.")
|
258 |
+
ckpt_path = os.path.join(self.ckptdir, "last.ckpt")
|
259 |
+
trainer.save_checkpoint(ckpt_path)
|
260 |
+
|
261 |
+
def on_pretrain_routine_start(self, trainer, pl_module):
|
262 |
+
if trainer.global_rank == 0:
|
263 |
+
# Create logdirs and save configs
|
264 |
+
# os.makedirs(self.logdir, exist_ok=True)
|
265 |
+
# os.makedirs(self.ckptdir, exist_ok=True)
|
266 |
+
# os.makedirs(self.cfgdir, exist_ok=True)
|
267 |
+
|
268 |
+
if "callbacks" in self.lightning_config:
|
269 |
+
if 'metrics_over_trainsteps_checkpoint' in self.lightning_config['callbacks']:
|
270 |
+
os.makedirs(os.path.join(self.ckptdir, 'trainstep_checkpoints'), exist_ok=True)
|
271 |
+
print("Project config")
|
272 |
+
print(OmegaConf.to_yaml(self.config))
|
273 |
+
OmegaConf.save(self.config,
|
274 |
+
os.path.join(self.cfgdir, "{}-project.yaml".format(self.now)))
|
275 |
+
|
276 |
+
print("Lightning config")
|
277 |
+
print(OmegaConf.to_yaml(self.lightning_config))
|
278 |
+
OmegaConf.save(OmegaConf.create({"lightning": self.lightning_config}),
|
279 |
+
os.path.join(self.cfgdir, "{}-lightning.yaml".format(self.now)))
|
280 |
+
|
281 |
+
def get_world_size():
|
282 |
+
if not dist.is_available():
|
283 |
+
return 1
|
284 |
+
if not dist.is_initialized():
|
285 |
+
return 1
|
286 |
+
return dist.get_world_size()
|
287 |
+
|
288 |
+
def all_gather(data):
|
289 |
+
"""
|
290 |
+
Run all_gather on arbitrary picklable data (not necessarily tensors)
|
291 |
+
Args:
|
292 |
+
data: any picklable object
|
293 |
+
Returns:
|
294 |
+
list[data]: list of data gathered from each rank
|
295 |
+
"""
|
296 |
+
world_size = get_world_size()
|
297 |
+
if world_size == 1:
|
298 |
+
return [data]
|
299 |
+
|
300 |
+
# serialized to a Tensor
|
301 |
+
origin_size = None
|
302 |
+
if not isinstance(data, torch.Tensor):
|
303 |
+
buffer = pickle.dumps(data)
|
304 |
+
storage = torch.ByteStorage.from_buffer(buffer)
|
305 |
+
tensor = torch.ByteTensor(storage).to("cuda")
|
306 |
+
else:
|
307 |
+
origin_size = data.size()
|
308 |
+
tensor = data.reshape(-1)
|
309 |
+
|
310 |
+
tensor_type = tensor.dtype
|
311 |
+
|
312 |
+
# obtain Tensor size of each rank
|
313 |
+
local_size = torch.LongTensor([tensor.numel()]).to("cuda")
|
314 |
+
size_list = [torch.LongTensor([0]).to("cuda") for _ in range(world_size)]
|
315 |
+
dist.all_gather(size_list, local_size)
|
316 |
+
size_list = [int(size.item()) for size in size_list]
|
317 |
+
max_size = max(size_list)
|
318 |
+
|
319 |
+
# receiving Tensor from all ranks
|
320 |
+
# we pad the tensor because torch all_gather does not support
|
321 |
+
# gathering tensors of different shapes
|
322 |
+
tensor_list = []
|
323 |
+
for _ in size_list:
|
324 |
+
tensor_list.append(torch.FloatTensor(size=(max_size,)).cuda().to(tensor_type))
|
325 |
+
if local_size != max_size:
|
326 |
+
padding = torch.FloatTensor(size=(max_size - local_size,)).cuda().to(tensor_type)
|
327 |
+
tensor = torch.cat((tensor, padding), dim=0)
|
328 |
+
dist.all_gather(tensor_list, tensor)
|
329 |
+
|
330 |
+
data_list = []
|
331 |
+
for size, tensor in zip(size_list, tensor_list):
|
332 |
+
if origin_size is None:
|
333 |
+
buffer = tensor.cpu().numpy().tobytes()[:size]
|
334 |
+
data_list.append(pickle.loads(buffer))
|
335 |
+
else:
|
336 |
+
buffer = tensor[:size]
|
337 |
+
data_list.append(buffer)
|
338 |
+
|
339 |
+
if origin_size is not None:
|
340 |
+
new_shape = [-1] + list(origin_size[1:])
|
341 |
+
resized_list = []
|
342 |
+
for data in data_list:
|
343 |
+
# suppose the difference of tensor size exist in first dimension
|
344 |
+
data = data.reshape(new_shape)
|
345 |
+
resized_list.append(data)
|
346 |
+
|
347 |
+
return resized_list
|
348 |
+
else:
|
349 |
+
return data_list
|
350 |
+
|
351 |
+
class ImageLogger(Callback):
|
352 |
+
def __init__(self, batch_frequency, max_images, clamp=True, increase_log_steps=True,
|
353 |
+
rescale=True, disabled=False, log_on_batch_idx=False, log_first_step=False,
|
354 |
+
log_images_kwargs=None):
|
355 |
+
super().__init__()
|
356 |
+
self.rescale = rescale
|
357 |
+
self.batch_freq = batch_frequency
|
358 |
+
self.max_images = max_images
|
359 |
+
self.logger_log_images = {
|
360 |
+
pl.loggers.TestTubeLogger: self._testtube,
|
361 |
+
}
|
362 |
+
self.log_steps = [2 ** n for n in range(6, int(np.log2(self.batch_freq)) + 1)]
|
363 |
+
if not increase_log_steps:
|
364 |
+
self.log_steps = [self.batch_freq]
|
365 |
+
self.clamp = clamp
|
366 |
+
self.disabled = disabled
|
367 |
+
self.log_on_batch_idx = log_on_batch_idx
|
368 |
+
self.log_images_kwargs = log_images_kwargs if log_images_kwargs else {}
|
369 |
+
self.log_first_step = log_first_step
|
370 |
+
|
371 |
+
@rank_zero_only
|
372 |
+
def _testtube(self, pl_module, images, batch_idx, split):
|
373 |
+
for k in images:
|
374 |
+
grid = torchvision.utils.make_grid(images[k])
|
375 |
+
grid = (grid + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w
|
376 |
+
|
377 |
+
tag = f"{split}/{k}"
|
378 |
+
pl_module.logger.experiment.add_image(
|
379 |
+
tag, grid,
|
380 |
+
global_step=pl_module.global_step)
|
381 |
+
|
382 |
+
@rank_zero_only
|
383 |
+
def log_local(self, save_dir, split, images, prompts,
|
384 |
+
global_step, current_epoch, batch_idx):
|
385 |
+
root = os.path.join(save_dir, "images", split)
|
386 |
+
names = {"reals": "before", "inputs": "after", "reconstruction": "before-vq", "samples": "after-gen"}
|
387 |
+
# print(root)
|
388 |
+
for k in images:
|
389 |
+
grid = torchvision.utils.make_grid(images[k], nrow=8)
|
390 |
+
if self.rescale:
|
391 |
+
grid = (grid + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w
|
392 |
+
grid = grid.transpose(0, 1).transpose(1, 2).squeeze(-1)
|
393 |
+
grid = grid.numpy()
|
394 |
+
grid = (grid * 255).astype(np.uint8)
|
395 |
+
filename = "gs-{:06}_e-{:06}_b-{:06}_{}.png".format(
|
396 |
+
global_step,
|
397 |
+
current_epoch,
|
398 |
+
batch_idx,
|
399 |
+
names[k])
|
400 |
+
path = os.path.join(root, filename)
|
401 |
+
os.makedirs(os.path.split(path)[0], exist_ok=True)
|
402 |
+
# print(path)
|
403 |
+
Image.fromarray(grid).save(path)
|
404 |
+
|
405 |
+
filename = "gs-{:06}_e-{:06}_b-{:06}_prompt.json".format(
|
406 |
+
global_step,
|
407 |
+
current_epoch,
|
408 |
+
batch_idx)
|
409 |
+
path = os.path.join(root, filename)
|
410 |
+
with open(path, "w") as f:
|
411 |
+
for p in prompts:
|
412 |
+
f.write(f"{json.dumps(p)}\n")
|
413 |
+
|
414 |
+
def log_img(self, pl_module, batch, batch_idx, split="train"):
|
415 |
+
check_idx = batch_idx if self.log_on_batch_idx else pl_module.global_step
|
416 |
+
if (self.check_frequency(check_idx) and # batch_idx % self.batch_freq == 0
|
417 |
+
hasattr(pl_module, "log_images") and
|
418 |
+
callable(pl_module.log_images) and
|
419 |
+
self.max_images > 0) or (split == "val" and batch_idx == 0):
|
420 |
+
logger = type(pl_module.logger)
|
421 |
+
|
422 |
+
is_train = pl_module.training
|
423 |
+
if is_train:
|
424 |
+
pl_module.eval()
|
425 |
+
|
426 |
+
with torch.no_grad():
|
427 |
+
images = pl_module.log_images(batch, split=split, **self.log_images_kwargs)
|
428 |
+
|
429 |
+
prompts = batch["edit"]["c_crossattn"][:self.max_images]
|
430 |
+
prompts = [p for ps in all_gather(prompts) for p in ps]
|
431 |
+
|
432 |
+
for k in images:
|
433 |
+
N = min(images[k].shape[0], self.max_images)
|
434 |
+
images[k] = images[k][:N]
|
435 |
+
images[k] = torch.cat(all_gather(images[k][:N]))
|
436 |
+
if isinstance(images[k], torch.Tensor):
|
437 |
+
images[k] = images[k].detach().cpu()
|
438 |
+
if self.clamp:
|
439 |
+
images[k] = torch.clamp(images[k], -1., 1.)
|
440 |
+
|
441 |
+
self.log_local(pl_module.logger.save_dir, split, images, prompts,
|
442 |
+
pl_module.global_step, pl_module.current_epoch, batch_idx)
|
443 |
+
|
444 |
+
logger_log_images = self.logger_log_images.get(logger, lambda *args, **kwargs: None)
|
445 |
+
logger_log_images(pl_module, images, pl_module.global_step, split)
|
446 |
+
|
447 |
+
if is_train:
|
448 |
+
pl_module.train()
|
449 |
+
|
450 |
+
def check_frequency(self, check_idx):
|
451 |
+
if ((check_idx % self.batch_freq) == 0 or (check_idx in self.log_steps)) and (
|
452 |
+
check_idx > 0 or self.log_first_step):
|
453 |
+
if len(self.log_steps) > 0:
|
454 |
+
self.log_steps.pop(0)
|
455 |
+
return True
|
456 |
+
return False
|
457 |
+
|
458 |
+
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
|
459 |
+
if not self.disabled and (pl_module.global_step > 0 or self.log_first_step):
|
460 |
+
self.log_img(pl_module, batch, batch_idx, split="train")
|
461 |
+
|
462 |
+
def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
|
463 |
+
if not self.disabled and pl_module.global_step > 0:
|
464 |
+
self.log_img(pl_module, batch, batch_idx, split="val")
|
465 |
+
if hasattr(pl_module, 'calibrate_grad_norm'):
|
466 |
+
if (pl_module.calibrate_grad_norm and batch_idx % 25 == 0) and batch_idx > 0:
|
467 |
+
self.log_gradients(trainer, pl_module, batch_idx=batch_idx)
|
468 |
+
|
469 |
+
|
470 |
+
class CUDACallback(Callback):
|
471 |
+
# see https://github.com/SeanNaren/minGPT/blob/master/mingpt/callback.py
|
472 |
+
def on_train_epoch_start(self, trainer, pl_module):
|
473 |
+
# Reset the memory use counter
|
474 |
+
torch.cuda.reset_peak_memory_stats(trainer.root_gpu)
|
475 |
+
torch.cuda.synchronize(trainer.root_gpu)
|
476 |
+
self.start_time = time.time()
|
477 |
+
|
478 |
+
def on_train_epoch_end(self, trainer, pl_module, outputs):
|
479 |
+
torch.cuda.synchronize(trainer.root_gpu)
|
480 |
+
max_memory = torch.cuda.max_memory_allocated(trainer.root_gpu) / 2 ** 20
|
481 |
+
epoch_time = time.time() - self.start_time
|
482 |
+
|
483 |
+
try:
|
484 |
+
max_memory = trainer.training_type_plugin.reduce(max_memory)
|
485 |
+
epoch_time = trainer.training_type_plugin.reduce(epoch_time)
|
486 |
+
|
487 |
+
rank_zero_info(f"Average Epoch time: {epoch_time:.2f} seconds")
|
488 |
+
rank_zero_info(f"Average Peak memory {max_memory:.2f}MiB")
|
489 |
+
except AttributeError:
|
490 |
+
pass
|
491 |
+
|
492 |
+
|
493 |
+
if __name__ == "__main__":
|
494 |
+
# custom parser to specify config files, train, test and debug mode,
|
495 |
+
# postfix, resume.
|
496 |
+
# `--key value` arguments are interpreted as arguments to the trainer.
|
497 |
+
# `nested.key=value` arguments are interpreted as config parameters.
|
498 |
+
# configs are merged from left-to-right followed by command line parameters.
|
499 |
+
|
500 |
+
# model:
|
501 |
+
# base_learning_rate: float
|
502 |
+
# target: path to lightning module
|
503 |
+
# params:
|
504 |
+
# key: value
|
505 |
+
# data:
|
506 |
+
# target: main.DataModuleFromConfig
|
507 |
+
# params:
|
508 |
+
# batch_size: int
|
509 |
+
# wrap: bool
|
510 |
+
# train:
|
511 |
+
# target: path to train dataset
|
512 |
+
# params:
|
513 |
+
# key: value
|
514 |
+
# validation:
|
515 |
+
# target: path to validation dataset
|
516 |
+
# params:
|
517 |
+
# key: value
|
518 |
+
# test:
|
519 |
+
# target: path to test dataset
|
520 |
+
# params:
|
521 |
+
# key: value
|
522 |
+
# lightning: (optional, has sane defaults and can be specified on cmdline)
|
523 |
+
# trainer:
|
524 |
+
# additional arguments to trainer
|
525 |
+
# logger:
|
526 |
+
# logger to instantiate
|
527 |
+
# modelcheckpoint:
|
528 |
+
# modelcheckpoint to instantiate
|
529 |
+
# callbacks:
|
530 |
+
# callback1:
|
531 |
+
# target: importpath
|
532 |
+
# params:
|
533 |
+
# key: value
|
534 |
+
|
535 |
+
now = datetime.datetime.now().strftime("%Y-%m-%dT%H-%M-%S")
|
536 |
+
|
537 |
+
# add cwd for convenience and to make classes in this file available when
|
538 |
+
# running as `python main.py`
|
539 |
+
# (in particular `main.DataModuleFromConfig`)
|
540 |
+
sys.path.append(os.getcwd())
|
541 |
+
|
542 |
+
parser = get_parser()
|
543 |
+
parser = Trainer.add_argparse_args(parser)
|
544 |
+
|
545 |
+
opt, unknown = parser.parse_known_args()
|
546 |
+
|
547 |
+
assert opt.name
|
548 |
+
cfg_fname = os.path.split(opt.base[0])[-1]
|
549 |
+
cfg_name = os.path.splitext(cfg_fname)[0]
|
550 |
+
nowname = f"{cfg_name}_{opt.name}"
|
551 |
+
logdir = os.path.join(opt.logdir, nowname)
|
552 |
+
ckpt = os.path.join(logdir, "checkpoints", "last.ckpt")
|
553 |
+
resume = False
|
554 |
+
|
555 |
+
if os.path.isfile(ckpt):
|
556 |
+
opt.resume_from_checkpoint = ckpt
|
557 |
+
base_configs = sorted(glob.glob(os.path.join(logdir, "configs/*.yaml")))
|
558 |
+
opt.base = base_configs + opt.base
|
559 |
+
_tmp = logdir.split("/")
|
560 |
+
nowname = _tmp[-1]
|
561 |
+
resume = True
|
562 |
+
|
563 |
+
ckptdir = os.path.join(logdir, "checkpoints")
|
564 |
+
cfgdir = os.path.join(logdir, "configs")
|
565 |
+
|
566 |
+
os.makedirs(logdir, exist_ok=True)
|
567 |
+
os.makedirs(ckptdir, exist_ok=True)
|
568 |
+
os.makedirs(cfgdir, exist_ok=True)
|
569 |
+
|
570 |
+
try:
|
571 |
+
# init and save configs
|
572 |
+
configs = [OmegaConf.load(cfg) for cfg in opt.base]
|
573 |
+
cli = OmegaConf.from_dotlist(unknown)
|
574 |
+
config = OmegaConf.merge(*configs, cli)
|
575 |
+
|
576 |
+
if resume:
|
577 |
+
# By default, when finetuning from Stable Diffusion, we load the EMA-only checkpoint to initialize all weights.
|
578 |
+
# If resuming InstructPix2Pix from a finetuning checkpoint, instead load both EMA and non-EMA weights.
|
579 |
+
config.model.params.load_ema = True
|
580 |
+
|
581 |
+
lightning_config = config.pop("lightning", OmegaConf.create())
|
582 |
+
# merge trainer cli with config
|
583 |
+
trainer_config = lightning_config.get("trainer", OmegaConf.create())
|
584 |
+
# default to ddp
|
585 |
+
trainer_config["accelerator"] = "ddp"
|
586 |
+
for k in nondefault_trainer_args(opt):
|
587 |
+
trainer_config[k] = getattr(opt, k)
|
588 |
+
if not "gpus" in trainer_config:
|
589 |
+
del trainer_config["accelerator"]
|
590 |
+
cpu = True
|
591 |
+
else:
|
592 |
+
gpuinfo = trainer_config["gpus"]
|
593 |
+
print(f"Running on GPUs {gpuinfo}")
|
594 |
+
cpu = False
|
595 |
+
trainer_opt = argparse.Namespace(**trainer_config)
|
596 |
+
lightning_config.trainer = trainer_config
|
597 |
+
|
598 |
+
# model
|
599 |
+
model = instantiate_from_config(config.model)
|
600 |
+
|
601 |
+
# trainer and callbacks
|
602 |
+
trainer_kwargs = dict()
|
603 |
+
|
604 |
+
# default logger configs
|
605 |
+
default_logger_cfgs = {
|
606 |
+
"wandb": {
|
607 |
+
"target": "pytorch_lightning.loggers.WandbLogger",
|
608 |
+
"params": {
|
609 |
+
"name": nowname,
|
610 |
+
"save_dir": logdir,
|
611 |
+
"id": nowname,
|
612 |
+
}
|
613 |
+
},
|
614 |
+
"testtube": {
|
615 |
+
"target": "pytorch_lightning.loggers.TestTubeLogger",
|
616 |
+
"params": {
|
617 |
+
"name": "testtube",
|
618 |
+
"save_dir": logdir,
|
619 |
+
}
|
620 |
+
},
|
621 |
+
}
|
622 |
+
default_logger_cfg = default_logger_cfgs["wandb"]
|
623 |
+
if "logger" in lightning_config:
|
624 |
+
logger_cfg = lightning_config.logger
|
625 |
+
else:
|
626 |
+
logger_cfg = OmegaConf.create()
|
627 |
+
logger_cfg = OmegaConf.merge(default_logger_cfg, logger_cfg)
|
628 |
+
trainer_kwargs["logger"] = instantiate_from_config(logger_cfg)
|
629 |
+
|
630 |
+
# modelcheckpoint - use TrainResult/EvalResult(checkpoint_on=metric) to
|
631 |
+
# specify which metric is used to determine best models
|
632 |
+
default_modelckpt_cfg = {
|
633 |
+
"target": "pytorch_lightning.callbacks.ModelCheckpoint",
|
634 |
+
"params": {
|
635 |
+
"dirpath": ckptdir,
|
636 |
+
"filename": "{epoch:06}",
|
637 |
+
"verbose": True,
|
638 |
+
"save_last": True,
|
639 |
+
}
|
640 |
+
}
|
641 |
+
|
642 |
+
if "modelcheckpoint" in lightning_config:
|
643 |
+
modelckpt_cfg = lightning_config.modelcheckpoint
|
644 |
+
else:
|
645 |
+
modelckpt_cfg = OmegaConf.create()
|
646 |
+
modelckpt_cfg = OmegaConf.merge(default_modelckpt_cfg, modelckpt_cfg)
|
647 |
+
print(f"Merged modelckpt-cfg: \n{modelckpt_cfg}")
|
648 |
+
if version.parse(pl.__version__) < version.parse('1.4.0'):
|
649 |
+
trainer_kwargs["checkpoint_callback"] = instantiate_from_config(modelckpt_cfg)
|
650 |
+
|
651 |
+
# add callback which sets up log directory
|
652 |
+
default_callbacks_cfg = {
|
653 |
+
"setup_callback": {
|
654 |
+
"target": "main.SetupCallback",
|
655 |
+
"params": {
|
656 |
+
"resume": opt.resume,
|
657 |
+
"now": now,
|
658 |
+
"logdir": logdir,
|
659 |
+
"ckptdir": ckptdir,
|
660 |
+
"cfgdir": cfgdir,
|
661 |
+
"config": config,
|
662 |
+
"lightning_config": lightning_config,
|
663 |
+
}
|
664 |
+
},
|
665 |
+
"image_logger": {
|
666 |
+
"target": "main.ImageLogger",
|
667 |
+
"params": {
|
668 |
+
"batch_frequency": 750,
|
669 |
+
"max_images": 4,
|
670 |
+
"clamp": True
|
671 |
+
}
|
672 |
+
},
|
673 |
+
"learning_rate_logger": {
|
674 |
+
"target": "main.LearningRateMonitor",
|
675 |
+
"params": {
|
676 |
+
"logging_interval": "step",
|
677 |
+
# "log_momentum": True
|
678 |
+
}
|
679 |
+
},
|
680 |
+
"cuda_callback": {
|
681 |
+
"target": "main.CUDACallback"
|
682 |
+
},
|
683 |
+
}
|
684 |
+
if version.parse(pl.__version__) >= version.parse('1.4.0'):
|
685 |
+
default_callbacks_cfg.update({'checkpoint_callback': modelckpt_cfg})
|
686 |
+
|
687 |
+
if "callbacks" in lightning_config:
|
688 |
+
callbacks_cfg = lightning_config.callbacks
|
689 |
+
else:
|
690 |
+
callbacks_cfg = OmegaConf.create()
|
691 |
+
|
692 |
+
print(
|
693 |
+
'Caution: Saving checkpoints every n train steps without deleting. This might require some free space.')
|
694 |
+
default_metrics_over_trainsteps_ckpt_dict = {
|
695 |
+
'metrics_over_trainsteps_checkpoint': {
|
696 |
+
"target": 'pytorch_lightning.callbacks.ModelCheckpoint',
|
697 |
+
'params': {
|
698 |
+
"dirpath": os.path.join(ckptdir, 'trainstep_checkpoints'),
|
699 |
+
"filename": "{epoch:06}-{step:09}",
|
700 |
+
"verbose": True,
|
701 |
+
'save_top_k': -1,
|
702 |
+
'every_n_train_steps': 1000,
|
703 |
+
'save_weights_only': True
|
704 |
+
}
|
705 |
+
}
|
706 |
+
}
|
707 |
+
default_callbacks_cfg.update(default_metrics_over_trainsteps_ckpt_dict)
|
708 |
+
|
709 |
+
callbacks_cfg = OmegaConf.merge(default_callbacks_cfg, callbacks_cfg)
|
710 |
+
if 'ignore_keys_callback' in callbacks_cfg and hasattr(trainer_opt, 'resume_from_checkpoint'):
|
711 |
+
callbacks_cfg.ignore_keys_callback.params['ckpt_path'] = trainer_opt.resume_from_checkpoint
|
712 |
+
elif 'ignore_keys_callback' in callbacks_cfg:
|
713 |
+
del callbacks_cfg['ignore_keys_callback']
|
714 |
+
|
715 |
+
trainer_kwargs["callbacks"] = [instantiate_from_config(callbacks_cfg[k]) for k in callbacks_cfg]
|
716 |
+
|
717 |
+
trainer = Trainer.from_argparse_args(trainer_opt, plugins=DDPPlugin(find_unused_parameters=False), **trainer_kwargs)
|
718 |
+
trainer.logdir = logdir ###
|
719 |
+
|
720 |
+
# data
|
721 |
+
data = instantiate_from_config(config.data)
|
722 |
+
# NOTE according to https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html
|
723 |
+
# calling these ourselves should not be necessary but it is.
|
724 |
+
# lightning still takes care of proper multiprocessing though
|
725 |
+
data.prepare_data()
|
726 |
+
data.setup()
|
727 |
+
print("#### Data #####")
|
728 |
+
for k in data.datasets:
|
729 |
+
print(f"{k}, {data.datasets[k].__class__.__name__}, {len(data.datasets[k])}")
|
730 |
+
|
731 |
+
# configure learning rate
|
732 |
+
bs, base_lr = config.data.params.batch_size, config.model.base_learning_rate
|
733 |
+
if not cpu:
|
734 |
+
ngpu = len(lightning_config.trainer.gpus.strip(",").split(','))
|
735 |
+
else:
|
736 |
+
ngpu = 1
|
737 |
+
if 'accumulate_grad_batches' in lightning_config.trainer:
|
738 |
+
accumulate_grad_batches = lightning_config.trainer.accumulate_grad_batches
|
739 |
+
else:
|
740 |
+
accumulate_grad_batches = 1
|
741 |
+
print(f"accumulate_grad_batches = {accumulate_grad_batches}")
|
742 |
+
lightning_config.trainer.accumulate_grad_batches = accumulate_grad_batches
|
743 |
+
if opt.scale_lr:
|
744 |
+
model.learning_rate = accumulate_grad_batches * ngpu * bs * base_lr
|
745 |
+
print(
|
746 |
+
"Setting learning rate to {:.2e} = {} (accumulate_grad_batches) * {} (num_gpus) * {} (batchsize) * {:.2e} (base_lr)".format(
|
747 |
+
model.learning_rate, accumulate_grad_batches, ngpu, bs, base_lr))
|
748 |
+
else:
|
749 |
+
model.learning_rate = base_lr
|
750 |
+
print("++++ NOT USING LR SCALING ++++")
|
751 |
+
print(f"Setting learning rate to {model.learning_rate:.2e}")
|
752 |
+
|
753 |
+
|
754 |
+
# allow checkpointing via USR1
|
755 |
+
def melk(*args, **kwargs):
|
756 |
+
# run all checkpoint hooks
|
757 |
+
if trainer.global_rank == 0:
|
758 |
+
print("Summoning checkpoint.")
|
759 |
+
ckpt_path = os.path.join(ckptdir, "last.ckpt")
|
760 |
+
trainer.save_checkpoint(ckpt_path)
|
761 |
+
|
762 |
+
|
763 |
+
def divein(*args, **kwargs):
|
764 |
+
if trainer.global_rank == 0:
|
765 |
+
import pudb;
|
766 |
+
pudb.set_trace()
|
767 |
+
|
768 |
+
|
769 |
+
import signal
|
770 |
+
|
771 |
+
signal.signal(signal.SIGUSR1, melk)
|
772 |
+
signal.signal(signal.SIGUSR2, divein)
|
773 |
+
|
774 |
+
# run
|
775 |
+
if opt.train:
|
776 |
+
try:
|
777 |
+
trainer.fit(model, data)
|
778 |
+
except Exception:
|
779 |
+
melk()
|
780 |
+
raise
|
781 |
+
if not opt.no_test and not trainer.interrupted:
|
782 |
+
trainer.test(model, data)
|
783 |
+
except Exception:
|
784 |
+
if opt.debug and trainer.global_rank == 0:
|
785 |
+
try:
|
786 |
+
import pudb as debugger
|
787 |
+
except ImportError:
|
788 |
+
import pdb as debugger
|
789 |
+
debugger.post_mortem()
|
790 |
+
raise
|
791 |
+
finally:
|
792 |
+
# move newly created debug project to debug_runs
|
793 |
+
if opt.debug and not opt.resume and trainer.global_rank == 0:
|
794 |
+
dst, name = os.path.split(logdir)
|
795 |
+
dst = os.path.join(dst, "debug_runs", name)
|
796 |
+
os.makedirs(os.path.split(dst)[0], exist_ok=True)
|
797 |
+
os.rename(logdir, dst)
|
798 |
+
if trainer.global_rank == 0:
|
799 |
+
print(trainer.profiler.summary())
|
metrics/clip_similarity.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import clip
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
import torch.nn.functional as F
|
7 |
+
from einops import rearrange
|
8 |
+
|
9 |
+
|
10 |
+
class ClipSimilarity(nn.Module):
|
11 |
+
def __init__(self, name: str = "ViT-L/14"):
|
12 |
+
super().__init__()
|
13 |
+
assert name in ("RN50", "RN101", "RN50x4", "RN50x16", "RN50x64", "ViT-B/32", "ViT-B/16", "ViT-L/14", "ViT-L/14@336px") # fmt: skip
|
14 |
+
self.size = {"RN50x4": 288, "RN50x16": 384, "RN50x64": 448, "ViT-L/14@336px": 336}.get(name, 224)
|
15 |
+
|
16 |
+
self.model, _ = clip.load(name, device="cpu", download_root="./")
|
17 |
+
self.model.eval().requires_grad_(False)
|
18 |
+
|
19 |
+
self.register_buffer("mean", torch.tensor((0.48145466, 0.4578275, 0.40821073)))
|
20 |
+
self.register_buffer("std", torch.tensor((0.26862954, 0.26130258, 0.27577711)))
|
21 |
+
|
22 |
+
def encode_text(self, text: list[str]) -> torch.Tensor:
|
23 |
+
text = clip.tokenize(text, truncate=True).to(next(self.parameters()).device)
|
24 |
+
text_features = self.model.encode_text(text)
|
25 |
+
text_features = text_features / text_features.norm(dim=1, keepdim=True)
|
26 |
+
return text_features
|
27 |
+
|
28 |
+
def encode_image(self, image: torch.Tensor) -> torch.Tensor: # Input images in range [0, 1].
|
29 |
+
image = F.interpolate(image.float(), size=self.size, mode="bicubic", align_corners=False)
|
30 |
+
image = image - rearrange(self.mean, "c -> 1 c 1 1")
|
31 |
+
image = image / rearrange(self.std, "c -> 1 c 1 1")
|
32 |
+
image_features = self.model.encode_image(image)
|
33 |
+
image_features = image_features / image_features.norm(dim=1, keepdim=True)
|
34 |
+
return image_features
|
35 |
+
|
36 |
+
def forward(
|
37 |
+
self, image_0: torch.Tensor, image_1: torch.Tensor, text_0: list[str], text_1: list[str]
|
38 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
39 |
+
image_features_0 = self.encode_image(image_0)
|
40 |
+
image_features_1 = self.encode_image(image_1)
|
41 |
+
text_features_0 = self.encode_text(text_0)
|
42 |
+
text_features_1 = self.encode_text(text_1)
|
43 |
+
sim_0 = F.cosine_similarity(image_features_0, text_features_0)
|
44 |
+
sim_1 = F.cosine_similarity(image_features_1, text_features_1)
|
45 |
+
sim_direction = F.cosine_similarity(image_features_1 - image_features_0, text_features_1 - text_features_0)
|
46 |
+
sim_image = F.cosine_similarity(image_features_0, image_features_1)
|
47 |
+
return sim_0, sim_1, sim_direction, sim_image
|
metrics/compute_metrics.py
ADDED
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import math
|
4 |
+
import random
|
5 |
+
import sys
|
6 |
+
from argparse import ArgumentParser
|
7 |
+
|
8 |
+
import einops
|
9 |
+
import k_diffusion as K
|
10 |
+
import numpy as np
|
11 |
+
import torch
|
12 |
+
import torch.nn as nn
|
13 |
+
from tqdm.auto import tqdm
|
14 |
+
from einops import rearrange
|
15 |
+
from omegaconf import OmegaConf
|
16 |
+
from PIL import Image, ImageOps
|
17 |
+
from torch import autocast
|
18 |
+
|
19 |
+
import json
|
20 |
+
import matplotlib.pyplot as plt
|
21 |
+
import seaborn
|
22 |
+
from pathlib import Path
|
23 |
+
|
24 |
+
sys.path.append("./")
|
25 |
+
|
26 |
+
from clip_similarity import ClipSimilarity
|
27 |
+
from edit_dataset import EditDatasetEval
|
28 |
+
|
29 |
+
sys.path.append("./stable_diffusion")
|
30 |
+
|
31 |
+
from ldm.util import instantiate_from_config
|
32 |
+
|
33 |
+
|
34 |
+
class CFGDenoiser(nn.Module):
|
35 |
+
def __init__(self, model):
|
36 |
+
super().__init__()
|
37 |
+
self.inner_model = model
|
38 |
+
|
39 |
+
def forward(self, z, sigma, cond, uncond, text_cfg_scale, image_cfg_scale):
|
40 |
+
cfg_z = einops.repeat(z, "1 ... -> n ...", n=3)
|
41 |
+
cfg_sigma = einops.repeat(sigma, "1 ... -> n ...", n=3)
|
42 |
+
cfg_cond = {
|
43 |
+
"c_crossattn": [torch.cat([cond["c_crossattn"][0], uncond["c_crossattn"][0], uncond["c_crossattn"][0]])],
|
44 |
+
"c_concat": [torch.cat([cond["c_concat"][0], cond["c_concat"][0], uncond["c_concat"][0]])],
|
45 |
+
}
|
46 |
+
out_cond, out_img_cond, out_uncond = self.inner_model(cfg_z, cfg_sigma, cond=cfg_cond).chunk(3)
|
47 |
+
return out_uncond + text_cfg_scale * (out_cond - out_img_cond) + image_cfg_scale * (out_img_cond - out_uncond)
|
48 |
+
|
49 |
+
|
50 |
+
def load_model_from_config(config, ckpt, vae_ckpt=None, verbose=False):
|
51 |
+
print(f"Loading model from {ckpt}")
|
52 |
+
pl_sd = torch.load(ckpt, map_location="cpu")
|
53 |
+
if "global_step" in pl_sd:
|
54 |
+
print(f"Global Step: {pl_sd['global_step']}")
|
55 |
+
sd = pl_sd["state_dict"]
|
56 |
+
if vae_ckpt is not None:
|
57 |
+
print(f"Loading VAE from {vae_ckpt}")
|
58 |
+
vae_sd = torch.load(vae_ckpt, map_location="cpu")["state_dict"]
|
59 |
+
sd = {
|
60 |
+
k: vae_sd[k[len("first_stage_model.") :]] if k.startswith("first_stage_model.") else v
|
61 |
+
for k, v in sd.items()
|
62 |
+
}
|
63 |
+
model = instantiate_from_config(config.model)
|
64 |
+
m, u = model.load_state_dict(sd, strict=False)
|
65 |
+
if len(m) > 0 and verbose:
|
66 |
+
print("missing keys:")
|
67 |
+
print(m)
|
68 |
+
if len(u) > 0 and verbose:
|
69 |
+
print("unexpected keys:")
|
70 |
+
print(u)
|
71 |
+
return model
|
72 |
+
|
73 |
+
class ImageEditor(nn.Module):
|
74 |
+
def __init__(self, config, ckpt, vae_ckpt=None):
|
75 |
+
super().__init__()
|
76 |
+
|
77 |
+
config = OmegaConf.load(config)
|
78 |
+
self.model = load_model_from_config(config, ckpt, vae_ckpt)
|
79 |
+
self.model.eval().cuda()
|
80 |
+
self.model_wrap = K.external.CompVisDenoiser(self.model)
|
81 |
+
self.model_wrap_cfg = CFGDenoiser(self.model_wrap)
|
82 |
+
self.null_token = self.model.get_learned_conditioning([""])
|
83 |
+
|
84 |
+
def forward(
|
85 |
+
self,
|
86 |
+
image: torch.Tensor,
|
87 |
+
edit: str,
|
88 |
+
scale_txt: float = 7.5,
|
89 |
+
scale_img: float = 1.0,
|
90 |
+
steps: int = 100,
|
91 |
+
) -> torch.Tensor:
|
92 |
+
assert image.dim() == 3
|
93 |
+
assert image.size(1) % 64 == 0
|
94 |
+
assert image.size(2) % 64 == 0
|
95 |
+
with torch.no_grad(), autocast("cuda"), self.model.ema_scope():
|
96 |
+
cond = {
|
97 |
+
"c_crossattn": [self.model.get_learned_conditioning([edit])],
|
98 |
+
"c_concat": [self.model.encode_first_stage(image[None]).mode()],
|
99 |
+
}
|
100 |
+
uncond = {
|
101 |
+
"c_crossattn": [self.model.get_learned_conditioning([""])],
|
102 |
+
"c_concat": [torch.zeros_like(cond["c_concat"][0])],
|
103 |
+
}
|
104 |
+
extra_args = {
|
105 |
+
"uncond": uncond,
|
106 |
+
"cond": cond,
|
107 |
+
"image_cfg_scale": scale_img,
|
108 |
+
"text_cfg_scale": scale_txt,
|
109 |
+
}
|
110 |
+
sigmas = self.model_wrap.get_sigmas(steps)
|
111 |
+
x = torch.randn_like(cond["c_concat"][0]) * sigmas[0]
|
112 |
+
x = K.sampling.sample_euler_ancestral(self.model_wrap_cfg, x, sigmas, extra_args=extra_args)
|
113 |
+
x = self.model.decode_first_stage(x)[0]
|
114 |
+
return x
|
115 |
+
|
116 |
+
|
117 |
+
def compute_metrics(config,
|
118 |
+
model_path,
|
119 |
+
vae_ckpt,
|
120 |
+
data_path,
|
121 |
+
output_path,
|
122 |
+
scales_img,
|
123 |
+
scales_txt,
|
124 |
+
num_samples = 5000,
|
125 |
+
split = "test",
|
126 |
+
steps = 50,
|
127 |
+
res = 512,
|
128 |
+
seed = 0):
|
129 |
+
editor = ImageEditor(config, model_path, vae_ckpt).cuda()
|
130 |
+
clip_similarity = ClipSimilarity().cuda()
|
131 |
+
|
132 |
+
|
133 |
+
|
134 |
+
outpath = Path(output_path, f"n={num_samples}_p={split}_s={steps}_r={res}_e={seed}.jsonl")
|
135 |
+
Path(output_path).mkdir(parents=True, exist_ok=True)
|
136 |
+
|
137 |
+
for scale_txt in scales_txt:
|
138 |
+
for scale_img in scales_img:
|
139 |
+
dataset = EditDatasetEval(
|
140 |
+
path=data_path,
|
141 |
+
split=split,
|
142 |
+
res=res
|
143 |
+
)
|
144 |
+
assert num_samples <= len(dataset)
|
145 |
+
print(f'Processing t={scale_txt}, i={scale_img}')
|
146 |
+
torch.manual_seed(seed)
|
147 |
+
perm = torch.randperm(len(dataset))
|
148 |
+
count = 0
|
149 |
+
i = 0
|
150 |
+
|
151 |
+
sim_0_avg = 0
|
152 |
+
sim_1_avg = 0
|
153 |
+
sim_direction_avg = 0
|
154 |
+
sim_image_avg = 0
|
155 |
+
count = 0
|
156 |
+
|
157 |
+
pbar = tqdm(total=num_samples)
|
158 |
+
while count < num_samples:
|
159 |
+
|
160 |
+
idx = perm[i].item()
|
161 |
+
sample = dataset[idx]
|
162 |
+
i += 1
|
163 |
+
|
164 |
+
gen = editor(sample["image_0"].cuda(), sample["edit"], scale_txt=scale_txt, scale_img=scale_img, steps=steps)
|
165 |
+
|
166 |
+
sim_0, sim_1, sim_direction, sim_image = clip_similarity(
|
167 |
+
sample["image_0"][None].cuda(), gen[None].cuda(), [sample["input_prompt"]], [sample["output_prompt"]]
|
168 |
+
)
|
169 |
+
sim_0_avg += sim_0.item()
|
170 |
+
sim_1_avg += sim_1.item()
|
171 |
+
sim_direction_avg += sim_direction.item()
|
172 |
+
sim_image_avg += sim_image.item()
|
173 |
+
count += 1
|
174 |
+
pbar.update(count)
|
175 |
+
pbar.close()
|
176 |
+
|
177 |
+
sim_0_avg /= count
|
178 |
+
sim_1_avg /= count
|
179 |
+
sim_direction_avg /= count
|
180 |
+
sim_image_avg /= count
|
181 |
+
|
182 |
+
with open(outpath, "a") as f:
|
183 |
+
f.write(f"{json.dumps(dict(sim_0=sim_0_avg, sim_1=sim_1_avg, sim_direction=sim_direction_avg, sim_image=sim_image_avg, num_samples=num_samples, split=split, scale_txt=scale_txt, scale_img=scale_img, steps=steps, res=res, seed=seed))}\n")
|
184 |
+
return outpath
|
185 |
+
|
186 |
+
def plot_metrics(metrics_file, output_path):
|
187 |
+
|
188 |
+
with open(metrics_file, 'r') as f:
|
189 |
+
data = [json.loads(line) for line in f]
|
190 |
+
|
191 |
+
plt.rcParams.update({'font.size': 11.5})
|
192 |
+
seaborn.set_style("darkgrid")
|
193 |
+
plt.figure(figsize=(20.5* 0.7, 10.8* 0.7), dpi=200)
|
194 |
+
|
195 |
+
x = [d["sim_direction"] for d in data]
|
196 |
+
y = [d["sim_image"] for d in data]
|
197 |
+
|
198 |
+
plt.plot(x, y, marker='o', linewidth=2, markersize=4)
|
199 |
+
|
200 |
+
plt.xlabel("CLIP Text-Image Direction Similarity", labelpad=10)
|
201 |
+
plt.ylabel("CLIP Image Similarity", labelpad=10)
|
202 |
+
|
203 |
+
plt.savefig(Path(output_path) / Path("plot.pdf"), bbox_inches="tight")
|
204 |
+
|
205 |
+
def main():
|
206 |
+
parser = ArgumentParser()
|
207 |
+
parser.add_argument("--resolution", default=512, type=int)
|
208 |
+
parser.add_argument("--steps", default=100, type=int)
|
209 |
+
parser.add_argument("--config", default="configs/generate.yaml", type=str)
|
210 |
+
parser.add_argument("--output_path", default="analysis/", type=str)
|
211 |
+
parser.add_argument("--ckpt", default="checkpoints/instruct-pix2pix-00-22000.ckpt", type=str)
|
212 |
+
parser.add_argument("--dataset", default="data/clip-filtered-dataset/", type=str)
|
213 |
+
parser.add_argument("--vae-ckpt", default=None, type=str)
|
214 |
+
args = parser.parse_args()
|
215 |
+
|
216 |
+
scales_img = [1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2]
|
217 |
+
scales_txt = [7.5]
|
218 |
+
|
219 |
+
metrics_file = compute_metrics(
|
220 |
+
args.config,
|
221 |
+
args.ckpt,
|
222 |
+
args.vae_ckpt,
|
223 |
+
args.dataset,
|
224 |
+
args.output_path,
|
225 |
+
scales_img,
|
226 |
+
scales_txt,
|
227 |
+
steps = args.steps,
|
228 |
+
)
|
229 |
+
|
230 |
+
plot_metrics(metrics_file, args.output_path)
|
231 |
+
|
232 |
+
|
233 |
+
|
234 |
+
if __name__ == "__main__":
|
235 |
+
main()
|
prompt_app.py
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from argparse import ArgumentParser
|
4 |
+
|
5 |
+
import datasets
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
import openai
|
9 |
+
|
10 |
+
from dataset_creation.generate_txt_dataset import generate
|
11 |
+
|
12 |
+
|
13 |
+
def main(openai_model: str):
|
14 |
+
dataset = datasets.load_dataset("ChristophSchuhmann/improved_aesthetics_6.5plus", split="train")
|
15 |
+
captions = dataset[np.random.permutation(len(dataset))]["TEXT"]
|
16 |
+
index = 0
|
17 |
+
|
18 |
+
def click_random():
|
19 |
+
nonlocal index
|
20 |
+
output = captions[index]
|
21 |
+
index = (index + 1) % len(captions)
|
22 |
+
return output
|
23 |
+
|
24 |
+
def click_generate(input: str):
|
25 |
+
if input == "":
|
26 |
+
raise gr.Error("Input caption is missing!")
|
27 |
+
edit_output = generate(openai_model, input)
|
28 |
+
if edit_output is None:
|
29 |
+
return "Failed :(", "Failed :("
|
30 |
+
return edit_output
|
31 |
+
|
32 |
+
with gr.Blocks(css="footer {visibility: hidden}") as demo:
|
33 |
+
txt_input = gr.Textbox(lines=3, label="Input Caption", interactive=True, placeholder="Type image caption here...") # fmt: skip
|
34 |
+
txt_edit = gr.Textbox(lines=1, label="GPT-3 Instruction", interactive=False)
|
35 |
+
txt_output = gr.Textbox(lines=3, label="GPT3 Edited Caption", interactive=False)
|
36 |
+
|
37 |
+
with gr.Row():
|
38 |
+
clear_btn = gr.Button("Clear")
|
39 |
+
random_btn = gr.Button("Random Input")
|
40 |
+
generate_btn = gr.Button("Generate Instruction + Edited Caption")
|
41 |
+
|
42 |
+
clear_btn.click(fn=lambda: ("", "", ""), inputs=[], outputs=[txt_input, txt_edit, txt_output])
|
43 |
+
random_btn.click(fn=click_random, inputs=[], outputs=[txt_input])
|
44 |
+
generate_btn.click(fn=click_generate, inputs=[txt_input], outputs=[txt_edit, txt_output])
|
45 |
+
|
46 |
+
demo.launch(share=True)
|
47 |
+
|
48 |
+
|
49 |
+
if __name__ == "__main__":
|
50 |
+
parser = ArgumentParser()
|
51 |
+
parser.add_argument("--openai-api-key", required=True, type=str)
|
52 |
+
parser.add_argument("--openai-model", required=True, type=str)
|
53 |
+
args = parser.parse_args()
|
54 |
+
openai.api_key = args.openai_api_key
|
55 |
+
main(args.openai_model)
|
scripts/download_checkpoints.sh
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
4 |
+
|
5 |
+
mkdir -p $SCRIPT_DIR/../checkpoints
|
6 |
+
|
7 |
+
curl http://instruct-pix2pix.eecs.berkeley.edu/instruct-pix2pix-00-22000.ckpt -o $SCRIPT_DIR/../checkpoints/instruct-pix2pix-00-22000.ckpt
|
scripts/download_data.sh
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
# Make data folder relative to script location
|
4 |
+
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
5 |
+
|
6 |
+
mkdir -p $SCRIPT_DIR/../data
|
7 |
+
|
8 |
+
# Copy text datasets
|
9 |
+
wget -q --show-progress http://instruct-pix2pix.eecs.berkeley.edu/gpt-generated-prompts.jsonl -O $SCRIPT_DIR/../data/gpt-generated-prompts.jsonl
|
10 |
+
wget -q --show-progress http://instruct-pix2pix.eecs.berkeley.edu/human-written-prompts.jsonl -O $SCRIPT_DIR/../data/human-written-prompts.jsonl
|
11 |
+
|
12 |
+
# If dataset name isn't provided, exit.
|
13 |
+
if [ -z $1 ]
|
14 |
+
then
|
15 |
+
exit 0
|
16 |
+
fi
|
17 |
+
|
18 |
+
# Copy dataset files
|
19 |
+
mkdir $SCRIPT_DIR/../data/$1
|
20 |
+
wget -A zip,json -R "index.html*" -q --show-progress -r --no-parent http://instruct-pix2pix.eecs.berkeley.edu/$1/ -nd -P $SCRIPT_DIR/../data/$1/
|
21 |
+
|
22 |
+
# Unzip to folders
|
23 |
+
unzip $SCRIPT_DIR/../data/$1/\*.zip -d $SCRIPT_DIR/../data/$1/
|
24 |
+
|
25 |
+
# Cleanup
|
26 |
+
rm -f $SCRIPT_DIR/../data/$1/*.zip
|
27 |
+
rm -f $SCRIPT_DIR/../data/$1/*.html
|
scripts/download_pretrained_sd.sh
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
4 |
+
|
5 |
+
mkdir -p $SCRIPT_DIR/../stable_diffusion/models/ldm/stable-diffusion-v1
|
6 |
+
curl -L https://huggingface.co/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.ckpt -o $SCRIPT_DIR/../stable_diffusion/models/ldm/stable-diffusion-v1/v1-5-pruned-emaonly.ckpt
|
7 |
+
curl -L https://huggingface.co/stabilityai/sd-vae-ft-mse-original/resolve/main/vae-ft-mse-840000-ema-pruned.ckpt -o $SCRIPT_DIR/../stable_diffusion/models/ldm/stable-diffusion-v1/vae-ft-mse-840000-ema-pruned.ckpt
|
stable_diffusion/LICENSE
ADDED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Copyright (c) 2022 Robin Rombach and Patrick Esser and contributors
|
2 |
+
|
3 |
+
CreativeML Open RAIL-M
|
4 |
+
dated August 22, 2022
|
5 |
+
|
6 |
+
Section I: PREAMBLE
|
7 |
+
|
8 |
+
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.
|
9 |
+
|
10 |
+
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.
|
11 |
+
|
12 |
+
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.
|
13 |
+
|
14 |
+
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 License aims to strike a balance between both in order to enable responsible open-science in the field of AI.
|
15 |
+
|
16 |
+
This License governs the use of the model (and its derivatives) and is informed by the model card associated with the model.
|
17 |
+
|
18 |
+
NOW THEREFORE, You and Licensor agree as follows:
|
19 |
+
|
20 |
+
1. Definitions
|
21 |
+
|
22 |
+
- "License" means the terms and conditions for use, reproduction, and Distribution as defined in this document.
|
23 |
+
- "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.
|
24 |
+
- "Output" means the results of operating a Model as embodied in informational content resulting therefrom.
|
25 |
+
- "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.
|
26 |
+
- "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.
|
27 |
+
- "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.
|
28 |
+
- "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.
|
29 |
+
- "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.
|
30 |
+
- "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.
|
31 |
+
- "Third Parties" means individuals or legal entities that are not under common control with Licensor or You.
|
32 |
+
- "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."
|
33 |
+
- "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.
|
34 |
+
|
35 |
+
Section II: INTELLECTUAL PROPERTY RIGHTS
|
36 |
+
|
37 |
+
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.
|
38 |
+
|
39 |
+
2. 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.
|
40 |
+
3. 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.
|
41 |
+
|
42 |
+
Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION
|
43 |
+
|
44 |
+
4. 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:
|
45 |
+
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.
|
46 |
+
You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License;
|
47 |
+
You must cause any modified files to carry prominent notices stating that You changed the files;
|
48 |
+
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.
|
49 |
+
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.
|
50 |
+
5. 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).
|
51 |
+
6. 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.
|
52 |
+
|
53 |
+
Section IV: OTHER PROVISIONS
|
54 |
+
|
55 |
+
7. 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, update the Model through electronic means, or modify the Output of the Model based on updates. You shall undertake reasonable efforts to use the latest version of the Model.
|
56 |
+
8. 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.
|
57 |
+
9. 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.
|
58 |
+
10. 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.
|
59 |
+
11. 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.
|
60 |
+
12. 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.
|
61 |
+
|
62 |
+
END OF TERMS AND CONDITIONS
|
63 |
+
|
64 |
+
|
65 |
+
|
66 |
+
|
67 |
+
Attachment A
|
68 |
+
|
69 |
+
Use Restrictions
|
70 |
+
|
71 |
+
You agree not to use the Model or Derivatives of the Model:
|
72 |
+
- In any way that violates any applicable national, federal, state, local or international law or regulation;
|
73 |
+
- For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
|
74 |
+
- To generate or disseminate verifiably false information and/or content with the purpose of harming others;
|
75 |
+
- To generate or disseminate personal identifiable information that can be used to harm an individual;
|
76 |
+
- To defame, disparage or otherwise harass others;
|
77 |
+
- For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation;
|
78 |
+
- 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;
|
79 |
+
- 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;
|
80 |
+
- For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories;
|
81 |
+
- To provide medical advice and medical results interpretation;
|
82 |
+
- 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).
|
stable_diffusion/README.md
ADDED
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Stable Diffusion
|
2 |
+
*Stable Diffusion was made possible thanks to a collaboration with [Stability AI](https://stability.ai/) and [Runway](https://runwayml.com/) and builds upon our previous work:*
|
3 |
+
|
4 |
+
[**High-Resolution Image Synthesis with Latent Diffusion Models**](https://ommer-lab.com/research/latent-diffusion-models/)<br/>
|
5 |
+
[Robin Rombach](https://github.com/rromb)\*,
|
6 |
+
[Andreas Blattmann](https://github.com/ablattmann)\*,
|
7 |
+
[Dominik Lorenz](https://github.com/qp-qp)\,
|
8 |
+
[Patrick Esser](https://github.com/pesser),
|
9 |
+
[Björn Ommer](https://hci.iwr.uni-heidelberg.de/Staff/bommer)<br/>
|
10 |
+
_[CVPR '22 Oral](https://openaccess.thecvf.com/content/CVPR2022/html/Rombach_High-Resolution_Image_Synthesis_With_Latent_Diffusion_Models_CVPR_2022_paper.html) |
|
11 |
+
[GitHub](https://github.com/CompVis/latent-diffusion) | [arXiv](https://arxiv.org/abs/2112.10752) | [Project page](https://ommer-lab.com/research/latent-diffusion-models/)_
|
12 |
+
|
13 |
+
![txt2img-stable2](assets/stable-samples/txt2img/merged-0006.png)
|
14 |
+
[Stable Diffusion](#stable-diffusion-v1) is a latent text-to-image diffusion
|
15 |
+
model.
|
16 |
+
Thanks to a generous compute donation from [Stability AI](https://stability.ai/) and support from [LAION](https://laion.ai/), we were able to train a Latent Diffusion Model on 512x512 images from a subset of the [LAION-5B](https://laion.ai/blog/laion-5b/) database.
|
17 |
+
Similar to Google's [Imagen](https://arxiv.org/abs/2205.11487),
|
18 |
+
this model uses a frozen CLIP ViT-L/14 text encoder to condition the model on text prompts.
|
19 |
+
With its 860M UNet and 123M text encoder, the model is relatively lightweight and runs on a GPU with at least 10GB VRAM.
|
20 |
+
See [this section](#stable-diffusion-v1) below and the [model card](https://huggingface.co/CompVis/stable-diffusion).
|
21 |
+
|
22 |
+
|
23 |
+
## Requirements
|
24 |
+
A suitable [conda](https://conda.io/) environment named `ldm` can be created
|
25 |
+
and activated with:
|
26 |
+
|
27 |
+
```
|
28 |
+
conda env create -f environment.yaml
|
29 |
+
conda activate ldm
|
30 |
+
```
|
31 |
+
|
32 |
+
You can also update an existing [latent diffusion](https://github.com/CompVis/latent-diffusion) environment by running
|
33 |
+
|
34 |
+
```
|
35 |
+
conda install pytorch torchvision -c pytorch
|
36 |
+
pip install transformers==4.19.2 diffusers invisible-watermark
|
37 |
+
pip install -e .
|
38 |
+
```
|
39 |
+
|
40 |
+
|
41 |
+
## Stable Diffusion v1
|
42 |
+
|
43 |
+
Stable Diffusion v1 refers to a specific configuration of the model
|
44 |
+
architecture that uses a downsampling-factor 8 autoencoder with an 860M UNet
|
45 |
+
and CLIP ViT-L/14 text encoder for the diffusion model. The model was pretrained on 256x256 images and
|
46 |
+
then finetuned on 512x512 images.
|
47 |
+
|
48 |
+
*Note: Stable Diffusion v1 is a general text-to-image diffusion model and therefore mirrors biases and (mis-)conceptions that are present
|
49 |
+
in its training data.
|
50 |
+
Details on the training procedure and data, as well as the intended use of the model can be found in the corresponding [model card](Stable_Diffusion_v1_Model_Card.md).*
|
51 |
+
|
52 |
+
The weights are available via [the CompVis organization at Hugging Face](https://huggingface.co/CompVis) under [a license which contains specific use-based restrictions to prevent misuse and harm as informed by the model card, but otherwise remains permissive](LICENSE). While commercial use is permitted under the terms of the license, **we do not recommend using the provided weights for services or products without additional safety mechanisms and considerations**, since there are [known limitations and biases](Stable_Diffusion_v1_Model_Card.md#limitations-and-bias) of the weights, and research on safe and ethical deployment of general text-to-image models is an ongoing effort. **The weights are research artifacts and should be treated as such.**
|
53 |
+
|
54 |
+
[The CreativeML OpenRAIL M license](LICENSE) is an [Open RAIL M license](https://www.licenses.ai/blog/2022/8/18/naming-convention-of-responsible-ai-licenses), adapted from the work that [BigScience](https://bigscience.huggingface.co/) and [the RAIL Initiative](https://www.licenses.ai/) are jointly carrying in the area of responsible AI licensing. See also [the article about the BLOOM Open RAIL license](https://bigscience.huggingface.co/blog/the-bigscience-rail-license) on which our license is based.
|
55 |
+
|
56 |
+
### Weights
|
57 |
+
|
58 |
+
We currently provide the following checkpoints:
|
59 |
+
|
60 |
+
- `sd-v1-1.ckpt`: 237k steps at resolution `256x256` on [laion2B-en](https://huggingface.co/datasets/laion/laion2B-en).
|
61 |
+
194k steps at resolution `512x512` on [laion-high-resolution](https://huggingface.co/datasets/laion/laion-high-resolution) (170M examples from LAION-5B with resolution `>= 1024x1024`).
|
62 |
+
- `sd-v1-2.ckpt`: Resumed from `sd-v1-1.ckpt`.
|
63 |
+
515k steps at resolution `512x512` on [laion-aesthetics v2 5+](https://laion.ai/blog/laion-aesthetics/) (a subset of laion2B-en with estimated aesthetics score `> 5.0`, and additionally
|
64 |
+
filtered to images with an original size `>= 512x512`, and an estimated watermark probability `< 0.5`. The watermark estimate is from the [LAION-5B](https://laion.ai/blog/laion-5b/) metadata, the aesthetics score is estimated using the [LAION-Aesthetics Predictor V2](https://github.com/christophschuhmann/improved-aesthetic-predictor)).
|
65 |
+
- `sd-v1-3.ckpt`: Resumed from `sd-v1-2.ckpt`. 195k steps at resolution `512x512` on "laion-aesthetics v2 5+" and 10\% dropping of the text-conditioning to improve [classifier-free guidance sampling](https://arxiv.org/abs/2207.12598).
|
66 |
+
- `sd-v1-4.ckpt`: Resumed from `sd-v1-2.ckpt`. 225k steps at resolution `512x512` on "laion-aesthetics v2 5+" and 10\% dropping of the text-conditioning to improve [classifier-free guidance sampling](https://arxiv.org/abs/2207.12598).
|
67 |
+
|
68 |
+
Evaluations with different classifier-free guidance scales (1.5, 2.0, 3.0, 4.0,
|
69 |
+
5.0, 6.0, 7.0, 8.0) and 50 PLMS sampling
|
70 |
+
steps show the relative improvements of the checkpoints:
|
71 |
+
![sd evaluation results](assets/v1-variants-scores.jpg)
|
72 |
+
|
73 |
+
|
74 |
+
|
75 |
+
### Text-to-Image with Stable Diffusion
|
76 |
+
![txt2img-stable2](assets/stable-samples/txt2img/merged-0005.png)
|
77 |
+
![txt2img-stable2](assets/stable-samples/txt2img/merged-0007.png)
|
78 |
+
|
79 |
+
Stable Diffusion is a latent diffusion model conditioned on the (non-pooled) text embeddings of a CLIP ViT-L/14 text encoder.
|
80 |
+
We provide a [reference script for sampling](#reference-sampling-script), but
|
81 |
+
there also exists a [diffusers integration](#diffusers-integration), which we
|
82 |
+
expect to see more active community development.
|
83 |
+
|
84 |
+
#### Reference Sampling Script
|
85 |
+
|
86 |
+
We provide a reference sampling script, which incorporates
|
87 |
+
|
88 |
+
- a [Safety Checker Module](https://github.com/CompVis/stable-diffusion/pull/36),
|
89 |
+
to reduce the probability of explicit outputs,
|
90 |
+
- an [invisible watermarking](https://github.com/ShieldMnt/invisible-watermark)
|
91 |
+
of the outputs, to help viewers [identify the images as machine-generated](scripts/tests/test_watermark.py).
|
92 |
+
|
93 |
+
After [obtaining the `stable-diffusion-v1-*-original` weights](#weights), link them
|
94 |
+
```
|
95 |
+
mkdir -p models/ldm/stable-diffusion-v1/
|
96 |
+
ln -s <path/to/model.ckpt> models/ldm/stable-diffusion-v1/model.ckpt
|
97 |
+
```
|
98 |
+
and sample with
|
99 |
+
```
|
100 |
+
python scripts/txt2img.py --prompt "a photograph of an astronaut riding a horse" --plms
|
101 |
+
```
|
102 |
+
|
103 |
+
By default, this uses a guidance scale of `--scale 7.5`, [Katherine Crowson's implementation](https://github.com/CompVis/latent-diffusion/pull/51) of the [PLMS](https://arxiv.org/abs/2202.09778) sampler,
|
104 |
+
and renders images of size 512x512 (which it was trained on) in 50 steps. All supported arguments are listed below (type `python scripts/txt2img.py --help`).
|
105 |
+
|
106 |
+
|
107 |
+
```commandline
|
108 |
+
usage: txt2img.py [-h] [--prompt [PROMPT]] [--outdir [OUTDIR]] [--skip_grid] [--skip_save] [--ddim_steps DDIM_STEPS] [--plms] [--laion400m] [--fixed_code] [--ddim_eta DDIM_ETA]
|
109 |
+
[--n_iter N_ITER] [--H H] [--W W] [--C C] [--f F] [--n_samples N_SAMPLES] [--n_rows N_ROWS] [--scale SCALE] [--from-file FROM_FILE] [--config CONFIG] [--ckpt CKPT]
|
110 |
+
[--seed SEED] [--precision {full,autocast}]
|
111 |
+
|
112 |
+
optional arguments:
|
113 |
+
-h, --help show this help message and exit
|
114 |
+
--prompt [PROMPT] the prompt to render
|
115 |
+
--outdir [OUTDIR] dir to write results to
|
116 |
+
--skip_grid do not save a grid, only individual samples. Helpful when evaluating lots of samples
|
117 |
+
--skip_save do not save individual samples. For speed measurements.
|
118 |
+
--ddim_steps DDIM_STEPS
|
119 |
+
number of ddim sampling steps
|
120 |
+
--plms use plms sampling
|
121 |
+
--laion400m uses the LAION400M model
|
122 |
+
--fixed_code if enabled, uses the same starting code across samples
|
123 |
+
--ddim_eta DDIM_ETA ddim eta (eta=0.0 corresponds to deterministic sampling
|
124 |
+
--n_iter N_ITER sample this often
|
125 |
+
--H H image height, in pixel space
|
126 |
+
--W W image width, in pixel space
|
127 |
+
--C C latent channels
|
128 |
+
--f F downsampling factor
|
129 |
+
--n_samples N_SAMPLES
|
130 |
+
how many samples to produce for each given prompt. A.k.a. batch size
|
131 |
+
--n_rows N_ROWS rows in the grid (default: n_samples)
|
132 |
+
--scale SCALE unconditional guidance scale: eps = eps(x, empty) + scale * (eps(x, cond) - eps(x, empty))
|
133 |
+
--from-file FROM_FILE
|
134 |
+
if specified, load prompts from this file
|
135 |
+
--config CONFIG path to config which constructs model
|
136 |
+
--ckpt CKPT path to checkpoint of model
|
137 |
+
--seed SEED the seed (for reproducible sampling)
|
138 |
+
--precision {full,autocast}
|
139 |
+
evaluate at this precision
|
140 |
+
```
|
141 |
+
Note: The inference config for all v1 versions is designed to be used with EMA-only checkpoints.
|
142 |
+
For this reason `use_ema=False` is set in the configuration, otherwise the code will try to switch from
|
143 |
+
non-EMA to EMA weights. If you want to examine the effect of EMA vs no EMA, we provide "full" checkpoints
|
144 |
+
which contain both types of weights. For these, `use_ema=False` will load and use the non-EMA weights.
|
145 |
+
|
146 |
+
|
147 |
+
#### Diffusers Integration
|
148 |
+
|
149 |
+
A simple way to download and sample Stable Diffusion is by using the [diffusers library](https://github.com/huggingface/diffusers/tree/main#new--stable-diffusion-is-now-fully-compatible-with-diffusers):
|
150 |
+
```py
|
151 |
+
# make sure you're logged in with `huggingface-cli login`
|
152 |
+
from torch import autocast
|
153 |
+
from diffusers import StableDiffusionPipeline
|
154 |
+
|
155 |
+
pipe = StableDiffusionPipeline.from_pretrained(
|
156 |
+
"CompVis/stable-diffusion-v1-4",
|
157 |
+
use_auth_token=True
|
158 |
+
).to("cuda")
|
159 |
+
|
160 |
+
prompt = "a photo of an astronaut riding a horse on mars"
|
161 |
+
with autocast("cuda"):
|
162 |
+
image = pipe(prompt)["sample"][0]
|
163 |
+
|
164 |
+
image.save("astronaut_rides_horse.png")
|
165 |
+
```
|
166 |
+
|
167 |
+
|
168 |
+
### Image Modification with Stable Diffusion
|
169 |
+
|
170 |
+
By using a diffusion-denoising mechanism as first proposed by [SDEdit](https://arxiv.org/abs/2108.01073), the model can be used for different
|
171 |
+
tasks such as text-guided image-to-image translation and upscaling. Similar to the txt2img sampling script,
|
172 |
+
we provide a script to perform image modification with Stable Diffusion.
|
173 |
+
|
174 |
+
The following describes an example where a rough sketch made in [Pinta](https://www.pinta-project.com/) is converted into a detailed artwork.
|
175 |
+
```
|
176 |
+
python scripts/img2img.py --prompt "A fantasy landscape, trending on artstation" --init-img <path-to-img.jpg> --strength 0.8
|
177 |
+
```
|
178 |
+
Here, strength is a value between 0.0 and 1.0, that controls the amount of noise that is added to the input image.
|
179 |
+
Values that approach 1.0 allow for lots of variations but will also produce images that are not semantically consistent with the input. See the following example.
|
180 |
+
|
181 |
+
**Input**
|
182 |
+
|
183 |
+
![sketch-in](assets/stable-samples/img2img/sketch-mountains-input.jpg)
|
184 |
+
|
185 |
+
**Outputs**
|
186 |
+
|
187 |
+
![out3](assets/stable-samples/img2img/mountains-3.png)
|
188 |
+
![out2](assets/stable-samples/img2img/mountains-2.png)
|
189 |
+
|
190 |
+
This procedure can, for example, also be used to upscale samples from the base model.
|
191 |
+
|
192 |
+
|
193 |
+
## Comments
|
194 |
+
|
195 |
+
- Our codebase for the diffusion models builds heavily on [OpenAI's ADM codebase](https://github.com/openai/guided-diffusion)
|
196 |
+
and [https://github.com/lucidrains/denoising-diffusion-pytorch](https://github.com/lucidrains/denoising-diffusion-pytorch).
|
197 |
+
Thanks for open-sourcing!
|
198 |
+
|
199 |
+
- The implementation of the transformer encoder is from [x-transformers](https://github.com/lucidrains/x-transformers) by [lucidrains](https://github.com/lucidrains?tab=repositories).
|
200 |
+
|
201 |
+
|
202 |
+
## BibTeX
|
203 |
+
|
204 |
+
```
|
205 |
+
@misc{rombach2021highresolution,
|
206 |
+
title={High-Resolution Image Synthesis with Latent Diffusion Models},
|
207 |
+
author={Robin Rombach and Andreas Blattmann and Dominik Lorenz and Patrick Esser and Björn Ommer},
|
208 |
+
year={2021},
|
209 |
+
eprint={2112.10752},
|
210 |
+
archivePrefix={arXiv},
|
211 |
+
primaryClass={cs.CV}
|
212 |
+
}
|
213 |
+
```
|
214 |
+
|
215 |
+
|
stable_diffusion/Stable_Diffusion_v1_Model_Card.md
ADDED
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Stable Diffusion v1 Model Card
|
2 |
+
This model card focuses on the model associated with the Stable Diffusion model, available [here](https://github.com/CompVis/stable-diffusion).
|
3 |
+
|
4 |
+
## Model Details
|
5 |
+
- **Developed by:** Robin Rombach, Patrick Esser
|
6 |
+
- **Model type:** Diffusion-based text-to-image generation model
|
7 |
+
- **Language(s):** English
|
8 |
+
- **License:** [Proprietary](LICENSE)
|
9 |
+
- **Model Description:** This is a model that can be used to generate and modify images based on text prompts. It is a [Latent Diffusion Model](https://arxiv.org/abs/2112.10752) that uses a fixed, pretrained text encoder ([CLIP ViT-L/14](https://arxiv.org/abs/2103.00020)) as suggested in the [Imagen paper](https://arxiv.org/abs/2205.11487).
|
10 |
+
- **Resources for more information:** [GitHub Repository](https://github.com/CompVis/stable-diffusion), [Paper](https://arxiv.org/abs/2112.10752).
|
11 |
+
- **Cite as:**
|
12 |
+
|
13 |
+
@InProceedings{Rombach_2022_CVPR,
|
14 |
+
author = {Rombach, Robin and Blattmann, Andreas and Lorenz, Dominik and Esser, Patrick and Ommer, Bj\"orn},
|
15 |
+
title = {High-Resolution Image Synthesis With Latent Diffusion Models},
|
16 |
+
booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)},
|
17 |
+
month = {June},
|
18 |
+
year = {2022},
|
19 |
+
pages = {10684-10695}
|
20 |
+
}
|
21 |
+
|
22 |
+
# Uses
|
23 |
+
|
24 |
+
## Direct Use
|
25 |
+
The model is intended for research purposes only. Possible research areas and
|
26 |
+
tasks include
|
27 |
+
|
28 |
+
- Safe deployment of models which have the potential to generate harmful content.
|
29 |
+
- Probing and understanding the limitations and biases of generative models.
|
30 |
+
- Generation of artworks and use in design and other artistic processes.
|
31 |
+
- Applications in educational or creative tools.
|
32 |
+
- Research on generative models.
|
33 |
+
|
34 |
+
Excluded uses are described below.
|
35 |
+
|
36 |
+
### Misuse, Malicious Use, and Out-of-Scope Use
|
37 |
+
_Note: This section is taken from the [DALLE-MINI model card](https://huggingface.co/dalle-mini/dalle-mini), but applies in the same way to Stable Diffusion v1_.
|
38 |
+
|
39 |
+
The model should not be used to intentionally create or disseminate images that create hostile or alienating environments for people. This includes generating images that people would foreseeably find disturbing, distressing, or offensive; or content that propagates historical or current stereotypes.
|
40 |
+
|
41 |
+
#### Out-of-Scope Use
|
42 |
+
The model was not trained to be factual or true representations of people or events, and therefore using the model to generate such content is out-of-scope for the abilities of this model.
|
43 |
+
|
44 |
+
#### Misuse and Malicious Use
|
45 |
+
Using the model to generate content that is cruel to individuals is a misuse of this model. This includes, but is not limited to:
|
46 |
+
|
47 |
+
- Generating demeaning, dehumanizing, or otherwise harmful representations of people or their environments, cultures, religions, etc.
|
48 |
+
- Intentionally promoting or propagating discriminatory content or harmful stereotypes.
|
49 |
+
- Impersonating individuals without their consent.
|
50 |
+
- Sexual content without consent of the people who might see it.
|
51 |
+
- Mis- and disinformation
|
52 |
+
- Representations of egregious violence and gore
|
53 |
+
- Sharing of copyrighted or licensed material in violation of its terms of use.
|
54 |
+
- Sharing content that is an alteration of copyrighted or licensed material in violation of its terms of use.
|
55 |
+
|
56 |
+
## Limitations and Bias
|
57 |
+
|
58 |
+
### Limitations
|
59 |
+
|
60 |
+
- The model does not achieve perfect photorealism
|
61 |
+
- The model cannot render legible text
|
62 |
+
- The model does not perform well on more difficult tasks which involve compositionality, such as rendering an image corresponding to “A red cube on top of a blue sphere”
|
63 |
+
- Faces and people in general may not be generated properly.
|
64 |
+
- The model was trained mainly with English captions and will not work as well in other languages.
|
65 |
+
- The autoencoding part of the model is lossy
|
66 |
+
- The model was trained on a large-scale dataset
|
67 |
+
[LAION-5B](https://laion.ai/blog/laion-5b/) which contains adult material
|
68 |
+
and is not fit for product use without additional safety mechanisms and
|
69 |
+
considerations.
|
70 |
+
- No additional measures were used to deduplicate the dataset. As a result, we observe some degree of memorization for images that are duplicated in the training data.
|
71 |
+
The training data can be searched at [https://rom1504.github.io/clip-retrieval/](https://rom1504.github.io/clip-retrieval/) to possibly assist in the detection of memorized images.
|
72 |
+
|
73 |
+
### Bias
|
74 |
+
While the capabilities of image generation models are impressive, they can also reinforce or exacerbate social biases.
|
75 |
+
Stable Diffusion v1 was primarily trained on subsets of [LAION-2B(en)](https://laion.ai/blog/laion-5b/),
|
76 |
+
which consists of images that are limited to English descriptions.
|
77 |
+
Texts and images from communities and cultures that use other languages are likely to be insufficiently accounted for.
|
78 |
+
This affects the overall output of the model, as white and western cultures are often set as the default. Further, the
|
79 |
+
ability of the model to generate content with non-English prompts is significantly worse than with English-language prompts.
|
80 |
+
Stable Diffusion v1 mirrors and exacerbates biases to such a degree that viewer discretion must be advised irrespective of the input or its intent.
|
81 |
+
|
82 |
+
|
83 |
+
## Training
|
84 |
+
|
85 |
+
**Training Data**
|
86 |
+
The model developers used the following dataset for training the model:
|
87 |
+
|
88 |
+
- LAION-5B and subsets thereof (see next section)
|
89 |
+
|
90 |
+
**Training Procedure**
|
91 |
+
Stable Diffusion v1 is a latent diffusion model which combines an autoencoder with a diffusion model that is trained in the latent space of the autoencoder. During training,
|
92 |
+
|
93 |
+
- Images are encoded through an encoder, which turns images into latent representations. The autoencoder uses a relative downsampling factor of 8 and maps images of shape H x W x 3 to latents of shape H/f x W/f x 4
|
94 |
+
- Text prompts are encoded through a ViT-L/14 text-encoder.
|
95 |
+
- The non-pooled output of the text encoder is fed into the UNet backbone of the latent diffusion model via cross-attention.
|
96 |
+
- The loss is a reconstruction objective between the noise that was added to the latent and the prediction made by the UNet.
|
97 |
+
|
98 |
+
We currently provide the following checkpoints:
|
99 |
+
|
100 |
+
- `sd-v1-1.ckpt`: 237k steps at resolution `256x256` on [laion2B-en](https://huggingface.co/datasets/laion/laion2B-en).
|
101 |
+
194k steps at resolution `512x512` on [laion-high-resolution](https://huggingface.co/datasets/laion/laion-high-resolution) (170M examples from LAION-5B with resolution `>= 1024x1024`).
|
102 |
+
- `sd-v1-2.ckpt`: Resumed from `sd-v1-1.ckpt`.
|
103 |
+
515k steps at resolution `512x512` on [laion-aesthetics v2 5+](https://laion.ai/blog/laion-aesthetics/) (a subset of laion2B-en with estimated aesthetics score `> 5.0`, and additionally
|
104 |
+
filtered to images with an original size `>= 512x512`, and an estimated watermark probability `< 0.5`. The watermark estimate is from the [LAION-5B](https://laion.ai/blog/laion-5b/) metadata, the aesthetics score is estimated using the [LAION-Aesthetics Predictor V2](https://github.com/christophschuhmann/improved-aesthetic-predictor)).
|
105 |
+
- `sd-v1-3.ckpt`: Resumed from `sd-v1-2.ckpt`. 195k steps at resolution `512x512` on "laion-aesthetics v2 5+" and 10\% dropping of the text-conditioning to improve [classifier-free guidance sampling](https://arxiv.org/abs/2207.12598).
|
106 |
+
- `sd-v1-4.ckpt`: Resumed from `sd-v1-2.ckpt`. 225k steps at resolution `512x512` on "laion-aesthetics v2 5+" and 10\% dropping of the text-conditioning to improve [classifier-free guidance sampling](https://arxiv.org/abs/2207.12598).
|
107 |
+
|
108 |
+
- **Hardware:** 32 x 8 x A100 GPUs
|
109 |
+
- **Optimizer:** AdamW
|
110 |
+
- **Gradient Accumulations**: 2
|
111 |
+
- **Batch:** 32 x 8 x 2 x 4 = 2048
|
112 |
+
- **Learning rate:** warmup to 0.0001 for 10,000 steps and then kept constant
|
113 |
+
|
114 |
+
## Evaluation Results
|
115 |
+
Evaluations with different classifier-free guidance scales (1.5, 2.0, 3.0, 4.0,
|
116 |
+
5.0, 6.0, 7.0, 8.0) and 50 PLMS sampling
|
117 |
+
steps show the relative improvements of the checkpoints:
|
118 |
+
|
119 |
+
![pareto](assets/v1-variants-scores.jpg)
|
120 |
+
|
121 |
+
Evaluated using 50 PLMS steps and 10000 random prompts from the COCO2017 validation set, evaluated at 512x512 resolution. Not optimized for FID scores.
|
122 |
+
|
123 |
+
## Environmental Impact
|
124 |
+
|
125 |
+
**Stable Diffusion v1** **Estimated Emissions**
|
126 |
+
Based on that information, we estimate the following CO2 emissions using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700). The hardware, runtime, cloud provider, and compute region were utilized to estimate the carbon impact.
|
127 |
+
|
128 |
+
- **Hardware Type:** A100 PCIe 40GB
|
129 |
+
- **Hours used:** 150000
|
130 |
+
- **Cloud Provider:** AWS
|
131 |
+
- **Compute Region:** US-east
|
132 |
+
- **Carbon Emitted (Power consumption x Time x Carbon produced based on location of power grid):** 11250 kg CO2 eq.
|
133 |
+
|
134 |
+
## Citation
|
135 |
+
@InProceedings{Rombach_2022_CVPR,
|
136 |
+
author = {Rombach, Robin and Blattmann, Andreas and Lorenz, Dominik and Esser, Patrick and Ommer, Bj\"orn},
|
137 |
+
title = {High-Resolution Image Synthesis With Latent Diffusion Models},
|
138 |
+
booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)},
|
139 |
+
month = {June},
|
140 |
+
year = {2022},
|
141 |
+
pages = {10684-10695}
|
142 |
+
}
|
143 |
+
|
144 |
+
*This model card was written by: Robin Rombach and Patrick Esser and is based on the [DALL-E Mini model card](https://huggingface.co/dalle-mini/dalle-mini).*
|
stable_diffusion/assets/a-painting-of-a-fire.png
ADDED
stable_diffusion/assets/a-photograph-of-a-fire.png
ADDED
stable_diffusion/assets/a-shirt-with-a-fire-printed-on-it.png
ADDED
stable_diffusion/assets/a-shirt-with-the-inscription-'fire'.png
ADDED
stable_diffusion/assets/a-watercolor-painting-of-a-fire.png
ADDED
stable_diffusion/assets/birdhouse.png
ADDED
stable_diffusion/assets/fire.png
ADDED
stable_diffusion/assets/inpainting.png
ADDED
stable_diffusion/assets/modelfigure.png
ADDED
stable_diffusion/assets/rdm-preview.jpg
ADDED
stable_diffusion/assets/reconstruction1.png
ADDED
stable_diffusion/assets/reconstruction2.png
ADDED
stable_diffusion/assets/results.gif.REMOVED.git-id
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
82b6590e670a32196093cc6333ea19e6547d07de
|
stable_diffusion/assets/rick.jpeg
ADDED
stable_diffusion/assets/stable-samples/img2img/mountains-1.png
ADDED
stable_diffusion/assets/stable-samples/img2img/mountains-2.png
ADDED
stable_diffusion/assets/stable-samples/img2img/mountains-3.png
ADDED
stable_diffusion/assets/stable-samples/img2img/sketch-mountains-input.jpg
ADDED
stable_diffusion/assets/stable-samples/img2img/upscaling-in.png.REMOVED.git-id
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
501c31c21751664957e69ce52cad1818b6d2f4ce
|
stable_diffusion/assets/stable-samples/img2img/upscaling-out.png.REMOVED.git-id
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
1c4bb25a779f34d86b2d90e584ac67af91bb1303
|
stable_diffusion/assets/stable-samples/txt2img/000002025.png
ADDED
stable_diffusion/assets/stable-samples/txt2img/000002035.png
ADDED
stable_diffusion/assets/stable-samples/txt2img/merged-0005.png.REMOVED.git-id
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
ca0a1af206555f0f208a1ab879e95efedc1b1c5b
|
stable_diffusion/assets/stable-samples/txt2img/merged-0006.png.REMOVED.git-id
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
999f3703230580e8c89e9081abd6a1f8f50896d4
|