Text-to-Image
Diffusers
stable-diffusion
kyan0045 commited on
Commit
a75c825
1 Parent(s): ce27d42

Upload 7 files

Browse files
Files changed (7) hide show
  1. LICENSE +82 -0
  2. README.md +15 -3
  3. Stable_Diffusion_v1_Model_Card.md +144 -0
  4. environment.yaml +31 -0
  5. main.py +741 -0
  6. notebook_helpers.py +270 -0
  7. setup.py +13 -0
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).
README.md CHANGED
@@ -1,3 +1,15 @@
1
- ---
2
- license: openrail
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stable Diffusion without the safety/NSFW filter and watermarking!
2
+
3
+ This is a fork of Stable Diffusion that disables the horribly inaccurate NSFW filter and unnecessary watermarking. The goal of this is three-fold:
4
+
5
+ 1. Saves precious time from images that get mistakenly censored, especially if you run this on a Colab notebook.
6
+ 2. Saves GPU memory by not loading the safety models, allowing for some more headroom on GPUs with smaller VRAM.
7
+ 3. Reverts the state of the Stable Diffusion scripts to the closed beta, when these weren't implemented yet.
8
+
9
+ Additionally, removing the watermark might reduce some quality loss or artifacts while using the software to generate images, although this is yet to be fully tested.
10
+
11
+ You can use this in the exact same way as the [original Stable Diffusion](https://github.com/CompVis/stable-diffusion) does.
12
+
13
+ For use in Colab notebooks that rely on the original Stable Diffusion, simply replace all instances linking to `!git clone https://github.com/CompVis/stable-diffusion.git` with `!git clone https://github.com/chemistzombie/stable-diffusion-unfiltered.git`
14
+
15
+ Disclaimer: I don't encourage or condone people to breach the [CreativeML Open RAIL-M license](https://huggingface.co/spaces/CompVis/stable-diffusion-license) used by Stable Diffusion. This repo is solely intended to address the issues with false positives that frequently occur while using the software, as well as improving usability on GPUs with smaller VRAM.
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).*
environment.yaml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: ldm
2
+ channels:
3
+ - pytorch
4
+ - defaults
5
+ dependencies:
6
+ - python=3.8.5
7
+ - pip=20.3
8
+ - cudatoolkit=11.3
9
+ - pytorch=1.11.0
10
+ - torchvision=0.12.0
11
+ - numpy=1.19.2
12
+ - pip:
13
+ - albumentations==0.4.3
14
+ - diffusers
15
+ - opencv-python==4.1.2.30
16
+ - pudb==2019.2
17
+ - invisible-watermark
18
+ - imageio==2.9.0
19
+ - imageio-ffmpeg==0.4.2
20
+ - pytorch-lightning==1.4.2
21
+ - omegaconf==2.1.1
22
+ - test-tube>=0.7.5
23
+ - streamlit>=0.73.1
24
+ - einops==0.3.0
25
+ - torch-fidelity==0.3.0
26
+ - transformers==4.19.2
27
+ - torchmetrics==0.6.0
28
+ - kornia==0.6
29
+ - -e git+https://github.com/CompVis/taming-transformers.git@master#egg=taming-transformers
30
+ - -e git+https://github.com/openai/CLIP.git@main#egg=clip
31
+ - -e .
main.py ADDED
@@ -0,0 +1,741 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse, os, sys, datetime, glob, importlib, csv
2
+ import numpy as np
3
+ import time
4
+ import torch
5
+ import torchvision
6
+ import pytorch_lightning as pl
7
+
8
+ from packaging import version
9
+ from omegaconf import OmegaConf
10
+ from torch.utils.data import random_split, DataLoader, Dataset, Subset
11
+ from functools import partial
12
+ from PIL import Image
13
+
14
+ from pytorch_lightning import seed_everything
15
+ from pytorch_lightning.trainer import Trainer
16
+ from pytorch_lightning.callbacks import ModelCheckpoint, Callback, LearningRateMonitor
17
+ from pytorch_lightning.utilities.distributed import rank_zero_only
18
+ from pytorch_lightning.utilities import rank_zero_info
19
+
20
+ from ldm.data.base import Txt2ImgIterableBaseDataset
21
+ from ldm.util import instantiate_from_config
22
+
23
+
24
+ def get_parser(**parser_kwargs):
25
+ def str2bool(v):
26
+ if isinstance(v, bool):
27
+ return v
28
+ if v.lower() in ("yes", "true", "t", "y", "1"):
29
+ return True
30
+ elif v.lower() in ("no", "false", "f", "n", "0"):
31
+ return False
32
+ else:
33
+ raise argparse.ArgumentTypeError("Boolean value expected.")
34
+
35
+ parser = argparse.ArgumentParser(**parser_kwargs)
36
+ parser.add_argument(
37
+ "-n",
38
+ "--name",
39
+ type=str,
40
+ const=True,
41
+ default="",
42
+ nargs="?",
43
+ help="postfix for logdir",
44
+ )
45
+ parser.add_argument(
46
+ "-r",
47
+ "--resume",
48
+ type=str,
49
+ const=True,
50
+ default="",
51
+ nargs="?",
52
+ help="resume from logdir or checkpoint in logdir",
53
+ )
54
+ parser.add_argument(
55
+ "-b",
56
+ "--base",
57
+ nargs="*",
58
+ metavar="base_config.yaml",
59
+ help="paths to base configs. Loaded from left-to-right. "
60
+ "Parameters can be overwritten or added with command-line options of the form `--key value`.",
61
+ default=list(),
62
+ )
63
+ parser.add_argument(
64
+ "-t",
65
+ "--train",
66
+ type=str2bool,
67
+ const=True,
68
+ default=False,
69
+ nargs="?",
70
+ help="train",
71
+ )
72
+ parser.add_argument(
73
+ "--no-test",
74
+ type=str2bool,
75
+ const=True,
76
+ default=False,
77
+ nargs="?",
78
+ help="disable test",
79
+ )
80
+ parser.add_argument(
81
+ "-p",
82
+ "--project",
83
+ help="name of new or path to existing project"
84
+ )
85
+ parser.add_argument(
86
+ "-d",
87
+ "--debug",
88
+ type=str2bool,
89
+ nargs="?",
90
+ const=True,
91
+ default=False,
92
+ help="enable post-mortem debugging",
93
+ )
94
+ parser.add_argument(
95
+ "-s",
96
+ "--seed",
97
+ type=int,
98
+ default=23,
99
+ help="seed for seed_everything",
100
+ )
101
+ parser.add_argument(
102
+ "-f",
103
+ "--postfix",
104
+ type=str,
105
+ default="",
106
+ help="post-postfix for default name",
107
+ )
108
+ parser.add_argument(
109
+ "-l",
110
+ "--logdir",
111
+ type=str,
112
+ default="logs",
113
+ help="directory for logging dat shit",
114
+ )
115
+ parser.add_argument(
116
+ "--scale_lr",
117
+ type=str2bool,
118
+ nargs="?",
119
+ const=True,
120
+ default=True,
121
+ help="scale base-lr by ngpu * batch_size * n_accumulate",
122
+ )
123
+ return parser
124
+
125
+
126
+ def nondefault_trainer_args(opt):
127
+ parser = argparse.ArgumentParser()
128
+ parser = Trainer.add_argparse_args(parser)
129
+ args = parser.parse_args([])
130
+ return sorted(k for k in vars(args) if getattr(opt, k) != getattr(args, k))
131
+
132
+
133
+ class WrappedDataset(Dataset):
134
+ """Wraps an arbitrary object with __len__ and __getitem__ into a pytorch dataset"""
135
+
136
+ def __init__(self, dataset):
137
+ self.data = dataset
138
+
139
+ def __len__(self):
140
+ return len(self.data)
141
+
142
+ def __getitem__(self, idx):
143
+ return self.data[idx]
144
+
145
+
146
+ def worker_init_fn(_):
147
+ worker_info = torch.utils.data.get_worker_info()
148
+
149
+ dataset = worker_info.dataset
150
+ worker_id = worker_info.id
151
+
152
+ if isinstance(dataset, Txt2ImgIterableBaseDataset):
153
+ split_size = dataset.num_records // worker_info.num_workers
154
+ # reset num_records to the true number to retain reliable length information
155
+ dataset.sample_ids = dataset.valid_ids[worker_id * split_size:(worker_id + 1) * split_size]
156
+ current_id = np.random.choice(len(np.random.get_state()[1]), 1)
157
+ return np.random.seed(np.random.get_state()[1][current_id] + worker_id)
158
+ else:
159
+ return np.random.seed(np.random.get_state()[1][0] + worker_id)
160
+
161
+
162
+ class DataModuleFromConfig(pl.LightningDataModule):
163
+ def __init__(self, batch_size, train=None, validation=None, test=None, predict=None,
164
+ wrap=False, num_workers=None, shuffle_test_loader=False, use_worker_init_fn=False,
165
+ shuffle_val_dataloader=False):
166
+ super().__init__()
167
+ self.batch_size = batch_size
168
+ self.dataset_configs = dict()
169
+ self.num_workers = num_workers if num_workers is not None else batch_size * 2
170
+ self.use_worker_init_fn = use_worker_init_fn
171
+ if train is not None:
172
+ self.dataset_configs["train"] = train
173
+ self.train_dataloader = self._train_dataloader
174
+ if validation is not None:
175
+ self.dataset_configs["validation"] = validation
176
+ self.val_dataloader = partial(self._val_dataloader, shuffle=shuffle_val_dataloader)
177
+ if test is not None:
178
+ self.dataset_configs["test"] = test
179
+ self.test_dataloader = partial(self._test_dataloader, shuffle=shuffle_test_loader)
180
+ if predict is not None:
181
+ self.dataset_configs["predict"] = predict
182
+ self.predict_dataloader = self._predict_dataloader
183
+ self.wrap = wrap
184
+
185
+ def prepare_data(self):
186
+ for data_cfg in self.dataset_configs.values():
187
+ instantiate_from_config(data_cfg)
188
+
189
+ def setup(self, stage=None):
190
+ self.datasets = dict(
191
+ (k, instantiate_from_config(self.dataset_configs[k]))
192
+ for k in self.dataset_configs)
193
+ if self.wrap:
194
+ for k in self.datasets:
195
+ self.datasets[k] = WrappedDataset(self.datasets[k])
196
+
197
+ def _train_dataloader(self):
198
+ is_iterable_dataset = isinstance(self.datasets['train'], Txt2ImgIterableBaseDataset)
199
+ if is_iterable_dataset or self.use_worker_init_fn:
200
+ init_fn = worker_init_fn
201
+ else:
202
+ init_fn = None
203
+ return DataLoader(self.datasets["train"], batch_size=self.batch_size,
204
+ num_workers=self.num_workers, shuffle=False if is_iterable_dataset else True,
205
+ worker_init_fn=init_fn)
206
+
207
+ def _val_dataloader(self, shuffle=False):
208
+ if isinstance(self.datasets['validation'], Txt2ImgIterableBaseDataset) or self.use_worker_init_fn:
209
+ init_fn = worker_init_fn
210
+ else:
211
+ init_fn = None
212
+ return DataLoader(self.datasets["validation"],
213
+ batch_size=self.batch_size,
214
+ num_workers=self.num_workers,
215
+ worker_init_fn=init_fn,
216
+ shuffle=shuffle)
217
+
218
+ def _test_dataloader(self, shuffle=False):
219
+ is_iterable_dataset = isinstance(self.datasets['train'], Txt2ImgIterableBaseDataset)
220
+ if is_iterable_dataset or self.use_worker_init_fn:
221
+ init_fn = worker_init_fn
222
+ else:
223
+ init_fn = None
224
+
225
+ # do not shuffle dataloader for iterable dataset
226
+ shuffle = shuffle and (not is_iterable_dataset)
227
+
228
+ return DataLoader(self.datasets["test"], batch_size=self.batch_size,
229
+ num_workers=self.num_workers, worker_init_fn=init_fn, shuffle=shuffle)
230
+
231
+ def _predict_dataloader(self, shuffle=False):
232
+ if isinstance(self.datasets['predict'], Txt2ImgIterableBaseDataset) or self.use_worker_init_fn:
233
+ init_fn = worker_init_fn
234
+ else:
235
+ init_fn = None
236
+ return DataLoader(self.datasets["predict"], batch_size=self.batch_size,
237
+ num_workers=self.num_workers, worker_init_fn=init_fn)
238
+
239
+
240
+ class SetupCallback(Callback):
241
+ def __init__(self, resume, now, logdir, ckptdir, cfgdir, config, lightning_config):
242
+ super().__init__()
243
+ self.resume = resume
244
+ self.now = now
245
+ self.logdir = logdir
246
+ self.ckptdir = ckptdir
247
+ self.cfgdir = cfgdir
248
+ self.config = config
249
+ self.lightning_config = lightning_config
250
+
251
+ def on_keyboard_interrupt(self, trainer, pl_module):
252
+ if trainer.global_rank == 0:
253
+ print("Summoning checkpoint.")
254
+ ckpt_path = os.path.join(self.ckptdir, "last.ckpt")
255
+ trainer.save_checkpoint(ckpt_path)
256
+
257
+ def on_pretrain_routine_start(self, trainer, pl_module):
258
+ if trainer.global_rank == 0:
259
+ # Create logdirs and save configs
260
+ os.makedirs(self.logdir, exist_ok=True)
261
+ os.makedirs(self.ckptdir, exist_ok=True)
262
+ os.makedirs(self.cfgdir, exist_ok=True)
263
+
264
+ if "callbacks" in self.lightning_config:
265
+ if 'metrics_over_trainsteps_checkpoint' in self.lightning_config['callbacks']:
266
+ os.makedirs(os.path.join(self.ckptdir, 'trainstep_checkpoints'), exist_ok=True)
267
+ print("Project config")
268
+ print(OmegaConf.to_yaml(self.config))
269
+ OmegaConf.save(self.config,
270
+ os.path.join(self.cfgdir, "{}-project.yaml".format(self.now)))
271
+
272
+ print("Lightning config")
273
+ print(OmegaConf.to_yaml(self.lightning_config))
274
+ OmegaConf.save(OmegaConf.create({"lightning": self.lightning_config}),
275
+ os.path.join(self.cfgdir, "{}-lightning.yaml".format(self.now)))
276
+
277
+ else:
278
+ # ModelCheckpoint callback created log directory --- remove it
279
+ if not self.resume and os.path.exists(self.logdir):
280
+ dst, name = os.path.split(self.logdir)
281
+ dst = os.path.join(dst, "child_runs", name)
282
+ os.makedirs(os.path.split(dst)[0], exist_ok=True)
283
+ try:
284
+ os.rename(self.logdir, dst)
285
+ except FileNotFoundError:
286
+ pass
287
+
288
+
289
+ class ImageLogger(Callback):
290
+ def __init__(self, batch_frequency, max_images, clamp=True, increase_log_steps=True,
291
+ rescale=True, disabled=False, log_on_batch_idx=False, log_first_step=False,
292
+ log_images_kwargs=None):
293
+ super().__init__()
294
+ self.rescale = rescale
295
+ self.batch_freq = batch_frequency
296
+ self.max_images = max_images
297
+ self.logger_log_images = {
298
+ pl.loggers.TestTubeLogger: self._testtube,
299
+ }
300
+ self.log_steps = [2 ** n for n in range(int(np.log2(self.batch_freq)) + 1)]
301
+ if not increase_log_steps:
302
+ self.log_steps = [self.batch_freq]
303
+ self.clamp = clamp
304
+ self.disabled = disabled
305
+ self.log_on_batch_idx = log_on_batch_idx
306
+ self.log_images_kwargs = log_images_kwargs if log_images_kwargs else {}
307
+ self.log_first_step = log_first_step
308
+
309
+ @rank_zero_only
310
+ def _testtube(self, pl_module, images, batch_idx, split):
311
+ for k in images:
312
+ grid = torchvision.utils.make_grid(images[k])
313
+ grid = (grid + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w
314
+
315
+ tag = f"{split}/{k}"
316
+ pl_module.logger.experiment.add_image(
317
+ tag, grid,
318
+ global_step=pl_module.global_step)
319
+
320
+ @rank_zero_only
321
+ def log_local(self, save_dir, split, images,
322
+ global_step, current_epoch, batch_idx):
323
+ root = os.path.join(save_dir, "images", split)
324
+ for k in images:
325
+ grid = torchvision.utils.make_grid(images[k], nrow=4)
326
+ if self.rescale:
327
+ grid = (grid + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w
328
+ grid = grid.transpose(0, 1).transpose(1, 2).squeeze(-1)
329
+ grid = grid.numpy()
330
+ grid = (grid * 255).astype(np.uint8)
331
+ filename = "{}_gs-{:06}_e-{:06}_b-{:06}.png".format(
332
+ k,
333
+ global_step,
334
+ current_epoch,
335
+ batch_idx)
336
+ path = os.path.join(root, filename)
337
+ os.makedirs(os.path.split(path)[0], exist_ok=True)
338
+ Image.fromarray(grid).save(path)
339
+
340
+ def log_img(self, pl_module, batch, batch_idx, split="train"):
341
+ check_idx = batch_idx if self.log_on_batch_idx else pl_module.global_step
342
+ if (self.check_frequency(check_idx) and # batch_idx % self.batch_freq == 0
343
+ hasattr(pl_module, "log_images") and
344
+ callable(pl_module.log_images) and
345
+ self.max_images > 0):
346
+ logger = type(pl_module.logger)
347
+
348
+ is_train = pl_module.training
349
+ if is_train:
350
+ pl_module.eval()
351
+
352
+ with torch.no_grad():
353
+ images = pl_module.log_images(batch, split=split, **self.log_images_kwargs)
354
+
355
+ for k in images:
356
+ N = min(images[k].shape[0], self.max_images)
357
+ images[k] = images[k][:N]
358
+ if isinstance(images[k], torch.Tensor):
359
+ images[k] = images[k].detach().cpu()
360
+ if self.clamp:
361
+ images[k] = torch.clamp(images[k], -1., 1.)
362
+
363
+ self.log_local(pl_module.logger.save_dir, split, images,
364
+ pl_module.global_step, pl_module.current_epoch, batch_idx)
365
+
366
+ logger_log_images = self.logger_log_images.get(logger, lambda *args, **kwargs: None)
367
+ logger_log_images(pl_module, images, pl_module.global_step, split)
368
+
369
+ if is_train:
370
+ pl_module.train()
371
+
372
+ def check_frequency(self, check_idx):
373
+ if ((check_idx % self.batch_freq) == 0 or (check_idx in self.log_steps)) and (
374
+ check_idx > 0 or self.log_first_step):
375
+ try:
376
+ self.log_steps.pop(0)
377
+ except IndexError as e:
378
+ print(e)
379
+ pass
380
+ return True
381
+ return False
382
+
383
+ def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
384
+ if not self.disabled and (pl_module.global_step > 0 or self.log_first_step):
385
+ self.log_img(pl_module, batch, batch_idx, split="train")
386
+
387
+ def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
388
+ if not self.disabled and pl_module.global_step > 0:
389
+ self.log_img(pl_module, batch, batch_idx, split="val")
390
+ if hasattr(pl_module, 'calibrate_grad_norm'):
391
+ if (pl_module.calibrate_grad_norm and batch_idx % 25 == 0) and batch_idx > 0:
392
+ self.log_gradients(trainer, pl_module, batch_idx=batch_idx)
393
+
394
+
395
+ class CUDACallback(Callback):
396
+ # see https://github.com/SeanNaren/minGPT/blob/master/mingpt/callback.py
397
+ def on_train_epoch_start(self, trainer, pl_module):
398
+ # Reset the memory use counter
399
+ torch.cuda.reset_peak_memory_stats(trainer.root_gpu)
400
+ torch.cuda.synchronize(trainer.root_gpu)
401
+ self.start_time = time.time()
402
+
403
+ def on_train_epoch_end(self, trainer, pl_module, outputs):
404
+ torch.cuda.synchronize(trainer.root_gpu)
405
+ max_memory = torch.cuda.max_memory_allocated(trainer.root_gpu) / 2 ** 20
406
+ epoch_time = time.time() - self.start_time
407
+
408
+ try:
409
+ max_memory = trainer.training_type_plugin.reduce(max_memory)
410
+ epoch_time = trainer.training_type_plugin.reduce(epoch_time)
411
+
412
+ rank_zero_info(f"Average Epoch time: {epoch_time:.2f} seconds")
413
+ rank_zero_info(f"Average Peak memory {max_memory:.2f}MiB")
414
+ except AttributeError:
415
+ pass
416
+
417
+
418
+ if __name__ == "__main__":
419
+ # custom parser to specify config files, train, test and debug mode,
420
+ # postfix, resume.
421
+ # `--key value` arguments are interpreted as arguments to the trainer.
422
+ # `nested.key=value` arguments are interpreted as config parameters.
423
+ # configs are merged from left-to-right followed by command line parameters.
424
+
425
+ # model:
426
+ # base_learning_rate: float
427
+ # target: path to lightning module
428
+ # params:
429
+ # key: value
430
+ # data:
431
+ # target: main.DataModuleFromConfig
432
+ # params:
433
+ # batch_size: int
434
+ # wrap: bool
435
+ # train:
436
+ # target: path to train dataset
437
+ # params:
438
+ # key: value
439
+ # validation:
440
+ # target: path to validation dataset
441
+ # params:
442
+ # key: value
443
+ # test:
444
+ # target: path to test dataset
445
+ # params:
446
+ # key: value
447
+ # lightning: (optional, has sane defaults and can be specified on cmdline)
448
+ # trainer:
449
+ # additional arguments to trainer
450
+ # logger:
451
+ # logger to instantiate
452
+ # modelcheckpoint:
453
+ # modelcheckpoint to instantiate
454
+ # callbacks:
455
+ # callback1:
456
+ # target: importpath
457
+ # params:
458
+ # key: value
459
+
460
+ now = datetime.datetime.now().strftime("%Y-%m-%dT%H-%M-%S")
461
+
462
+ # add cwd for convenience and to make classes in this file available when
463
+ # running as `python main.py`
464
+ # (in particular `main.DataModuleFromConfig`)
465
+ sys.path.append(os.getcwd())
466
+
467
+ parser = get_parser()
468
+ parser = Trainer.add_argparse_args(parser)
469
+
470
+ opt, unknown = parser.parse_known_args()
471
+ if opt.name and opt.resume:
472
+ raise ValueError(
473
+ "-n/--name and -r/--resume cannot be specified both."
474
+ "If you want to resume training in a new log folder, "
475
+ "use -n/--name in combination with --resume_from_checkpoint"
476
+ )
477
+ if opt.resume:
478
+ if not os.path.exists(opt.resume):
479
+ raise ValueError("Cannot find {}".format(opt.resume))
480
+ if os.path.isfile(opt.resume):
481
+ paths = opt.resume.split("/")
482
+ # idx = len(paths)-paths[::-1].index("logs")+1
483
+ # logdir = "/".join(paths[:idx])
484
+ logdir = "/".join(paths[:-2])
485
+ ckpt = opt.resume
486
+ else:
487
+ assert os.path.isdir(opt.resume), opt.resume
488
+ logdir = opt.resume.rstrip("/")
489
+ ckpt = os.path.join(logdir, "checkpoints", "last.ckpt")
490
+
491
+ opt.resume_from_checkpoint = ckpt
492
+ base_configs = sorted(glob.glob(os.path.join(logdir, "configs/*.yaml")))
493
+ opt.base = base_configs + opt.base
494
+ _tmp = logdir.split("/")
495
+ nowname = _tmp[-1]
496
+ else:
497
+ if opt.name:
498
+ name = "_" + opt.name
499
+ elif opt.base:
500
+ cfg_fname = os.path.split(opt.base[0])[-1]
501
+ cfg_name = os.path.splitext(cfg_fname)[0]
502
+ name = "_" + cfg_name
503
+ else:
504
+ name = ""
505
+ nowname = now + name + opt.postfix
506
+ logdir = os.path.join(opt.logdir, nowname)
507
+
508
+ ckptdir = os.path.join(logdir, "checkpoints")
509
+ cfgdir = os.path.join(logdir, "configs")
510
+ seed_everything(opt.seed)
511
+
512
+ try:
513
+ # init and save configs
514
+ configs = [OmegaConf.load(cfg) for cfg in opt.base]
515
+ cli = OmegaConf.from_dotlist(unknown)
516
+ config = OmegaConf.merge(*configs, cli)
517
+ lightning_config = config.pop("lightning", OmegaConf.create())
518
+ # merge trainer cli with config
519
+ trainer_config = lightning_config.get("trainer", OmegaConf.create())
520
+ # default to ddp
521
+ trainer_config["accelerator"] = "ddp"
522
+ for k in nondefault_trainer_args(opt):
523
+ trainer_config[k] = getattr(opt, k)
524
+ if not "gpus" in trainer_config:
525
+ del trainer_config["accelerator"]
526
+ cpu = True
527
+ else:
528
+ gpuinfo = trainer_config["gpus"]
529
+ print(f"Running on GPUs {gpuinfo}")
530
+ cpu = False
531
+ trainer_opt = argparse.Namespace(**trainer_config)
532
+ lightning_config.trainer = trainer_config
533
+
534
+ # model
535
+ model = instantiate_from_config(config.model)
536
+
537
+ # trainer and callbacks
538
+ trainer_kwargs = dict()
539
+
540
+ # default logger configs
541
+ default_logger_cfgs = {
542
+ "wandb": {
543
+ "target": "pytorch_lightning.loggers.WandbLogger",
544
+ "params": {
545
+ "name": nowname,
546
+ "save_dir": logdir,
547
+ "offline": opt.debug,
548
+ "id": nowname,
549
+ }
550
+ },
551
+ "testtube": {
552
+ "target": "pytorch_lightning.loggers.TestTubeLogger",
553
+ "params": {
554
+ "name": "testtube",
555
+ "save_dir": logdir,
556
+ }
557
+ },
558
+ }
559
+ default_logger_cfg = default_logger_cfgs["testtube"]
560
+ if "logger" in lightning_config:
561
+ logger_cfg = lightning_config.logger
562
+ else:
563
+ logger_cfg = OmegaConf.create()
564
+ logger_cfg = OmegaConf.merge(default_logger_cfg, logger_cfg)
565
+ trainer_kwargs["logger"] = instantiate_from_config(logger_cfg)
566
+
567
+ # modelcheckpoint - use TrainResult/EvalResult(checkpoint_on=metric) to
568
+ # specify which metric is used to determine best models
569
+ default_modelckpt_cfg = {
570
+ "target": "pytorch_lightning.callbacks.ModelCheckpoint",
571
+ "params": {
572
+ "dirpath": ckptdir,
573
+ "filename": "{epoch:06}",
574
+ "verbose": True,
575
+ "save_last": True,
576
+ }
577
+ }
578
+ if hasattr(model, "monitor"):
579
+ print(f"Monitoring {model.monitor} as checkpoint metric.")
580
+ default_modelckpt_cfg["params"]["monitor"] = model.monitor
581
+ default_modelckpt_cfg["params"]["save_top_k"] = 3
582
+
583
+ if "modelcheckpoint" in lightning_config:
584
+ modelckpt_cfg = lightning_config.modelcheckpoint
585
+ else:
586
+ modelckpt_cfg = OmegaConf.create()
587
+ modelckpt_cfg = OmegaConf.merge(default_modelckpt_cfg, modelckpt_cfg)
588
+ print(f"Merged modelckpt-cfg: \n{modelckpt_cfg}")
589
+ if version.parse(pl.__version__) < version.parse('1.4.0'):
590
+ trainer_kwargs["checkpoint_callback"] = instantiate_from_config(modelckpt_cfg)
591
+
592
+ # add callback which sets up log directory
593
+ default_callbacks_cfg = {
594
+ "setup_callback": {
595
+ "target": "main.SetupCallback",
596
+ "params": {
597
+ "resume": opt.resume,
598
+ "now": now,
599
+ "logdir": logdir,
600
+ "ckptdir": ckptdir,
601
+ "cfgdir": cfgdir,
602
+ "config": config,
603
+ "lightning_config": lightning_config,
604
+ }
605
+ },
606
+ "image_logger": {
607
+ "target": "main.ImageLogger",
608
+ "params": {
609
+ "batch_frequency": 750,
610
+ "max_images": 4,
611
+ "clamp": True
612
+ }
613
+ },
614
+ "learning_rate_logger": {
615
+ "target": "main.LearningRateMonitor",
616
+ "params": {
617
+ "logging_interval": "step",
618
+ # "log_momentum": True
619
+ }
620
+ },
621
+ "cuda_callback": {
622
+ "target": "main.CUDACallback"
623
+ },
624
+ }
625
+ if version.parse(pl.__version__) >= version.parse('1.4.0'):
626
+ default_callbacks_cfg.update({'checkpoint_callback': modelckpt_cfg})
627
+
628
+ if "callbacks" in lightning_config:
629
+ callbacks_cfg = lightning_config.callbacks
630
+ else:
631
+ callbacks_cfg = OmegaConf.create()
632
+
633
+ if 'metrics_over_trainsteps_checkpoint' in callbacks_cfg:
634
+ print(
635
+ 'Caution: Saving checkpoints every n train steps without deleting. This might require some free space.')
636
+ default_metrics_over_trainsteps_ckpt_dict = {
637
+ 'metrics_over_trainsteps_checkpoint':
638
+ {"target": 'pytorch_lightning.callbacks.ModelCheckpoint',
639
+ 'params': {
640
+ "dirpath": os.path.join(ckptdir, 'trainstep_checkpoints'),
641
+ "filename": "{epoch:06}-{step:09}",
642
+ "verbose": True,
643
+ 'save_top_k': -1,
644
+ 'every_n_train_steps': 10000,
645
+ 'save_weights_only': True
646
+ }
647
+ }
648
+ }
649
+ default_callbacks_cfg.update(default_metrics_over_trainsteps_ckpt_dict)
650
+
651
+ callbacks_cfg = OmegaConf.merge(default_callbacks_cfg, callbacks_cfg)
652
+ if 'ignore_keys_callback' in callbacks_cfg and hasattr(trainer_opt, 'resume_from_checkpoint'):
653
+ callbacks_cfg.ignore_keys_callback.params['ckpt_path'] = trainer_opt.resume_from_checkpoint
654
+ elif 'ignore_keys_callback' in callbacks_cfg:
655
+ del callbacks_cfg['ignore_keys_callback']
656
+
657
+ trainer_kwargs["callbacks"] = [instantiate_from_config(callbacks_cfg[k]) for k in callbacks_cfg]
658
+
659
+ trainer = Trainer.from_argparse_args(trainer_opt, **trainer_kwargs)
660
+ trainer.logdir = logdir ###
661
+
662
+ # data
663
+ data = instantiate_from_config(config.data)
664
+ # NOTE according to https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html
665
+ # calling these ourselves should not be necessary but it is.
666
+ # lightning still takes care of proper multiprocessing though
667
+ data.prepare_data()
668
+ data.setup()
669
+ print("#### Data #####")
670
+ for k in data.datasets:
671
+ print(f"{k}, {data.datasets[k].__class__.__name__}, {len(data.datasets[k])}")
672
+
673
+ # configure learning rate
674
+ bs, base_lr = config.data.params.batch_size, config.model.base_learning_rate
675
+ if not cpu:
676
+ ngpu = len(lightning_config.trainer.gpus.strip(",").split(','))
677
+ else:
678
+ ngpu = 1
679
+ if 'accumulate_grad_batches' in lightning_config.trainer:
680
+ accumulate_grad_batches = lightning_config.trainer.accumulate_grad_batches
681
+ else:
682
+ accumulate_grad_batches = 1
683
+ print(f"accumulate_grad_batches = {accumulate_grad_batches}")
684
+ lightning_config.trainer.accumulate_grad_batches = accumulate_grad_batches
685
+ if opt.scale_lr:
686
+ model.learning_rate = accumulate_grad_batches * ngpu * bs * base_lr
687
+ print(
688
+ "Setting learning rate to {:.2e} = {} (accumulate_grad_batches) * {} (num_gpus) * {} (batchsize) * {:.2e} (base_lr)".format(
689
+ model.learning_rate, accumulate_grad_batches, ngpu, bs, base_lr))
690
+ else:
691
+ model.learning_rate = base_lr
692
+ print("++++ NOT USING LR SCALING ++++")
693
+ print(f"Setting learning rate to {model.learning_rate:.2e}")
694
+
695
+
696
+ # allow checkpointing via USR1
697
+ def melk(*args, **kwargs):
698
+ # run all checkpoint hooks
699
+ if trainer.global_rank == 0:
700
+ print("Summoning checkpoint.")
701
+ ckpt_path = os.path.join(ckptdir, "last.ckpt")
702
+ trainer.save_checkpoint(ckpt_path)
703
+
704
+
705
+ def divein(*args, **kwargs):
706
+ if trainer.global_rank == 0:
707
+ import pudb;
708
+ pudb.set_trace()
709
+
710
+
711
+ import signal
712
+
713
+ signal.signal(signal.SIGUSR1, melk)
714
+ signal.signal(signal.SIGUSR2, divein)
715
+
716
+ # run
717
+ if opt.train:
718
+ try:
719
+ trainer.fit(model, data)
720
+ except Exception:
721
+ melk()
722
+ raise
723
+ if not opt.no_test and not trainer.interrupted:
724
+ trainer.test(model, data)
725
+ except Exception:
726
+ if opt.debug and trainer.global_rank == 0:
727
+ try:
728
+ import pudb as debugger
729
+ except ImportError:
730
+ import pdb as debugger
731
+ debugger.post_mortem()
732
+ raise
733
+ finally:
734
+ # move newly created debug project to debug_runs
735
+ if opt.debug and not opt.resume and trainer.global_rank == 0:
736
+ dst, name = os.path.split(logdir)
737
+ dst = os.path.join(dst, "debug_runs", name)
738
+ os.makedirs(os.path.split(dst)[0], exist_ok=True)
739
+ os.rename(logdir, dst)
740
+ if trainer.global_rank == 0:
741
+ print(trainer.profiler.summary())
notebook_helpers.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torchvision.datasets.utils import download_url
2
+ from ldm.util import instantiate_from_config
3
+ import torch
4
+ import os
5
+ # todo ?
6
+ from google.colab import files
7
+ from IPython.display import Image as ipyimg
8
+ import ipywidgets as widgets
9
+ from PIL import Image
10
+ from numpy import asarray
11
+ from einops import rearrange, repeat
12
+ import torch, torchvision
13
+ from ldm.models.diffusion.ddim import DDIMSampler
14
+ from ldm.util import ismap
15
+ import time
16
+ from omegaconf import OmegaConf
17
+
18
+
19
+ def download_models(mode):
20
+
21
+ if mode == "superresolution":
22
+ # this is the small bsr light model
23
+ url_conf = 'https://heibox.uni-heidelberg.de/f/31a76b13ea27482981b4/?dl=1'
24
+ url_ckpt = 'https://heibox.uni-heidelberg.de/f/578df07c8fc04ffbadf3/?dl=1'
25
+
26
+ path_conf = 'logs/diffusion/superresolution_bsr/configs/project.yaml'
27
+ path_ckpt = 'logs/diffusion/superresolution_bsr/checkpoints/last.ckpt'
28
+
29
+ download_url(url_conf, path_conf)
30
+ download_url(url_ckpt, path_ckpt)
31
+
32
+ path_conf = path_conf + '/?dl=1' # fix it
33
+ path_ckpt = path_ckpt + '/?dl=1' # fix it
34
+ return path_conf, path_ckpt
35
+
36
+ else:
37
+ raise NotImplementedError
38
+
39
+
40
+ def load_model_from_config(config, ckpt):
41
+ print(f"Loading model from {ckpt}")
42
+ pl_sd = torch.load(ckpt, map_location="cpu")
43
+ global_step = pl_sd["global_step"]
44
+ sd = pl_sd["state_dict"]
45
+ model = instantiate_from_config(config.model)
46
+ m, u = model.load_state_dict(sd, strict=False)
47
+ model.cuda()
48
+ model.eval()
49
+ return {"model": model}, global_step
50
+
51
+
52
+ def get_model(mode):
53
+ path_conf, path_ckpt = download_models(mode)
54
+ config = OmegaConf.load(path_conf)
55
+ model, step = load_model_from_config(config, path_ckpt)
56
+ return model
57
+
58
+
59
+ def get_custom_cond(mode):
60
+ dest = "data/example_conditioning"
61
+
62
+ if mode == "superresolution":
63
+ uploaded_img = files.upload()
64
+ filename = next(iter(uploaded_img))
65
+ name, filetype = filename.split(".") # todo assumes just one dot in name !
66
+ os.rename(f"{filename}", f"{dest}/{mode}/custom_{name}.{filetype}")
67
+
68
+ elif mode == "text_conditional":
69
+ w = widgets.Text(value='A cake with cream!', disabled=True)
70
+ display(w)
71
+
72
+ with open(f"{dest}/{mode}/custom_{w.value[:20]}.txt", 'w') as f:
73
+ f.write(w.value)
74
+
75
+ elif mode == "class_conditional":
76
+ w = widgets.IntSlider(min=0, max=1000)
77
+ display(w)
78
+ with open(f"{dest}/{mode}/custom.txt", 'w') as f:
79
+ f.write(w.value)
80
+
81
+ else:
82
+ raise NotImplementedError(f"cond not implemented for mode{mode}")
83
+
84
+
85
+ def get_cond_options(mode):
86
+ path = "data/example_conditioning"
87
+ path = os.path.join(path, mode)
88
+ onlyfiles = [f for f in sorted(os.listdir(path))]
89
+ return path, onlyfiles
90
+
91
+
92
+ def select_cond_path(mode):
93
+ path = "data/example_conditioning" # todo
94
+ path = os.path.join(path, mode)
95
+ onlyfiles = [f for f in sorted(os.listdir(path))]
96
+
97
+ selected = widgets.RadioButtons(
98
+ options=onlyfiles,
99
+ description='Select conditioning:',
100
+ disabled=False
101
+ )
102
+ display(selected)
103
+ selected_path = os.path.join(path, selected.value)
104
+ return selected_path
105
+
106
+
107
+ def get_cond(mode, selected_path):
108
+ example = dict()
109
+ if mode == "superresolution":
110
+ up_f = 4
111
+ visualize_cond_img(selected_path)
112
+
113
+ c = Image.open(selected_path)
114
+ c = torch.unsqueeze(torchvision.transforms.ToTensor()(c), 0)
115
+ c_up = torchvision.transforms.functional.resize(c, size=[up_f * c.shape[2], up_f * c.shape[3]], antialias=True)
116
+ c_up = rearrange(c_up, '1 c h w -> 1 h w c')
117
+ c = rearrange(c, '1 c h w -> 1 h w c')
118
+ c = 2. * c - 1.
119
+
120
+ c = c.to(torch.device("cuda"))
121
+ example["LR_image"] = c
122
+ example["image"] = c_up
123
+
124
+ return example
125
+
126
+
127
+ def visualize_cond_img(path):
128
+ display(ipyimg(filename=path))
129
+
130
+
131
+ def run(model, selected_path, task, custom_steps, resize_enabled=False, classifier_ckpt=None, global_step=None):
132
+
133
+ example = get_cond(task, selected_path)
134
+
135
+ save_intermediate_vid = False
136
+ n_runs = 1
137
+ masked = False
138
+ guider = None
139
+ ckwargs = None
140
+ mode = 'ddim'
141
+ ddim_use_x0_pred = False
142
+ temperature = 1.
143
+ eta = 1.
144
+ make_progrow = True
145
+ custom_shape = None
146
+
147
+ height, width = example["image"].shape[1:3]
148
+ split_input = height >= 128 and width >= 128
149
+
150
+ if split_input:
151
+ ks = 128
152
+ stride = 64
153
+ vqf = 4 #
154
+ model.split_input_params = {"ks": (ks, ks), "stride": (stride, stride),
155
+ "vqf": vqf,
156
+ "patch_distributed_vq": True,
157
+ "tie_braker": False,
158
+ "clip_max_weight": 0.5,
159
+ "clip_min_weight": 0.01,
160
+ "clip_max_tie_weight": 0.5,
161
+ "clip_min_tie_weight": 0.01}
162
+ else:
163
+ if hasattr(model, "split_input_params"):
164
+ delattr(model, "split_input_params")
165
+
166
+ invert_mask = False
167
+
168
+ x_T = None
169
+ for n in range(n_runs):
170
+ if custom_shape is not None:
171
+ x_T = torch.randn(1, custom_shape[1], custom_shape[2], custom_shape[3]).to(model.device)
172
+ x_T = repeat(x_T, '1 c h w -> b c h w', b=custom_shape[0])
173
+
174
+ logs = make_convolutional_sample(example, model,
175
+ mode=mode, custom_steps=custom_steps,
176
+ eta=eta, swap_mode=False , masked=masked,
177
+ invert_mask=invert_mask, quantize_x0=False,
178
+ custom_schedule=None, decode_interval=10,
179
+ resize_enabled=resize_enabled, custom_shape=custom_shape,
180
+ temperature=temperature, noise_dropout=0.,
181
+ corrector=guider, corrector_kwargs=ckwargs, x_T=x_T, save_intermediate_vid=save_intermediate_vid,
182
+ make_progrow=make_progrow,ddim_use_x0_pred=ddim_use_x0_pred
183
+ )
184
+ return logs
185
+
186
+
187
+ @torch.no_grad()
188
+ def convsample_ddim(model, cond, steps, shape, eta=1.0, callback=None, normals_sequence=None,
189
+ mask=None, x0=None, quantize_x0=False, img_callback=None,
190
+ temperature=1., noise_dropout=0., score_corrector=None,
191
+ corrector_kwargs=None, x_T=None, log_every_t=None
192
+ ):
193
+
194
+ ddim = DDIMSampler(model)
195
+ bs = shape[0] # dont know where this comes from but wayne
196
+ shape = shape[1:] # cut batch dim
197
+ print(f"Sampling with eta = {eta}; steps: {steps}")
198
+ samples, intermediates = ddim.sample(steps, batch_size=bs, shape=shape, conditioning=cond, callback=callback,
199
+ normals_sequence=normals_sequence, quantize_x0=quantize_x0, eta=eta,
200
+ mask=mask, x0=x0, temperature=temperature, verbose=False,
201
+ score_corrector=score_corrector,
202
+ corrector_kwargs=corrector_kwargs, x_T=x_T)
203
+
204
+ return samples, intermediates
205
+
206
+
207
+ @torch.no_grad()
208
+ def make_convolutional_sample(batch, model, mode="vanilla", custom_steps=None, eta=1.0, swap_mode=False, masked=False,
209
+ invert_mask=True, quantize_x0=False, custom_schedule=None, decode_interval=1000,
210
+ resize_enabled=False, custom_shape=None, temperature=1., noise_dropout=0., corrector=None,
211
+ corrector_kwargs=None, x_T=None, save_intermediate_vid=False, make_progrow=True,ddim_use_x0_pred=False):
212
+ log = dict()
213
+
214
+ z, c, x, xrec, xc = model.get_input(batch, model.first_stage_key,
215
+ return_first_stage_outputs=True,
216
+ force_c_encode=not (hasattr(model, 'split_input_params')
217
+ and model.cond_stage_key == 'coordinates_bbox'),
218
+ return_original_cond=True)
219
+
220
+ log_every_t = 1 if save_intermediate_vid else None
221
+
222
+ if custom_shape is not None:
223
+ z = torch.randn(custom_shape)
224
+ print(f"Generating {custom_shape[0]} samples of shape {custom_shape[1:]}")
225
+
226
+ z0 = None
227
+
228
+ log["input"] = x
229
+ log["reconstruction"] = xrec
230
+
231
+ if ismap(xc):
232
+ log["original_conditioning"] = model.to_rgb(xc)
233
+ if hasattr(model, 'cond_stage_key'):
234
+ log[model.cond_stage_key] = model.to_rgb(xc)
235
+
236
+ else:
237
+ log["original_conditioning"] = xc if xc is not None else torch.zeros_like(x)
238
+ if model.cond_stage_model:
239
+ log[model.cond_stage_key] = xc if xc is not None else torch.zeros_like(x)
240
+ if model.cond_stage_key =='class_label':
241
+ log[model.cond_stage_key] = xc[model.cond_stage_key]
242
+
243
+ with model.ema_scope("Plotting"):
244
+ t0 = time.time()
245
+ img_cb = None
246
+
247
+ sample, intermediates = convsample_ddim(model, c, steps=custom_steps, shape=z.shape,
248
+ eta=eta,
249
+ quantize_x0=quantize_x0, img_callback=img_cb, mask=None, x0=z0,
250
+ temperature=temperature, noise_dropout=noise_dropout,
251
+ score_corrector=corrector, corrector_kwargs=corrector_kwargs,
252
+ x_T=x_T, log_every_t=log_every_t)
253
+ t1 = time.time()
254
+
255
+ if ddim_use_x0_pred:
256
+ sample = intermediates['pred_x0'][-1]
257
+
258
+ x_sample = model.decode_first_stage(sample)
259
+
260
+ try:
261
+ x_sample_noquant = model.decode_first_stage(sample, force_not_quantize=True)
262
+ log["sample_noquant"] = x_sample_noquant
263
+ log["sample_diff"] = torch.abs(x_sample_noquant - x_sample)
264
+ except:
265
+ pass
266
+
267
+ log["sample"] = x_sample
268
+ log["time"] = t1 - t0
269
+
270
+ return log
setup.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name='latent-diffusion',
5
+ version='0.0.1',
6
+ description='',
7
+ packages=find_packages(),
8
+ install_requires=[
9
+ 'torch',
10
+ 'numpy',
11
+ 'tqdm',
12
+ ],
13
+ )