Anonymous-123 commited on
Commit
ec0fdfd
1 Parent(s): 4689172

Add application file

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. app.py +102 -0
  2. editing_diffusion/0 +0 -0
  3. editing_diffusion/CLIP/.github/workflows/test.yml +17 -0
  4. editing_diffusion/CLIP/.gitignore +10 -0
  5. editing_diffusion/CLIP/CLIP.png +0 -0
  6. editing_diffusion/CLIP/LICENSE +22 -0
  7. editing_diffusion/CLIP/MANIFEST.in +1 -0
  8. editing_diffusion/CLIP/README.md +193 -0
  9. editing_diffusion/CLIP/clip/__init__.py +1 -0
  10. editing_diffusion/CLIP/clip/bpe_simple_vocab_16e6.txt.gz +3 -0
  11. editing_diffusion/CLIP/clip/clip.py +225 -0
  12. editing_diffusion/CLIP/clip/model.py +432 -0
  13. editing_diffusion/CLIP/clip/simple_tokenizer.py +132 -0
  14. editing_diffusion/CLIP/data/yfcc100m.md +14 -0
  15. editing_diffusion/CLIP/model-card.md +120 -0
  16. editing_diffusion/CLIP/notebooks/Interacting_with_CLIP.ipynb +0 -0
  17. editing_diffusion/CLIP/notebooks/Prompt_Engineering_for_ImageNet.ipynb +1108 -0
  18. editing_diffusion/CLIP/requirements.txt +5 -0
  19. editing_diffusion/CLIP/setup.py +21 -0
  20. editing_diffusion/CLIP/tests/test_consistency.py +25 -0
  21. editing_diffusion/checkpoints/256x256_classifier.pt +3 -0
  22. editing_diffusion/checkpoints/256x256_diffusion_uncond.pt +3 -0
  23. editing_diffusion/guided_diffusion/.gitignore +3 -0
  24. editing_diffusion/guided_diffusion/LICENSE +21 -0
  25. editing_diffusion/guided_diffusion/README.md +176 -0
  26. editing_diffusion/guided_diffusion/datasets/README.md +27 -0
  27. editing_diffusion/guided_diffusion/datasets/lsun_bedroom.py +54 -0
  28. editing_diffusion/guided_diffusion/guided_diffusion/__init__.py +3 -0
  29. editing_diffusion/guided_diffusion/guided_diffusion/dist_util.py +93 -0
  30. editing_diffusion/guided_diffusion/guided_diffusion/fp16_util.py +236 -0
  31. editing_diffusion/guided_diffusion/guided_diffusion/gaussian_diffusion.py +922 -0
  32. editing_diffusion/guided_diffusion/guided_diffusion/image_datasets.py +167 -0
  33. editing_diffusion/guided_diffusion/guided_diffusion/logger.py +495 -0
  34. editing_diffusion/guided_diffusion/guided_diffusion/losses.py +77 -0
  35. editing_diffusion/guided_diffusion/guided_diffusion/nn.py +170 -0
  36. editing_diffusion/guided_diffusion/guided_diffusion/resample.py +154 -0
  37. editing_diffusion/guided_diffusion/guided_diffusion/respace.py +128 -0
  38. editing_diffusion/guided_diffusion/guided_diffusion/script_util.py +452 -0
  39. editing_diffusion/guided_diffusion/guided_diffusion/train_util.py +301 -0
  40. editing_diffusion/guided_diffusion/guided_diffusion/unet.py +894 -0
  41. editing_diffusion/guided_diffusion/model-card.md +59 -0
  42. editing_diffusion/guided_diffusion/scripts/classifier_sample.py +131 -0
  43. editing_diffusion/guided_diffusion/scripts/classifier_train.py +226 -0
  44. editing_diffusion/guided_diffusion/scripts/image_nll.py +96 -0
  45. editing_diffusion/guided_diffusion/scripts/image_sample.py +108 -0
  46. editing_diffusion/guided_diffusion/scripts/image_train.py +83 -0
  47. editing_diffusion/guided_diffusion/scripts/super_res_sample.py +119 -0
  48. editing_diffusion/guided_diffusion/scripts/super_res_train.py +98 -0
  49. editing_diffusion/guided_diffusion/setup.py +7 -0
  50. editing_diffusion/main.py +9 -0
app.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import sys
4
+ sys.path.append(".")
5
+
6
+ #@title Import stuff
7
+ import gc
8
+
9
+ import subprocess
10
+ import shutil
11
+ from PIL import Image
12
+ import time
13
+
14
+ import imageio
15
+
16
+
17
+ # def run(initial_image, mask, Backgrounds, Backgrounds_complexity, Size, Angle, Steps, num_of_Images):
18
+ def run(source_img, Backgrounds, Backgrounds_complexity, Size, Angle, Steps, num_of_Images):
19
+ print('-------------------starting to process-------------------')
20
+ if os.path.exists('results'):
21
+ shutil.rmtree("results")
22
+ if os.path.exists('tmp'):
23
+ shutil.rmtree("tmp")
24
+ time.sleep(1)
25
+ os.makedirs('results', exist_ok=True)
26
+ os.makedirs('tmp/img', exist_ok=True)
27
+ os.makedirs('tmp/mask', exist_ok=True)
28
+ os.makedirs('tmp/bg', exist_ok=True)
29
+
30
+ '''
31
+ print('-----initial_image: ', initial_image)
32
+ init_image = Image.open(initial_image)
33
+ mask = Image.open(mask)
34
+ init_image = init_image.resize((256,256))
35
+ mask = mask.resize((256,256))
36
+ init_image.save("tmp/img/input.JPEG")
37
+ mask.save("tmp/mask/input.png")
38
+ '''
39
+ imageio.imwrite("tmp/img/input.JPEG", source_img["image"])
40
+ imageio.imwrite("tmp/mask/input.png", source_img["mask"])
41
+
42
+ initial_image = Image.open('tmp/img/input.JPEG').resize((256,256))
43
+ initial_image.save('tmp/img/input.JPEG')
44
+ mask = Image.open('tmp/mask/input.png').resize((256,256))
45
+ mask.save('tmp/mask/input.png')
46
+
47
+
48
+ if Backgrounds:
49
+ background_specific = Backgrounds
50
+ if background_specific is not None:
51
+ background_specific = Image.open(background_specific).convert('RGB') # Specified background
52
+ background_specific = background_specific.resize((256,256))
53
+ background_specific.save('tmp/bg/bg.png')
54
+ background_specific = '../tmp/bg/bg.png'
55
+ else:
56
+ background_specific = ""
57
+
58
+ Backgrounds_complexity = Backgrounds_complexity
59
+ Size = Size
60
+ Angle = Angle
61
+ Steps = Steps
62
+ num_of_Images = num_of_Images
63
+ print(Backgrounds_complexity, background_specific, Size, Angle, Steps, num_of_Images)
64
+ p = subprocess.Popen(["sh", "run.sh", str(Backgrounds_complexity), background_specific, str(Size), str(Angle), str(Steps), str(num_of_Images)])
65
+
66
+ # subprocess.Popen(["cd", "object_removal/TFill/"])
67
+ # subprocess.Popen(["python", "test.py"])
68
+
69
+ return_code = p.wait()
70
+ print('----return_code: ', return_code)
71
+
72
+ if os.path.exists('results/edited.png'):
73
+ return Image.open('results/edited.png')
74
+ else:
75
+ return Image.open('tmp/img/input.JPEG')
76
+
77
+
78
+ image = gr.outputs.Image(type="pil", label="Your result")
79
+ css = ".output-image{height: 528px !important} .output-carousel .output-image{height:272px !important} a{text-decoration: underline}"
80
+ iface = gr.Interface(fn=run, inputs=[
81
+ # gr.inputs.Image(type="filepath", label='initial_image'),
82
+ gr.Image(source="upload", type="numpy", tool="sketch", elem_id="source_container"),
83
+ # gr.inputs.Image(type="filepath", label='mask - object mask', optional=True),
84
+ gr.inputs.Image(type="filepath", label='Backgrounds - optional, specified backgrounds'),
85
+ gr.inputs.Slider(label="Backgrounds_complexity - How complicated you wish to the generated image to be", default=0, step=1, minimum=-30, maximum=30),
86
+ gr.inputs.Slider(label="Size - Object pixel rates", default=0.1, step=0.02, minimum=0.01, maximum=0.5),
87
+ gr.inputs.Slider(label="Angle - Object angle", default=0, step=10, minimum=-180, maximum=180),
88
+ gr.inputs.Slider(label="Steps - more steps can increase quality but will take longer to generate",default=10,maximum=100,minimum=1,step=1),
89
+ gr.inputs.Slider(label="num_of_Images - How many images you wish to generate", default=2, step=1, minimum=1, maximum=4),
90
+
91
+ # gr.inputs.Radio(label="Width", choices=[32,64,128,256],default=256),
92
+ # gr.inputs.Radio(label="Height", choices=[32,64,128,256],default=256),
93
+ # gr.inputs.Textbox(label="Prompt - try adding increments to your prompt such as 'oil on canvas', 'a painting', 'a book cover'",default="chalk pastel drawing of a dog wearing a funny hat"),
94
+ #gr.inputs.Slider(label="ETA - between 0 and 1. Lower values can provide better quality, higher values can be more diverse",default=0.0,minimum=0.0, maximum=1.0,step=0.1),
95
+ ],
96
+ # outputs=[image,gr.outputs.Carousel(label="Individual images",components=["image"]),gr.outputs.Textbox(label="Error")],
97
+ outputs=["image"],
98
+ css=css,
99
+ title="Image Editing with Controls of Object Attributes including Backgrounds, Sizes, Positions and Directions",
100
+ description="Gradio Demo for Image Editing with Controls of Object Attributes including Backgrounds, Sizes, Positions and Directions",
101
+ article="ImageNet-E")
102
+ iface.launch(enable_queue=True,share=True)
editing_diffusion/0 ADDED
File without changes
editing_diffusion/CLIP/.github/workflows/test.yml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: test
2
+ on: push
3
+ jobs:
4
+ CLIP-test:
5
+ runs-on: ubuntu-latest
6
+ strategy:
7
+ matrix:
8
+ python-version: [3.7, 3.8]
9
+ pytorch-version: [1.7.1, 1.9.0]
10
+ steps:
11
+ - uses: conda-incubator/setup-miniconda@v2
12
+ - run: conda install -n test python=${{ matrix.python-version }} pytorch=${{ matrix.pytorch-version }} torchvision cpuonly -c pytorch
13
+ - uses: actions/checkout@v2
14
+ - run: echo "$CONDA/envs/test/bin" >> $GITHUB_PATH
15
+ - run: pip install pytest
16
+ - run: pip install .
17
+ - run: pytest
editing_diffusion/CLIP/.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.egg-info
5
+ .pytest_cache
6
+ .ipynb_checkpoints
7
+
8
+ thumbs.db
9
+ .DS_Store
10
+ .idea
editing_diffusion/CLIP/CLIP.png ADDED
editing_diffusion/CLIP/LICENSE ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2021 OpenAI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
editing_diffusion/CLIP/MANIFEST.in ADDED
@@ -0,0 +1 @@
 
 
1
+ include clip/bpe_simple_vocab_16e6.txt.gz
editing_diffusion/CLIP/README.md ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CLIP
2
+
3
+ [[Blog]](https://openai.com/blog/clip/) [[Paper]](https://arxiv.org/abs/2103.00020) [[Model Card]](model-card.md) [[Colab]](https://colab.research.google.com/github/openai/clip/blob/master/notebooks/Interacting_with_CLIP.ipynb)
4
+
5
+ CLIP (Contrastive Language-Image Pre-Training) is a neural network trained on a variety of (image, text) pairs. It can be instructed in natural language to predict the most relevant text snippet, given an image, without directly optimizing for the task, similarly to the zero-shot capabilities of GPT-2 and 3. We found CLIP matches the performance of the original ResNet50 on ImageNet “zero-shot” without using any of the original 1.28M labeled examples, overcoming several major challenges in computer vision.
6
+
7
+
8
+
9
+ ## Approach
10
+
11
+ ![CLIP](CLIP.png)
12
+
13
+
14
+
15
+ ## Usage
16
+
17
+ First, [install PyTorch 1.7.1](https://pytorch.org/get-started/locally/) and torchvision, as well as small additional dependencies, and then install this repo as a Python package. On a CUDA GPU machine, the following will do the trick:
18
+
19
+ ```bash
20
+ $ conda install --yes -c pytorch pytorch=1.7.1 torchvision cudatoolkit=11.0
21
+ $ pip install ftfy regex tqdm
22
+ $ pip install git+https://github.com/openai/CLIP.git
23
+ ```
24
+
25
+ Replace `cudatoolkit=11.0` above with the appropriate CUDA version on your machine or `cpuonly` when installing on a machine without a GPU.
26
+
27
+ ```python
28
+ import torch
29
+ import clip
30
+ from PIL import Image
31
+
32
+ device = "cuda" if torch.cuda.is_available() else "cpu"
33
+ model, preprocess = clip.load("ViT-B/32", device=device)
34
+
35
+ image = preprocess(Image.open("CLIP.png")).unsqueeze(0).to(device)
36
+ text = clip.tokenize(["a diagram", "a dog", "a cat"]).to(device)
37
+
38
+ with torch.no_grad():
39
+ image_features = model.encode_image(image)
40
+ text_features = model.encode_text(text)
41
+
42
+ logits_per_image, logits_per_text = model(image, text)
43
+ probs = logits_per_image.softmax(dim=-1).cpu().numpy()
44
+
45
+ print("Label probs:", probs) # prints: [[0.9927937 0.00421068 0.00299572]]
46
+ ```
47
+
48
+
49
+ ## API
50
+
51
+ The CLIP module `clip` provides the following methods:
52
+
53
+ #### `clip.available_models()`
54
+
55
+ Returns the names of the available CLIP models.
56
+
57
+ #### `clip.load(name, device=..., jit=False)`
58
+
59
+ Returns the model and the TorchVision transform needed by the model, specified by the model name returned by `clip.available_models()`. It will download the model as necessary. The `name` argument can also be a path to a local checkpoint.
60
+
61
+ The device to run the model can be optionally specified, and the default is to use the first CUDA device if there is any, otherwise the CPU. When `jit` is `False`, a non-JIT version of the model will be loaded.
62
+
63
+ #### `clip.tokenize(text: Union[str, List[str]], context_length=77)`
64
+
65
+ Returns a LongTensor containing tokenized sequences of given text input(s). This can be used as the input to the model
66
+
67
+ ---
68
+
69
+ The model returned by `clip.load()` supports the following methods:
70
+
71
+ #### `model.encode_image(image: Tensor)`
72
+
73
+ Given a batch of images, returns the image features encoded by the vision portion of the CLIP model.
74
+
75
+ #### `model.encode_text(text: Tensor)`
76
+
77
+ Given a batch of text tokens, returns the text features encoded by the language portion of the CLIP model.
78
+
79
+ #### `model(image: Tensor, text: Tensor)`
80
+
81
+ Given a batch of images and a batch of text tokens, returns two Tensors, containing the logit scores corresponding to each image and text input. The values are cosine similarities between the corresponding image and text features, times 100.
82
+
83
+
84
+
85
+ ## More Examples
86
+
87
+ ### Zero-Shot Prediction
88
+
89
+ The code below performs zero-shot prediction using CLIP, as shown in Appendix B in the paper. This example takes an image from the [CIFAR-100 dataset](https://www.cs.toronto.edu/~kriz/cifar.html), and predicts the most likely labels among the 100 textual labels from the dataset.
90
+
91
+ ```python
92
+ import os
93
+ import clip
94
+ import torch
95
+ from torchvision.datasets import CIFAR100
96
+
97
+ # Load the model
98
+ device = "cuda" if torch.cuda.is_available() else "cpu"
99
+ model, preprocess = clip.load('ViT-B/32', device)
100
+
101
+ # Download the dataset
102
+ cifar100 = CIFAR100(root=os.path.expanduser("~/.cache"), download=True, train=False)
103
+
104
+ # Prepare the inputs
105
+ image, class_id = cifar100[3637]
106
+ image_input = preprocess(image).unsqueeze(0).to(device)
107
+ text_inputs = torch.cat([clip.tokenize(f"a photo of a {c}") for c in cifar100.classes]).to(device)
108
+
109
+ # Calculate features
110
+ with torch.no_grad():
111
+ image_features = model.encode_image(image_input)
112
+ text_features = model.encode_text(text_inputs)
113
+
114
+ # Pick the top 5 most similar labels for the image
115
+ image_features /= image_features.norm(dim=-1, keepdim=True)
116
+ text_features /= text_features.norm(dim=-1, keepdim=True)
117
+ similarity = (100.0 * image_features @ text_features.T).softmax(dim=-1)
118
+ values, indices = similarity[0].topk(5)
119
+
120
+ # Print the result
121
+ print("\nTop predictions:\n")
122
+ for value, index in zip(values, indices):
123
+ print(f"{cifar100.classes[index]:>16s}: {100 * value.item():.2f}%")
124
+ ```
125
+
126
+ The output will look like the following (the exact numbers may be slightly different depending on the compute device):
127
+
128
+ ```
129
+ Top predictions:
130
+
131
+ snake: 65.31%
132
+ turtle: 12.29%
133
+ sweet_pepper: 3.83%
134
+ lizard: 1.88%
135
+ crocodile: 1.75%
136
+ ```
137
+
138
+ Note that this example uses the `encode_image()` and `encode_text()` methods that return the encoded features of given inputs.
139
+
140
+
141
+ ### Linear-probe evaluation
142
+
143
+ The example below uses [scikit-learn](https://scikit-learn.org/) to perform logistic regression on image features.
144
+
145
+ ```python
146
+ import os
147
+ import clip
148
+ import torch
149
+
150
+ import numpy as np
151
+ from sklearn.linear_model import LogisticRegression
152
+ from torch.utils.data import DataLoader
153
+ from torchvision.datasets import CIFAR100
154
+ from tqdm import tqdm
155
+
156
+ # Load the model
157
+ device = "cuda" if torch.cuda.is_available() else "cpu"
158
+ model, preprocess = clip.load('ViT-B/32', device)
159
+
160
+ # Load the dataset
161
+ root = os.path.expanduser("~/.cache")
162
+ train = CIFAR100(root, download=True, train=True, transform=preprocess)
163
+ test = CIFAR100(root, download=True, train=False, transform=preprocess)
164
+
165
+
166
+ def get_features(dataset):
167
+ all_features = []
168
+ all_labels = []
169
+
170
+ with torch.no_grad():
171
+ for images, labels in tqdm(DataLoader(dataset, batch_size=100)):
172
+ features = model.encode_image(images.to(device))
173
+
174
+ all_features.append(features)
175
+ all_labels.append(labels)
176
+
177
+ return torch.cat(all_features).cpu().numpy(), torch.cat(all_labels).cpu().numpy()
178
+
179
+ # Calculate the image features
180
+ train_features, train_labels = get_features(train)
181
+ test_features, test_labels = get_features(test)
182
+
183
+ # Perform logistic regression
184
+ classifier = LogisticRegression(random_state=0, C=0.316, max_iter=1000, verbose=1)
185
+ classifier.fit(train_features, train_labels)
186
+
187
+ # Evaluate using the logistic regression classifier
188
+ predictions = classifier.predict(test_features)
189
+ accuracy = np.mean((test_labels == predictions).astype(np.float)) * 100.
190
+ print(f"Accuracy = {accuracy:.3f}")
191
+ ```
192
+
193
+ Note that the `C` value should be determined via a hyperparameter sweep using a validation split.
editing_diffusion/CLIP/clip/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .clip import *
editing_diffusion/CLIP/clip/bpe_simple_vocab_16e6.txt.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a
3
+ size 1356917
editing_diffusion/CLIP/clip/clip.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import os
3
+ import urllib
4
+ import warnings
5
+ from typing import Any, Union, List
6
+
7
+ import torch
8
+ from PIL import Image
9
+ from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
10
+ from tqdm import tqdm
11
+
12
+ from .model import build_model
13
+ from .simple_tokenizer import SimpleTokenizer as _Tokenizer
14
+
15
+ try:
16
+ from torchvision.transforms import InterpolationMode
17
+ BICUBIC = InterpolationMode.BICUBIC
18
+ except ImportError:
19
+ BICUBIC = Image.BICUBIC
20
+
21
+
22
+ if torch.__version__.split(".") < ["1", "7", "1"]:
23
+ warnings.warn("PyTorch version 1.7.1 or higher is recommended")
24
+
25
+
26
+ __all__ = ["available_models", "load", "tokenize"]
27
+ _tokenizer = _Tokenizer()
28
+
29
+ _MODELS = {
30
+ "RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
31
+ "RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt",
32
+ "RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt",
33
+ "RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt",
34
+ "ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
35
+ "ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt",
36
+ }
37
+
38
+
39
+ def _download(url: str, root: str):
40
+ os.makedirs(root, exist_ok=True)
41
+ filename = os.path.basename(url)
42
+
43
+ expected_sha256 = url.split("/")[-2]
44
+ download_target = os.path.join(root, filename)
45
+
46
+ if os.path.exists(download_target) and not os.path.isfile(download_target):
47
+ raise RuntimeError(f"{download_target} exists and is not a regular file")
48
+
49
+ if os.path.isfile(download_target):
50
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256:
51
+ return download_target
52
+ else:
53
+ warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
54
+ import pdb
55
+ pdb.set_trace()
56
+ with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
57
+ with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True, unit_divisor=1024) as loop:
58
+ while True:
59
+ buffer = source.read(8192)
60
+ if not buffer:
61
+ break
62
+
63
+ output.write(buffer)
64
+ loop.update(len(buffer))
65
+
66
+ if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256:
67
+ raise RuntimeError(f"Model has been downloaded but the SHA256 checksum does not not match")
68
+
69
+ return download_target
70
+
71
+
72
+ def _transform(n_px):
73
+ return Compose([
74
+ Resize(n_px, interpolation=BICUBIC),
75
+ CenterCrop(n_px),
76
+ lambda image: image.convert("RGB"),
77
+ ToTensor(),
78
+ Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
79
+ ])
80
+
81
+
82
+ def available_models() -> List[str]:
83
+ """Returns the names of available CLIP models"""
84
+ return list(_MODELS.keys())
85
+
86
+
87
+ def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit: bool = False, download_root: str = None):
88
+ """Load a CLIP model
89
+
90
+ Parameters
91
+ ----------
92
+ name : str
93
+ A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
94
+
95
+ device : Union[str, torch.device]
96
+ The device to put the loaded model
97
+
98
+ jit : bool
99
+ Whether to load the optimized JIT model or more hackable non-JIT model (default).
100
+
101
+ download_root: str
102
+ path to download the model files; by default, it uses "~/.cache/clip"
103
+
104
+ Returns
105
+ -------
106
+ model : torch.nn.Module
107
+ The CLIP model
108
+
109
+ preprocess : Callable[[PIL.Image], torch.Tensor]
110
+ A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
111
+ """
112
+ if name in _MODELS:
113
+ model_path = _download(_MODELS[name], download_root or os.path.expanduser("~/.cache/clip"))
114
+ elif os.path.isfile(name):
115
+ model_path = name
116
+ else:
117
+ raise RuntimeError(f"Model {name} not found; available models = {available_models()}")
118
+
119
+ try:
120
+ # loading JIT archive
121
+ model = torch.jit.load(model_path, map_location=device if jit else "cpu").eval()
122
+ state_dict = None
123
+ except RuntimeError:
124
+ # loading saved state dict
125
+ if jit:
126
+ warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
127
+ jit = False
128
+ state_dict = torch.load(model_path, map_location="cpu")
129
+
130
+ if not jit:
131
+ model = build_model(state_dict or model.state_dict()).to(device)
132
+ if str(device) == "cpu":
133
+ model.float()
134
+ return model, _transform(model.visual.input_resolution)
135
+
136
+ # patch the device names
137
+ device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
138
+ device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
139
+
140
+ def patch_device(module):
141
+ try:
142
+ graphs = [module.graph] if hasattr(module, "graph") else []
143
+ except RuntimeError:
144
+ graphs = []
145
+
146
+ if hasattr(module, "forward1"):
147
+ graphs.append(module.forward1.graph)
148
+
149
+ for graph in graphs:
150
+ for node in graph.findAllNodes("prim::Constant"):
151
+ if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"):
152
+ node.copyAttributes(device_node)
153
+
154
+ model.apply(patch_device)
155
+ patch_device(model.encode_image)
156
+ patch_device(model.encode_text)
157
+
158
+ # patch dtype to float32 on CPU
159
+ if str(device) == "cpu":
160
+ float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
161
+ float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
162
+ float_node = float_input.node()
163
+
164
+ def patch_float(module):
165
+ try:
166
+ graphs = [module.graph] if hasattr(module, "graph") else []
167
+ except RuntimeError:
168
+ graphs = []
169
+
170
+ if hasattr(module, "forward1"):
171
+ graphs.append(module.forward1.graph)
172
+
173
+ for graph in graphs:
174
+ for node in graph.findAllNodes("aten::to"):
175
+ inputs = list(node.inputs())
176
+ for i in [1, 2]: # dtype can be the second or third argument to aten::to()
177
+ if inputs[i].node()["value"] == 5:
178
+ inputs[i].node().copyAttributes(float_node)
179
+
180
+ model.apply(patch_float)
181
+ patch_float(model.encode_image)
182
+ patch_float(model.encode_text)
183
+
184
+ model.float()
185
+
186
+ return model, _transform(model.input_resolution.item())
187
+
188
+
189
+ def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = False) -> torch.LongTensor:
190
+ """
191
+ Returns the tokenized representation of given input string(s)
192
+
193
+ Parameters
194
+ ----------
195
+ texts : Union[str, List[str]]
196
+ An input string or a list of input strings to tokenize
197
+
198
+ context_length : int
199
+ The context length to use; all CLIP models use 77 as the context length
200
+
201
+ truncate: bool
202
+ Whether to truncate the text in case its encoding is longer than the context length
203
+
204
+ Returns
205
+ -------
206
+ A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length]
207
+ """
208
+ if isinstance(texts, str):
209
+ texts = [texts]
210
+
211
+ sot_token = _tokenizer.encoder["<|startoftext|>"]
212
+ eot_token = _tokenizer.encoder["<|endoftext|>"]
213
+ all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
214
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
215
+
216
+ for i, tokens in enumerate(all_tokens):
217
+ if len(tokens) > context_length:
218
+ if truncate:
219
+ tokens = tokens[:context_length]
220
+ tokens[-1] = eot_token
221
+ else:
222
+ raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}")
223
+ result[i, :len(tokens)] = torch.tensor(tokens)
224
+
225
+ return result
editing_diffusion/CLIP/clip/model.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from typing import Tuple, Union
3
+
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch import nn
8
+
9
+
10
+ class Bottleneck(nn.Module):
11
+ expansion = 4
12
+
13
+ def __init__(self, inplanes, planes, stride=1):
14
+ super().__init__()
15
+
16
+ # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
17
+ self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
18
+ self.bn1 = nn.BatchNorm2d(planes)
19
+
20
+ self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
21
+ self.bn2 = nn.BatchNorm2d(planes)
22
+
23
+ self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
24
+
25
+ self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
26
+ self.bn3 = nn.BatchNorm2d(planes * self.expansion)
27
+
28
+ self.relu = nn.ReLU(inplace=True)
29
+ self.downsample = None
30
+ self.stride = stride
31
+
32
+ if stride > 1 or inplanes != planes * Bottleneck.expansion:
33
+ # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
34
+ self.downsample = nn.Sequential(OrderedDict([
35
+ ("-1", nn.AvgPool2d(stride)),
36
+ ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
37
+ ("1", nn.BatchNorm2d(planes * self.expansion))
38
+ ]))
39
+
40
+ def forward(self, x: torch.Tensor):
41
+ identity = x
42
+
43
+ out = self.relu(self.bn1(self.conv1(x)))
44
+ out = self.relu(self.bn2(self.conv2(out)))
45
+ out = self.avgpool(out)
46
+ out = self.bn3(self.conv3(out))
47
+
48
+ if self.downsample is not None:
49
+ identity = self.downsample(x)
50
+
51
+ out += identity
52
+ out = self.relu(out)
53
+ return out
54
+
55
+
56
+ class AttentionPool2d(nn.Module):
57
+ def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
58
+ super().__init__()
59
+ self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
60
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
61
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
62
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
63
+ self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
64
+ self.num_heads = num_heads
65
+
66
+ def forward(self, x):
67
+ x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC
68
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
69
+ x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
70
+ x, _ = F.multi_head_attention_forward(
71
+ query=x, key=x, value=x,
72
+ embed_dim_to_check=x.shape[-1],
73
+ num_heads=self.num_heads,
74
+ q_proj_weight=self.q_proj.weight,
75
+ k_proj_weight=self.k_proj.weight,
76
+ v_proj_weight=self.v_proj.weight,
77
+ in_proj_weight=None,
78
+ in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
79
+ bias_k=None,
80
+ bias_v=None,
81
+ add_zero_attn=False,
82
+ dropout_p=0,
83
+ out_proj_weight=self.c_proj.weight,
84
+ out_proj_bias=self.c_proj.bias,
85
+ use_separate_proj_weight=True,
86
+ training=self.training,
87
+ need_weights=False
88
+ )
89
+
90
+ return x[0]
91
+
92
+
93
+ class ModifiedResNet(nn.Module):
94
+ """
95
+ A ResNet class that is similar to torchvision's but contains the following changes:
96
+ - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
97
+ - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
98
+ - The final pooling layer is a QKV attention instead of an average pool
99
+ """
100
+
101
+ def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
102
+ super().__init__()
103
+ self.output_dim = output_dim
104
+ self.input_resolution = input_resolution
105
+
106
+ # the 3-layer stem
107
+ self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
108
+ self.bn1 = nn.BatchNorm2d(width // 2)
109
+ self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
110
+ self.bn2 = nn.BatchNorm2d(width // 2)
111
+ self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
112
+ self.bn3 = nn.BatchNorm2d(width)
113
+ self.avgpool = nn.AvgPool2d(2)
114
+ self.relu = nn.ReLU(inplace=True)
115
+
116
+ # residual layers
117
+ self._inplanes = width # this is a *mutable* variable used during construction
118
+ self.layer1 = self._make_layer(width, layers[0])
119
+ self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
120
+ self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
121
+ self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
122
+
123
+ embed_dim = width * 32 # the ResNet feature dimension
124
+ self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
125
+
126
+ def _make_layer(self, planes, blocks, stride=1):
127
+ layers = [Bottleneck(self._inplanes, planes, stride)]
128
+
129
+ self._inplanes = planes * Bottleneck.expansion
130
+ for _ in range(1, blocks):
131
+ layers.append(Bottleneck(self._inplanes, planes))
132
+
133
+ return nn.Sequential(*layers)
134
+
135
+ def forward(self, x):
136
+ def stem(x):
137
+ for conv, bn in [(self.conv1, self.bn1), (self.conv2, self.bn2), (self.conv3, self.bn3)]:
138
+ x = self.relu(bn(conv(x)))
139
+ x = self.avgpool(x)
140
+ return x
141
+
142
+ x = x.type(self.conv1.weight.dtype)
143
+ x = stem(x)
144
+ x = self.layer1(x)
145
+ x = self.layer2(x)
146
+ x = self.layer3(x)
147
+ x = self.layer4(x)
148
+ x = self.attnpool(x)
149
+
150
+ return x
151
+
152
+
153
+ class LayerNorm(nn.LayerNorm):
154
+ """Subclass torch's LayerNorm to handle fp16."""
155
+
156
+ def forward(self, x: torch.Tensor):
157
+ orig_type = x.dtype
158
+ ret = super().forward(x.type(torch.float32))
159
+ return ret.type(orig_type)
160
+
161
+
162
+ class QuickGELU(nn.Module):
163
+ def forward(self, x: torch.Tensor):
164
+ return x * torch.sigmoid(1.702 * x)
165
+
166
+
167
+ class ResidualAttentionBlock(nn.Module):
168
+ def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
169
+ super().__init__()
170
+
171
+ self.attn = nn.MultiheadAttention(d_model, n_head)
172
+ self.ln_1 = LayerNorm(d_model)
173
+ self.mlp = nn.Sequential(OrderedDict([
174
+ ("c_fc", nn.Linear(d_model, d_model * 4)),
175
+ ("gelu", QuickGELU()),
176
+ ("c_proj", nn.Linear(d_model * 4, d_model))
177
+ ]))
178
+ self.ln_2 = LayerNorm(d_model)
179
+ self.attn_mask = attn_mask
180
+
181
+ def attention(self, x: torch.Tensor):
182
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
183
+ return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
184
+
185
+ def forward(self, x: torch.Tensor):
186
+ x = x + self.attention(self.ln_1(x))
187
+ x = x + self.mlp(self.ln_2(x))
188
+ return x
189
+
190
+
191
+ class Transformer(nn.Module):
192
+ def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
193
+ super().__init__()
194
+ self.width = width
195
+ self.layers = layers
196
+ self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
197
+
198
+ def forward(self, x: torch.Tensor):
199
+ return self.resblocks(x)
200
+
201
+
202
+ class VisionTransformer(nn.Module):
203
+ def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
204
+ super().__init__()
205
+ self.input_resolution = input_resolution
206
+ self.output_dim = output_dim
207
+ self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
208
+
209
+ scale = width ** -0.5
210
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
211
+ self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
212
+ self.ln_pre = LayerNorm(width)
213
+
214
+ self.transformer = Transformer(width, layers, heads)
215
+
216
+ self.ln_post = LayerNorm(width)
217
+ self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
218
+
219
+ def forward(self, x: torch.Tensor):
220
+ x = self.conv1(x) # shape = [*, width, grid, grid]
221
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
222
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
223
+ x = torch.cat([self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]
224
+ x = x + self.positional_embedding.to(x.dtype)
225
+ x = self.ln_pre(x)
226
+
227
+ x = x.permute(1, 0, 2) # NLD -> LND
228
+ x = self.transformer(x)
229
+ x = x.permute(1, 0, 2) # LND -> NLD
230
+
231
+ x = self.ln_post(x[:, 0, :])
232
+
233
+ if self.proj is not None:
234
+ x = x @ self.proj
235
+
236
+ return x
237
+
238
+
239
+ class CLIP(nn.Module):
240
+ def __init__(self,
241
+ embed_dim: int,
242
+ # vision
243
+ image_resolution: int,
244
+ vision_layers: Union[Tuple[int, int, int, int], int],
245
+ vision_width: int,
246
+ vision_patch_size: int,
247
+ # text
248
+ context_length: int,
249
+ vocab_size: int,
250
+ transformer_width: int,
251
+ transformer_heads: int,
252
+ transformer_layers: int
253
+ ):
254
+ super().__init__()
255
+
256
+ self.context_length = context_length
257
+
258
+ if isinstance(vision_layers, (tuple, list)):
259
+ vision_heads = vision_width * 32 // 64
260
+ self.visual = ModifiedResNet(
261
+ layers=vision_layers,
262
+ output_dim=embed_dim,
263
+ heads=vision_heads,
264
+ input_resolution=image_resolution,
265
+ width=vision_width
266
+ )
267
+ else:
268
+ vision_heads = vision_width // 64
269
+ self.visual = VisionTransformer(
270
+ input_resolution=image_resolution,
271
+ patch_size=vision_patch_size,
272
+ width=vision_width,
273
+ layers=vision_layers,
274
+ heads=vision_heads,
275
+ output_dim=embed_dim
276
+ )
277
+
278
+ self.transformer = Transformer(
279
+ width=transformer_width,
280
+ layers=transformer_layers,
281
+ heads=transformer_heads,
282
+ attn_mask=self.build_attention_mask()
283
+ )
284
+
285
+ self.vocab_size = vocab_size
286
+ self.token_embedding = nn.Embedding(vocab_size, transformer_width)
287
+ self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
288
+ self.ln_final = LayerNorm(transformer_width)
289
+
290
+ self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
291
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
292
+
293
+ self.initialize_parameters()
294
+
295
+ def initialize_parameters(self):
296
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
297
+ nn.init.normal_(self.positional_embedding, std=0.01)
298
+
299
+ if isinstance(self.visual, ModifiedResNet):
300
+ if self.visual.attnpool is not None:
301
+ std = self.visual.attnpool.c_proj.in_features ** -0.5
302
+ nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
303
+ nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
304
+ nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
305
+ nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
306
+
307
+ for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
308
+ for name, param in resnet_block.named_parameters():
309
+ if name.endswith("bn3.weight"):
310
+ nn.init.zeros_(param)
311
+
312
+ proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
313
+ attn_std = self.transformer.width ** -0.5
314
+ fc_std = (2 * self.transformer.width) ** -0.5
315
+ for block in self.transformer.resblocks:
316
+ nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
317
+ nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
318
+ nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
319
+ nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
320
+
321
+ if self.text_projection is not None:
322
+ nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
323
+
324
+ def build_attention_mask(self):
325
+ # lazily create causal attention mask, with full attention between the vision tokens
326
+ # pytorch uses additive attention mask; fill with -inf
327
+ mask = torch.empty(self.context_length, self.context_length)
328
+ mask.fill_(float("-inf"))
329
+ mask.triu_(1) # zero out the lower diagonal
330
+ return mask
331
+
332
+ @property
333
+ def dtype(self):
334
+ return self.visual.conv1.weight.dtype
335
+
336
+ def encode_image(self, image):
337
+ return self.visual(image.type(self.dtype))
338
+
339
+ def encode_text(self, text):
340
+ x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
341
+
342
+ x = x + self.positional_embedding.type(self.dtype)
343
+ x = x.permute(1, 0, 2) # NLD -> LND
344
+ x = self.transformer(x)
345
+ x = x.permute(1, 0, 2) # LND -> NLD
346
+ x = self.ln_final(x).type(self.dtype)
347
+
348
+ # x.shape = [batch_size, n_ctx, transformer.width]
349
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
350
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
351
+
352
+ return x
353
+
354
+ def forward(self, image, text):
355
+ image_features = self.encode_image(image)
356
+ text_features = self.encode_text(text)
357
+
358
+ # normalized features
359
+ image_features = image_features / image_features.norm(dim=-1, keepdim=True)
360
+ text_features = text_features / text_features.norm(dim=-1, keepdim=True)
361
+
362
+ # cosine similarity as logits
363
+ logit_scale = self.logit_scale.exp()
364
+ logits_per_image = logit_scale * image_features @ text_features.t()
365
+ logits_per_text = logit_scale * text_features @ image_features.t()
366
+
367
+ # shape = [global_batch_size, global_batch_size]
368
+ return logits_per_image, logits_per_text
369
+
370
+
371
+ def convert_weights(model: nn.Module):
372
+ """Convert applicable model parameters to fp16"""
373
+
374
+ def _convert_weights_to_fp16(l):
375
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
376
+ l.weight.data = l.weight.data.half()
377
+ if l.bias is not None:
378
+ l.bias.data = l.bias.data.half()
379
+
380
+ if isinstance(l, nn.MultiheadAttention):
381
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
382
+ tensor = getattr(l, attr)
383
+ if tensor is not None:
384
+ tensor.data = tensor.data.half()
385
+
386
+ for name in ["text_projection", "proj"]:
387
+ if hasattr(l, name):
388
+ attr = getattr(l, name)
389
+ if attr is not None:
390
+ attr.data = attr.data.half()
391
+
392
+ model.apply(_convert_weights_to_fp16)
393
+
394
+
395
+ def build_model(state_dict: dict):
396
+ vit = "visual.proj" in state_dict
397
+
398
+ if vit:
399
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
400
+ vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
401
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
402
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
403
+ image_resolution = vision_patch_size * grid_size
404
+ else:
405
+ counts: list = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]]
406
+ vision_layers = tuple(counts)
407
+ vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
408
+ output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
409
+ vision_patch_size = None
410
+ assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
411
+ image_resolution = output_width * 32
412
+
413
+ embed_dim = state_dict["text_projection"].shape[1]
414
+ context_length = state_dict["positional_embedding"].shape[0]
415
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
416
+ transformer_width = state_dict["ln_final.weight"].shape[0]
417
+ transformer_heads = transformer_width // 64
418
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks")))
419
+
420
+ model = CLIP(
421
+ embed_dim,
422
+ image_resolution, vision_layers, vision_width, vision_patch_size,
423
+ context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
424
+ )
425
+
426
+ for key in ["input_resolution", "context_length", "vocab_size"]:
427
+ if key in state_dict:
428
+ del state_dict[key]
429
+
430
+ convert_weights(model)
431
+ model.load_state_dict(state_dict)
432
+ return model.eval()
editing_diffusion/CLIP/clip/simple_tokenizer.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gzip
2
+ import html
3
+ import os
4
+ from functools import lru_cache
5
+
6
+ import ftfy
7
+ import regex as re
8
+
9
+
10
+ @lru_cache()
11
+ def default_bpe():
12
+ return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
13
+
14
+
15
+ @lru_cache()
16
+ def bytes_to_unicode():
17
+ """
18
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
19
+ The reversible bpe codes work on unicode strings.
20
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
21
+ When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
22
+ This is a signficant percentage of your normal, say, 32K bpe vocab.
23
+ To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
24
+ And avoids mapping to whitespace/control characters the bpe code barfs on.
25
+ """
26
+ bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
27
+ cs = bs[:]
28
+ n = 0
29
+ for b in range(2**8):
30
+ if b not in bs:
31
+ bs.append(b)
32
+ cs.append(2**8+n)
33
+ n += 1
34
+ cs = [chr(n) for n in cs]
35
+ return dict(zip(bs, cs))
36
+
37
+
38
+ def get_pairs(word):
39
+ """Return set of symbol pairs in a word.
40
+ Word is represented as tuple of symbols (symbols being variable-length strings).
41
+ """
42
+ pairs = set()
43
+ prev_char = word[0]
44
+ for char in word[1:]:
45
+ pairs.add((prev_char, char))
46
+ prev_char = char
47
+ return pairs
48
+
49
+
50
+ def basic_clean(text):
51
+ text = ftfy.fix_text(text)
52
+ text = html.unescape(html.unescape(text))
53
+ return text.strip()
54
+
55
+
56
+ def whitespace_clean(text):
57
+ text = re.sub(r'\s+', ' ', text)
58
+ text = text.strip()
59
+ return text
60
+
61
+
62
+ class SimpleTokenizer(object):
63
+ def __init__(self, bpe_path: str = default_bpe()):
64
+ self.byte_encoder = bytes_to_unicode()
65
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
66
+ merges = gzip.open(bpe_path).read().decode("utf-8").split('\n')
67
+ merges = merges[1:49152-256-2+1]
68
+ merges = [tuple(merge.split()) for merge in merges]
69
+ vocab = list(bytes_to_unicode().values())
70
+ vocab = vocab + [v+'</w>' for v in vocab]
71
+ for merge in merges:
72
+ vocab.append(''.join(merge))
73
+ vocab.extend(['<|startoftext|>', '<|endoftext|>'])
74
+ self.encoder = dict(zip(vocab, range(len(vocab))))
75
+ self.decoder = {v: k for k, v in self.encoder.items()}
76
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
77
+ self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'}
78
+ self.pat = re.compile(r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE)
79
+
80
+ def bpe(self, token):
81
+ if token in self.cache:
82
+ return self.cache[token]
83
+ word = tuple(token[:-1]) + ( token[-1] + '</w>',)
84
+ pairs = get_pairs(word)
85
+
86
+ if not pairs:
87
+ return token+'</w>'
88
+
89
+ while True:
90
+ bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf')))
91
+ if bigram not in self.bpe_ranks:
92
+ break
93
+ first, second = bigram
94
+ new_word = []
95
+ i = 0
96
+ while i < len(word):
97
+ try:
98
+ j = word.index(first, i)
99
+ new_word.extend(word[i:j])
100
+ i = j
101
+ except:
102
+ new_word.extend(word[i:])
103
+ break
104
+
105
+ if word[i] == first and i < len(word)-1 and word[i+1] == second:
106
+ new_word.append(first+second)
107
+ i += 2
108
+ else:
109
+ new_word.append(word[i])
110
+ i += 1
111
+ new_word = tuple(new_word)
112
+ word = new_word
113
+ if len(word) == 1:
114
+ break
115
+ else:
116
+ pairs = get_pairs(word)
117
+ word = ' '.join(word)
118
+ self.cache[token] = word
119
+ return word
120
+
121
+ def encode(self, text):
122
+ bpe_tokens = []
123
+ text = whitespace_clean(basic_clean(text)).lower()
124
+ for token in re.findall(self.pat, text):
125
+ token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
126
+ bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
127
+ return bpe_tokens
128
+
129
+ def decode(self, tokens):
130
+ text = ''.join([self.decoder[token] for token in tokens])
131
+ text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ')
132
+ return text
editing_diffusion/CLIP/data/yfcc100m.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The YFCC100M Subset
2
+
3
+ In the paper, we performed a dataset ablation using a subset of the YFCC100M dataset and showed that the performance remained largely similar.
4
+
5
+ The subset contains 14,829,396 images, about 15% of the full dataset, which have been filtered to only keep those with natural languag titles and/or descriptions in English.
6
+
7
+ We provide the list of (line number, photo identifier, photo hash) of each image contained in this subset. These correspond to the first three columns in the dataset's metadata TSV file.
8
+
9
+ ```
10
+ wget https://openaipublic.azureedge.net/clip/data/yfcc100m_subset_data.tsv.bz2
11
+ bunzip2 yfcc100m_subset_data.tsv.bz2
12
+ ```
13
+
14
+ Use of the underlying media files is subject to the Creative Commons licenses chosen by their creators/uploaders. For more information about the YFCC100M dataset, visit [the official website](https://multimediacommons.wordpress.com/yfcc100m-core-dataset/).
editing_diffusion/CLIP/model-card.md ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model Card: CLIP
2
+
3
+ Inspired by [Model Cards for Model Reporting (Mitchell et al.)](https://arxiv.org/abs/1810.03993) and [Lessons from Archives (Jo & Gebru)](https://arxiv.org/pdf/1912.10389.pdf), we’re providing some accompanying information about the multimodal model.
4
+
5
+ ## Model Details
6
+
7
+ The CLIP model was developed by researchers at OpenAI to learn about what contributes to robustness in computer vision tasks. The model was also developed to test the ability of models to generalize to arbitrary image classification tasks in a zero-shot manner. It was not developed for general model deployment - to deploy models like CLIP, researchers will first need to carefully study their capabilities in relation to the specific context they’re being deployed within.
8
+
9
+ ### Model Date
10
+
11
+ January 2021
12
+
13
+ ### Model Type
14
+
15
+ The base model uses a ResNet50 with several modifications as an image encoder and uses a masked self-attention Transformer as a text encoder. These encoders are trained to maximize the similarity of (image, text) pairs via a contrastive loss. There is also a variant of the model where the ResNet image encoder is replaced with a Vision Transformer.
16
+
17
+ ### Model Versions
18
+
19
+ Initially, we’ve released one CLIP model based on the Vision Transformer architecture equivalent to ViT-B/32, along with the RN50 model, using the architecture equivalent to ResNet-50.
20
+
21
+ As part of the staged release process, we have also released the RN101 model, as well as RN50x4, a RN50 scaled up 4x according to the [EfficientNet](https://arxiv.org/abs/1905.11946) scaling rule. In July 2021, we additionally released the RN50x16 and ViT-B/16 models.
22
+
23
+ Please see the paper linked below for further details about their specification.
24
+
25
+ ### Documents
26
+
27
+ - [Blog Post](https://openai.com/blog/clip/)
28
+ - [CLIP Paper](https://arxiv.org/abs/2103.00020)
29
+
30
+
31
+
32
+ ## Model Use
33
+
34
+ ### Intended Use
35
+
36
+ The model is intended as a research output for research communities. We hope that this model will enable researchers to better understand and explore zero-shot, arbitrary image classification. We also hope it can be used for interdisciplinary studies of the potential impact of such models - the CLIP paper includes a discussion of potential downstream impacts to provide an example for this sort of analysis.
37
+
38
+ #### Primary intended uses
39
+
40
+ The primary intended users of these models are AI researchers.
41
+
42
+ We primarily imagine the model will be used by researchers to better understand robustness, generalization, and other capabilities, biases, and constraints of computer vision models.
43
+
44
+ ### Out-of-Scope Use Cases
45
+
46
+ **Any** deployed use case of the model - whether commercial or not - is currently out of scope. Non-deployed use cases such as image search in a constrained environment, are also not recommended unless there is thorough in-domain testing of the model with a specific, fixed class taxonomy. This is because our safety assessment demonstrated a high need for task specific testing especially given the variability of CLIP’s performance with different class taxonomies. This makes untested and unconstrained deployment of the model in any use case currently potentially harmful.
47
+
48
+ Certain use cases which would fall under the domain of surveillance and facial recognition are always out-of-scope regardless of performance of the model. This is because the use of artificial intelligence for tasks such as these can be premature currently given the lack of testing norms and checks to ensure its fair use.
49
+
50
+ Since the model has not been purposefully trained in or evaluated on any languages other than English, its use should be limited to English language use cases.
51
+
52
+
53
+
54
+ ## Data
55
+
56
+ The model was trained on publicly available image-caption data. This was done through a combination of crawling a handful of websites and using commonly-used pre-existing image datasets such as [YFCC100M](http://projects.dfki.uni-kl.de/yfcc100m/). A large portion of the data comes from our crawling of the internet. This means that the data is more representative of people and societies most connected to the internet which tend to skew towards more developed nations, and younger, male users.
57
+
58
+ ### Data Mission Statement
59
+
60
+ Our goal with building this dataset was to test out robustness and generalizability in computer vision tasks. As a result, the focus was on gathering large quantities of data from different publicly-available internet data sources. The data was gathered in a mostly non-interventionist manner. However, we only crawled websites that had policies against excessively violent and adult images and allowed us to filter out such content. We do not intend for this dataset to be used as the basis for any commercial or deployed model and will not be releasing the dataset.
61
+
62
+
63
+
64
+ ## Performance and Limitations
65
+
66
+ ### Performance
67
+
68
+ We have evaluated the performance of CLIP on a wide range of benchmarks across a variety of computer vision datasets such as OCR to texture recognition to fine-grained classification. The paper describes model performance on the following datasets:
69
+
70
+ - Food101
71
+ - CIFAR10
72
+ - CIFAR100
73
+ - Birdsnap
74
+ - SUN397
75
+ - Stanford Cars
76
+ - FGVC Aircraft
77
+ - VOC2007
78
+ - DTD
79
+ - Oxford-IIIT Pet dataset
80
+ - Caltech101
81
+ - Flowers102
82
+ - MNIST
83
+ - SVHN
84
+ - IIIT5K
85
+ - Hateful Memes
86
+ - SST-2
87
+ - UCF101
88
+ - Kinetics700
89
+ - Country211
90
+ - CLEVR Counting
91
+ - KITTI Distance
92
+ - STL-10
93
+ - RareAct
94
+ - Flickr30
95
+ - MSCOCO
96
+ - ImageNet
97
+ - ImageNet-A
98
+ - ImageNet-R
99
+ - ImageNet Sketch
100
+ - ObjectNet (ImageNet Overlap)
101
+ - Youtube-BB
102
+ - ImageNet-Vid
103
+
104
+ ## Limitations
105
+
106
+ CLIP and our analysis of it have a number of limitations. CLIP currently struggles with respect to certain tasks such as fine grained classification and counting objects. CLIP also poses issues with regards to fairness and bias which we discuss in the paper and briefly in the next section. Additionally, our approach to testing CLIP also has an important limitation- in many cases we have used linear probes to evaluate the performance of CLIP and there is evidence suggesting that linear probes can underestimate model performance.
107
+
108
+ ### Bias and Fairness
109
+
110
+ We find that the performance of CLIP - and the specific biases it exhibits - can depend significantly on class design and the choices one makes for categories to include and exclude. We tested the risk of certain kinds of denigration with CLIP by classifying images of people from [Fairface](https://arxiv.org/abs/1908.04913) into crime-related and non-human animal categories. We found significant disparities with respect to race and gender. Additionally, we found that these disparities could shift based on how the classes were constructed. (Details captured in the Broader Impacts Section in the paper).
111
+
112
+ We also tested the performance of CLIP on gender, race and age classification using the Fairface dataset (We default to using race categories as they are constructed in the Fairface dataset.) in order to assess quality of performance across different demographics. We found accuracy >96% across all races for gender classification with ‘Middle Eastern’ having the highest accuracy (98.4%) and ‘White’ having the lowest (96.5%). Additionally, CLIP averaged ~93% for racial classification and ~63% for age classification. Our use of evaluations to test for gender, race and age classification as well as denigration harms is simply to evaluate performance of the model across people and surface potential risks and not to demonstrate an endorsement/enthusiasm for such tasks.
113
+
114
+
115
+
116
+ ## Feedback
117
+
118
+ ### Where to send questions or comments about the model
119
+
120
+ Please use [this Google Form](https://forms.gle/Uv7afRH5dvY34ZEs9)
editing_diffusion/CLIP/notebooks/Interacting_with_CLIP.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
editing_diffusion/CLIP/notebooks/Prompt_Engineering_for_ImageNet.ipynb ADDED
@@ -0,0 +1,1108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "name": "Prompt Engineering for ImageNet.ipynb",
7
+ "provenance": [],
8
+ "collapsed_sections": []
9
+ },
10
+ "kernelspec": {
11
+ "name": "python3",
12
+ "display_name": "Python 3"
13
+ },
14
+ "accelerator": "GPU",
15
+ "widgets": {
16
+ "application/vnd.jupyter.widget-state+json": {
17
+ "66a1639713ae441d8a9b873381f9d774": {
18
+ "model_module": "@jupyter-widgets/controls",
19
+ "model_name": "HBoxModel",
20
+ "state": {
21
+ "_view_name": "HBoxView",
22
+ "_dom_classes": [],
23
+ "_model_name": "HBoxModel",
24
+ "_view_module": "@jupyter-widgets/controls",
25
+ "_model_module_version": "1.5.0",
26
+ "_view_count": null,
27
+ "_view_module_version": "1.5.0",
28
+ "box_style": "",
29
+ "layout": "IPY_MODEL_610b775178c645e2b4663b77cc0c67b6",
30
+ "_model_module": "@jupyter-widgets/controls",
31
+ "children": [
32
+ "IPY_MODEL_412dd15f0d8542f5ab2730f8616fb582",
33
+ "IPY_MODEL_5e6315f36b4e4eeea5c6294b024e0c97"
34
+ ]
35
+ }
36
+ },
37
+ "610b775178c645e2b4663b77cc0c67b6": {
38
+ "model_module": "@jupyter-widgets/base",
39
+ "model_name": "LayoutModel",
40
+ "state": {
41
+ "_view_name": "LayoutView",
42
+ "grid_template_rows": null,
43
+ "right": null,
44
+ "justify_content": null,
45
+ "_view_module": "@jupyter-widgets/base",
46
+ "overflow": null,
47
+ "_model_module_version": "1.2.0",
48
+ "_view_count": null,
49
+ "flex_flow": null,
50
+ "width": null,
51
+ "min_width": null,
52
+ "border": null,
53
+ "align_items": null,
54
+ "bottom": null,
55
+ "_model_module": "@jupyter-widgets/base",
56
+ "top": null,
57
+ "grid_column": null,
58
+ "overflow_y": null,
59
+ "overflow_x": null,
60
+ "grid_auto_flow": null,
61
+ "grid_area": null,
62
+ "grid_template_columns": null,
63
+ "flex": null,
64
+ "_model_name": "LayoutModel",
65
+ "justify_items": null,
66
+ "grid_row": null,
67
+ "max_height": null,
68
+ "align_content": null,
69
+ "visibility": null,
70
+ "align_self": null,
71
+ "height": null,
72
+ "min_height": null,
73
+ "padding": null,
74
+ "grid_auto_rows": null,
75
+ "grid_gap": null,
76
+ "max_width": null,
77
+ "order": null,
78
+ "_view_module_version": "1.2.0",
79
+ "grid_template_areas": null,
80
+ "object_position": null,
81
+ "object_fit": null,
82
+ "grid_auto_columns": null,
83
+ "margin": null,
84
+ "display": null,
85
+ "left": null
86
+ }
87
+ },
88
+ "412dd15f0d8542f5ab2730f8616fb582": {
89
+ "model_module": "@jupyter-widgets/controls",
90
+ "model_name": "FloatProgressModel",
91
+ "state": {
92
+ "_view_name": "ProgressView",
93
+ "style": "IPY_MODEL_085d5388abda4202bfa66d0c088452f8",
94
+ "_dom_classes": [],
95
+ "description": "100%",
96
+ "_model_name": "FloatProgressModel",
97
+ "bar_style": "success",
98
+ "max": 1000,
99
+ "_view_module": "@jupyter-widgets/controls",
100
+ "_model_module_version": "1.5.0",
101
+ "value": 1000,
102
+ "_view_count": null,
103
+ "_view_module_version": "1.5.0",
104
+ "orientation": "horizontal",
105
+ "min": 0,
106
+ "description_tooltip": null,
107
+ "_model_module": "@jupyter-widgets/controls",
108
+ "layout": "IPY_MODEL_f75124b64aa147c693c67a78f8e3a231"
109
+ }
110
+ },
111
+ "5e6315f36b4e4eeea5c6294b024e0c97": {
112
+ "model_module": "@jupyter-widgets/controls",
113
+ "model_name": "HTMLModel",
114
+ "state": {
115
+ "_view_name": "HTMLView",
116
+ "style": "IPY_MODEL_6e5676a054874243b55fc6d120a07d01",
117
+ "_dom_classes": [],
118
+ "description": "",
119
+ "_model_name": "HTMLModel",
120
+ "placeholder": "​",
121
+ "_view_module": "@jupyter-widgets/controls",
122
+ "_model_module_version": "1.5.0",
123
+ "value": " 1000/1000 [16:51&lt;00:00, 1.01s/it]",
124
+ "_view_count": null,
125
+ "_view_module_version": "1.5.0",
126
+ "description_tooltip": null,
127
+ "_model_module": "@jupyter-widgets/controls",
128
+ "layout": "IPY_MODEL_dc6d1416c01a4047935ee15c3fd2eb1c"
129
+ }
130
+ },
131
+ "085d5388abda4202bfa66d0c088452f8": {
132
+ "model_module": "@jupyter-widgets/controls",
133
+ "model_name": "ProgressStyleModel",
134
+ "state": {
135
+ "_view_name": "StyleView",
136
+ "_model_name": "ProgressStyleModel",
137
+ "description_width": "initial",
138
+ "_view_module": "@jupyter-widgets/base",
139
+ "_model_module_version": "1.5.0",
140
+ "_view_count": null,
141
+ "_view_module_version": "1.2.0",
142
+ "bar_color": null,
143
+ "_model_module": "@jupyter-widgets/controls"
144
+ }
145
+ },
146
+ "f75124b64aa147c693c67a78f8e3a231": {
147
+ "model_module": "@jupyter-widgets/base",
148
+ "model_name": "LayoutModel",
149
+ "state": {
150
+ "_view_name": "LayoutView",
151
+ "grid_template_rows": null,
152
+ "right": null,
153
+ "justify_content": null,
154
+ "_view_module": "@jupyter-widgets/base",
155
+ "overflow": null,
156
+ "_model_module_version": "1.2.0",
157
+ "_view_count": null,
158
+ "flex_flow": null,
159
+ "width": null,
160
+ "min_width": null,
161
+ "border": null,
162
+ "align_items": null,
163
+ "bottom": null,
164
+ "_model_module": "@jupyter-widgets/base",
165
+ "top": null,
166
+ "grid_column": null,
167
+ "overflow_y": null,
168
+ "overflow_x": null,
169
+ "grid_auto_flow": null,
170
+ "grid_area": null,
171
+ "grid_template_columns": null,
172
+ "flex": null,
173
+ "_model_name": "LayoutModel",
174
+ "justify_items": null,
175
+ "grid_row": null,
176
+ "max_height": null,
177
+ "align_content": null,
178
+ "visibility": null,
179
+ "align_self": null,
180
+ "height": null,
181
+ "min_height": null,
182
+ "padding": null,
183
+ "grid_auto_rows": null,
184
+ "grid_gap": null,
185
+ "max_width": null,
186
+ "order": null,
187
+ "_view_module_version": "1.2.0",
188
+ "grid_template_areas": null,
189
+ "object_position": null,
190
+ "object_fit": null,
191
+ "grid_auto_columns": null,
192
+ "margin": null,
193
+ "display": null,
194
+ "left": null
195
+ }
196
+ },
197
+ "6e5676a054874243b55fc6d120a07d01": {
198
+ "model_module": "@jupyter-widgets/controls",
199
+ "model_name": "DescriptionStyleModel",
200
+ "state": {
201
+ "_view_name": "StyleView",
202
+ "_model_name": "DescriptionStyleModel",
203
+ "description_width": "",
204
+ "_view_module": "@jupyter-widgets/base",
205
+ "_model_module_version": "1.5.0",
206
+ "_view_count": null,
207
+ "_view_module_version": "1.2.0",
208
+ "_model_module": "@jupyter-widgets/controls"
209
+ }
210
+ },
211
+ "dc6d1416c01a4047935ee15c3fd2eb1c": {
212
+ "model_module": "@jupyter-widgets/base",
213
+ "model_name": "LayoutModel",
214
+ "state": {
215
+ "_view_name": "LayoutView",
216
+ "grid_template_rows": null,
217
+ "right": null,
218
+ "justify_content": null,
219
+ "_view_module": "@jupyter-widgets/base",
220
+ "overflow": null,
221
+ "_model_module_version": "1.2.0",
222
+ "_view_count": null,
223
+ "flex_flow": null,
224
+ "width": null,
225
+ "min_width": null,
226
+ "border": null,
227
+ "align_items": null,
228
+ "bottom": null,
229
+ "_model_module": "@jupyter-widgets/base",
230
+ "top": null,
231
+ "grid_column": null,
232
+ "overflow_y": null,
233
+ "overflow_x": null,
234
+ "grid_auto_flow": null,
235
+ "grid_area": null,
236
+ "grid_template_columns": null,
237
+ "flex": null,
238
+ "_model_name": "LayoutModel",
239
+ "justify_items": null,
240
+ "grid_row": null,
241
+ "max_height": null,
242
+ "align_content": null,
243
+ "visibility": null,
244
+ "align_self": null,
245
+ "height": null,
246
+ "min_height": null,
247
+ "padding": null,
248
+ "grid_auto_rows": null,
249
+ "grid_gap": null,
250
+ "max_width": null,
251
+ "order": null,
252
+ "_view_module_version": "1.2.0",
253
+ "grid_template_areas": null,
254
+ "object_position": null,
255
+ "object_fit": null,
256
+ "grid_auto_columns": null,
257
+ "margin": null,
258
+ "display": null,
259
+ "left": null
260
+ }
261
+ },
262
+ "84f80a7f3e764346969a347b0f71b24e": {
263
+ "model_module": "@jupyter-widgets/controls",
264
+ "model_name": "HBoxModel",
265
+ "state": {
266
+ "_view_name": "HBoxView",
267
+ "_dom_classes": [],
268
+ "_model_name": "HBoxModel",
269
+ "_view_module": "@jupyter-widgets/controls",
270
+ "_model_module_version": "1.5.0",
271
+ "_view_count": null,
272
+ "_view_module_version": "1.5.0",
273
+ "box_style": "",
274
+ "layout": "IPY_MODEL_392656f01b2945f3bd7903783ed8cc96",
275
+ "_model_module": "@jupyter-widgets/controls",
276
+ "children": [
277
+ "IPY_MODEL_8e47a435519b4ce090879b4be2f61f99",
278
+ "IPY_MODEL_41b1ed6b0a9745c1a595377670b15ff4"
279
+ ]
280
+ }
281
+ },
282
+ "392656f01b2945f3bd7903783ed8cc96": {
283
+ "model_module": "@jupyter-widgets/base",
284
+ "model_name": "LayoutModel",
285
+ "state": {
286
+ "_view_name": "LayoutView",
287
+ "grid_template_rows": null,
288
+ "right": null,
289
+ "justify_content": null,
290
+ "_view_module": "@jupyter-widgets/base",
291
+ "overflow": null,
292
+ "_model_module_version": "1.2.0",
293
+ "_view_count": null,
294
+ "flex_flow": null,
295
+ "width": null,
296
+ "min_width": null,
297
+ "border": null,
298
+ "align_items": null,
299
+ "bottom": null,
300
+ "_model_module": "@jupyter-widgets/base",
301
+ "top": null,
302
+ "grid_column": null,
303
+ "overflow_y": null,
304
+ "overflow_x": null,
305
+ "grid_auto_flow": null,
306
+ "grid_area": null,
307
+ "grid_template_columns": null,
308
+ "flex": null,
309
+ "_model_name": "LayoutModel",
310
+ "justify_items": null,
311
+ "grid_row": null,
312
+ "max_height": null,
313
+ "align_content": null,
314
+ "visibility": null,
315
+ "align_self": null,
316
+ "height": null,
317
+ "min_height": null,
318
+ "padding": null,
319
+ "grid_auto_rows": null,
320
+ "grid_gap": null,
321
+ "max_width": null,
322
+ "order": null,
323
+ "_view_module_version": "1.2.0",
324
+ "grid_template_areas": null,
325
+ "object_position": null,
326
+ "object_fit": null,
327
+ "grid_auto_columns": null,
328
+ "margin": null,
329
+ "display": null,
330
+ "left": null
331
+ }
332
+ },
333
+ "8e47a435519b4ce090879b4be2f61f99": {
334
+ "model_module": "@jupyter-widgets/controls",
335
+ "model_name": "FloatProgressModel",
336
+ "state": {
337
+ "_view_name": "ProgressView",
338
+ "style": "IPY_MODEL_179b8ae1eb7f4a828f953e889b141725",
339
+ "_dom_classes": [],
340
+ "description": "100%",
341
+ "_model_name": "FloatProgressModel",
342
+ "bar_style": "success",
343
+ "max": 313,
344
+ "_view_module": "@jupyter-widgets/controls",
345
+ "_model_module_version": "1.5.0",
346
+ "value": 313,
347
+ "_view_count": null,
348
+ "_view_module_version": "1.5.0",
349
+ "orientation": "horizontal",
350
+ "min": 0,
351
+ "description_tooltip": null,
352
+ "_model_module": "@jupyter-widgets/controls",
353
+ "layout": "IPY_MODEL_d8708e8414fd44f4abd6590c9b57996f"
354
+ }
355
+ },
356
+ "41b1ed6b0a9745c1a595377670b15ff4": {
357
+ "model_module": "@jupyter-widgets/controls",
358
+ "model_name": "HTMLModel",
359
+ "state": {
360
+ "_view_name": "HTMLView",
361
+ "style": "IPY_MODEL_800e30f5b4f24475a2b0046da0703631",
362
+ "_dom_classes": [],
363
+ "description": "",
364
+ "_model_name": "HTMLModel",
365
+ "placeholder": "​",
366
+ "_view_module": "@jupyter-widgets/controls",
367
+ "_model_module_version": "1.5.0",
368
+ "value": " 313/313 [02:31&lt;00:00, 2.07it/s]",
369
+ "_view_count": null,
370
+ "_view_module_version": "1.5.0",
371
+ "description_tooltip": null,
372
+ "_model_module": "@jupyter-widgets/controls",
373
+ "layout": "IPY_MODEL_8764308b948745f1a677332fd21fcaf0"
374
+ }
375
+ },
376
+ "179b8ae1eb7f4a828f953e889b141725": {
377
+ "model_module": "@jupyter-widgets/controls",
378
+ "model_name": "ProgressStyleModel",
379
+ "state": {
380
+ "_view_name": "StyleView",
381
+ "_model_name": "ProgressStyleModel",
382
+ "description_width": "initial",
383
+ "_view_module": "@jupyter-widgets/base",
384
+ "_model_module_version": "1.5.0",
385
+ "_view_count": null,
386
+ "_view_module_version": "1.2.0",
387
+ "bar_color": null,
388
+ "_model_module": "@jupyter-widgets/controls"
389
+ }
390
+ },
391
+ "d8708e8414fd44f4abd6590c9b57996f": {
392
+ "model_module": "@jupyter-widgets/base",
393
+ "model_name": "LayoutModel",
394
+ "state": {
395
+ "_view_name": "LayoutView",
396
+ "grid_template_rows": null,
397
+ "right": null,
398
+ "justify_content": null,
399
+ "_view_module": "@jupyter-widgets/base",
400
+ "overflow": null,
401
+ "_model_module_version": "1.2.0",
402
+ "_view_count": null,
403
+ "flex_flow": null,
404
+ "width": null,
405
+ "min_width": null,
406
+ "border": null,
407
+ "align_items": null,
408
+ "bottom": null,
409
+ "_model_module": "@jupyter-widgets/base",
410
+ "top": null,
411
+ "grid_column": null,
412
+ "overflow_y": null,
413
+ "overflow_x": null,
414
+ "grid_auto_flow": null,
415
+ "grid_area": null,
416
+ "grid_template_columns": null,
417
+ "flex": null,
418
+ "_model_name": "LayoutModel",
419
+ "justify_items": null,
420
+ "grid_row": null,
421
+ "max_height": null,
422
+ "align_content": null,
423
+ "visibility": null,
424
+ "align_self": null,
425
+ "height": null,
426
+ "min_height": null,
427
+ "padding": null,
428
+ "grid_auto_rows": null,
429
+ "grid_gap": null,
430
+ "max_width": null,
431
+ "order": null,
432
+ "_view_module_version": "1.2.0",
433
+ "grid_template_areas": null,
434
+ "object_position": null,
435
+ "object_fit": null,
436
+ "grid_auto_columns": null,
437
+ "margin": null,
438
+ "display": null,
439
+ "left": null
440
+ }
441
+ },
442
+ "800e30f5b4f24475a2b0046da0703631": {
443
+ "model_module": "@jupyter-widgets/controls",
444
+ "model_name": "DescriptionStyleModel",
445
+ "state": {
446
+ "_view_name": "StyleView",
447
+ "_model_name": "DescriptionStyleModel",
448
+ "description_width": "",
449
+ "_view_module": "@jupyter-widgets/base",
450
+ "_model_module_version": "1.5.0",
451
+ "_view_count": null,
452
+ "_view_module_version": "1.2.0",
453
+ "_model_module": "@jupyter-widgets/controls"
454
+ }
455
+ },
456
+ "8764308b948745f1a677332fd21fcaf0": {
457
+ "model_module": "@jupyter-widgets/base",
458
+ "model_name": "LayoutModel",
459
+ "state": {
460
+ "_view_name": "LayoutView",
461
+ "grid_template_rows": null,
462
+ "right": null,
463
+ "justify_content": null,
464
+ "_view_module": "@jupyter-widgets/base",
465
+ "overflow": null,
466
+ "_model_module_version": "1.2.0",
467
+ "_view_count": null,
468
+ "flex_flow": null,
469
+ "width": null,
470
+ "min_width": null,
471
+ "border": null,
472
+ "align_items": null,
473
+ "bottom": null,
474
+ "_model_module": "@jupyter-widgets/base",
475
+ "top": null,
476
+ "grid_column": null,
477
+ "overflow_y": null,
478
+ "overflow_x": null,
479
+ "grid_auto_flow": null,
480
+ "grid_area": null,
481
+ "grid_template_columns": null,
482
+ "flex": null,
483
+ "_model_name": "LayoutModel",
484
+ "justify_items": null,
485
+ "grid_row": null,
486
+ "max_height": null,
487
+ "align_content": null,
488
+ "visibility": null,
489
+ "align_self": null,
490
+ "height": null,
491
+ "min_height": null,
492
+ "padding": null,
493
+ "grid_auto_rows": null,
494
+ "grid_gap": null,
495
+ "max_width": null,
496
+ "order": null,
497
+ "_view_module_version": "1.2.0",
498
+ "grid_template_areas": null,
499
+ "object_position": null,
500
+ "object_fit": null,
501
+ "grid_auto_columns": null,
502
+ "margin": null,
503
+ "display": null,
504
+ "left": null
505
+ }
506
+ }
507
+ }
508
+ }
509
+ },
510
+ "cells": [
511
+ {
512
+ "cell_type": "markdown",
513
+ "metadata": {
514
+ "id": "53N4k0pj_9qL"
515
+ },
516
+ "source": [
517
+ "# Preparation for Colab\n",
518
+ "\n",
519
+ "Make sure you're running a GPU runtime; if not, select \"GPU\" as the hardware accelerator in Runtime > Change Runtime Type in the menu. The next cells will install the `clip` package and its dependencies, and check if PyTorch 1.7.1 or later is installed."
520
+ ]
521
+ },
522
+ {
523
+ "cell_type": "code",
524
+ "metadata": {
525
+ "colab": {
526
+ "base_uri": "https://localhost:8080/"
527
+ },
528
+ "id": "0BpdJkdBssk9",
529
+ "outputId": "41a4070f-5321-4fc4-bd4d-0b5c1f476d56"
530
+ },
531
+ "source": [
532
+ "! pip install ftfy regex tqdm\n",
533
+ "! pip install git+https://github.com/openai/CLIP.git"
534
+ ],
535
+ "execution_count": 1,
536
+ "outputs": [
537
+ {
538
+ "output_type": "stream",
539
+ "text": [
540
+ "Collecting ftfy\n",
541
+ " Downloading ftfy-6.0.3.tar.gz (64 kB)\n",
542
+ "\u001b[?25l\r\u001b[K |█████ | 10 kB 14.9 MB/s eta 0:00:01\r\u001b[K |██████████▏ | 20 kB 18.7 MB/s eta 0:00:01\r\u001b[K |███████████████▎ | 30 kB 9.0 MB/s eta 0:00:01\r\u001b[K |████████████████████▍ | 40 kB 4.1 MB/s eta 0:00:01\r\u001b[K |█████████████████████████▌ | 51 kB 4.6 MB/s eta 0:00:01\r\u001b[K |██████████████████████████████▋ | 61 kB 4.7 MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 64 kB 1.3 MB/s \n",
543
+ "\u001b[?25hRequirement already satisfied: regex in /usr/local/lib/python3.7/dist-packages (2019.12.20)\n",
544
+ "Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (4.41.1)\n",
545
+ "Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from ftfy) (0.2.5)\n",
546
+ "Building wheels for collected packages: ftfy\n",
547
+ " Building wheel for ftfy (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
548
+ " Created wheel for ftfy: filename=ftfy-6.0.3-py3-none-any.whl size=41934 sha256=90ec193331444b2c4ff1cd81935e7de42065b89d304db7efac67bcfd87c27873\n",
549
+ " Stored in directory: /root/.cache/pip/wheels/19/f5/38/273eb3b5e76dfd850619312f693716ac4518b498f5ffb6f56d\n",
550
+ "Successfully built ftfy\n",
551
+ "Installing collected packages: ftfy\n",
552
+ "Successfully installed ftfy-6.0.3\n",
553
+ "Collecting git+https://github.com/openai/CLIP.git\n",
554
+ " Cloning https://github.com/openai/CLIP.git to /tmp/pip-req-build-hqnbveqi\n",
555
+ " Running command git clone -q https://github.com/openai/CLIP.git /tmp/pip-req-build-hqnbveqi\n",
556
+ "Requirement already satisfied: ftfy in /usr/local/lib/python3.7/dist-packages (from clip==1.0) (6.0.3)\n",
557
+ "Requirement already satisfied: regex in /usr/local/lib/python3.7/dist-packages (from clip==1.0) (2019.12.20)\n",
558
+ "Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from clip==1.0) (4.41.1)\n",
559
+ "Requirement already satisfied: torch in /usr/local/lib/python3.7/dist-packages (from clip==1.0) (1.9.0+cu102)\n",
560
+ "Requirement already satisfied: torchvision in /usr/local/lib/python3.7/dist-packages (from clip==1.0) (0.10.0+cu102)\n",
561
+ "Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from ftfy->clip==1.0) (0.2.5)\n",
562
+ "Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch->clip==1.0) (3.7.4.3)\n",
563
+ "Requirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from torchvision->clip==1.0) (1.19.5)\n",
564
+ "Requirement already satisfied: pillow>=5.3.0 in /usr/local/lib/python3.7/dist-packages (from torchvision->clip==1.0) (7.1.2)\n",
565
+ "Building wheels for collected packages: clip\n",
566
+ " Building wheel for clip (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
567
+ " Created wheel for clip: filename=clip-1.0-py3-none-any.whl size=1369080 sha256=fda43d2b80cfb2b33c2d43e23ea5f53293a9a8b48d5f9e341de527f6adfbf5a3\n",
568
+ " Stored in directory: /tmp/pip-ephem-wheel-cache-kmmplf44/wheels/fd/b9/c3/5b4470e35ed76e174bff77c92f91da82098d5e35fd5bc8cdac\n",
569
+ "Successfully built clip\n",
570
+ "Installing collected packages: clip\n",
571
+ "Successfully installed clip-1.0\n"
572
+ ],
573
+ "name": "stdout"
574
+ }
575
+ ]
576
+ },
577
+ {
578
+ "cell_type": "code",
579
+ "metadata": {
580
+ "id": "C1hkDT38hSaP",
581
+ "colab": {
582
+ "base_uri": "https://localhost:8080/"
583
+ },
584
+ "outputId": "e10d4f17-8fa6-4b75-a18f-f0c38990b5a3"
585
+ },
586
+ "source": [
587
+ "import numpy as np\n",
588
+ "import torch\n",
589
+ "import clip\n",
590
+ "from tqdm.notebook import tqdm\n",
591
+ "\n",
592
+ "print(\"Torch version:\", torch.__version__)\n",
593
+ "\n",
594
+ "assert torch.__version__.split(\".\") >= [\"1\", \"7\", \"1\"], \"PyTorch 1.7.1 or later is required\""
595
+ ],
596
+ "execution_count": 2,
597
+ "outputs": [
598
+ {
599
+ "output_type": "stream",
600
+ "text": [
601
+ "Torch version: 1.9.0+cu102\n"
602
+ ],
603
+ "name": "stdout"
604
+ }
605
+ ]
606
+ },
607
+ {
608
+ "cell_type": "markdown",
609
+ "metadata": {
610
+ "id": "eFxgLV5HAEEw"
611
+ },
612
+ "source": [
613
+ "# Loading the model\n",
614
+ "\n",
615
+ "Download and instantiate a CLIP model using the `clip` module that we just installed."
616
+ ]
617
+ },
618
+ {
619
+ "cell_type": "code",
620
+ "metadata": {
621
+ "id": "uLFS29hnhlY4",
622
+ "colab": {
623
+ "base_uri": "https://localhost:8080/"
624
+ },
625
+ "outputId": "09abb234-693e-4efb-953f-e1847ba95758"
626
+ },
627
+ "source": [
628
+ "clip.available_models()"
629
+ ],
630
+ "execution_count": 3,
631
+ "outputs": [
632
+ {
633
+ "output_type": "execute_result",
634
+ "data": {
635
+ "text/plain": [
636
+ "['RN50', 'RN101', 'RN50x4', 'RN50x16', 'ViT-B/32', 'ViT-B/16']"
637
+ ]
638
+ },
639
+ "metadata": {
640
+ "tags": []
641
+ },
642
+ "execution_count": 3
643
+ }
644
+ ]
645
+ },
646
+ {
647
+ "cell_type": "code",
648
+ "metadata": {
649
+ "id": "cboKZocQlSYX",
650
+ "colab": {
651
+ "base_uri": "https://localhost:8080/"
652
+ },
653
+ "outputId": "240acdd0-ca62-45db-8418-9e4ef73e8aff"
654
+ },
655
+ "source": [
656
+ "model, preprocess = clip.load(\"ViT-B/32\")"
657
+ ],
658
+ "execution_count": 4,
659
+ "outputs": [
660
+ {
661
+ "output_type": "stream",
662
+ "text": [
663
+ "100%|███████████████████████████████████████| 338M/338M [00:05<00:00, 63.6MiB/s]\n"
664
+ ],
665
+ "name": "stderr"
666
+ }
667
+ ]
668
+ },
669
+ {
670
+ "cell_type": "code",
671
+ "metadata": {
672
+ "colab": {
673
+ "base_uri": "https://localhost:8080/"
674
+ },
675
+ "id": "IBRVTY9lbGm8",
676
+ "outputId": "785019a1-1f40-45b0-e349-b0d4ec3173bf"
677
+ },
678
+ "source": [
679
+ "input_resolution = model.visual.input_resolution\n",
680
+ "context_length = model.context_length\n",
681
+ "vocab_size = model.vocab_size\n",
682
+ "\n",
683
+ "print(\"Model parameters:\", f\"{np.sum([int(np.prod(p.shape)) for p in model.parameters()]):,}\")\n",
684
+ "print(\"Input resolution:\", input_resolution)\n",
685
+ "print(\"Context length:\", context_length)\n",
686
+ "print(\"Vocab size:\", vocab_size)"
687
+ ],
688
+ "execution_count": 5,
689
+ "outputs": [
690
+ {
691
+ "output_type": "stream",
692
+ "text": [
693
+ "Model parameters: 151,277,313\n",
694
+ "Input resolution: 224\n",
695
+ "Context length: 77\n",
696
+ "Vocab size: 49408\n"
697
+ ],
698
+ "name": "stdout"
699
+ }
700
+ ]
701
+ },
702
+ {
703
+ "cell_type": "markdown",
704
+ "metadata": {
705
+ "id": "LhO3OtOmF8M4"
706
+ },
707
+ "source": [
708
+ "# Preparing ImageNet labels and prompts\n",
709
+ "\n",
710
+ "The following cell contains the 1,000 labels for the ImageNet dataset, followed by the text templates we'll use as \"prompt engineering\"."
711
+ ]
712
+ },
713
+ {
714
+ "cell_type": "code",
715
+ "metadata": {
716
+ "id": "R2HbOZrqa0jF"
717
+ },
718
+ "source": [
719
+ "imagenet_classes = [\"tench\", \"goldfish\", \"great white shark\", \"tiger shark\", \"hammerhead shark\", \"electric ray\", \"stingray\", \"rooster\", \"hen\", \"ostrich\", \"brambling\", \"goldfinch\", \"house finch\", \"junco\", \"indigo bunting\", \"American robin\", \"bulbul\", \"jay\", \"magpie\", \"chickadee\", \"American dipper\", \"kite (bird of prey)\", \"bald eagle\", \"vulture\", \"great grey owl\", \"fire salamander\", \"smooth newt\", \"newt\", \"spotted salamander\", \"axolotl\", \"American bullfrog\", \"tree frog\", \"tailed frog\", \"loggerhead sea turtle\", \"leatherback sea turtle\", \"mud turtle\", \"terrapin\", \"box turtle\", \"banded gecko\", \"green iguana\", \"Carolina anole\", \"desert grassland whiptail lizard\", \"agama\", \"frilled-necked lizard\", \"alligator lizard\", \"Gila monster\", \"European green lizard\", \"chameleon\", \"Komodo dragon\", \"Nile crocodile\", \"American alligator\", \"triceratops\", \"worm snake\", \"ring-necked snake\", \"eastern hog-nosed snake\", \"smooth green snake\", \"kingsnake\", \"garter snake\", \"water snake\", \"vine snake\", \"night snake\", \"boa constrictor\", \"African rock python\", \"Indian cobra\", \"green mamba\", \"sea snake\", \"Saharan horned viper\", \"eastern diamondback rattlesnake\", \"sidewinder rattlesnake\", \"trilobite\", \"harvestman\", \"scorpion\", \"yellow garden spider\", \"barn spider\", \"European garden spider\", \"southern black widow\", \"tarantula\", \"wolf spider\", \"tick\", \"centipede\", \"black grouse\", \"ptarmigan\", \"ruffed grouse\", \"prairie grouse\", \"peafowl\", \"quail\", \"partridge\", \"african grey parrot\", \"macaw\", \"sulphur-crested cockatoo\", \"lorikeet\", \"coucal\", \"bee eater\", \"hornbill\", \"hummingbird\", \"jacamar\", \"toucan\", \"duck\", \"red-breasted merganser\", \"goose\", \"black swan\", \"tusker\", \"echidna\", \"platypus\", \"wallaby\", \"koala\", \"wombat\", \"jellyfish\", \"sea anemone\", \"brain coral\", \"flatworm\", \"nematode\", \"conch\", \"snail\", \"slug\", \"sea slug\", \"chiton\", \"chambered nautilus\", \"Dungeness crab\", \"rock crab\", \"fiddler crab\", \"red king crab\", \"American lobster\", \"spiny lobster\", \"crayfish\", \"hermit crab\", \"isopod\", \"white stork\", \"black stork\", \"spoonbill\", \"flamingo\", \"little blue heron\", \"great egret\", \"bittern bird\", \"crane bird\", \"limpkin\", \"common gallinule\", \"American coot\", \"bustard\", \"ruddy turnstone\", \"dunlin\", \"common redshank\", \"dowitcher\", \"oystercatcher\", \"pelican\", \"king penguin\", \"albatross\", \"grey whale\", \"killer whale\", \"dugong\", \"sea lion\", \"Chihuahua\", \"Japanese Chin\", \"Maltese\", \"Pekingese\", \"Shih Tzu\", \"King Charles Spaniel\", \"Papillon\", \"toy terrier\", \"Rhodesian Ridgeback\", \"Afghan Hound\", \"Basset Hound\", \"Beagle\", \"Bloodhound\", \"Bluetick Coonhound\", \"Black and Tan Coonhound\", \"Treeing Walker Coonhound\", \"English foxhound\", \"Redbone Coonhound\", \"borzoi\", \"Irish Wolfhound\", \"Italian Greyhound\", \"Whippet\", \"Ibizan Hound\", \"Norwegian Elkhound\", \"Otterhound\", \"Saluki\", \"Scottish Deerhound\", \"Weimaraner\", \"Staffordshire Bull Terrier\", \"American Staffordshire Terrier\", \"Bedlington Terrier\", \"Border Terrier\", \"Kerry Blue Terrier\", \"Irish Terrier\", \"Norfolk Terrier\", \"Norwich Terrier\", \"Yorkshire Terrier\", \"Wire Fox Terrier\", \"Lakeland Terrier\", \"Sealyham Terrier\", \"Airedale Terrier\", \"Cairn Terrier\", \"Australian Terrier\", \"Dandie Dinmont Terrier\", \"Boston Terrier\", \"Miniature Schnauzer\", \"Giant Schnauzer\", \"Standard Schnauzer\", \"Scottish Terrier\", \"Tibetan Terrier\", \"Australian Silky Terrier\", \"Soft-coated Wheaten Terrier\", \"West Highland White Terrier\", \"Lhasa Apso\", \"Flat-Coated Retriever\", \"Curly-coated Retriever\", \"Golden Retriever\", \"Labrador Retriever\", \"Chesapeake Bay Retriever\", \"German Shorthaired Pointer\", \"Vizsla\", \"English Setter\", \"Irish Setter\", \"Gordon Setter\", \"Brittany dog\", \"Clumber Spaniel\", \"English Springer Spaniel\", \"Welsh Springer Spaniel\", \"Cocker Spaniel\", \"Sussex Spaniel\", \"Irish Water Spaniel\", \"Kuvasz\", \"Schipperke\", \"Groenendael dog\", \"Malinois\", \"Briard\", \"Australian Kelpie\", \"Komondor\", \"Old English Sheepdog\", \"Shetland Sheepdog\", \"collie\", \"Border Collie\", \"Bouvier des Flandres dog\", \"Rottweiler\", \"German Shepherd Dog\", \"Dobermann\", \"Miniature Pinscher\", \"Greater Swiss Mountain Dog\", \"Bernese Mountain Dog\", \"Appenzeller Sennenhund\", \"Entlebucher Sennenhund\", \"Boxer\", \"Bullmastiff\", \"Tibetan Mastiff\", \"French Bulldog\", \"Great Dane\", \"St. Bernard\", \"husky\", \"Alaskan Malamute\", \"Siberian Husky\", \"Dalmatian\", \"Affenpinscher\", \"Basenji\", \"pug\", \"Leonberger\", \"Newfoundland dog\", \"Great Pyrenees dog\", \"Samoyed\", \"Pomeranian\", \"Chow Chow\", \"Keeshond\", \"brussels griffon\", \"Pembroke Welsh Corgi\", \"Cardigan Welsh Corgi\", \"Toy Poodle\", \"Miniature Poodle\", \"Standard Poodle\", \"Mexican hairless dog (xoloitzcuintli)\", \"grey wolf\", \"Alaskan tundra wolf\", \"red wolf or maned wolf\", \"coyote\", \"dingo\", \"dhole\", \"African wild dog\", \"hyena\", \"red fox\", \"kit fox\", \"Arctic fox\", \"grey fox\", \"tabby cat\", \"tiger cat\", \"Persian cat\", \"Siamese cat\", \"Egyptian Mau\", \"cougar\", \"lynx\", \"leopard\", \"snow leopard\", \"jaguar\", \"lion\", \"tiger\", \"cheetah\", \"brown bear\", \"American black bear\", \"polar bear\", \"sloth bear\", \"mongoose\", \"meerkat\", \"tiger beetle\", \"ladybug\", \"ground beetle\", \"longhorn beetle\", \"leaf beetle\", \"dung beetle\", \"rhinoceros beetle\", \"weevil\", \"fly\", \"bee\", \"ant\", \"grasshopper\", \"cricket insect\", \"stick insect\", \"cockroach\", \"praying mantis\", \"cicada\", \"leafhopper\", \"lacewing\", \"dragonfly\", \"damselfly\", \"red admiral butterfly\", \"ringlet butterfly\", \"monarch butterfly\", \"small white butterfly\", \"sulphur butterfly\", \"gossamer-winged butterfly\", \"starfish\", \"sea urchin\", \"sea cucumber\", \"cottontail rabbit\", \"hare\", \"Angora rabbit\", \"hamster\", \"porcupine\", \"fox squirrel\", \"marmot\", \"beaver\", \"guinea pig\", \"common sorrel horse\", \"zebra\", \"pig\", \"wild boar\", \"warthog\", \"hippopotamus\", \"ox\", \"water buffalo\", \"bison\", \"ram (adult male sheep)\", \"bighorn sheep\", \"Alpine ibex\", \"hartebeest\", \"impala (antelope)\", \"gazelle\", \"arabian camel\", \"llama\", \"weasel\", \"mink\", \"European polecat\", \"black-footed ferret\", \"otter\", \"skunk\", \"badger\", \"armadillo\", \"three-toed sloth\", \"orangutan\", \"gorilla\", \"chimpanzee\", \"gibbon\", \"siamang\", \"guenon\", \"patas monkey\", \"baboon\", \"macaque\", \"langur\", \"black-and-white colobus\", \"proboscis monkey\", \"marmoset\", \"white-headed capuchin\", \"howler monkey\", \"titi monkey\", \"Geoffroy's spider monkey\", \"common squirrel monkey\", \"ring-tailed lemur\", \"indri\", \"Asian elephant\", \"African bush elephant\", \"red panda\", \"giant panda\", \"snoek fish\", \"eel\", \"silver salmon\", \"rock beauty fish\", \"clownfish\", \"sturgeon\", \"gar fish\", \"lionfish\", \"pufferfish\", \"abacus\", \"abaya\", \"academic gown\", \"accordion\", \"acoustic guitar\", \"aircraft carrier\", \"airliner\", \"airship\", \"altar\", \"ambulance\", \"amphibious vehicle\", \"analog clock\", \"apiary\", \"apron\", \"trash can\", \"assault rifle\", \"backpack\", \"bakery\", \"balance beam\", \"balloon\", \"ballpoint pen\", \"Band-Aid\", \"banjo\", \"baluster / handrail\", \"barbell\", \"barber chair\", \"barbershop\", \"barn\", \"barometer\", \"barrel\", \"wheelbarrow\", \"baseball\", \"basketball\", \"bassinet\", \"bassoon\", \"swimming cap\", \"bath towel\", \"bathtub\", \"station wagon\", \"lighthouse\", \"beaker\", \"military hat (bearskin or shako)\", \"beer bottle\", \"beer glass\", \"bell tower\", \"baby bib\", \"tandem bicycle\", \"bikini\", \"ring binder\", \"binoculars\", \"birdhouse\", \"boathouse\", \"bobsleigh\", \"bolo tie\", \"poke bonnet\", \"bookcase\", \"bookstore\", \"bottle cap\", \"hunting bow\", \"bow tie\", \"brass memorial plaque\", \"bra\", \"breakwater\", \"breastplate\", \"broom\", \"bucket\", \"buckle\", \"bulletproof vest\", \"high-speed train\", \"butcher shop\", \"taxicab\", \"cauldron\", \"candle\", \"cannon\", \"canoe\", \"can opener\", \"cardigan\", \"car mirror\", \"carousel\", \"tool kit\", \"cardboard box / carton\", \"car wheel\", \"automated teller machine\", \"cassette\", \"cassette player\", \"castle\", \"catamaran\", \"CD player\", \"cello\", \"mobile phone\", \"chain\", \"chain-link fence\", \"chain mail\", \"chainsaw\", \"storage chest\", \"chiffonier\", \"bell or wind chime\", \"china cabinet\", \"Christmas stocking\", \"church\", \"movie theater\", \"cleaver\", \"cliff dwelling\", \"cloak\", \"clogs\", \"cocktail shaker\", \"coffee mug\", \"coffeemaker\", \"spiral or coil\", \"combination lock\", \"computer keyboard\", \"candy store\", \"container ship\", \"convertible\", \"corkscrew\", \"cornet\", \"cowboy boot\", \"cowboy hat\", \"cradle\", \"construction crane\", \"crash helmet\", \"crate\", \"infant bed\", \"Crock Pot\", \"croquet ball\", \"crutch\", \"cuirass\", \"dam\", \"desk\", \"desktop computer\", \"rotary dial telephone\", \"diaper\", \"digital clock\", \"digital watch\", \"dining table\", \"dishcloth\", \"dishwasher\", \"disc brake\", \"dock\", \"dog sled\", \"dome\", \"doormat\", \"drilling rig\", \"drum\", \"drumstick\", \"dumbbell\", \"Dutch oven\", \"electric fan\", \"electric guitar\", \"electric locomotive\", \"entertainment center\", \"envelope\", \"espresso machine\", \"face powder\", \"feather boa\", \"filing cabinet\", \"fireboat\", \"fire truck\", \"fire screen\", \"flagpole\", \"flute\", \"folding chair\", \"football helmet\", \"forklift\", \"fountain\", \"fountain pen\", \"four-poster bed\", \"freight car\", \"French horn\", \"frying pan\", \"fur coat\", \"garbage truck\", \"gas mask or respirator\", \"gas pump\", \"goblet\", \"go-kart\", \"golf ball\", \"golf cart\", \"gondola\", \"gong\", \"gown\", \"grand piano\", \"greenhouse\", \"radiator grille\", \"grocery store\", \"guillotine\", \"hair clip\", \"hair spray\", \"half-track\", \"hammer\", \"hamper\", \"hair dryer\", \"hand-held computer\", \"handkerchief\", \"hard disk drive\", \"harmonica\", \"harp\", \"combine harvester\", \"hatchet\", \"holster\", \"home theater\", \"honeycomb\", \"hook\", \"hoop skirt\", \"gymnastic horizontal bar\", \"horse-drawn vehicle\", \"hourglass\", \"iPod\", \"clothes iron\", \"carved pumpkin\", \"jeans\", \"jeep\", \"T-shirt\", \"jigsaw puzzle\", \"rickshaw\", \"joystick\", \"kimono\", \"knee pad\", \"knot\", \"lab coat\", \"ladle\", \"lampshade\", \"laptop computer\", \"lawn mower\", \"lens cap\", \"letter opener\", \"library\", \"lifeboat\", \"lighter\", \"limousine\", \"ocean liner\", \"lipstick\", \"slip-on shoe\", \"lotion\", \"music speaker\", \"loupe magnifying glass\", \"sawmill\", \"magnetic compass\", \"messenger bag\", \"mailbox\", \"tights\", \"one-piece bathing suit\", \"manhole cover\", \"maraca\", \"marimba\", \"mask\", \"matchstick\", \"maypole\", \"maze\", \"measuring cup\", \"medicine cabinet\", \"megalith\", \"microphone\", \"microwave oven\", \"military uniform\", \"milk can\", \"minibus\", \"miniskirt\", \"minivan\", \"missile\", \"mitten\", \"mixing bowl\", \"mobile home\", \"ford model t\", \"modem\", \"monastery\", \"monitor\", \"moped\", \"mortar and pestle\", \"graduation cap\", \"mosque\", \"mosquito net\", \"vespa\", \"mountain bike\", \"tent\", \"computer mouse\", \"mousetrap\", \"moving van\", \"muzzle\", \"metal nail\", \"neck brace\", \"necklace\", \"baby pacifier\", \"notebook computer\", \"obelisk\", \"oboe\", \"ocarina\", \"odometer\", \"oil filter\", \"pipe organ\", \"oscilloscope\", \"overskirt\", \"bullock cart\", \"oxygen mask\", \"product packet / packaging\", \"paddle\", \"paddle wheel\", \"padlock\", \"paintbrush\", \"pajamas\", \"palace\", \"pan flute\", \"paper towel\", \"parachute\", \"parallel bars\", \"park bench\", \"parking meter\", \"railroad car\", \"patio\", \"payphone\", \"pedestal\", \"pencil case\", \"pencil sharpener\", \"perfume\", \"Petri dish\", \"photocopier\", \"plectrum\", \"Pickelhaube\", \"picket fence\", \"pickup truck\", \"pier\", \"piggy bank\", \"pill bottle\", \"pillow\", \"ping-pong ball\", \"pinwheel\", \"pirate ship\", \"drink pitcher\", \"block plane\", \"planetarium\", \"plastic bag\", \"plate rack\", \"farm plow\", \"plunger\", \"Polaroid camera\", \"pole\", \"police van\", \"poncho\", \"pool table\", \"soda bottle\", \"plant pot\", \"potter's wheel\", \"power drill\", \"prayer rug\", \"printer\", \"prison\", \"missile\", \"projector\", \"hockey puck\", \"punching bag\", \"purse\", \"quill\", \"quilt\", \"race car\", \"racket\", \"radiator\", \"radio\", \"radio telescope\", \"rain barrel\", \"recreational vehicle\", \"fishing casting reel\", \"reflex camera\", \"refrigerator\", \"remote control\", \"restaurant\", \"revolver\", \"rifle\", \"rocking chair\", \"rotisserie\", \"eraser\", \"rugby ball\", \"ruler measuring stick\", \"sneaker\", \"safe\", \"safety pin\", \"salt shaker\", \"sandal\", \"sarong\", \"saxophone\", \"scabbard\", \"weighing scale\", \"school bus\", \"schooner\", \"scoreboard\", \"CRT monitor\", \"screw\", \"screwdriver\", \"seat belt\", \"sewing machine\", \"shield\", \"shoe store\", \"shoji screen / room divider\", \"shopping basket\", \"shopping cart\", \"shovel\", \"shower cap\", \"shower curtain\", \"ski\", \"balaclava ski mask\", \"sleeping bag\", \"slide rule\", \"sliding door\", \"slot machine\", \"snorkel\", \"snowmobile\", \"snowplow\", \"soap dispenser\", \"soccer ball\", \"sock\", \"solar thermal collector\", \"sombrero\", \"soup bowl\", \"keyboard space bar\", \"space heater\", \"space shuttle\", \"spatula\", \"motorboat\", \"spider web\", \"spindle\", \"sports car\", \"spotlight\", \"stage\", \"steam locomotive\", \"through arch bridge\", \"steel drum\", \"stethoscope\", \"scarf\", \"stone wall\", \"stopwatch\", \"stove\", \"strainer\", \"tram\", \"stretcher\", \"couch\", \"stupa\", \"submarine\", \"suit\", \"sundial\", \"sunglasses\", \"sunglasses\", \"sunscreen\", \"suspension bridge\", \"mop\", \"sweatshirt\", \"swim trunks / shorts\", \"swing\", \"electrical switch\", \"syringe\", \"table lamp\", \"tank\", \"tape player\", \"teapot\", \"teddy bear\", \"television\", \"tennis ball\", \"thatched roof\", \"front curtain\", \"thimble\", \"threshing machine\", \"throne\", \"tile roof\", \"toaster\", \"tobacco shop\", \"toilet seat\", \"torch\", \"totem pole\", \"tow truck\", \"toy store\", \"tractor\", \"semi-trailer truck\", \"tray\", \"trench coat\", \"tricycle\", \"trimaran\", \"tripod\", \"triumphal arch\", \"trolleybus\", \"trombone\", \"hot tub\", \"turnstile\", \"typewriter keyboard\", \"umbrella\", \"unicycle\", \"upright piano\", \"vacuum cleaner\", \"vase\", \"vaulted or arched ceiling\", \"velvet fabric\", \"vending machine\", \"vestment\", \"viaduct\", \"violin\", \"volleyball\", \"waffle iron\", \"wall clock\", \"wallet\", \"wardrobe\", \"military aircraft\", \"sink\", \"washing machine\", \"water bottle\", \"water jug\", \"water tower\", \"whiskey jug\", \"whistle\", \"hair wig\", \"window screen\", \"window shade\", \"Windsor tie\", \"wine bottle\", \"airplane wing\", \"wok\", \"wooden spoon\", \"wool\", \"split-rail fence\", \"shipwreck\", \"sailboat\", \"yurt\", \"website\", \"comic book\", \"crossword\", \"traffic or street sign\", \"traffic light\", \"dust jacket\", \"menu\", \"plate\", \"guacamole\", \"consomme\", \"hot pot\", \"trifle\", \"ice cream\", \"popsicle\", \"baguette\", \"bagel\", \"pretzel\", \"cheeseburger\", \"hot dog\", \"mashed potatoes\", \"cabbage\", \"broccoli\", \"cauliflower\", \"zucchini\", \"spaghetti squash\", \"acorn squash\", \"butternut squash\", \"cucumber\", \"artichoke\", \"bell pepper\", \"cardoon\", \"mushroom\", \"Granny Smith apple\", \"strawberry\", \"orange\", \"lemon\", \"fig\", \"pineapple\", \"banana\", \"jackfruit\", \"cherimoya (custard apple)\", \"pomegranate\", \"hay\", \"carbonara\", \"chocolate syrup\", \"dough\", \"meatloaf\", \"pizza\", \"pot pie\", \"burrito\", \"red wine\", \"espresso\", \"tea cup\", \"eggnog\", \"mountain\", \"bubble\", \"cliff\", \"coral reef\", \"geyser\", \"lakeshore\", \"promontory\", \"sandbar\", \"beach\", \"valley\", \"volcano\", \"baseball player\", \"bridegroom\", \"scuba diver\", \"rapeseed\", \"daisy\", \"yellow lady's slipper\", \"corn\", \"acorn\", \"rose hip\", \"horse chestnut seed\", \"coral fungus\", \"agaric\", \"gyromitra\", \"stinkhorn mushroom\", \"earth star fungus\", \"hen of the woods mushroom\", \"bolete\", \"corn cob\", \"toilet paper\"]"
720
+ ],
721
+ "execution_count": 6,
722
+ "outputs": []
723
+ },
724
+ {
725
+ "cell_type": "markdown",
726
+ "metadata": {
727
+ "id": "eMQSCuBta2G6"
728
+ },
729
+ "source": [
730
+ "A subset of these class names are modified from the default ImageNet class names sourced from Anish Athalye's imagenet-simple-labels.\n",
731
+ "\n",
732
+ "These edits were made via trial and error and concentrated on the lowest performing classes according to top_1 and top_5 accuracy on the ImageNet training set for the RN50, RN101, and RN50x4 models. These tweaks improve top_1 by 1.5% on ViT-B/32 over using the default class names. Alec got bored somewhere along the way as gains started to diminish and never finished updating / tweaking the list. He also didn't revisit this with the better performing RN50x16, RN50x64, or any of the ViT models. He thinks it's likely another 0.5% to 1% top_1 could be gained from further work here. It'd be interesting to more rigorously study / understand this.\n",
733
+ "\n",
734
+ "Some examples beyond the crane/crane -> construction crane / bird crane issue mentioned in Section 3.1.4 of the paper include:\n",
735
+ "\n",
736
+ "- CLIP interprets \"nail\" as \"fingernail\" so we changed the label to \"metal nail\".\n",
737
+ "- ImageNet kite class refers to the bird of prey, not the flying toy, so we changed \"kite\" to \"kite (bird of prey)\"\n",
738
+ "- The ImageNet class for red wolf seems to include a lot of mislabeled maned wolfs so we changed \"red wolf\" to \"red wolf or maned wolf\""
739
+ ]
740
+ },
741
+ {
742
+ "cell_type": "code",
743
+ "metadata": {
744
+ "id": "toGtcd-Ji_MD",
745
+ "colab": {
746
+ "base_uri": "https://localhost:8080/"
747
+ },
748
+ "outputId": "b6eb0753-2bee-4144-abe3-fbd23f35f555"
749
+ },
750
+ "source": [
751
+ "imagenet_templates = [\n",
752
+ " 'a bad photo of a {}.',\n",
753
+ " 'a photo of many {}.',\n",
754
+ " 'a sculpture of a {}.',\n",
755
+ " 'a photo of the hard to see {}.',\n",
756
+ " 'a low resolution photo of the {}.',\n",
757
+ " 'a rendering of a {}.',\n",
758
+ " 'graffiti of a {}.',\n",
759
+ " 'a bad photo of the {}.',\n",
760
+ " 'a cropped photo of the {}.',\n",
761
+ " 'a tattoo of a {}.',\n",
762
+ " 'the embroidered {}.',\n",
763
+ " 'a photo of a hard to see {}.',\n",
764
+ " 'a bright photo of a {}.',\n",
765
+ " 'a photo of a clean {}.',\n",
766
+ " 'a photo of a dirty {}.',\n",
767
+ " 'a dark photo of the {}.',\n",
768
+ " 'a drawing of a {}.',\n",
769
+ " 'a photo of my {}.',\n",
770
+ " 'the plastic {}.',\n",
771
+ " 'a photo of the cool {}.',\n",
772
+ " 'a close-up photo of a {}.',\n",
773
+ " 'a black and white photo of the {}.',\n",
774
+ " 'a painting of the {}.',\n",
775
+ " 'a painting of a {}.',\n",
776
+ " 'a pixelated photo of the {}.',\n",
777
+ " 'a sculpture of the {}.',\n",
778
+ " 'a bright photo of the {}.',\n",
779
+ " 'a cropped photo of a {}.',\n",
780
+ " 'a plastic {}.',\n",
781
+ " 'a photo of the dirty {}.',\n",
782
+ " 'a jpeg corrupted photo of a {}.',\n",
783
+ " 'a blurry photo of the {}.',\n",
784
+ " 'a photo of the {}.',\n",
785
+ " 'a good photo of the {}.',\n",
786
+ " 'a rendering of the {}.',\n",
787
+ " 'a {} in a video game.',\n",
788
+ " 'a photo of one {}.',\n",
789
+ " 'a doodle of a {}.',\n",
790
+ " 'a close-up photo of the {}.',\n",
791
+ " 'a photo of a {}.',\n",
792
+ " 'the origami {}.',\n",
793
+ " 'the {} in a video game.',\n",
794
+ " 'a sketch of a {}.',\n",
795
+ " 'a doodle of the {}.',\n",
796
+ " 'a origami {}.',\n",
797
+ " 'a low resolution photo of a {}.',\n",
798
+ " 'the toy {}.',\n",
799
+ " 'a rendition of the {}.',\n",
800
+ " 'a photo of the clean {}.',\n",
801
+ " 'a photo of a large {}.',\n",
802
+ " 'a rendition of a {}.',\n",
803
+ " 'a photo of a nice {}.',\n",
804
+ " 'a photo of a weird {}.',\n",
805
+ " 'a blurry photo of a {}.',\n",
806
+ " 'a cartoon {}.',\n",
807
+ " 'art of a {}.',\n",
808
+ " 'a sketch of the {}.',\n",
809
+ " 'a embroidered {}.',\n",
810
+ " 'a pixelated photo of a {}.',\n",
811
+ " 'itap of the {}.',\n",
812
+ " 'a jpeg corrupted photo of the {}.',\n",
813
+ " 'a good photo of a {}.',\n",
814
+ " 'a plushie {}.',\n",
815
+ " 'a photo of the nice {}.',\n",
816
+ " 'a photo of the small {}.',\n",
817
+ " 'a photo of the weird {}.',\n",
818
+ " 'the cartoon {}.',\n",
819
+ " 'art of the {}.',\n",
820
+ " 'a drawing of the {}.',\n",
821
+ " 'a photo of the large {}.',\n",
822
+ " 'a black and white photo of a {}.',\n",
823
+ " 'the plushie {}.',\n",
824
+ " 'a dark photo of a {}.',\n",
825
+ " 'itap of a {}.',\n",
826
+ " 'graffiti of the {}.',\n",
827
+ " 'a toy {}.',\n",
828
+ " 'itap of my {}.',\n",
829
+ " 'a photo of a cool {}.',\n",
830
+ " 'a photo of a small {}.',\n",
831
+ " 'a tattoo of the {}.',\n",
832
+ "]\n",
833
+ "\n",
834
+ "print(f\"{len(imagenet_classes)} classes, {len(imagenet_templates)} templates\")"
835
+ ],
836
+ "execution_count": 7,
837
+ "outputs": [
838
+ {
839
+ "output_type": "stream",
840
+ "text": [
841
+ "1000 classes, 80 templates\n"
842
+ ],
843
+ "name": "stdout"
844
+ }
845
+ ]
846
+ },
847
+ {
848
+ "cell_type": "markdown",
849
+ "metadata": {
850
+ "id": "aRB5OzgpHwqQ"
851
+ },
852
+ "source": [
853
+ "A similar, intuition-guided trial and error based on the ImageNet training set was used for templates. This list is pretty haphazard and was gradually made / expanded over the course of about a year of the project and was revisited / tweaked every few months. A surprising / weird thing was adding templates intended to help ImageNet-R performance (specifying different possible renditions of an object) improved standard ImageNet accuracy too.\n",
854
+ "\n",
855
+ "After the 80 templates were \"locked\" for the paper, we ran sequential forward selection over the list of 80 templates. The search terminated after ensembling 7 templates and selected them in the order below.\n",
856
+ "\n",
857
+ "1. itap of a {}.\n",
858
+ "2. a bad photo of the {}.\n",
859
+ "3. a origami {}.\n",
860
+ "4. a photo of the large {}.\n",
861
+ "5. a {} in a video game.\n",
862
+ "6. art of the {}.\n",
863
+ "7. a photo of the small {}.\n",
864
+ "\n",
865
+ "Speculating, we think it's interesting to see different scales (large and small), a difficult view (a bad photo), and \"abstract\" versions (origami, video game, art), were all selected for, but we haven't studied this in any detail. This subset performs a bit better than the full 80 ensemble reported in the paper, especially for the smaller models."
866
+ ]
867
+ },
868
+ {
869
+ "cell_type": "markdown",
870
+ "metadata": {
871
+ "id": "4W8ARJVqBJXs"
872
+ },
873
+ "source": [
874
+ "# Loading the Images\n",
875
+ "\n",
876
+ "The ILSVRC2012 datasets are no longer available for download publicly. We instead download the ImageNet-V2 dataset by [Recht et al.](https://arxiv.org/abs/1902.10811).\n",
877
+ "\n",
878
+ "If you have the ImageNet dataset downloaded, you can replace the dataset with the official torchvision loader, e.g.:\n",
879
+ "\n",
880
+ "```python\n",
881
+ "images = torchvision.datasets.ImageNet(\"path/to/imagenet\", split='val', transform=preprocess)\n",
882
+ "```"
883
+ ]
884
+ },
885
+ {
886
+ "cell_type": "code",
887
+ "metadata": {
888
+ "colab": {
889
+ "base_uri": "https://localhost:8080/"
890
+ },
891
+ "id": "moHR4UlHKsDc",
892
+ "outputId": "40731297-edc7-4cd0-be75-ed426c8fb005"
893
+ },
894
+ "source": [
895
+ "! pip install git+https://github.com/modestyachts/ImageNetV2_pytorch\n",
896
+ "\n",
897
+ "from imagenetv2_pytorch import ImageNetV2Dataset\n",
898
+ "\n",
899
+ "images = ImageNetV2Dataset(transform=preprocess)\n",
900
+ "loader = torch.utils.data.DataLoader(images, batch_size=32, num_workers=2)"
901
+ ],
902
+ "execution_count": 8,
903
+ "outputs": [
904
+ {
905
+ "output_type": "stream",
906
+ "text": [
907
+ "Collecting git+https://github.com/modestyachts/ImageNetV2_pytorch\n",
908
+ " Cloning https://github.com/modestyachts/ImageNetV2_pytorch to /tmp/pip-req-build-0kih0kn2\n",
909
+ " Running command git clone -q https://github.com/modestyachts/ImageNetV2_pytorch /tmp/pip-req-build-0kih0kn2\n",
910
+ "Building wheels for collected packages: imagenetv2-pytorch\n",
911
+ " Building wheel for imagenetv2-pytorch (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
912
+ " Created wheel for imagenetv2-pytorch: filename=imagenetv2_pytorch-0.1-py3-none-any.whl size=2663 sha256=ac31e0ed9c61afc5e0271eed315d3a82844a79ae64f8ce43fc1c98928cec129f\n",
913
+ " Stored in directory: /tmp/pip-ephem-wheel-cache-745b5n1m/wheels/ab/ee/f4/73bce5c7f68d28ce632ef33ae87ce60aaca021eb2b3b31a6fa\n",
914
+ "Successfully built imagenetv2-pytorch\n",
915
+ "Installing collected packages: imagenetv2-pytorch\n",
916
+ "Successfully installed imagenetv2-pytorch-0.1\n",
917
+ "Dataset matched-frequency not found on disk, downloading....\n"
918
+ ],
919
+ "name": "stdout"
920
+ },
921
+ {
922
+ "output_type": "stream",
923
+ "text": [
924
+ "100%|██████████| 1.26G/1.26G [01:02<00:00, 20.2MiB/s]\n"
925
+ ],
926
+ "name": "stderr"
927
+ },
928
+ {
929
+ "output_type": "stream",
930
+ "text": [
931
+ "Extracting....\n"
932
+ ],
933
+ "name": "stdout"
934
+ }
935
+ ]
936
+ },
937
+ {
938
+ "cell_type": "markdown",
939
+ "metadata": {
940
+ "id": "fz6D-F-Wbrtp"
941
+ },
942
+ "source": [
943
+ "# Creating zero-shot classifier weights"
944
+ ]
945
+ },
946
+ {
947
+ "cell_type": "code",
948
+ "metadata": {
949
+ "colab": {
950
+ "base_uri": "https://localhost:8080/",
951
+ "height": 67,
952
+ "referenced_widgets": [
953
+ "66a1639713ae441d8a9b873381f9d774",
954
+ "610b775178c645e2b4663b77cc0c67b6",
955
+ "412dd15f0d8542f5ab2730f8616fb582",
956
+ "5e6315f36b4e4eeea5c6294b024e0c97",
957
+ "085d5388abda4202bfa66d0c088452f8",
958
+ "f75124b64aa147c693c67a78f8e3a231",
959
+ "6e5676a054874243b55fc6d120a07d01",
960
+ "dc6d1416c01a4047935ee15c3fd2eb1c"
961
+ ]
962
+ },
963
+ "id": "sRqDoz1Gbsii",
964
+ "outputId": "312b8ebf-3961-4903-d8cb-3b7a94cc97b6"
965
+ },
966
+ "source": [
967
+ "def zeroshot_classifier(classnames, templates):\n",
968
+ " with torch.no_grad():\n",
969
+ " zeroshot_weights = []\n",
970
+ " for classname in tqdm(classnames):\n",
971
+ " texts = [template.format(classname) for template in templates] #format with class\n",
972
+ " texts = clip.tokenize(texts).cuda() #tokenize\n",
973
+ " class_embeddings = model.encode_text(texts) #embed with text encoder\n",
974
+ " class_embeddings /= class_embeddings.norm(dim=-1, keepdim=True)\n",
975
+ " class_embedding = class_embeddings.mean(dim=0)\n",
976
+ " class_embedding /= class_embedding.norm()\n",
977
+ " zeroshot_weights.append(class_embedding)\n",
978
+ " zeroshot_weights = torch.stack(zeroshot_weights, dim=1).cuda()\n",
979
+ " return zeroshot_weights\n",
980
+ "\n",
981
+ "\n",
982
+ "zeroshot_weights = zeroshot_classifier(imagenet_classes, imagenet_templates)"
983
+ ],
984
+ "execution_count": 9,
985
+ "outputs": [
986
+ {
987
+ "output_type": "display_data",
988
+ "data": {
989
+ "application/vnd.jupyter.widget-view+json": {
990
+ "model_id": "66a1639713ae441d8a9b873381f9d774",
991
+ "version_minor": 0,
992
+ "version_major": 2
993
+ },
994
+ "text/plain": [
995
+ "HBox(children=(FloatProgress(value=0.0, max=1000.0), HTML(value='')))"
996
+ ]
997
+ },
998
+ "metadata": {
999
+ "tags": []
1000
+ }
1001
+ },
1002
+ {
1003
+ "output_type": "stream",
1004
+ "text": [
1005
+ "\n"
1006
+ ],
1007
+ "name": "stdout"
1008
+ }
1009
+ ]
1010
+ },
1011
+ {
1012
+ "cell_type": "markdown",
1013
+ "metadata": {
1014
+ "id": "1fZo7hG8iJP5"
1015
+ },
1016
+ "source": [
1017
+ "# Zero-shot prediction"
1018
+ ]
1019
+ },
1020
+ {
1021
+ "cell_type": "code",
1022
+ "metadata": {
1023
+ "id": "j4kPSZoShQxN"
1024
+ },
1025
+ "source": [
1026
+ "def accuracy(output, target, topk=(1,)):\n",
1027
+ " pred = output.topk(max(topk), 1, True, True)[1].t()\n",
1028
+ " correct = pred.eq(target.view(1, -1).expand_as(pred))\n",
1029
+ " return [float(correct[:k].reshape(-1).float().sum(0, keepdim=True).cpu().numpy()) for k in topk]"
1030
+ ],
1031
+ "execution_count": 10,
1032
+ "outputs": []
1033
+ },
1034
+ {
1035
+ "cell_type": "code",
1036
+ "metadata": {
1037
+ "colab": {
1038
+ "base_uri": "https://localhost:8080/",
1039
+ "height": 102,
1040
+ "referenced_widgets": [
1041
+ "84f80a7f3e764346969a347b0f71b24e",
1042
+ "392656f01b2945f3bd7903783ed8cc96",
1043
+ "8e47a435519b4ce090879b4be2f61f99",
1044
+ "41b1ed6b0a9745c1a595377670b15ff4",
1045
+ "179b8ae1eb7f4a828f953e889b141725",
1046
+ "d8708e8414fd44f4abd6590c9b57996f",
1047
+ "800e30f5b4f24475a2b0046da0703631",
1048
+ "8764308b948745f1a677332fd21fcaf0"
1049
+ ]
1050
+ },
1051
+ "id": "wKJ7YsdlkDXo",
1052
+ "outputId": "ab824854-38e4-4d37-ad40-2a7ce3c5fd43"
1053
+ },
1054
+ "source": [
1055
+ "with torch.no_grad():\n",
1056
+ " top1, top5, n = 0., 0., 0.\n",
1057
+ " for i, (images, target) in enumerate(tqdm(loader)):\n",
1058
+ " images = images.cuda()\n",
1059
+ " target = target.cuda()\n",
1060
+ " \n",
1061
+ " # predict\n",
1062
+ " image_features = model.encode_image(images)\n",
1063
+ " image_features /= image_features.norm(dim=-1, keepdim=True)\n",
1064
+ " logits = 100. * image_features @ zeroshot_weights\n",
1065
+ "\n",
1066
+ " # measure accuracy\n",
1067
+ " acc1, acc5 = accuracy(logits, target, topk=(1, 5))\n",
1068
+ " top1 += acc1\n",
1069
+ " top5 += acc5\n",
1070
+ " n += images.size(0)\n",
1071
+ "\n",
1072
+ "top1 = (top1 / n) * 100\n",
1073
+ "top5 = (top5 / n) * 100 \n",
1074
+ "\n",
1075
+ "print(f\"Top-1 accuracy: {top1:.2f}\")\n",
1076
+ "print(f\"Top-5 accuracy: {top5:.2f}\")"
1077
+ ],
1078
+ "execution_count": 11,
1079
+ "outputs": [
1080
+ {
1081
+ "output_type": "display_data",
1082
+ "data": {
1083
+ "application/vnd.jupyter.widget-view+json": {
1084
+ "model_id": "84f80a7f3e764346969a347b0f71b24e",
1085
+ "version_minor": 0,
1086
+ "version_major": 2
1087
+ },
1088
+ "text/plain": [
1089
+ "HBox(children=(FloatProgress(value=0.0, max=313.0), HTML(value='')))"
1090
+ ]
1091
+ },
1092
+ "metadata": {
1093
+ "tags": []
1094
+ }
1095
+ },
1096
+ {
1097
+ "output_type": "stream",
1098
+ "text": [
1099
+ "\n",
1100
+ "Top-1 accuracy: 55.93\n",
1101
+ "Top-5 accuracy: 83.36\n"
1102
+ ],
1103
+ "name": "stdout"
1104
+ }
1105
+ ]
1106
+ }
1107
+ ]
1108
+ }
editing_diffusion/CLIP/requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ftfy
2
+ regex
3
+ tqdm
4
+ torch
5
+ torchvision
editing_diffusion/CLIP/setup.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import pkg_resources
4
+ from setuptools import setup, find_packages
5
+
6
+ setup(
7
+ name="clip",
8
+ py_modules=["clip"],
9
+ version="1.0",
10
+ description="",
11
+ author="OpenAI",
12
+ packages=find_packages(exclude=["tests*"]),
13
+ install_requires=[
14
+ str(r)
15
+ for r in pkg_resources.parse_requirements(
16
+ open(os.path.join(os.path.dirname(__file__), "requirements.txt"))
17
+ )
18
+ ],
19
+ include_package_data=True,
20
+ extras_require={'dev': ['pytest']},
21
+ )
editing_diffusion/CLIP/tests/test_consistency.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+ import torch
4
+ from PIL import Image
5
+
6
+ import clip
7
+
8
+
9
+ @pytest.mark.parametrize('model_name', clip.available_models())
10
+ def test_consistency(model_name):
11
+ device = "cpu"
12
+ jit_model, transform = clip.load(model_name, device=device, jit=True)
13
+ py_model, _ = clip.load(model_name, device=device, jit=False)
14
+
15
+ image = transform(Image.open("CLIP.png")).unsqueeze(0).to(device)
16
+ text = clip.tokenize(["a diagram", "a dog", "a cat"]).to(device)
17
+
18
+ with torch.no_grad():
19
+ logits_per_image, _ = jit_model(image, text)
20
+ jit_probs = logits_per_image.softmax(dim=-1).cpu().numpy()
21
+
22
+ logits_per_image, _ = py_model(image, text)
23
+ py_probs = logits_per_image.softmax(dim=-1).cpu().numpy()
24
+
25
+ assert np.allclose(jit_probs, py_probs, atol=0.01, rtol=0.1)
editing_diffusion/checkpoints/256x256_classifier.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:49bded0549ec22b73ea4c63277814d9ce5ab1784f67b88e7ee79a1f061922a67
3
+ size 216496432
editing_diffusion/checkpoints/256x256_diffusion_uncond.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a37c32fffd316cd494cf3f35b339936debdc1576dad13fe57c42399a5dbc78b1
3
+ size 2211383297
editing_diffusion/guided_diffusion/.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ .DS_Store
2
+ __pycache__/
3
+
editing_diffusion/guided_diffusion/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2021 OpenAI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
editing_diffusion/guided_diffusion/README.md ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # guided-diffusion
2
+
3
+ This is the codebase for [Diffusion Models Beat GANS on Image Synthesis](http://arxiv.org/abs/2105.05233).
4
+
5
+ This repository is based on [openai/improved-diffusion](https://github.com/openai/improved-diffusion), with modifications for classifier conditioning and architecture improvements.
6
+
7
+ # Download pre-trained models
8
+
9
+ We have released checkpoints for the main models in the paper. Before using these models, please review the corresponding [model card](model-card.md) to understand the intended use and limitations of these models.
10
+
11
+ Here are the download links for each model checkpoint:
12
+
13
+ * 64x64 classifier: [64x64_classifier.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/64x64_classifier.pt)
14
+ * 64x64 diffusion: [64x64_diffusion.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/64x64_diffusion.pt)
15
+ * 128x128 classifier: [128x128_classifier.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/128x128_classifier.pt)
16
+ * 128x128 diffusion: [128x128_diffusion.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/128x128_diffusion.pt)
17
+ * 256x256 classifier: [256x256_classifier.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_classifier.pt)
18
+ * 256x256 diffusion: [256x256_diffusion.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion.pt)
19
+ * 256x256 diffusion (not class conditional): [256x256_diffusion_uncond.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt)
20
+ * 512x512 classifier: [512x512_classifier.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/512x512_classifier.pt)
21
+ * 512x512 diffusion: [512x512_diffusion.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/512x512_diffusion.pt)
22
+ * 64x64 -&gt; 256x256 upsampler: [64_256_upsampler.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/64_256_upsampler.pt)
23
+ * 128x128 -&gt; 512x512 upsampler: [128_512_upsampler.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/128_512_upsampler.pt)
24
+ * LSUN bedroom: [lsun_bedroom.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/lsun_bedroom.pt)
25
+ * LSUN cat: [lsun_cat.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/lsun_cat.pt)
26
+ * LSUN horse: [lsun_horse.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/lsun_horse.pt)
27
+ * LSUN horse (no dropout): [lsun_horse_nodropout.pt](https://openaipublic.blob.core.windows.net/diffusion/jul-2021/lsun_horse_nodropout.pt)
28
+
29
+ # Sampling from pre-trained models
30
+
31
+ To sample from these models, you can use the `classifier_sample.py`, `image_sample.py`, and `super_res_sample.py` scripts.
32
+ Here, we provide flags for sampling from all of these models.
33
+ We assume that you have downloaded the relevant model checkpoints into a folder called `models/`.
34
+
35
+ For these examples, we will generate 100 samples with batch size 4. Feel free to change these values.
36
+
37
+ ```
38
+ SAMPLE_FLAGS="--batch_size 4 --num_samples 100 --timestep_respacing 250"
39
+ ```
40
+
41
+ ## Classifier guidance
42
+
43
+ Note for these sampling runs that you can set `--classifier_scale 0` to sample from the base diffusion model.
44
+ You may also use the `image_sample.py` script instead of `classifier_sample.py` in that case.
45
+
46
+ * 64x64 model:
47
+
48
+ ```
49
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --dropout 0.1 --image_size 64 --learn_sigma True --noise_schedule cosine --num_channels 192 --num_head_channels 64 --num_res_blocks 3 --resblock_updown True --use_new_attention_order True --use_fp16 True --use_scale_shift_norm True"
50
+ python classifier_sample.py $MODEL_FLAGS --classifier_scale 1.0 --classifier_path models/64x64_classifier.pt --model_path models/64x64_diffusion.pt $SAMPLE_FLAGS
51
+ ```
52
+
53
+ * 128x128 model:
54
+
55
+ ```
56
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --image_size 128 --learn_sigma True --noise_schedule linear --num_channels 256 --num_heads 4 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
57
+ python classifier_sample.py $MODEL_FLAGS --classifier_scale 0.5 --classifier_path models/128x128_classifier.pt --model_path models/128x128_diffusion.pt $SAMPLE_FLAGS
58
+ ```
59
+
60
+ * 256x256 model:
61
+
62
+ ```
63
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --image_size 256 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
64
+ python classifier_sample.py $MODEL_FLAGS --classifier_scale 1.0 --classifier_path models/256x256_classifier.pt --model_path models/256x256_diffusion.pt $SAMPLE_FLAGS
65
+ ```
66
+
67
+ * 256x256 model (unconditional):
68
+
69
+ ```
70
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond False --diffusion_steps 1000 --image_size 256 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
71
+ python classifier_sample.py $MODEL_FLAGS --classifier_scale 10.0 --classifier_path models/256x256_classifier.pt --model_path models/256x256_diffusion.pt $SAMPLE_FLAGS
72
+ ```
73
+
74
+ * 512x512 model:
75
+
76
+ ```
77
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --image_size 512 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 False --use_scale_shift_norm True"
78
+ python classifier_sample.py $MODEL_FLAGS --classifier_scale 4.0 --classifier_path models/512x512_classifier.pt --model_path models/512x512_diffusion.pt $SAMPLE_FLAGS
79
+ ```
80
+
81
+ ## Upsampling
82
+
83
+ For these runs, we assume you have some base samples in a file `64_samples.npz` or `128_samples.npz` for the two respective models.
84
+
85
+ * 64 -&gt; 256:
86
+
87
+ ```
88
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --diffusion_steps 1000 --large_size 256 --small_size 64 --learn_sigma True --noise_schedule linear --num_channels 192 --num_heads 4 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
89
+ python super_res_sample.py $MODEL_FLAGS --model_path models/64_256_upsampler.pt --base_samples 64_samples.npz $SAMPLE_FLAGS
90
+ ```
91
+
92
+ * 128 -&gt; 512:
93
+
94
+ ```
95
+ MODEL_FLAGS="--attention_resolutions 32,16 --class_cond True --diffusion_steps 1000 --large_size 512 --small_size 128 --learn_sigma True --noise_schedule linear --num_channels 192 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
96
+ python super_res_sample.py $MODEL_FLAGS --model_path models/128_512_upsampler.pt $SAMPLE_FLAGS --base_samples 128_samples.npz
97
+ ```
98
+
99
+ ## LSUN models
100
+
101
+ These models are class-unconditional and correspond to a single LSUN class. Here, we show how to sample from `lsun_bedroom.pt`, but the other two LSUN checkpoints should work as well:
102
+
103
+ ```
104
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond False --diffusion_steps 1000 --dropout 0.1 --image_size 256 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
105
+ python image_sample.py $MODEL_FLAGS --model_path models/lsun_bedroom.pt $SAMPLE_FLAGS
106
+ ```
107
+
108
+ You can sample from `lsun_horse_nodropout.pt` by changing the dropout flag:
109
+
110
+ ```
111
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond False --diffusion_steps 1000 --dropout 0.0 --image_size 256 --learn_sigma True --noise_schedule linear --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
112
+ python image_sample.py $MODEL_FLAGS --model_path models/lsun_horse_nodropout.pt $SAMPLE_FLAGS
113
+ ```
114
+
115
+ Note that for these models, the best samples result from using 1000 timesteps:
116
+
117
+ ```
118
+ SAMPLE_FLAGS="--batch_size 4 --num_samples 100 --timestep_respacing 1000"
119
+ ```
120
+
121
+ # Results
122
+
123
+ This table summarizes our ImageNet results for pure guided diffusion models:
124
+
125
+ | Dataset | FID | Precision | Recall |
126
+ |------------------|------|-----------|--------|
127
+ | ImageNet 64x64 | 2.07 | 0.74 | 0.63 |
128
+ | ImageNet 128x128 | 2.97 | 0.78 | 0.59 |
129
+ | ImageNet 256x256 | 4.59 | 0.82 | 0.52 |
130
+ | ImageNet 512x512 | 7.72 | 0.87 | 0.42 |
131
+
132
+ This table shows the best results for high resolutions when using upsampling and guidance together:
133
+
134
+ | Dataset | FID | Precision | Recall |
135
+ |------------------|------|-----------|--------|
136
+ | ImageNet 256x256 | 3.94 | 0.83 | 0.53 |
137
+ | ImageNet 512x512 | 3.85 | 0.84 | 0.53 |
138
+
139
+ Finally, here are the unguided results on individual LSUN classes:
140
+
141
+ | Dataset | FID | Precision | Recall |
142
+ |--------------|------|-----------|--------|
143
+ | LSUN Bedroom | 1.90 | 0.66 | 0.51 |
144
+ | LSUN Cat | 5.57 | 0.63 | 0.52 |
145
+ | LSUN Horse | 2.57 | 0.71 | 0.55 |
146
+
147
+ # Training models
148
+
149
+ Training diffusion models is described in the [parent repository](https://github.com/openai/improved-diffusion). Training a classifier is similar. We assume you have put training hyperparameters into a `TRAIN_FLAGS` variable, and classifier hyperparameters into a `CLASSIFIER_FLAGS` variable. Then you can run:
150
+
151
+ ```
152
+ mpiexec -n N python scripts/classifier_train.py --data_dir path/to/imagenet $TRAIN_FLAGS $CLASSIFIER_FLAGS
153
+ ```
154
+
155
+ Make sure to divide the batch size in `TRAIN_FLAGS` by the number of MPI processes you are using.
156
+
157
+ Here are flags for training the 128x128 classifier. You can modify these for training classifiers at other resolutions:
158
+
159
+ ```sh
160
+ TRAIN_FLAGS="--iterations 300000 --anneal_lr True --batch_size 256 --lr 3e-4 --save_interval 10000 --weight_decay 0.05"
161
+ CLASSIFIER_FLAGS="--image_size 128 --classifier_attention_resolutions 32,16,8 --classifier_depth 2 --classifier_width 128 --classifier_pool attention --classifier_resblock_updown True --classifier_use_scale_shift_norm True"
162
+ ```
163
+
164
+ For sampling from a 128x128 classifier-guided model, 25 step DDIM:
165
+
166
+ ```sh
167
+ MODEL_FLAGS="--attention_resolutions 32,16,8 --class_cond True --image_size 128 --learn_sigma True --num_channels 256 --num_heads 4 --num_res_blocks 2 --resblock_updown True --use_fp16 True --use_scale_shift_norm True"
168
+ CLASSIFIER_FLAGS="--image_size 128 --classifier_attention_resolutions 32,16,8 --classifier_depth 2 --classifier_width 128 --classifier_pool attention --classifier_resblock_updown True --classifier_use_scale_shift_norm True --classifier_scale 1.0 --classifier_use_fp16 True"
169
+ SAMPLE_FLAGS="--batch_size 4 --num_samples 50000 --timestep_respacing ddim25 --use_ddim True"
170
+ mpiexec -n N python scripts/classifier_sample.py \
171
+ --model_path /path/to/model.pt \
172
+ --classifier_path path/to/classifier.pt \
173
+ $MODEL_FLAGS $CLASSIFIER_FLAGS $SAMPLE_FLAGS
174
+ ```
175
+
176
+ To sample for 250 timesteps without DDIM, replace `--timestep_respacing ddim25` to `--timestep_respacing 250`, and replace `--use_ddim True` with `--use_ddim False`.
editing_diffusion/guided_diffusion/datasets/README.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Downloading datasets
2
+
3
+ This directory includes instructions and scripts for downloading ImageNet and LSUN bedrooms for use in this codebase.
4
+
5
+ ## Class-conditional ImageNet
6
+
7
+ For our class-conditional models, we use the official ILSVRC2012 dataset with manual center cropping and downsampling. To obtain this dataset, navigate to [this page on image-net.org](http://www.image-net.org/challenges/LSVRC/2012/downloads) and sign in (or create an account if you do not already have one). Then click on the link reading "Training images (Task 1 & 2)". This is a 138GB tar file containing 1000 sub-tar files, one per class.
8
+
9
+ Once the file is downloaded, extract it and look inside. You should see 1000 `.tar` files. You need to extract each of these, which may be impractical to do by hand on your operating system. To automate the process on a Unix-based system, you can `cd` into the directory and run this short shell script:
10
+
11
+ ```
12
+ for file in *.tar; do tar xf "$file"; rm "$file"; done
13
+ ```
14
+
15
+ This will extract and remove each tar file in turn.
16
+
17
+ Once all of the images have been extracted, the resulting directory should be usable as a data directory (the `--data_dir` argument for the training script). The filenames should all start with WNID (class ids) followed by underscores, like `n01440764_2708.JPEG`. Conveniently (but not by accident) this is how the automated data-loader expects to discover class labels.
18
+
19
+ ## LSUN bedroom
20
+
21
+ To download and pre-process LSUN bedroom, clone [fyu/lsun](https://github.com/fyu/lsun) on GitHub and run their download script `python3 download.py bedroom`. The result will be an "lmdb" database named like `bedroom_train_lmdb`. You can pass this to our [lsun_bedroom.py](lsun_bedroom.py) script like so:
22
+
23
+ ```
24
+ python lsun_bedroom.py bedroom_train_lmdb lsun_train_output_dir
25
+ ```
26
+
27
+ This creates a directory called `lsun_train_output_dir`. This directory can be passed to the training scripts via the `--data_dir` argument.
editing_diffusion/guided_diffusion/datasets/lsun_bedroom.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Convert an LSUN lmdb database into a directory of images.
3
+ """
4
+
5
+ import argparse
6
+ import io
7
+ import os
8
+
9
+ from PIL import Image
10
+ import lmdb
11
+ import numpy as np
12
+
13
+
14
+ def read_images(lmdb_path, image_size):
15
+ env = lmdb.open(lmdb_path, map_size=1099511627776, max_readers=100, readonly=True)
16
+ with env.begin(write=False) as transaction:
17
+ cursor = transaction.cursor()
18
+ for _, webp_data in cursor:
19
+ img = Image.open(io.BytesIO(webp_data))
20
+ width, height = img.size
21
+ scale = image_size / min(width, height)
22
+ img = img.resize(
23
+ (int(round(scale * width)), int(round(scale * height))),
24
+ resample=Image.BOX,
25
+ )
26
+ arr = np.array(img)
27
+ h, w, _ = arr.shape
28
+ h_off = (h - image_size) // 2
29
+ w_off = (w - image_size) // 2
30
+ arr = arr[h_off : h_off + image_size, w_off : w_off + image_size]
31
+ yield arr
32
+
33
+
34
+ def dump_images(out_dir, images, prefix):
35
+ if not os.path.exists(out_dir):
36
+ os.mkdir(out_dir)
37
+ for i, img in enumerate(images):
38
+ Image.fromarray(img).save(os.path.join(out_dir, f"{prefix}_{i:07d}.png"))
39
+
40
+
41
+ def main():
42
+ parser = argparse.ArgumentParser()
43
+ parser.add_argument("--image-size", help="new image size", type=int, default=256)
44
+ parser.add_argument("--prefix", help="class name", type=str, default="bedroom")
45
+ parser.add_argument("lmdb_path", help="path to an LSUN lmdb database")
46
+ parser.add_argument("out_dir", help="path to output directory")
47
+ args = parser.parse_args()
48
+
49
+ images = read_images(args.lmdb_path, args.image_size)
50
+ dump_images(args.out_dir, images, args.prefix)
51
+
52
+
53
+ if __name__ == "__main__":
54
+ main()
editing_diffusion/guided_diffusion/guided_diffusion/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """
2
+ Codebase for "Improved Denoising Diffusion Probabilistic Models".
3
+ """
editing_diffusion/guided_diffusion/guided_diffusion/dist_util.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helpers for distributed training.
3
+ """
4
+
5
+ import io
6
+ import os
7
+ import socket
8
+
9
+ import blobfile as bf
10
+ from mpi4py import MPI
11
+ import torch as th
12
+ import torch.distributed as dist
13
+
14
+ # Change this to reflect your cluster layout.
15
+ # The GPU for a given rank is (rank % GPUS_PER_NODE).
16
+ GPUS_PER_NODE = 8
17
+
18
+ SETUP_RETRY_COUNT = 3
19
+
20
+
21
+ def setup_dist():
22
+ """
23
+ Setup a distributed process group.
24
+ """
25
+ if dist.is_initialized():
26
+ return
27
+ os.environ["CUDA_VISIBLE_DEVICES"] = f"{MPI.COMM_WORLD.Get_rank() % GPUS_PER_NODE}"
28
+
29
+ comm = MPI.COMM_WORLD
30
+ backend = "gloo" if not th.cuda.is_available() else "nccl"
31
+
32
+ if backend == "gloo":
33
+ hostname = "localhost"
34
+ else:
35
+ hostname = socket.gethostbyname(socket.getfqdn())
36
+ os.environ["MASTER_ADDR"] = comm.bcast(hostname, root=0)
37
+ os.environ["RANK"] = str(comm.rank)
38
+ os.environ["WORLD_SIZE"] = str(comm.size)
39
+
40
+ port = comm.bcast(_find_free_port(), root=0)
41
+ os.environ["MASTER_PORT"] = str(port)
42
+ dist.init_process_group(backend=backend, init_method="env://")
43
+
44
+
45
+ def dev():
46
+ """
47
+ Get the device to use for torch.distributed.
48
+ """
49
+ if th.cuda.is_available():
50
+ return th.device(f"cuda")
51
+ return th.device("cpu")
52
+
53
+
54
+ def load_state_dict(path, **kwargs):
55
+ """
56
+ Load a PyTorch file without redundant fetches across MPI ranks.
57
+ """
58
+ chunk_size = 2 ** 30 # MPI has a relatively small size limit
59
+ if MPI.COMM_WORLD.Get_rank() == 0:
60
+ with bf.BlobFile(path, "rb") as f:
61
+ data = f.read()
62
+ num_chunks = len(data) // chunk_size
63
+ if len(data) % chunk_size:
64
+ num_chunks += 1
65
+ MPI.COMM_WORLD.bcast(num_chunks)
66
+ for i in range(0, len(data), chunk_size):
67
+ MPI.COMM_WORLD.bcast(data[i : i + chunk_size])
68
+ else:
69
+ num_chunks = MPI.COMM_WORLD.bcast(None)
70
+ data = bytes()
71
+ for _ in range(num_chunks):
72
+ data += MPI.COMM_WORLD.bcast(None)
73
+
74
+ return th.load(io.BytesIO(data), **kwargs)
75
+
76
+
77
+ def sync_params(params):
78
+ """
79
+ Synchronize a sequence of Tensors across ranks from rank 0.
80
+ """
81
+ for p in params:
82
+ with th.no_grad():
83
+ dist.broadcast(p, 0)
84
+
85
+
86
+ def _find_free_port():
87
+ try:
88
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
89
+ s.bind(("", 0))
90
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
91
+ return s.getsockname()[1]
92
+ finally:
93
+ s.close()
editing_diffusion/guided_diffusion/guided_diffusion/fp16_util.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helpers to train with 16-bit precision.
3
+ """
4
+
5
+ import numpy as np
6
+ import torch as th
7
+ import torch.nn as nn
8
+ from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
9
+
10
+ from . import logger
11
+
12
+ INITIAL_LOG_LOSS_SCALE = 20.0
13
+
14
+
15
+ def convert_module_to_f16(l):
16
+ """
17
+ Convert primitive modules to float16.
18
+ """
19
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):
20
+ l.weight.data = l.weight.data.half()
21
+ if l.bias is not None:
22
+ l.bias.data = l.bias.data.half()
23
+
24
+
25
+ def convert_module_to_f32(l):
26
+ """
27
+ Convert primitive modules to float32, undoing convert_module_to_f16().
28
+ """
29
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):
30
+ l.weight.data = l.weight.data.float()
31
+ if l.bias is not None:
32
+ l.bias.data = l.bias.data.float()
33
+
34
+
35
+ def make_master_params(param_groups_and_shapes):
36
+ """
37
+ Copy model parameters into a (differently-shaped) list of full-precision
38
+ parameters.
39
+ """
40
+ master_params = []
41
+ for param_group, shape in param_groups_and_shapes:
42
+ master_param = nn.Parameter(
43
+ _flatten_dense_tensors(
44
+ [param.detach().float() for (_, param) in param_group]
45
+ ).view(shape)
46
+ )
47
+ master_param.requires_grad = True
48
+ master_params.append(master_param)
49
+ return master_params
50
+
51
+
52
+ def model_grads_to_master_grads(param_groups_and_shapes, master_params):
53
+ """
54
+ Copy the gradients from the model parameters into the master parameters
55
+ from make_master_params().
56
+ """
57
+ for master_param, (param_group, shape) in zip(
58
+ master_params, param_groups_and_shapes
59
+ ):
60
+ master_param.grad = _flatten_dense_tensors(
61
+ [param_grad_or_zeros(param) for (_, param) in param_group]
62
+ ).view(shape)
63
+
64
+
65
+ def master_params_to_model_params(param_groups_and_shapes, master_params):
66
+ """
67
+ Copy the master parameter data back into the model parameters.
68
+ """
69
+ # Without copying to a list, if a generator is passed, this will
70
+ # silently not copy any parameters.
71
+ for master_param, (param_group, _) in zip(master_params, param_groups_and_shapes):
72
+ for (_, param), unflat_master_param in zip(
73
+ param_group, unflatten_master_params(param_group, master_param.view(-1))
74
+ ):
75
+ param.detach().copy_(unflat_master_param)
76
+
77
+
78
+ def unflatten_master_params(param_group, master_param):
79
+ return _unflatten_dense_tensors(master_param, [param for (_, param) in param_group])
80
+
81
+
82
+ def get_param_groups_and_shapes(named_model_params):
83
+ named_model_params = list(named_model_params)
84
+ scalar_vector_named_params = (
85
+ [(n, p) for (n, p) in named_model_params if p.ndim <= 1],
86
+ (-1),
87
+ )
88
+ matrix_named_params = (
89
+ [(n, p) for (n, p) in named_model_params if p.ndim > 1],
90
+ (1, -1),
91
+ )
92
+ return [scalar_vector_named_params, matrix_named_params]
93
+
94
+
95
+ def master_params_to_state_dict(
96
+ model, param_groups_and_shapes, master_params, use_fp16
97
+ ):
98
+ if use_fp16:
99
+ state_dict = model.state_dict()
100
+ for master_param, (param_group, _) in zip(
101
+ master_params, param_groups_and_shapes
102
+ ):
103
+ for (name, _), unflat_master_param in zip(
104
+ param_group, unflatten_master_params(param_group, master_param.view(-1))
105
+ ):
106
+ assert name in state_dict
107
+ state_dict[name] = unflat_master_param
108
+ else:
109
+ state_dict = model.state_dict()
110
+ for i, (name, _value) in enumerate(model.named_parameters()):
111
+ assert name in state_dict
112
+ state_dict[name] = master_params[i]
113
+ return state_dict
114
+
115
+
116
+ def state_dict_to_master_params(model, state_dict, use_fp16):
117
+ if use_fp16:
118
+ named_model_params = [
119
+ (name, state_dict[name]) for name, _ in model.named_parameters()
120
+ ]
121
+ param_groups_and_shapes = get_param_groups_and_shapes(named_model_params)
122
+ master_params = make_master_params(param_groups_and_shapes)
123
+ else:
124
+ master_params = [state_dict[name] for name, _ in model.named_parameters()]
125
+ return master_params
126
+
127
+
128
+ def zero_master_grads(master_params):
129
+ for param in master_params:
130
+ param.grad = None
131
+
132
+
133
+ def zero_grad(model_params):
134
+ for param in model_params:
135
+ # Taken from https://pytorch.org/docs/stable/_modules/torch/optim/optimizer.html#Optimizer.add_param_group
136
+ if param.grad is not None:
137
+ param.grad.detach_()
138
+ param.grad.zero_()
139
+
140
+
141
+ def param_grad_or_zeros(param):
142
+ if param.grad is not None:
143
+ return param.grad.data.detach()
144
+ else:
145
+ return th.zeros_like(param)
146
+
147
+
148
+ class MixedPrecisionTrainer:
149
+ def __init__(
150
+ self,
151
+ *,
152
+ model,
153
+ use_fp16=False,
154
+ fp16_scale_growth=1e-3,
155
+ initial_lg_loss_scale=INITIAL_LOG_LOSS_SCALE,
156
+ ):
157
+ self.model = model
158
+ self.use_fp16 = use_fp16
159
+ self.fp16_scale_growth = fp16_scale_growth
160
+
161
+ self.model_params = list(self.model.parameters())
162
+ self.master_params = self.model_params
163
+ self.param_groups_and_shapes = None
164
+ self.lg_loss_scale = initial_lg_loss_scale
165
+
166
+ if self.use_fp16:
167
+ self.param_groups_and_shapes = get_param_groups_and_shapes(
168
+ self.model.named_parameters()
169
+ )
170
+ self.master_params = make_master_params(self.param_groups_and_shapes)
171
+ self.model.convert_to_fp16()
172
+
173
+ def zero_grad(self):
174
+ zero_grad(self.model_params)
175
+
176
+ def backward(self, loss: th.Tensor):
177
+ if self.use_fp16:
178
+ loss_scale = 2 ** self.lg_loss_scale
179
+ (loss * loss_scale).backward()
180
+ else:
181
+ loss.backward()
182
+
183
+ def optimize(self, opt: th.optim.Optimizer):
184
+ if self.use_fp16:
185
+ return self._optimize_fp16(opt)
186
+ else:
187
+ return self._optimize_normal(opt)
188
+
189
+ def _optimize_fp16(self, opt: th.optim.Optimizer):
190
+ logger.logkv_mean("lg_loss_scale", self.lg_loss_scale)
191
+ model_grads_to_master_grads(self.param_groups_and_shapes, self.master_params)
192
+ grad_norm, param_norm = self._compute_norms(grad_scale=2 ** self.lg_loss_scale)
193
+ if check_overflow(grad_norm):
194
+ self.lg_loss_scale -= 1
195
+ logger.log(f"Found NaN, decreased lg_loss_scale to {self.lg_loss_scale}")
196
+ zero_master_grads(self.master_params)
197
+ return False
198
+
199
+ logger.logkv_mean("grad_norm", grad_norm)
200
+ logger.logkv_mean("param_norm", param_norm)
201
+
202
+ self.master_params[0].grad.mul_(1.0 / (2 ** self.lg_loss_scale))
203
+ opt.step()
204
+ zero_master_grads(self.master_params)
205
+ master_params_to_model_params(self.param_groups_and_shapes, self.master_params)
206
+ self.lg_loss_scale += self.fp16_scale_growth
207
+ return True
208
+
209
+ def _optimize_normal(self, opt: th.optim.Optimizer):
210
+ grad_norm, param_norm = self._compute_norms()
211
+ logger.logkv_mean("grad_norm", grad_norm)
212
+ logger.logkv_mean("param_norm", param_norm)
213
+ opt.step()
214
+ return True
215
+
216
+ def _compute_norms(self, grad_scale=1.0):
217
+ grad_norm = 0.0
218
+ param_norm = 0.0
219
+ for p in self.master_params:
220
+ with th.no_grad():
221
+ param_norm += th.norm(p, p=2, dtype=th.float32).item() ** 2
222
+ if p.grad is not None:
223
+ grad_norm += th.norm(p.grad, p=2, dtype=th.float32).item() ** 2
224
+ return np.sqrt(grad_norm) / grad_scale, np.sqrt(param_norm)
225
+
226
+ def master_params_to_state_dict(self, master_params):
227
+ return master_params_to_state_dict(
228
+ self.model, self.param_groups_and_shapes, master_params, self.use_fp16
229
+ )
230
+
231
+ def state_dict_to_master_params(self, state_dict):
232
+ return state_dict_to_master_params(self.model, state_dict, self.use_fp16)
233
+
234
+
235
+ def check_overflow(value):
236
+ return (value == float("inf")) or (value == -float("inf")) or (value != value)
editing_diffusion/guided_diffusion/guided_diffusion/gaussian_diffusion.py ADDED
@@ -0,0 +1,922 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This code started out as a PyTorch port of Ho et al's diffusion models:
3
+ https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py
4
+
5
+ Docstrings have been added, as well as DDIM sampling and a new collection of beta schedules.
6
+ """
7
+
8
+ import enum
9
+ import math
10
+
11
+ import numpy as np
12
+ import torch as th
13
+
14
+ from .nn import mean_flat
15
+ from .losses import normal_kl, discretized_gaussian_log_likelihood
16
+
17
+ import pdb
18
+
19
+
20
+ def get_named_beta_schedule(schedule_name, num_diffusion_timesteps):
21
+ """
22
+ Get a pre-defined beta schedule for the given name.
23
+
24
+ The beta schedule library consists of beta schedules which remain similar
25
+ in the limit of num_diffusion_timesteps.
26
+ Beta schedules may be added, but should not be removed or changed once
27
+ they are committed to maintain backwards compatibility.
28
+ """
29
+ if schedule_name == "linear":
30
+ # Linear schedule from Ho et al, extended to work for any number of
31
+ # diffusion steps.
32
+ scale = 1000 / num_diffusion_timesteps
33
+ beta_start = scale * 0.0001
34
+ beta_end = scale * 0.02
35
+ return np.linspace(beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64)
36
+ elif schedule_name == "cosine":
37
+ return betas_for_alpha_bar(
38
+ num_diffusion_timesteps, lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2,
39
+ )
40
+ else:
41
+ raise NotImplementedError(f"unknown beta schedule: {schedule_name}")
42
+
43
+
44
+ def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
45
+ """
46
+ Create a beta schedule that discretizes the given alpha_t_bar function,
47
+ which defines the cumulative product of (1-beta) over time from t = [0,1].
48
+
49
+ :param num_diffusion_timesteps: the number of betas to produce.
50
+ :param alpha_bar: a lambda that takes an argument t from 0 to 1 and
51
+ produces the cumulative product of (1-beta) up to that
52
+ part of the diffusion process.
53
+ :param max_beta: the maximum beta to use; use values lower than 1 to
54
+ prevent singularities.
55
+ """
56
+ betas = []
57
+ for i in range(num_diffusion_timesteps):
58
+ t1 = i / num_diffusion_timesteps
59
+ t2 = (i + 1) / num_diffusion_timesteps
60
+ betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
61
+ return np.array(betas)
62
+
63
+
64
+ class ModelMeanType(enum.Enum):
65
+ """
66
+ Which type of output the model predicts.
67
+ """
68
+
69
+ PREVIOUS_X = enum.auto() # the model predicts x_{t-1}
70
+ START_X = enum.auto() # the model predicts x_0
71
+ EPSILON = enum.auto() # the model predicts epsilon
72
+
73
+
74
+ class ModelVarType(enum.Enum):
75
+ """
76
+ What is used as the model's output variance.
77
+
78
+ The LEARNED_RANGE option has been added to allow the model to predict
79
+ values between FIXED_SMALL and FIXED_LARGE, making its job easier.
80
+ """
81
+
82
+ LEARNED = enum.auto()
83
+ FIXED_SMALL = enum.auto()
84
+ FIXED_LARGE = enum.auto()
85
+ LEARNED_RANGE = enum.auto()
86
+
87
+
88
+ class LossType(enum.Enum):
89
+ MSE = enum.auto() # use raw MSE loss (and KL when learning variances)
90
+ RESCALED_MSE = enum.auto() # use raw MSE loss (with RESCALED_KL when learning variances)
91
+ KL = enum.auto() # use the variational lower-bound
92
+ RESCALED_KL = enum.auto() # like KL, but rescale to estimate the full VLB
93
+
94
+ def is_vb(self):
95
+ return self == LossType.KL or self == LossType.RESCALED_KL
96
+
97
+
98
+ class GaussianDiffusion:
99
+ """
100
+ Utilities for training and sampling diffusion models.
101
+
102
+ Ported directly from here, and then adapted over time to further experimentation.
103
+ https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py#L42
104
+
105
+ :param betas: a 1-D numpy array of betas for each diffusion timestep,
106
+ starting at T and going to 1.
107
+ :param model_mean_type: a ModelMeanType determining what the model outputs.
108
+ :param model_var_type: a ModelVarType determining how variance is output.
109
+ :param loss_type: a LossType determining the loss function to use.
110
+ :param rescale_timesteps: if True, pass floating point timesteps into the
111
+ model so that they are always scaled like in the
112
+ original paper (0 to 1000).
113
+ """
114
+
115
+ def __init__(
116
+ self, *, betas, model_mean_type, model_var_type, loss_type, rescale_timesteps=False,
117
+ ):
118
+ self.model_mean_type = model_mean_type
119
+ self.model_var_type = model_var_type
120
+ self.loss_type = loss_type
121
+ self.rescale_timesteps = rescale_timesteps
122
+
123
+ # Use float64 for accuracy.
124
+ betas = np.array(betas, dtype=np.float64)
125
+ self.betas = betas
126
+ assert len(betas.shape) == 1, "betas must be 1-D"
127
+ assert (betas > 0).all() and (betas <= 1).all()
128
+
129
+ self.num_timesteps = int(betas.shape[0])
130
+
131
+ alphas = 1.0 - betas
132
+ self.alphas_cumprod = np.cumprod(alphas, axis=0)
133
+ self.alphas_cumprod_prev = np.append(1.0, self.alphas_cumprod[:-1])
134
+ self.alphas_cumprod_next = np.append(self.alphas_cumprod[1:], 0.0)
135
+ assert self.alphas_cumprod_prev.shape == (self.num_timesteps,)
136
+
137
+ # calculations for diffusion q(x_t | x_{t-1}) and others
138
+ self.sqrt_alphas_cumprod = np.sqrt(self.alphas_cumprod)
139
+ self.sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - self.alphas_cumprod)
140
+ self.log_one_minus_alphas_cumprod = np.log(1.0 - self.alphas_cumprod)
141
+ self.sqrt_recip_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod)
142
+ self.sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod - 1)
143
+
144
+ # calculations for posterior q(x_{t-1} | x_t, x_0)
145
+ self.posterior_variance = (
146
+ betas * (1.0 - self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod)
147
+ )
148
+ # log calculation clipped because the posterior variance is 0 at the
149
+ # beginning of the diffusion chain.
150
+ self.posterior_log_variance_clipped = np.log(
151
+ np.append(self.posterior_variance[1], self.posterior_variance[1:])
152
+ )
153
+ self.posterior_mean_coef1 = (
154
+ betas * np.sqrt(self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod)
155
+ )
156
+ self.posterior_mean_coef2 = (
157
+ (1.0 - self.alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - self.alphas_cumprod)
158
+ )
159
+
160
+ def q_mean_variance(self, x_start, t):
161
+ """
162
+ Get the distribution q(x_t | x_0).
163
+
164
+ :param x_start: the [N x C x ...] tensor of noiseless inputs.
165
+ :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
166
+ :return: A tuple (mean, variance, log_variance), all of x_start's shape.
167
+ """
168
+ mean = _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
169
+ variance = _extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
170
+ log_variance = _extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
171
+ return mean, variance, log_variance
172
+
173
+ def q_sample(self, x_start, t, noise=None):
174
+ """
175
+ Diffuse the data for a given number of diffusion steps.
176
+
177
+ In other words, sample from q(x_t | x_0).
178
+
179
+ :param x_start: the initial data batch.
180
+ :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
181
+ :param noise: if specified, the split-out normal noise.
182
+ :return: A noisy version of x_start.
183
+ """
184
+ if noise is None:
185
+ noise = th.randn_like(x_start)
186
+ assert noise.shape == x_start.shape
187
+ return (
188
+ _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
189
+ + _extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise
190
+ )
191
+
192
+ def q_posterior_mean_variance(self, x_start, x_t, t):
193
+ """
194
+ Compute the mean and variance of the diffusion posterior:
195
+
196
+ q(x_{t-1} | x_t, x_0)
197
+
198
+ """
199
+ assert x_start.shape == x_t.shape
200
+ posterior_mean = (
201
+ _extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start
202
+ + _extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
203
+ )
204
+ posterior_variance = _extract_into_tensor(self.posterior_variance, t, x_t.shape)
205
+ posterior_log_variance_clipped = _extract_into_tensor(
206
+ self.posterior_log_variance_clipped, t, x_t.shape
207
+ )
208
+ assert (
209
+ posterior_mean.shape[0]
210
+ == posterior_variance.shape[0]
211
+ == posterior_log_variance_clipped.shape[0]
212
+ == x_start.shape[0]
213
+ )
214
+ return posterior_mean, posterior_variance, posterior_log_variance_clipped
215
+
216
+ def p_mean_variance(self, model, x, t, clip_denoised=True, denoised_fn=None, model_kwargs=None):
217
+ """
218
+ Apply the model to get p(x_{t-1} | x_t), as well as a prediction of
219
+ the initial x, x_0.
220
+
221
+ :param model: the model, which takes a signal and a batch of timesteps
222
+ as input.
223
+ :param x: the [N x C x ...] tensor at time t.
224
+ :param t: a 1-D Tensor of timesteps.
225
+ :param clip_denoised: if True, clip the denoised signal into [-1, 1].
226
+ :param denoised_fn: if not None, a function which applies to the
227
+ x_start prediction before it is used to sample. Applies before
228
+ clip_denoised.
229
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
230
+ pass to the model. This can be used for conditioning.
231
+ :return: a dict with the following keys:
232
+ - 'mean': the model mean output.
233
+ - 'variance': the model variance output.
234
+ - 'log_variance': the log of 'variance'.
235
+ - 'pred_xstart': the prediction for x_0.
236
+ """
237
+ if model_kwargs is None:
238
+ model_kwargs = {}
239
+
240
+ B, C = x.shape[:2]
241
+ assert t.shape == (B,)
242
+ model_output = model(x, self._scale_timesteps(t), **model_kwargs)
243
+
244
+ if self.model_var_type in [ModelVarType.LEARNED, ModelVarType.LEARNED_RANGE]:
245
+ assert model_output.shape == (B, C * 2, *x.shape[2:])
246
+ model_output, model_var_values = th.split(model_output, C, dim=1)
247
+ if self.model_var_type == ModelVarType.LEARNED:
248
+ model_log_variance = model_var_values
249
+ model_variance = th.exp(model_log_variance)
250
+ else:
251
+ min_log = _extract_into_tensor(self.posterior_log_variance_clipped, t, x.shape)
252
+ max_log = _extract_into_tensor(np.log(self.betas), t, x.shape)
253
+ # The model_var_values is [-1, 1] for [min_var, max_var].
254
+ frac = (model_var_values + 1) / 2
255
+ model_log_variance = frac * max_log + (1 - frac) * min_log
256
+ model_variance = th.exp(model_log_variance)
257
+ else:
258
+ model_variance, model_log_variance = {
259
+ # for fixedlarge, we set the initial (log-)variance like so
260
+ # to get a better decoder log likelihood.
261
+ ModelVarType.FIXED_LARGE: (
262
+ np.append(self.posterior_variance[1], self.betas[1:]),
263
+ np.log(np.append(self.posterior_variance[1], self.betas[1:])),
264
+ ),
265
+ ModelVarType.FIXED_SMALL: (
266
+ self.posterior_variance,
267
+ self.posterior_log_variance_clipped,
268
+ ),
269
+ }[self.model_var_type]
270
+ model_variance = _extract_into_tensor(model_variance, t, x.shape)
271
+ model_log_variance = _extract_into_tensor(model_log_variance, t, x.shape)
272
+
273
+ def process_xstart(x):
274
+ if denoised_fn is not None:
275
+ x = denoised_fn(x)
276
+ if clip_denoised:
277
+ return x.clamp(-1, 1)
278
+ return x
279
+
280
+ if self.model_mean_type == ModelMeanType.PREVIOUS_X:
281
+ pred_xstart = process_xstart(
282
+ self._predict_xstart_from_xprev(x_t=x, t=t, xprev=model_output)
283
+ )
284
+ model_mean = model_output
285
+ elif self.model_mean_type in [ModelMeanType.START_X, ModelMeanType.EPSILON]:
286
+ if self.model_mean_type == ModelMeanType.START_X:
287
+ pred_xstart = process_xstart(model_output)
288
+ else:
289
+ pred_xstart = process_xstart(
290
+ self._predict_xstart_from_eps(x_t=x, t=t, eps=model_output)
291
+ )
292
+ model_mean, _, _ = self.q_posterior_mean_variance(x_start=pred_xstart, x_t=x, t=t)
293
+ else:
294
+ raise NotImplementedError(self.model_mean_type)
295
+
296
+ assert model_mean.shape == model_log_variance.shape == pred_xstart.shape == x.shape
297
+ return {
298
+ "mean": model_mean,
299
+ "variance": model_variance,
300
+ "log_variance": model_log_variance,
301
+ "pred_xstart": pred_xstart,
302
+ }
303
+
304
+ def _predict_xstart_from_eps(self, x_t, t, eps):
305
+ assert x_t.shape == eps.shape
306
+ return (
307
+ _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t
308
+ - _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * eps
309
+ )
310
+
311
+ def _predict_xstart_from_xprev(self, x_t, t, xprev):
312
+ assert x_t.shape == xprev.shape
313
+ return ( # (xprev - coef2*x_t) / coef1
314
+ _extract_into_tensor(1.0 / self.posterior_mean_coef1, t, x_t.shape) * xprev
315
+ - _extract_into_tensor(
316
+ self.posterior_mean_coef2 / self.posterior_mean_coef1, t, x_t.shape
317
+ )
318
+ * x_t
319
+ )
320
+
321
+ def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
322
+ return (
323
+ _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart
324
+ ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
325
+
326
+ def _scale_timesteps(self, t):
327
+ if self.rescale_timesteps:
328
+ return t.float() * (1000.0 / self.num_timesteps)
329
+ return t
330
+
331
+ def condition_mean(self, cond_fn, p_mean_var, x, t, model_kwargs=None):
332
+ """
333
+ Compute the mean for the previous step, given a function cond_fn that
334
+ computes the gradient of a conditional log probability with respect to
335
+ x. In particular, cond_fn computes grad(log(p(y|x))), and we want to
336
+ condition on y.
337
+
338
+ This uses the conditioning strategy from Sohl-Dickstein et al. (2015).
339
+ """
340
+ gradient = cond_fn(x, self._scale_timesteps(t), **model_kwargs)
341
+ new_mean = p_mean_var["mean"].float() + p_mean_var["variance"] * gradient.float()
342
+ return new_mean
343
+
344
+ def condition_score(self, cond_fn, p_mean_var, x, t, model_kwargs=None):
345
+ """
346
+ Compute what the p_mean_variance output would have been, should the
347
+ model's score function be conditioned by cond_fn.
348
+
349
+ See condition_mean() for details on cond_fn.
350
+
351
+ Unlike condition_mean(), this instead uses the conditioning strategy
352
+ from Song et al (2020).
353
+ """
354
+ alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
355
+
356
+ eps = self._predict_eps_from_xstart(x, t, p_mean_var["pred_xstart"])
357
+ eps = eps - (1 - alpha_bar).sqrt() * cond_fn(x, self._scale_timesteps(t), **model_kwargs)
358
+
359
+ out = p_mean_var.copy()
360
+ out["pred_xstart"] = self._predict_xstart_from_eps(x, t, eps)
361
+ out["mean"], _, _ = self.q_posterior_mean_variance(x_start=out["pred_xstart"], x_t=x, t=t)
362
+ return out
363
+
364
+ def p_sample(
365
+ self, model, x, t, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None,
366
+ ):
367
+ """
368
+ Sample x_{t-1} from the model at the given timestep.
369
+
370
+ :param model: the model to sample from.
371
+ :param x: the current tensor at x_{t-1}.
372
+ :param t: the value of t, starting at 0 for the first diffusion step.
373
+ :param clip_denoised: if True, clip the x_start prediction to [-1, 1].
374
+ :param denoised_fn: if not None, a function which applies to the
375
+ x_start prediction before it is used to sample.
376
+ :param cond_fn: if not None, this is a gradient function that acts
377
+ similarly to the model.
378
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
379
+ pass to the model. This can be used for conditioning.
380
+ :return: a dict containing the following keys:
381
+ - 'sample': a random sample from the model.
382
+ - 'pred_xstart': a prediction of x_0.
383
+ """
384
+ out = self.p_mean_variance(
385
+ model,
386
+ x,
387
+ t,
388
+ clip_denoised=clip_denoised,
389
+ denoised_fn=denoised_fn,
390
+ model_kwargs=model_kwargs,
391
+ )
392
+ noise = th.randn_like(x)
393
+ nonzero_mask = (
394
+ (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
395
+ ) # no noise when t == 0
396
+ if cond_fn is not None:
397
+ out["mean"] = self.condition_mean(cond_fn, out, x, t, model_kwargs=model_kwargs)
398
+ sample = out["mean"] + nonzero_mask * th.exp(0.5 * out["log_variance"]) * noise
399
+ return {"sample": sample, "pred_xstart": out["pred_xstart"]}
400
+
401
+ def p_sample_loop(
402
+ self,
403
+ model,
404
+ shape,
405
+ noise=None,
406
+ clip_denoised=True,
407
+ denoised_fn=None,
408
+ cond_fn=None,
409
+ model_kwargs=None,
410
+ device=None,
411
+ progress=False,
412
+ skip_timesteps=0,
413
+ init_image=None,
414
+ randomize_class=False,
415
+ ):
416
+ """
417
+ Generate samples from the model.
418
+
419
+ :param model: the model module.
420
+ :param shape: the shape of the samples, (N, C, H, W).
421
+ :param noise: if specified, the noise from the encoder to sample.
422
+ Should be of the same shape as `shape`.
423
+ :param clip_denoised: if True, clip x_start predictions to [-1, 1].
424
+ :param denoised_fn: if not None, a function which applies to the
425
+ x_start prediction before it is used to sample.
426
+ :param cond_fn: if not None, this is a gradient function that acts
427
+ similarly to the model.
428
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
429
+ pass to the model. This can be used for conditioning.
430
+ :param device: if specified, the device to create the samples on.
431
+ If not specified, use a model parameter's device.
432
+ :param progress: if True, show a tqdm progress bar.
433
+ :return: a non-differentiable batch of samples.
434
+ """
435
+ final = None
436
+ for sample in self.p_sample_loop_progressive(
437
+ model,
438
+ shape,
439
+ noise=noise,
440
+ clip_denoised=clip_denoised,
441
+ denoised_fn=denoised_fn,
442
+ cond_fn=cond_fn,
443
+ model_kwargs=model_kwargs,
444
+ device=device,
445
+ progress=progress,
446
+ skip_timesteps=skip_timesteps,
447
+ init_image=init_image,
448
+ randomize_class=randomize_class,
449
+ ):
450
+ final = sample
451
+ return final["sample"]
452
+
453
+ def p_sample_loop_progressive(
454
+ self,
455
+ model,
456
+ shape,
457
+ noise=None,
458
+ clip_denoised=True,
459
+ denoised_fn=None,
460
+ cond_fn=None,
461
+ model_kwargs=None,
462
+ device=None,
463
+ progress=False,
464
+ skip_timesteps=0,
465
+ init_image=None,
466
+ postprocess_fn=None,
467
+ randomize_class=False,
468
+ ):
469
+ """
470
+ Generate samples from the model and yield intermediate samples from
471
+ each timestep of diffusion.
472
+
473
+ Arguments are the same as p_sample_loop().
474
+ Returns a generator over dicts, where each dict is the return value of
475
+ p_sample().
476
+ """
477
+ # if device is None:
478
+ # device = next(model.parameters()).device
479
+ assert isinstance(shape, (tuple, list))
480
+ if noise is not None:
481
+ img = noise
482
+ '''
483
+ img_guidance = noise.to(device)
484
+ t_batch = th.tensor([int(t0*self.num_timesteps)-1]*len(img_guidance), device=device)
485
+ img = self.q_sample(img_guidance, t_batch)
486
+ indices = list(range(int(t0*self.num_timesteps)))[::-1]
487
+ '''
488
+ else:
489
+ img = th.randn(*shape, device=device)
490
+
491
+ # pdb.set_trace()
492
+ if skip_timesteps and init_image is None:
493
+ init_image = th.zeros_like(img)
494
+
495
+ indices = list(range(self.num_timesteps - skip_timesteps))[::-1]
496
+
497
+ batch_size = shape[0]
498
+ init_image_batch = th.tile(init_image, dims=(batch_size, 1, 1, 1))
499
+ img = self.q_sample(
500
+ x_start=init_image_batch,
501
+ t=th.tensor(indices[0], dtype=th.long, device=device),
502
+ noise=img,
503
+ )
504
+
505
+ if progress:
506
+ # Lazy import so that we don't depend on tqdm.
507
+ from tqdm.auto import tqdm
508
+
509
+ indices = tqdm(indices)
510
+
511
+ for i in indices:
512
+ t = th.tensor([i] * shape[0], device=device)
513
+ if randomize_class and "y" in model_kwargs:
514
+ model_kwargs["y"] = th.randint(
515
+ low=0,
516
+ high=model.num_classes,
517
+ size=model_kwargs["y"].shape,
518
+ device=model_kwargs["y"].device,
519
+ )
520
+ with th.no_grad():
521
+ out = self.p_sample(
522
+ model,
523
+ img,
524
+ t,
525
+ clip_denoised=clip_denoised,
526
+ denoised_fn=denoised_fn,
527
+ cond_fn=cond_fn,
528
+ model_kwargs=model_kwargs,
529
+ )
530
+ if postprocess_fn is not None:
531
+ out = postprocess_fn(out, t)
532
+
533
+ yield out
534
+ img = out["sample"]
535
+
536
+ def ddim_sample(
537
+ self,
538
+ model,
539
+ x,
540
+ t,
541
+ clip_denoised=True,
542
+ denoised_fn=None,
543
+ cond_fn=None,
544
+ model_kwargs=None,
545
+ eta=0.0,
546
+ ):
547
+ """
548
+ Sample x_{t-1} from the model using DDIM.
549
+
550
+ Same usage as p_sample().
551
+ """
552
+ out = self.p_mean_variance(
553
+ model,
554
+ x,
555
+ t,
556
+ clip_denoised=clip_denoised,
557
+ denoised_fn=denoised_fn,
558
+ model_kwargs=model_kwargs,
559
+ )
560
+ if cond_fn is not None:
561
+ out = self.condition_score(cond_fn, out, x, t, model_kwargs=model_kwargs)
562
+
563
+ # Usually our model outputs epsilon, but we re-derive it
564
+ # in case we used x_start or x_prev prediction.
565
+ eps = self._predict_eps_from_xstart(x, t, out["pred_xstart"])
566
+
567
+ alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
568
+ alpha_bar_prev = _extract_into_tensor(self.alphas_cumprod_prev, t, x.shape)
569
+ sigma = (
570
+ eta
571
+ * th.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar))
572
+ * th.sqrt(1 - alpha_bar / alpha_bar_prev)
573
+ )
574
+ # Equation 12.
575
+ noise = th.randn_like(x)
576
+ mean_pred = (
577
+ out["pred_xstart"] * th.sqrt(alpha_bar_prev)
578
+ + th.sqrt(1 - alpha_bar_prev - sigma ** 2) * eps
579
+ )
580
+ nonzero_mask = (
581
+ (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
582
+ ) # no noise when t == 0
583
+ sample = mean_pred + nonzero_mask * sigma * noise
584
+ return {"sample": sample, "pred_xstart": out["pred_xstart"]}
585
+
586
+ def ddim_reverse_sample(
587
+ self, model, x, t, clip_denoised=True, denoised_fn=None, model_kwargs=None, eta=0.0,
588
+ ):
589
+ """
590
+ Sample x_{t+1} from the model using DDIM reverse ODE.
591
+ """
592
+ assert eta == 0.0, "Reverse ODE only for deterministic path"
593
+ out = self.p_mean_variance(
594
+ model,
595
+ x,
596
+ t,
597
+ clip_denoised=clip_denoised,
598
+ denoised_fn=denoised_fn,
599
+ model_kwargs=model_kwargs,
600
+ )
601
+ # Usually our model outputs epsilon, but we re-derive it
602
+ # in case we used x_start or x_prev prediction.
603
+ eps = (
604
+ _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x.shape) * x
605
+ - out["pred_xstart"]
606
+ ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x.shape)
607
+ alpha_bar_next = _extract_into_tensor(self.alphas_cumprod_next, t, x.shape)
608
+
609
+ # Equation 12. reversed
610
+ mean_pred = out["pred_xstart"] * th.sqrt(alpha_bar_next) + th.sqrt(1 - alpha_bar_next) * eps
611
+
612
+ return {"sample": mean_pred, "pred_xstart": out["pred_xstart"]}
613
+
614
+ def ddim_sample_loop(
615
+ self,
616
+ model,
617
+ shape,
618
+ noise=None,
619
+ clip_denoised=True,
620
+ denoised_fn=None,
621
+ cond_fn=None,
622
+ model_kwargs=None,
623
+ device=None,
624
+ progress=False,
625
+ eta=0.0,
626
+ skip_timesteps=0,
627
+ init_image=None,
628
+ randomize_class=False,
629
+ ):
630
+ """
631
+ Generate samples from the model using DDIM.
632
+
633
+ Same usage as p_sample_loop().
634
+ """
635
+ final = None
636
+ for sample in self.ddim_sample_loop_progressive(
637
+ model,
638
+ shape,
639
+ noise=noise,
640
+ clip_denoised=clip_denoised,
641
+ denoised_fn=denoised_fn,
642
+ cond_fn=cond_fn,
643
+ model_kwargs=model_kwargs,
644
+ device=device,
645
+ progress=progress,
646
+ eta=eta,
647
+ skip_timesteps=skip_timesteps,
648
+ init_image=init_image,
649
+ randomize_class=randomize_class,
650
+ ):
651
+ final = sample
652
+ return final["sample"]
653
+
654
+ def ddim_sample_loop_progressive(
655
+ self,
656
+ model,
657
+ shape,
658
+ noise=None,
659
+ clip_denoised=True,
660
+ denoised_fn=None,
661
+ cond_fn=None,
662
+ model_kwargs=None,
663
+ device=None,
664
+ progress=False,
665
+ eta=0.0,
666
+ skip_timesteps=0,
667
+ init_image=None,
668
+ postprocess_fn=None,
669
+ randomize_class=False,
670
+ ):
671
+ """
672
+ Use DDIM to sample from the model and yield intermediate samples from
673
+ each timestep of DDIM.
674
+
675
+ Same usage as p_sample_loop_progressive().
676
+ """
677
+ if device is None:
678
+ device = next(model.parameters()).device
679
+ assert isinstance(shape, (tuple, list))
680
+ if noise is not None:
681
+ img = noise
682
+ else:
683
+ img = th.randn(*shape, device=device)
684
+
685
+ if skip_timesteps and init_image is None:
686
+ init_image = th.zeros_like(img)
687
+
688
+ indices = list(range(self.num_timesteps - skip_timesteps))[::-1]
689
+
690
+ if init_image is not None:
691
+ my_t = th.ones([shape[0]], device=device, dtype=th.long) * indices[0]
692
+ batch_size = shape[0]
693
+ init_image_batch = th.tile(init_image, dims=(batch_size, 1, 1, 1))
694
+ img = self.q_sample(init_image_batch, my_t, img)
695
+
696
+ if progress:
697
+ # Lazy import so that we don't depend on tqdm.
698
+ from tqdm.auto import tqdm
699
+
700
+ indices = tqdm(indices)
701
+
702
+ for i in indices:
703
+ t = th.tensor([i] * shape[0], device=device)
704
+ if randomize_class and "y" in model_kwargs:
705
+ model_kwargs["y"] = th.randint(
706
+ low=0,
707
+ high=model.num_classes,
708
+ size=model_kwargs["y"].shape,
709
+ device=model_kwargs["y"].device,
710
+ )
711
+ with th.no_grad():
712
+ out = self.ddim_sample(
713
+ model,
714
+ img,
715
+ t,
716
+ clip_denoised=clip_denoised,
717
+ denoised_fn=denoised_fn,
718
+ cond_fn=cond_fn,
719
+ model_kwargs=model_kwargs,
720
+ eta=eta,
721
+ )
722
+
723
+ if postprocess_fn is not None:
724
+ out = postprocess_fn(out, t)
725
+
726
+ yield out
727
+ img = out["sample"]
728
+
729
+ def _vb_terms_bpd(self, model, x_start, x_t, t, clip_denoised=True, model_kwargs=None):
730
+ """
731
+ Get a term for the variational lower-bound.
732
+
733
+ The resulting units are bits (rather than nats, as one might expect).
734
+ This allows for comparison to other papers.
735
+
736
+ :return: a dict with the following keys:
737
+ - 'output': a shape [N] tensor of NLLs or KLs.
738
+ - 'pred_xstart': the x_0 predictions.
739
+ """
740
+ true_mean, _, true_log_variance_clipped = self.q_posterior_mean_variance(
741
+ x_start=x_start, x_t=x_t, t=t
742
+ )
743
+ out = self.p_mean_variance(
744
+ model, x_t, t, clip_denoised=clip_denoised, model_kwargs=model_kwargs
745
+ )
746
+ kl = normal_kl(true_mean, true_log_variance_clipped, out["mean"], out["log_variance"])
747
+ kl = mean_flat(kl) / np.log(2.0)
748
+
749
+ decoder_nll = -discretized_gaussian_log_likelihood(
750
+ x_start, means=out["mean"], log_scales=0.5 * out["log_variance"]
751
+ )
752
+ assert decoder_nll.shape == x_start.shape
753
+ decoder_nll = mean_flat(decoder_nll) / np.log(2.0)
754
+
755
+ # At the first timestep return the decoder NLL,
756
+ # otherwise return KL(q(x_{t-1}|x_t,x_0) || p(x_{t-1}|x_t))
757
+ output = th.where((t == 0), decoder_nll, kl)
758
+ return {"output": output, "pred_xstart": out["pred_xstart"]}
759
+
760
+ def training_losses(self, model, x_start, t, model_kwargs=None, noise=None):
761
+ """
762
+ Compute training losses for a single timestep.
763
+
764
+ :param model: the model to evaluate loss on.
765
+ :param x_start: the [N x C x ...] tensor of inputs.
766
+ :param t: a batch of timestep indices.
767
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
768
+ pass to the model. This can be used for conditioning.
769
+ :param noise: if specified, the specific Gaussian noise to try to remove.
770
+ :return: a dict with the key "loss" containing a tensor of shape [N].
771
+ Some mean or variance settings may also have other keys.
772
+ """
773
+ if model_kwargs is None:
774
+ model_kwargs = {}
775
+ if noise is None:
776
+ noise = th.randn_like(x_start)
777
+ x_t = self.q_sample(x_start, t, noise=noise)
778
+
779
+ terms = {}
780
+
781
+ if self.loss_type == LossType.KL or self.loss_type == LossType.RESCALED_KL:
782
+ terms["loss"] = self._vb_terms_bpd(
783
+ model=model,
784
+ x_start=x_start,
785
+ x_t=x_t,
786
+ t=t,
787
+ clip_denoised=False,
788
+ model_kwargs=model_kwargs,
789
+ )["output"]
790
+ if self.loss_type == LossType.RESCALED_KL:
791
+ terms["loss"] *= self.num_timesteps
792
+ elif self.loss_type == LossType.MSE or self.loss_type == LossType.RESCALED_MSE:
793
+ model_output = model(x_t, self._scale_timesteps(t), **model_kwargs)
794
+
795
+ if self.model_var_type in [
796
+ ModelVarType.LEARNED,
797
+ ModelVarType.LEARNED_RANGE,
798
+ ]:
799
+ B, C = x_t.shape[:2]
800
+ assert model_output.shape == (B, C * 2, *x_t.shape[2:])
801
+ model_output, model_var_values = th.split(model_output, C, dim=1)
802
+ # Learn the variance using the variational bound, but don't let
803
+ # it affect our mean prediction.
804
+ frozen_out = th.cat([model_output.detach(), model_var_values], dim=1)
805
+ terms["vb"] = self._vb_terms_bpd(
806
+ model=lambda *args, r=frozen_out: r,
807
+ x_start=x_start,
808
+ x_t=x_t,
809
+ t=t,
810
+ clip_denoised=False,
811
+ )["output"]
812
+ if self.loss_type == LossType.RESCALED_MSE:
813
+ # Divide by 1000 for equivalence with initial implementation.
814
+ # Without a factor of 1/1000, the VB term hurts the MSE term.
815
+ terms["vb"] *= self.num_timesteps / 1000.0
816
+
817
+ target = {
818
+ ModelMeanType.PREVIOUS_X: self.q_posterior_mean_variance(
819
+ x_start=x_start, x_t=x_t, t=t
820
+ )[0],
821
+ ModelMeanType.START_X: x_start,
822
+ ModelMeanType.EPSILON: noise,
823
+ }[self.model_mean_type]
824
+ assert model_output.shape == target.shape == x_start.shape
825
+ terms["mse"] = mean_flat((target - model_output) ** 2)
826
+ if "vb" in terms:
827
+ terms["loss"] = terms["mse"] + terms["vb"]
828
+ else:
829
+ terms["loss"] = terms["mse"]
830
+ else:
831
+ raise NotImplementedError(self.loss_type)
832
+
833
+ return terms
834
+
835
+ def _prior_bpd(self, x_start):
836
+ """
837
+ Get the prior KL term for the variational lower-bound, measured in
838
+ bits-per-dim.
839
+
840
+ This term can't be optimized, as it only depends on the encoder.
841
+
842
+ :param x_start: the [N x C x ...] tensor of inputs.
843
+ :return: a batch of [N] KL values (in bits), one per batch element.
844
+ """
845
+ batch_size = x_start.shape[0]
846
+ t = th.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
847
+ qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
848
+ kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
849
+ return mean_flat(kl_prior) / np.log(2.0)
850
+
851
+ def calc_bpd_loop(self, model, x_start, clip_denoised=True, model_kwargs=None):
852
+ """
853
+ Compute the entire variational lower-bound, measured in bits-per-dim,
854
+ as well as other related quantities.
855
+
856
+ :param model: the model to evaluate loss on.
857
+ :param x_start: the [N x C x ...] tensor of inputs.
858
+ :param clip_denoised: if True, clip denoised samples.
859
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
860
+ pass to the model. This can be used for conditioning.
861
+
862
+ :return: a dict containing the following keys:
863
+ - total_bpd: the total variational lower-bound, per batch element.
864
+ - prior_bpd: the prior term in the lower-bound.
865
+ - vb: an [N x T] tensor of terms in the lower-bound.
866
+ - xstart_mse: an [N x T] tensor of x_0 MSEs for each timestep.
867
+ - mse: an [N x T] tensor of epsilon MSEs for each timestep.
868
+ """
869
+ device = x_start.device
870
+ batch_size = x_start.shape[0]
871
+
872
+ vb = []
873
+ xstart_mse = []
874
+ mse = []
875
+ for t in list(range(self.num_timesteps))[::-1]:
876
+ t_batch = th.tensor([t] * batch_size, device=device)
877
+ noise = th.randn_like(x_start)
878
+ x_t = self.q_sample(x_start=x_start, t=t_batch, noise=noise)
879
+ # Calculate VLB term at the current timestep
880
+ with th.no_grad():
881
+ out = self._vb_terms_bpd(
882
+ model,
883
+ x_start=x_start,
884
+ x_t=x_t,
885
+ t=t_batch,
886
+ clip_denoised=clip_denoised,
887
+ model_kwargs=model_kwargs,
888
+ )
889
+ vb.append(out["output"])
890
+ xstart_mse.append(mean_flat((out["pred_xstart"] - x_start) ** 2))
891
+ eps = self._predict_eps_from_xstart(x_t, t_batch, out["pred_xstart"])
892
+ mse.append(mean_flat((eps - noise) ** 2))
893
+
894
+ vb = th.stack(vb, dim=1)
895
+ xstart_mse = th.stack(xstart_mse, dim=1)
896
+ mse = th.stack(mse, dim=1)
897
+
898
+ prior_bpd = self._prior_bpd(x_start)
899
+ total_bpd = vb.sum(dim=1) + prior_bpd
900
+ return {
901
+ "total_bpd": total_bpd,
902
+ "prior_bpd": prior_bpd,
903
+ "vb": vb,
904
+ "xstart_mse": xstart_mse,
905
+ "mse": mse,
906
+ }
907
+
908
+
909
+ def _extract_into_tensor(arr, timesteps, broadcast_shape):
910
+ """
911
+ Extract values from a 1-D numpy array for a batch of indices.
912
+
913
+ :param arr: the 1-D numpy array.
914
+ :param timesteps: a tensor of indices into the array to extract.
915
+ :param broadcast_shape: a larger shape of K dimensions with the batch
916
+ dimension equal to the length of timesteps.
917
+ :return: a tensor of shape [batch_size, 1, ...] where the shape has K dims.
918
+ """
919
+ res = th.from_numpy(arr).to(device=timesteps.device)[timesteps].float()
920
+ while len(res.shape) < len(broadcast_shape):
921
+ res = res[..., None]
922
+ return res.expand(broadcast_shape)
editing_diffusion/guided_diffusion/guided_diffusion/image_datasets.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import random
3
+
4
+ from PIL import Image
5
+ import blobfile as bf
6
+ from mpi4py import MPI
7
+ import numpy as np
8
+ from torch.utils.data import DataLoader, Dataset
9
+
10
+
11
+ def load_data(
12
+ *,
13
+ data_dir,
14
+ batch_size,
15
+ image_size,
16
+ class_cond=False,
17
+ deterministic=False,
18
+ random_crop=False,
19
+ random_flip=True,
20
+ ):
21
+ """
22
+ For a dataset, create a generator over (images, kwargs) pairs.
23
+
24
+ Each images is an NCHW float tensor, and the kwargs dict contains zero or
25
+ more keys, each of which map to a batched Tensor of their own.
26
+ The kwargs dict can be used for class labels, in which case the key is "y"
27
+ and the values are integer tensors of class labels.
28
+
29
+ :param data_dir: a dataset directory.
30
+ :param batch_size: the batch size of each returned pair.
31
+ :param image_size: the size to which images are resized.
32
+ :param class_cond: if True, include a "y" key in returned dicts for class
33
+ label. If classes are not available and this is true, an
34
+ exception will be raised.
35
+ :param deterministic: if True, yield results in a deterministic order.
36
+ :param random_crop: if True, randomly crop the images for augmentation.
37
+ :param random_flip: if True, randomly flip the images for augmentation.
38
+ """
39
+ if not data_dir:
40
+ raise ValueError("unspecified data directory")
41
+ all_files = _list_image_files_recursively(data_dir)
42
+ classes = None
43
+ if class_cond:
44
+ # Assume classes are the first part of the filename,
45
+ # before an underscore.
46
+ class_names = [bf.basename(path).split("_")[0] for path in all_files]
47
+ sorted_classes = {x: i for i, x in enumerate(sorted(set(class_names)))}
48
+ classes = [sorted_classes[x] for x in class_names]
49
+ dataset = ImageDataset(
50
+ image_size,
51
+ all_files,
52
+ classes=classes,
53
+ shard=MPI.COMM_WORLD.Get_rank(),
54
+ num_shards=MPI.COMM_WORLD.Get_size(),
55
+ random_crop=random_crop,
56
+ random_flip=random_flip,
57
+ )
58
+ if deterministic:
59
+ loader = DataLoader(
60
+ dataset, batch_size=batch_size, shuffle=False, num_workers=1, drop_last=True
61
+ )
62
+ else:
63
+ loader = DataLoader(
64
+ dataset, batch_size=batch_size, shuffle=True, num_workers=1, drop_last=True
65
+ )
66
+ while True:
67
+ yield from loader
68
+
69
+
70
+ def _list_image_files_recursively(data_dir):
71
+ results = []
72
+ for entry in sorted(bf.listdir(data_dir)):
73
+ full_path = bf.join(data_dir, entry)
74
+ ext = entry.split(".")[-1]
75
+ if "." in entry and ext.lower() in ["jpg", "jpeg", "png", "gif"]:
76
+ results.append(full_path)
77
+ elif bf.isdir(full_path):
78
+ results.extend(_list_image_files_recursively(full_path))
79
+ return results
80
+
81
+
82
+ class ImageDataset(Dataset):
83
+ def __init__(
84
+ self,
85
+ resolution,
86
+ image_paths,
87
+ classes=None,
88
+ shard=0,
89
+ num_shards=1,
90
+ random_crop=False,
91
+ random_flip=True,
92
+ ):
93
+ super().__init__()
94
+ self.resolution = resolution
95
+ self.local_images = image_paths[shard:][::num_shards]
96
+ self.local_classes = None if classes is None else classes[shard:][::num_shards]
97
+ self.random_crop = random_crop
98
+ self.random_flip = random_flip
99
+
100
+ def __len__(self):
101
+ return len(self.local_images)
102
+
103
+ def __getitem__(self, idx):
104
+ path = self.local_images[idx]
105
+ with bf.BlobFile(path, "rb") as f:
106
+ pil_image = Image.open(f)
107
+ pil_image.load()
108
+ pil_image = pil_image.convert("RGB")
109
+
110
+ if self.random_crop:
111
+ arr = random_crop_arr(pil_image, self.resolution)
112
+ else:
113
+ arr = center_crop_arr(pil_image, self.resolution)
114
+
115
+ if self.random_flip and random.random() < 0.5:
116
+ arr = arr[:, ::-1]
117
+
118
+ arr = arr.astype(np.float32) / 127.5 - 1
119
+
120
+ out_dict = {}
121
+ if self.local_classes is not None:
122
+ out_dict["y"] = np.array(self.local_classes[idx], dtype=np.int64)
123
+ return np.transpose(arr, [2, 0, 1]), out_dict
124
+
125
+
126
+ def center_crop_arr(pil_image, image_size):
127
+ # We are not on a new enough PIL to support the `reducing_gap`
128
+ # argument, which uses BOX downsampling at powers of two first.
129
+ # Thus, we do it by hand to improve downsample quality.
130
+ while min(*pil_image.size) >= 2 * image_size:
131
+ pil_image = pil_image.resize(
132
+ tuple(x // 2 for x in pil_image.size), resample=Image.BOX
133
+ )
134
+
135
+ scale = image_size / min(*pil_image.size)
136
+ pil_image = pil_image.resize(
137
+ tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC
138
+ )
139
+
140
+ arr = np.array(pil_image)
141
+ crop_y = (arr.shape[0] - image_size) // 2
142
+ crop_x = (arr.shape[1] - image_size) // 2
143
+ return arr[crop_y : crop_y + image_size, crop_x : crop_x + image_size]
144
+
145
+
146
+ def random_crop_arr(pil_image, image_size, min_crop_frac=0.8, max_crop_frac=1.0):
147
+ min_smaller_dim_size = math.ceil(image_size / max_crop_frac)
148
+ max_smaller_dim_size = math.ceil(image_size / min_crop_frac)
149
+ smaller_dim_size = random.randrange(min_smaller_dim_size, max_smaller_dim_size + 1)
150
+
151
+ # We are not on a new enough PIL to support the `reducing_gap`
152
+ # argument, which uses BOX downsampling at powers of two first.
153
+ # Thus, we do it by hand to improve downsample quality.
154
+ while min(*pil_image.size) >= 2 * smaller_dim_size:
155
+ pil_image = pil_image.resize(
156
+ tuple(x // 2 for x in pil_image.size), resample=Image.BOX
157
+ )
158
+
159
+ scale = smaller_dim_size / min(*pil_image.size)
160
+ pil_image = pil_image.resize(
161
+ tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC
162
+ )
163
+
164
+ arr = np.array(pil_image)
165
+ crop_y = random.randrange(arr.shape[0] - image_size + 1)
166
+ crop_x = random.randrange(arr.shape[1] - image_size + 1)
167
+ return arr[crop_y : crop_y + image_size, crop_x : crop_x + image_size]
editing_diffusion/guided_diffusion/guided_diffusion/logger.py ADDED
@@ -0,0 +1,495 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Logger copied from OpenAI baselines to avoid extra RL-based dependencies:
3
+ https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/logger.py
4
+ """
5
+
6
+ import os
7
+ import sys
8
+ import shutil
9
+ import os.path as osp
10
+ import json
11
+ import time
12
+ import datetime
13
+ import tempfile
14
+ import warnings
15
+ from collections import defaultdict
16
+ from contextlib import contextmanager
17
+
18
+ DEBUG = 10
19
+ INFO = 20
20
+ WARN = 30
21
+ ERROR = 40
22
+
23
+ DISABLED = 50
24
+
25
+
26
+ class KVWriter(object):
27
+ def writekvs(self, kvs):
28
+ raise NotImplementedError
29
+
30
+
31
+ class SeqWriter(object):
32
+ def writeseq(self, seq):
33
+ raise NotImplementedError
34
+
35
+
36
+ class HumanOutputFormat(KVWriter, SeqWriter):
37
+ def __init__(self, filename_or_file):
38
+ if isinstance(filename_or_file, str):
39
+ self.file = open(filename_or_file, "wt")
40
+ self.own_file = True
41
+ else:
42
+ assert hasattr(filename_or_file, "read"), (
43
+ "expected file or str, got %s" % filename_or_file
44
+ )
45
+ self.file = filename_or_file
46
+ self.own_file = False
47
+
48
+ def writekvs(self, kvs):
49
+ # Create strings for printing
50
+ key2str = {}
51
+ for (key, val) in sorted(kvs.items()):
52
+ if hasattr(val, "__float__"):
53
+ valstr = "%-8.3g" % val
54
+ else:
55
+ valstr = str(val)
56
+ key2str[self._truncate(key)] = self._truncate(valstr)
57
+
58
+ # Find max widths
59
+ if len(key2str) == 0:
60
+ print("WARNING: tried to write empty key-value dict")
61
+ return
62
+ else:
63
+ keywidth = max(map(len, key2str.keys()))
64
+ valwidth = max(map(len, key2str.values()))
65
+
66
+ # Write out the data
67
+ dashes = "-" * (keywidth + valwidth + 7)
68
+ lines = [dashes]
69
+ for (key, val) in sorted(key2str.items(), key=lambda kv: kv[0].lower()):
70
+ lines.append(
71
+ "| %s%s | %s%s |"
72
+ % (key, " " * (keywidth - len(key)), val, " " * (valwidth - len(val)))
73
+ )
74
+ lines.append(dashes)
75
+ self.file.write("\n".join(lines) + "\n")
76
+
77
+ # Flush the output to the file
78
+ self.file.flush()
79
+
80
+ def _truncate(self, s):
81
+ maxlen = 30
82
+ return s[: maxlen - 3] + "..." if len(s) > maxlen else s
83
+
84
+ def writeseq(self, seq):
85
+ seq = list(seq)
86
+ for (i, elem) in enumerate(seq):
87
+ self.file.write(elem)
88
+ if i < len(seq) - 1: # add space unless this is the last one
89
+ self.file.write(" ")
90
+ self.file.write("\n")
91
+ self.file.flush()
92
+
93
+ def close(self):
94
+ if self.own_file:
95
+ self.file.close()
96
+
97
+
98
+ class JSONOutputFormat(KVWriter):
99
+ def __init__(self, filename):
100
+ self.file = open(filename, "wt")
101
+
102
+ def writekvs(self, kvs):
103
+ for k, v in sorted(kvs.items()):
104
+ if hasattr(v, "dtype"):
105
+ kvs[k] = float(v)
106
+ self.file.write(json.dumps(kvs) + "\n")
107
+ self.file.flush()
108
+
109
+ def close(self):
110
+ self.file.close()
111
+
112
+
113
+ class CSVOutputFormat(KVWriter):
114
+ def __init__(self, filename):
115
+ self.file = open(filename, "w+t")
116
+ self.keys = []
117
+ self.sep = ","
118
+
119
+ def writekvs(self, kvs):
120
+ # Add our current row to the history
121
+ extra_keys = list(kvs.keys() - self.keys)
122
+ extra_keys.sort()
123
+ if extra_keys:
124
+ self.keys.extend(extra_keys)
125
+ self.file.seek(0)
126
+ lines = self.file.readlines()
127
+ self.file.seek(0)
128
+ for (i, k) in enumerate(self.keys):
129
+ if i > 0:
130
+ self.file.write(",")
131
+ self.file.write(k)
132
+ self.file.write("\n")
133
+ for line in lines[1:]:
134
+ self.file.write(line[:-1])
135
+ self.file.write(self.sep * len(extra_keys))
136
+ self.file.write("\n")
137
+ for (i, k) in enumerate(self.keys):
138
+ if i > 0:
139
+ self.file.write(",")
140
+ v = kvs.get(k)
141
+ if v is not None:
142
+ self.file.write(str(v))
143
+ self.file.write("\n")
144
+ self.file.flush()
145
+
146
+ def close(self):
147
+ self.file.close()
148
+
149
+
150
+ class TensorBoardOutputFormat(KVWriter):
151
+ """
152
+ Dumps key/value pairs into TensorBoard's numeric format.
153
+ """
154
+
155
+ def __init__(self, dir):
156
+ os.makedirs(dir, exist_ok=True)
157
+ self.dir = dir
158
+ self.step = 1
159
+ prefix = "events"
160
+ path = osp.join(osp.abspath(dir), prefix)
161
+ import tensorflow as tf
162
+ from tensorflow.python import pywrap_tensorflow
163
+ from tensorflow.core.util import event_pb2
164
+ from tensorflow.python.util import compat
165
+
166
+ self.tf = tf
167
+ self.event_pb2 = event_pb2
168
+ self.pywrap_tensorflow = pywrap_tensorflow
169
+ self.writer = pywrap_tensorflow.EventsWriter(compat.as_bytes(path))
170
+
171
+ def writekvs(self, kvs):
172
+ def summary_val(k, v):
173
+ kwargs = {"tag": k, "simple_value": float(v)}
174
+ return self.tf.Summary.Value(**kwargs)
175
+
176
+ summary = self.tf.Summary(value=[summary_val(k, v) for k, v in kvs.items()])
177
+ event = self.event_pb2.Event(wall_time=time.time(), summary=summary)
178
+ event.step = (
179
+ self.step
180
+ ) # is there any reason why you'd want to specify the step?
181
+ self.writer.WriteEvent(event)
182
+ self.writer.Flush()
183
+ self.step += 1
184
+
185
+ def close(self):
186
+ if self.writer:
187
+ self.writer.Close()
188
+ self.writer = None
189
+
190
+
191
+ def make_output_format(format, ev_dir, log_suffix=""):
192
+ os.makedirs(ev_dir, exist_ok=True)
193
+ if format == "stdout":
194
+ return HumanOutputFormat(sys.stdout)
195
+ elif format == "log":
196
+ return HumanOutputFormat(osp.join(ev_dir, "log%s.txt" % log_suffix))
197
+ elif format == "json":
198
+ return JSONOutputFormat(osp.join(ev_dir, "progress%s.json" % log_suffix))
199
+ elif format == "csv":
200
+ return CSVOutputFormat(osp.join(ev_dir, "progress%s.csv" % log_suffix))
201
+ elif format == "tensorboard":
202
+ return TensorBoardOutputFormat(osp.join(ev_dir, "tb%s" % log_suffix))
203
+ else:
204
+ raise ValueError("Unknown format specified: %s" % (format,))
205
+
206
+
207
+ # ================================================================
208
+ # API
209
+ # ================================================================
210
+
211
+
212
+ def logkv(key, val):
213
+ """
214
+ Log a value of some diagnostic
215
+ Call this once for each diagnostic quantity, each iteration
216
+ If called many times, last value will be used.
217
+ """
218
+ get_current().logkv(key, val)
219
+
220
+
221
+ def logkv_mean(key, val):
222
+ """
223
+ The same as logkv(), but if called many times, values averaged.
224
+ """
225
+ get_current().logkv_mean(key, val)
226
+
227
+
228
+ def logkvs(d):
229
+ """
230
+ Log a dictionary of key-value pairs
231
+ """
232
+ for (k, v) in d.items():
233
+ logkv(k, v)
234
+
235
+
236
+ def dumpkvs():
237
+ """
238
+ Write all of the diagnostics from the current iteration
239
+ """
240
+ return get_current().dumpkvs()
241
+
242
+
243
+ def getkvs():
244
+ return get_current().name2val
245
+
246
+
247
+ def log(*args, level=INFO):
248
+ """
249
+ Write the sequence of args, with no separators, to the console and output files (if you've configured an output file).
250
+ """
251
+ get_current().log(*args, level=level)
252
+
253
+
254
+ def debug(*args):
255
+ log(*args, level=DEBUG)
256
+
257
+
258
+ def info(*args):
259
+ log(*args, level=INFO)
260
+
261
+
262
+ def warn(*args):
263
+ log(*args, level=WARN)
264
+
265
+
266
+ def error(*args):
267
+ log(*args, level=ERROR)
268
+
269
+
270
+ def set_level(level):
271
+ """
272
+ Set logging threshold on current logger.
273
+ """
274
+ get_current().set_level(level)
275
+
276
+
277
+ def set_comm(comm):
278
+ get_current().set_comm(comm)
279
+
280
+
281
+ def get_dir():
282
+ """
283
+ Get directory that log files are being written to.
284
+ will be None if there is no output directory (i.e., if you didn't call start)
285
+ """
286
+ return get_current().get_dir()
287
+
288
+
289
+ record_tabular = logkv
290
+ dump_tabular = dumpkvs
291
+
292
+
293
+ @contextmanager
294
+ def profile_kv(scopename):
295
+ logkey = "wait_" + scopename
296
+ tstart = time.time()
297
+ try:
298
+ yield
299
+ finally:
300
+ get_current().name2val[logkey] += time.time() - tstart
301
+
302
+
303
+ def profile(n):
304
+ """
305
+ Usage:
306
+ @profile("my_func")
307
+ def my_func(): code
308
+ """
309
+
310
+ def decorator_with_name(func):
311
+ def func_wrapper(*args, **kwargs):
312
+ with profile_kv(n):
313
+ return func(*args, **kwargs)
314
+
315
+ return func_wrapper
316
+
317
+ return decorator_with_name
318
+
319
+
320
+ # ================================================================
321
+ # Backend
322
+ # ================================================================
323
+
324
+
325
+ def get_current():
326
+ if Logger.CURRENT is None:
327
+ _configure_default_logger()
328
+
329
+ return Logger.CURRENT
330
+
331
+
332
+ class Logger(object):
333
+ DEFAULT = None # A logger with no output files. (See right below class definition)
334
+ # So that you can still log to the terminal without setting up any output files
335
+ CURRENT = None # Current logger being used by the free functions above
336
+
337
+ def __init__(self, dir, output_formats, comm=None):
338
+ self.name2val = defaultdict(float) # values this iteration
339
+ self.name2cnt = defaultdict(int)
340
+ self.level = INFO
341
+ self.dir = dir
342
+ self.output_formats = output_formats
343
+ self.comm = comm
344
+
345
+ # Logging API, forwarded
346
+ # ----------------------------------------
347
+ def logkv(self, key, val):
348
+ self.name2val[key] = val
349
+
350
+ def logkv_mean(self, key, val):
351
+ oldval, cnt = self.name2val[key], self.name2cnt[key]
352
+ self.name2val[key] = oldval * cnt / (cnt + 1) + val / (cnt + 1)
353
+ self.name2cnt[key] = cnt + 1
354
+
355
+ def dumpkvs(self):
356
+ if self.comm is None:
357
+ d = self.name2val
358
+ else:
359
+ d = mpi_weighted_mean(
360
+ self.comm,
361
+ {
362
+ name: (val, self.name2cnt.get(name, 1))
363
+ for (name, val) in self.name2val.items()
364
+ },
365
+ )
366
+ if self.comm.rank != 0:
367
+ d["dummy"] = 1 # so we don't get a warning about empty dict
368
+ out = d.copy() # Return the dict for unit testing purposes
369
+ for fmt in self.output_formats:
370
+ if isinstance(fmt, KVWriter):
371
+ fmt.writekvs(d)
372
+ self.name2val.clear()
373
+ self.name2cnt.clear()
374
+ return out
375
+
376
+ def log(self, *args, level=INFO):
377
+ if self.level <= level:
378
+ self._do_log(args)
379
+
380
+ # Configuration
381
+ # ----------------------------------------
382
+ def set_level(self, level):
383
+ self.level = level
384
+
385
+ def set_comm(self, comm):
386
+ self.comm = comm
387
+
388
+ def get_dir(self):
389
+ return self.dir
390
+
391
+ def close(self):
392
+ for fmt in self.output_formats:
393
+ fmt.close()
394
+
395
+ # Misc
396
+ # ----------------------------------------
397
+ def _do_log(self, args):
398
+ for fmt in self.output_formats:
399
+ if isinstance(fmt, SeqWriter):
400
+ fmt.writeseq(map(str, args))
401
+
402
+
403
+ def get_rank_without_mpi_import():
404
+ # check environment variables here instead of importing mpi4py
405
+ # to avoid calling MPI_Init() when this module is imported
406
+ for varname in ["PMI_RANK", "OMPI_COMM_WORLD_RANK"]:
407
+ if varname in os.environ:
408
+ return int(os.environ[varname])
409
+ return 0
410
+
411
+
412
+ def mpi_weighted_mean(comm, local_name2valcount):
413
+ """
414
+ Copied from: https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/common/mpi_util.py#L110
415
+ Perform a weighted average over dicts that are each on a different node
416
+ Input: local_name2valcount: dict mapping key -> (value, count)
417
+ Returns: key -> mean
418
+ """
419
+ all_name2valcount = comm.gather(local_name2valcount)
420
+ if comm.rank == 0:
421
+ name2sum = defaultdict(float)
422
+ name2count = defaultdict(float)
423
+ for n2vc in all_name2valcount:
424
+ for (name, (val, count)) in n2vc.items():
425
+ try:
426
+ val = float(val)
427
+ except ValueError:
428
+ if comm.rank == 0:
429
+ warnings.warn(
430
+ "WARNING: tried to compute mean on non-float {}={}".format(
431
+ name, val
432
+ )
433
+ )
434
+ else:
435
+ name2sum[name] += val * count
436
+ name2count[name] += count
437
+ return {name: name2sum[name] / name2count[name] for name in name2sum}
438
+ else:
439
+ return {}
440
+
441
+
442
+ def configure(dir=None, format_strs=None, comm=None, log_suffix=""):
443
+ """
444
+ If comm is provided, average all numerical stats across that comm
445
+ """
446
+ if dir is None:
447
+ dir = os.getenv("OPENAI_LOGDIR")
448
+ if dir is None:
449
+ dir = osp.join(
450
+ tempfile.gettempdir(),
451
+ datetime.datetime.now().strftime("openai-%Y-%m-%d-%H-%M-%S-%f"),
452
+ )
453
+ assert isinstance(dir, str)
454
+ dir = os.path.expanduser(dir)
455
+ os.makedirs(os.path.expanduser(dir), exist_ok=True)
456
+
457
+ rank = get_rank_without_mpi_import()
458
+ if rank > 0:
459
+ log_suffix = log_suffix + "-rank%03i" % rank
460
+
461
+ if format_strs is None:
462
+ if rank == 0:
463
+ format_strs = os.getenv("OPENAI_LOG_FORMAT", "stdout,log,csv").split(",")
464
+ else:
465
+ format_strs = os.getenv("OPENAI_LOG_FORMAT_MPI", "log").split(",")
466
+ format_strs = filter(None, format_strs)
467
+ output_formats = [make_output_format(f, dir, log_suffix) for f in format_strs]
468
+
469
+ Logger.CURRENT = Logger(dir=dir, output_formats=output_formats, comm=comm)
470
+ if output_formats:
471
+ log("Logging to %s" % dir)
472
+
473
+
474
+ def _configure_default_logger():
475
+ configure()
476
+ Logger.DEFAULT = Logger.CURRENT
477
+
478
+
479
+ def reset():
480
+ if Logger.CURRENT is not Logger.DEFAULT:
481
+ Logger.CURRENT.close()
482
+ Logger.CURRENT = Logger.DEFAULT
483
+ log("Reset logger")
484
+
485
+
486
+ @contextmanager
487
+ def scoped_configure(dir=None, format_strs=None, comm=None):
488
+ prevlogger = Logger.CURRENT
489
+ configure(dir=dir, format_strs=format_strs, comm=comm)
490
+ try:
491
+ yield
492
+ finally:
493
+ Logger.CURRENT.close()
494
+ Logger.CURRENT = prevlogger
495
+
editing_diffusion/guided_diffusion/guided_diffusion/losses.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helpers for various likelihood-based losses. These are ported from the original
3
+ Ho et al. diffusion models codebase:
4
+ https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/utils.py
5
+ """
6
+
7
+ import numpy as np
8
+
9
+ import torch as th
10
+
11
+
12
+ def normal_kl(mean1, logvar1, mean2, logvar2):
13
+ """
14
+ Compute the KL divergence between two gaussians.
15
+
16
+ Shapes are automatically broadcasted, so batches can be compared to
17
+ scalars, among other use cases.
18
+ """
19
+ tensor = None
20
+ for obj in (mean1, logvar1, mean2, logvar2):
21
+ if isinstance(obj, th.Tensor):
22
+ tensor = obj
23
+ break
24
+ assert tensor is not None, "at least one argument must be a Tensor"
25
+
26
+ # Force variances to be Tensors. Broadcasting helps convert scalars to
27
+ # Tensors, but it does not work for th.exp().
28
+ logvar1, logvar2 = [
29
+ x if isinstance(x, th.Tensor) else th.tensor(x).to(tensor)
30
+ for x in (logvar1, logvar2)
31
+ ]
32
+
33
+ return 0.5 * (
34
+ -1.0
35
+ + logvar2
36
+ - logvar1
37
+ + th.exp(logvar1 - logvar2)
38
+ + ((mean1 - mean2) ** 2) * th.exp(-logvar2)
39
+ )
40
+
41
+
42
+ def approx_standard_normal_cdf(x):
43
+ """
44
+ A fast approximation of the cumulative distribution function of the
45
+ standard normal.
46
+ """
47
+ return 0.5 * (1.0 + th.tanh(np.sqrt(2.0 / np.pi) * (x + 0.044715 * th.pow(x, 3))))
48
+
49
+
50
+ def discretized_gaussian_log_likelihood(x, *, means, log_scales):
51
+ """
52
+ Compute the log-likelihood of a Gaussian distribution discretizing to a
53
+ given image.
54
+
55
+ :param x: the target images. It is assumed that this was uint8 values,
56
+ rescaled to the range [-1, 1].
57
+ :param means: the Gaussian mean Tensor.
58
+ :param log_scales: the Gaussian log stddev Tensor.
59
+ :return: a tensor like x of log probabilities (in nats).
60
+ """
61
+ assert x.shape == means.shape == log_scales.shape
62
+ centered_x = x - means
63
+ inv_stdv = th.exp(-log_scales)
64
+ plus_in = inv_stdv * (centered_x + 1.0 / 255.0)
65
+ cdf_plus = approx_standard_normal_cdf(plus_in)
66
+ min_in = inv_stdv * (centered_x - 1.0 / 255.0)
67
+ cdf_min = approx_standard_normal_cdf(min_in)
68
+ log_cdf_plus = th.log(cdf_plus.clamp(min=1e-12))
69
+ log_one_minus_cdf_min = th.log((1.0 - cdf_min).clamp(min=1e-12))
70
+ cdf_delta = cdf_plus - cdf_min
71
+ log_probs = th.where(
72
+ x < -0.999,
73
+ log_cdf_plus,
74
+ th.where(x > 0.999, log_one_minus_cdf_min, th.log(cdf_delta.clamp(min=1e-12))),
75
+ )
76
+ assert log_probs.shape == x.shape
77
+ return log_probs
editing_diffusion/guided_diffusion/guided_diffusion/nn.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Various utilities for neural networks.
3
+ """
4
+
5
+ import math
6
+
7
+ import torch as th
8
+ import torch.nn as nn
9
+
10
+
11
+ # PyTorch 1.7 has SiLU, but we support PyTorch 1.5.
12
+ class SiLU(nn.Module):
13
+ def forward(self, x):
14
+ return x * th.sigmoid(x)
15
+
16
+
17
+ class GroupNorm32(nn.GroupNorm):
18
+ def forward(self, x):
19
+ return super().forward(x.float()).type(x.dtype)
20
+
21
+
22
+ def conv_nd(dims, *args, **kwargs):
23
+ """
24
+ Create a 1D, 2D, or 3D convolution module.
25
+ """
26
+ if dims == 1:
27
+ return nn.Conv1d(*args, **kwargs)
28
+ elif dims == 2:
29
+ return nn.Conv2d(*args, **kwargs)
30
+ elif dims == 3:
31
+ return nn.Conv3d(*args, **kwargs)
32
+ raise ValueError(f"unsupported dimensions: {dims}")
33
+
34
+
35
+ def linear(*args, **kwargs):
36
+ """
37
+ Create a linear module.
38
+ """
39
+ return nn.Linear(*args, **kwargs)
40
+
41
+
42
+ def avg_pool_nd(dims, *args, **kwargs):
43
+ """
44
+ Create a 1D, 2D, or 3D average pooling module.
45
+ """
46
+ if dims == 1:
47
+ return nn.AvgPool1d(*args, **kwargs)
48
+ elif dims == 2:
49
+ return nn.AvgPool2d(*args, **kwargs)
50
+ elif dims == 3:
51
+ return nn.AvgPool3d(*args, **kwargs)
52
+ raise ValueError(f"unsupported dimensions: {dims}")
53
+
54
+
55
+ def update_ema(target_params, source_params, rate=0.99):
56
+ """
57
+ Update target parameters to be closer to those of source parameters using
58
+ an exponential moving average.
59
+
60
+ :param target_params: the target parameter sequence.
61
+ :param source_params: the source parameter sequence.
62
+ :param rate: the EMA rate (closer to 1 means slower).
63
+ """
64
+ for targ, src in zip(target_params, source_params):
65
+ targ.detach().mul_(rate).add_(src, alpha=1 - rate)
66
+
67
+
68
+ def zero_module(module):
69
+ """
70
+ Zero out the parameters of a module and return it.
71
+ """
72
+ for p in module.parameters():
73
+ p.detach().zero_()
74
+ return module
75
+
76
+
77
+ def scale_module(module, scale):
78
+ """
79
+ Scale the parameters of a module and return it.
80
+ """
81
+ for p in module.parameters():
82
+ p.detach().mul_(scale)
83
+ return module
84
+
85
+
86
+ def mean_flat(tensor):
87
+ """
88
+ Take the mean over all non-batch dimensions.
89
+ """
90
+ return tensor.mean(dim=list(range(1, len(tensor.shape))))
91
+
92
+
93
+ def normalization(channels):
94
+ """
95
+ Make a standard normalization layer.
96
+
97
+ :param channels: number of input channels.
98
+ :return: an nn.Module for normalization.
99
+ """
100
+ return GroupNorm32(32, channels)
101
+
102
+
103
+ def timestep_embedding(timesteps, dim, max_period=10000):
104
+ """
105
+ Create sinusoidal timestep embeddings.
106
+
107
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
108
+ These may be fractional.
109
+ :param dim: the dimension of the output.
110
+ :param max_period: controls the minimum frequency of the embeddings.
111
+ :return: an [N x dim] Tensor of positional embeddings.
112
+ """
113
+ half = dim // 2
114
+ freqs = th.exp(
115
+ -math.log(max_period) * th.arange(start=0, end=half, dtype=th.float32) / half
116
+ ).to(device=timesteps.device)
117
+ args = timesteps[:, None].float() * freqs[None]
118
+ embedding = th.cat([th.cos(args), th.sin(args)], dim=-1)
119
+ if dim % 2:
120
+ embedding = th.cat([embedding, th.zeros_like(embedding[:, :1])], dim=-1)
121
+ return embedding
122
+
123
+
124
+ def checkpoint(func, inputs, params, flag):
125
+ """
126
+ Evaluate a function without caching intermediate activations, allowing for
127
+ reduced memory at the expense of extra compute in the backward pass.
128
+
129
+ :param func: the function to evaluate.
130
+ :param inputs: the argument sequence to pass to `func`.
131
+ :param params: a sequence of parameters `func` depends on but does not
132
+ explicitly take as arguments.
133
+ :param flag: if False, disable gradient checkpointing.
134
+ """
135
+ if flag:
136
+ args = tuple(inputs) + tuple(params)
137
+ return CheckpointFunction.apply(func, len(inputs), *args)
138
+ else:
139
+ return func(*inputs)
140
+
141
+
142
+ class CheckpointFunction(th.autograd.Function):
143
+ @staticmethod
144
+ def forward(ctx, run_function, length, *args):
145
+ ctx.run_function = run_function
146
+ ctx.input_tensors = list(args[:length])
147
+ ctx.input_params = list(args[length:])
148
+ with th.no_grad():
149
+ output_tensors = ctx.run_function(*ctx.input_tensors)
150
+ return output_tensors
151
+
152
+ @staticmethod
153
+ def backward(ctx, *output_grads):
154
+ ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
155
+ with th.enable_grad():
156
+ # Fixes a bug where the first op in run_function modifies the
157
+ # Tensor storage in place, which is not allowed for detach()'d
158
+ # Tensors.
159
+ shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
160
+ output_tensors = ctx.run_function(*shallow_copies)
161
+ input_grads = th.autograd.grad(
162
+ output_tensors,
163
+ ctx.input_tensors + ctx.input_params,
164
+ output_grads,
165
+ allow_unused=True,
166
+ )
167
+ del ctx.input_tensors
168
+ del ctx.input_params
169
+ del output_tensors
170
+ return (None, None) + input_grads
editing_diffusion/guided_diffusion/guided_diffusion/resample.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+
3
+ import numpy as np
4
+ import torch as th
5
+ import torch.distributed as dist
6
+
7
+
8
+ def create_named_schedule_sampler(name, diffusion):
9
+ """
10
+ Create a ScheduleSampler from a library of pre-defined samplers.
11
+
12
+ :param name: the name of the sampler.
13
+ :param diffusion: the diffusion object to sample for.
14
+ """
15
+ if name == "uniform":
16
+ return UniformSampler(diffusion)
17
+ elif name == "loss-second-moment":
18
+ return LossSecondMomentResampler(diffusion)
19
+ else:
20
+ raise NotImplementedError(f"unknown schedule sampler: {name}")
21
+
22
+
23
+ class ScheduleSampler(ABC):
24
+ """
25
+ A distribution over timesteps in the diffusion process, intended to reduce
26
+ variance of the objective.
27
+
28
+ By default, samplers perform unbiased importance sampling, in which the
29
+ objective's mean is unchanged.
30
+ However, subclasses may override sample() to change how the resampled
31
+ terms are reweighted, allowing for actual changes in the objective.
32
+ """
33
+
34
+ @abstractmethod
35
+ def weights(self):
36
+ """
37
+ Get a numpy array of weights, one per diffusion step.
38
+
39
+ The weights needn't be normalized, but must be positive.
40
+ """
41
+
42
+ def sample(self, batch_size, device):
43
+ """
44
+ Importance-sample timesteps for a batch.
45
+
46
+ :param batch_size: the number of timesteps.
47
+ :param device: the torch device to save to.
48
+ :return: a tuple (timesteps, weights):
49
+ - timesteps: a tensor of timestep indices.
50
+ - weights: a tensor of weights to scale the resulting losses.
51
+ """
52
+ w = self.weights()
53
+ p = w / np.sum(w)
54
+ indices_np = np.random.choice(len(p), size=(batch_size,), p=p)
55
+ indices = th.from_numpy(indices_np).long().to(device)
56
+ weights_np = 1 / (len(p) * p[indices_np])
57
+ weights = th.from_numpy(weights_np).float().to(device)
58
+ return indices, weights
59
+
60
+
61
+ class UniformSampler(ScheduleSampler):
62
+ def __init__(self, diffusion):
63
+ self.diffusion = diffusion
64
+ self._weights = np.ones([diffusion.num_timesteps])
65
+
66
+ def weights(self):
67
+ return self._weights
68
+
69
+
70
+ class LossAwareSampler(ScheduleSampler):
71
+ def update_with_local_losses(self, local_ts, local_losses):
72
+ """
73
+ Update the reweighting using losses from a model.
74
+
75
+ Call this method from each rank with a batch of timesteps and the
76
+ corresponding losses for each of those timesteps.
77
+ This method will perform synchronization to make sure all of the ranks
78
+ maintain the exact same reweighting.
79
+
80
+ :param local_ts: an integer Tensor of timesteps.
81
+ :param local_losses: a 1D Tensor of losses.
82
+ """
83
+ batch_sizes = [
84
+ th.tensor([0], dtype=th.int32, device=local_ts.device)
85
+ for _ in range(dist.get_world_size())
86
+ ]
87
+ dist.all_gather(
88
+ batch_sizes,
89
+ th.tensor([len(local_ts)], dtype=th.int32, device=local_ts.device),
90
+ )
91
+
92
+ # Pad all_gather batches to be the maximum batch size.
93
+ batch_sizes = [x.item() for x in batch_sizes]
94
+ max_bs = max(batch_sizes)
95
+
96
+ timestep_batches = [th.zeros(max_bs).to(local_ts) for bs in batch_sizes]
97
+ loss_batches = [th.zeros(max_bs).to(local_losses) for bs in batch_sizes]
98
+ dist.all_gather(timestep_batches, local_ts)
99
+ dist.all_gather(loss_batches, local_losses)
100
+ timesteps = [
101
+ x.item() for y, bs in zip(timestep_batches, batch_sizes) for x in y[:bs]
102
+ ]
103
+ losses = [x.item() for y, bs in zip(loss_batches, batch_sizes) for x in y[:bs]]
104
+ self.update_with_all_losses(timesteps, losses)
105
+
106
+ @abstractmethod
107
+ def update_with_all_losses(self, ts, losses):
108
+ """
109
+ Update the reweighting using losses from a model.
110
+
111
+ Sub-classes should override this method to update the reweighting
112
+ using losses from the model.
113
+
114
+ This method directly updates the reweighting without synchronizing
115
+ between workers. It is called by update_with_local_losses from all
116
+ ranks with identical arguments. Thus, it should have deterministic
117
+ behavior to maintain state across workers.
118
+
119
+ :param ts: a list of int timesteps.
120
+ :param losses: a list of float losses, one per timestep.
121
+ """
122
+
123
+
124
+ class LossSecondMomentResampler(LossAwareSampler):
125
+ def __init__(self, diffusion, history_per_term=10, uniform_prob=0.001):
126
+ self.diffusion = diffusion
127
+ self.history_per_term = history_per_term
128
+ self.uniform_prob = uniform_prob
129
+ self._loss_history = np.zeros(
130
+ [diffusion.num_timesteps, history_per_term], dtype=np.float64
131
+ )
132
+ self._loss_counts = np.zeros([diffusion.num_timesteps], dtype=np.int)
133
+
134
+ def weights(self):
135
+ if not self._warmed_up():
136
+ return np.ones([self.diffusion.num_timesteps], dtype=np.float64)
137
+ weights = np.sqrt(np.mean(self._loss_history ** 2, axis=-1))
138
+ weights /= np.sum(weights)
139
+ weights *= 1 - self.uniform_prob
140
+ weights += self.uniform_prob / len(weights)
141
+ return weights
142
+
143
+ def update_with_all_losses(self, ts, losses):
144
+ for t, loss in zip(ts, losses):
145
+ if self._loss_counts[t] == self.history_per_term:
146
+ # Shift out the oldest loss term.
147
+ self._loss_history[t, :-1] = self._loss_history[t, 1:]
148
+ self._loss_history[t, -1] = loss
149
+ else:
150
+ self._loss_history[t, self._loss_counts[t]] = loss
151
+ self._loss_counts[t] += 1
152
+
153
+ def _warmed_up(self):
154
+ return (self._loss_counts == self.history_per_term).all()
editing_diffusion/guided_diffusion/guided_diffusion/respace.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch as th
3
+
4
+ from .gaussian_diffusion import GaussianDiffusion
5
+
6
+
7
+ def space_timesteps(num_timesteps, section_counts):
8
+ """
9
+ Create a list of timesteps to use from an original diffusion process,
10
+ given the number of timesteps we want to take from equally-sized portions
11
+ of the original process.
12
+
13
+ For example, if there's 300 timesteps and the section counts are [10,15,20]
14
+ then the first 100 timesteps are strided to be 10 timesteps, the second 100
15
+ are strided to be 15 timesteps, and the final 100 are strided to be 20.
16
+
17
+ If the stride is a string starting with "ddim", then the fixed striding
18
+ from the DDIM paper is used, and only one section is allowed.
19
+
20
+ :param num_timesteps: the number of diffusion steps in the original
21
+ process to divide up.
22
+ :param section_counts: either a list of numbers, or a string containing
23
+ comma-separated numbers, indicating the step count
24
+ per section. As a special case, use "ddimN" where N
25
+ is a number of steps to use the striding from the
26
+ DDIM paper.
27
+ :return: a set of diffusion steps from the original process to use.
28
+ """
29
+ if isinstance(section_counts, str):
30
+ if section_counts.startswith("ddim"):
31
+ desired_count = int(section_counts[len("ddim") :])
32
+ for i in range(1, num_timesteps):
33
+ if len(range(0, num_timesteps, i)) == desired_count:
34
+ return set(range(0, num_timesteps, i))
35
+ raise ValueError(
36
+ f"cannot create exactly {num_timesteps} steps with an integer stride"
37
+ )
38
+ section_counts = [int(x) for x in section_counts.split(",")]
39
+ size_per = num_timesteps // len(section_counts)
40
+ extra = num_timesteps % len(section_counts)
41
+ start_idx = 0
42
+ all_steps = []
43
+ for i, section_count in enumerate(section_counts):
44
+ size = size_per + (1 if i < extra else 0)
45
+ if size < section_count:
46
+ raise ValueError(
47
+ f"cannot divide section of {size} steps into {section_count}"
48
+ )
49
+ if section_count <= 1:
50
+ frac_stride = 1
51
+ else:
52
+ frac_stride = (size - 1) / (section_count - 1)
53
+ cur_idx = 0.0
54
+ taken_steps = []
55
+ for _ in range(section_count):
56
+ taken_steps.append(start_idx + round(cur_idx))
57
+ cur_idx += frac_stride
58
+ all_steps += taken_steps
59
+ start_idx += size
60
+ return set(all_steps)
61
+
62
+
63
+ class SpacedDiffusion(GaussianDiffusion):
64
+ """
65
+ A diffusion process which can skip steps in a base diffusion process.
66
+
67
+ :param use_timesteps: a collection (sequence or set) of timesteps from the
68
+ original diffusion process to retain.
69
+ :param kwargs: the kwargs to create the base diffusion process.
70
+ """
71
+
72
+ def __init__(self, use_timesteps, **kwargs):
73
+ self.use_timesteps = set(use_timesteps)
74
+ self.timestep_map = []
75
+ self.original_num_steps = len(kwargs["betas"])
76
+
77
+ base_diffusion = GaussianDiffusion(**kwargs) # pylint: disable=missing-kwoa
78
+ last_alpha_cumprod = 1.0
79
+ new_betas = []
80
+ for i, alpha_cumprod in enumerate(base_diffusion.alphas_cumprod):
81
+ if i in self.use_timesteps:
82
+ new_betas.append(1 - alpha_cumprod / last_alpha_cumprod)
83
+ last_alpha_cumprod = alpha_cumprod
84
+ self.timestep_map.append(i)
85
+ kwargs["betas"] = np.array(new_betas)
86
+ super().__init__(**kwargs)
87
+
88
+ def p_mean_variance(
89
+ self, model, *args, **kwargs
90
+ ): # pylint: disable=signature-differs
91
+ return super().p_mean_variance(self._wrap_model(model), *args, **kwargs)
92
+
93
+ def training_losses(
94
+ self, model, *args, **kwargs
95
+ ): # pylint: disable=signature-differs
96
+ return super().training_losses(self._wrap_model(model), *args, **kwargs)
97
+
98
+ def condition_mean(self, cond_fn, *args, **kwargs):
99
+ return super().condition_mean(self._wrap_model(cond_fn), *args, **kwargs)
100
+
101
+ def condition_score(self, cond_fn, *args, **kwargs):
102
+ return super().condition_score(self._wrap_model(cond_fn), *args, **kwargs)
103
+
104
+ def _wrap_model(self, model):
105
+ if isinstance(model, _WrappedModel):
106
+ return model
107
+ return _WrappedModel(
108
+ model, self.timestep_map, self.rescale_timesteps, self.original_num_steps
109
+ )
110
+
111
+ def _scale_timesteps(self, t):
112
+ # Scaling is done by the wrapped model.
113
+ return t
114
+
115
+
116
+ class _WrappedModel:
117
+ def __init__(self, model, timestep_map, rescale_timesteps, original_num_steps):
118
+ self.model = model
119
+ self.timestep_map = timestep_map
120
+ self.rescale_timesteps = rescale_timesteps
121
+ self.original_num_steps = original_num_steps
122
+
123
+ def __call__(self, x, ts, **kwargs):
124
+ map_tensor = th.tensor(self.timestep_map, device=ts.device, dtype=ts.dtype)
125
+ new_ts = map_tensor[ts]
126
+ if self.rescale_timesteps:
127
+ new_ts = new_ts.float() * (1000.0 / self.original_num_steps)
128
+ return self.model(x, new_ts, **kwargs)
editing_diffusion/guided_diffusion/guided_diffusion/script_util.py ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import inspect
3
+
4
+ from . import gaussian_diffusion as gd
5
+ from .respace import SpacedDiffusion, space_timesteps
6
+ from .unet import SuperResModel, UNetModel, EncoderUNetModel
7
+
8
+ NUM_CLASSES = 1000
9
+
10
+
11
+ def diffusion_defaults():
12
+ """
13
+ Defaults for image and classifier training.
14
+ """
15
+ return dict(
16
+ learn_sigma=False,
17
+ diffusion_steps=1000,
18
+ noise_schedule="linear",
19
+ timestep_respacing="",
20
+ use_kl=False,
21
+ predict_xstart=False,
22
+ rescale_timesteps=False,
23
+ rescale_learned_sigmas=False,
24
+ )
25
+
26
+
27
+ def classifier_defaults():
28
+ """
29
+ Defaults for classifier models.
30
+ """
31
+ return dict(
32
+ image_size=64,
33
+ classifier_use_fp16=False,
34
+ classifier_width=128,
35
+ classifier_depth=2,
36
+ classifier_attention_resolutions="32,16,8", # 16
37
+ classifier_use_scale_shift_norm=True, # False
38
+ classifier_resblock_updown=True, # False
39
+ classifier_pool="attention",
40
+ )
41
+
42
+
43
+ def model_and_diffusion_defaults():
44
+ """
45
+ Defaults for image training.
46
+ """
47
+ res = dict(
48
+ image_size=64,
49
+ num_channels=128,
50
+ num_res_blocks=2,
51
+ num_heads=4,
52
+ num_heads_upsample=-1,
53
+ num_head_channels=-1,
54
+ attention_resolutions="16,8",
55
+ channel_mult="",
56
+ dropout=0.0,
57
+ class_cond=False,
58
+ use_checkpoint=False,
59
+ use_scale_shift_norm=True,
60
+ resblock_updown=False,
61
+ use_fp16=False,
62
+ use_new_attention_order=False,
63
+ )
64
+ res.update(diffusion_defaults())
65
+ return res
66
+
67
+
68
+ def classifier_and_diffusion_defaults():
69
+ res = classifier_defaults()
70
+ res.update(diffusion_defaults())
71
+ return res
72
+
73
+
74
+ def create_model_and_diffusion(
75
+ image_size,
76
+ class_cond,
77
+ learn_sigma,
78
+ num_channels,
79
+ num_res_blocks,
80
+ channel_mult,
81
+ num_heads,
82
+ num_head_channels,
83
+ num_heads_upsample,
84
+ attention_resolutions,
85
+ dropout,
86
+ diffusion_steps,
87
+ noise_schedule,
88
+ timestep_respacing,
89
+ use_kl,
90
+ predict_xstart,
91
+ rescale_timesteps,
92
+ rescale_learned_sigmas,
93
+ use_checkpoint,
94
+ use_scale_shift_norm,
95
+ resblock_updown,
96
+ use_fp16,
97
+ use_new_attention_order,
98
+ ):
99
+ model = create_model(
100
+ image_size,
101
+ num_channels,
102
+ num_res_blocks,
103
+ channel_mult=channel_mult,
104
+ learn_sigma=learn_sigma,
105
+ class_cond=class_cond,
106
+ use_checkpoint=use_checkpoint,
107
+ attention_resolutions=attention_resolutions,
108
+ num_heads=num_heads,
109
+ num_head_channels=num_head_channels,
110
+ num_heads_upsample=num_heads_upsample,
111
+ use_scale_shift_norm=use_scale_shift_norm,
112
+ dropout=dropout,
113
+ resblock_updown=resblock_updown,
114
+ use_fp16=use_fp16,
115
+ use_new_attention_order=use_new_attention_order,
116
+ )
117
+ diffusion = create_gaussian_diffusion(
118
+ steps=diffusion_steps,
119
+ learn_sigma=learn_sigma,
120
+ noise_schedule=noise_schedule,
121
+ use_kl=use_kl,
122
+ predict_xstart=predict_xstart,
123
+ rescale_timesteps=rescale_timesteps,
124
+ rescale_learned_sigmas=rescale_learned_sigmas,
125
+ timestep_respacing=timestep_respacing,
126
+ )
127
+ return model, diffusion
128
+
129
+
130
+ def create_model(
131
+ image_size,
132
+ num_channels,
133
+ num_res_blocks,
134
+ channel_mult="",
135
+ learn_sigma=False,
136
+ class_cond=False,
137
+ use_checkpoint=False,
138
+ attention_resolutions="16",
139
+ num_heads=1,
140
+ num_head_channels=-1,
141
+ num_heads_upsample=-1,
142
+ use_scale_shift_norm=False,
143
+ dropout=0,
144
+ resblock_updown=False,
145
+ use_fp16=False,
146
+ use_new_attention_order=False,
147
+ ):
148
+ if channel_mult == "":
149
+ if image_size == 512:
150
+ channel_mult = (0.5, 1, 1, 2, 2, 4, 4)
151
+ elif image_size == 256:
152
+ channel_mult = (1, 1, 2, 2, 4, 4)
153
+ elif image_size == 128:
154
+ channel_mult = (1, 1, 2, 3, 4)
155
+ elif image_size == 64:
156
+ channel_mult = (1, 2, 3, 4)
157
+ else:
158
+ raise ValueError(f"unsupported image size: {image_size}")
159
+ else:
160
+ channel_mult = tuple(int(ch_mult) for ch_mult in channel_mult.split(","))
161
+
162
+ attention_ds = []
163
+ for res in attention_resolutions.split(","):
164
+ attention_ds.append(image_size // int(res))
165
+
166
+ return UNetModel(
167
+ image_size=image_size,
168
+ in_channels=3,
169
+ model_channels=num_channels,
170
+ out_channels=(3 if not learn_sigma else 6),
171
+ num_res_blocks=num_res_blocks,
172
+ attention_resolutions=tuple(attention_ds),
173
+ dropout=dropout,
174
+ channel_mult=channel_mult,
175
+ num_classes=(NUM_CLASSES if class_cond else None),
176
+ use_checkpoint=use_checkpoint,
177
+ use_fp16=use_fp16,
178
+ num_heads=num_heads,
179
+ num_head_channels=num_head_channels,
180
+ num_heads_upsample=num_heads_upsample,
181
+ use_scale_shift_norm=use_scale_shift_norm,
182
+ resblock_updown=resblock_updown,
183
+ use_new_attention_order=use_new_attention_order,
184
+ )
185
+
186
+
187
+ def create_classifier_and_diffusion(
188
+ image_size,
189
+ classifier_use_fp16,
190
+ classifier_width,
191
+ classifier_depth,
192
+ classifier_attention_resolutions,
193
+ classifier_use_scale_shift_norm,
194
+ classifier_resblock_updown,
195
+ classifier_pool,
196
+ learn_sigma,
197
+ diffusion_steps,
198
+ noise_schedule,
199
+ timestep_respacing,
200
+ use_kl,
201
+ predict_xstart,
202
+ rescale_timesteps,
203
+ rescale_learned_sigmas,
204
+ ):
205
+ classifier = create_classifier(
206
+ image_size,
207
+ classifier_use_fp16,
208
+ classifier_width,
209
+ classifier_depth,
210
+ classifier_attention_resolutions,
211
+ classifier_use_scale_shift_norm,
212
+ classifier_resblock_updown,
213
+ classifier_pool,
214
+ )
215
+ diffusion = create_gaussian_diffusion(
216
+ steps=diffusion_steps,
217
+ learn_sigma=learn_sigma,
218
+ noise_schedule=noise_schedule,
219
+ use_kl=use_kl,
220
+ predict_xstart=predict_xstart,
221
+ rescale_timesteps=rescale_timesteps,
222
+ rescale_learned_sigmas=rescale_learned_sigmas,
223
+ timestep_respacing=timestep_respacing,
224
+ )
225
+ return classifier, diffusion
226
+
227
+
228
+ def create_classifier(
229
+ image_size,
230
+ classifier_use_fp16,
231
+ classifier_width,
232
+ classifier_depth,
233
+ classifier_attention_resolutions,
234
+ classifier_use_scale_shift_norm,
235
+ classifier_resblock_updown,
236
+ classifier_pool,
237
+ ):
238
+ if image_size == 512:
239
+ channel_mult = (0.5, 1, 1, 2, 2, 4, 4)
240
+ elif image_size == 256:
241
+ channel_mult = (1, 1, 2, 2, 4, 4)
242
+ elif image_size == 128:
243
+ channel_mult = (1, 1, 2, 3, 4)
244
+ elif image_size == 64:
245
+ channel_mult = (1, 2, 3, 4)
246
+ else:
247
+ raise ValueError(f"unsupported image size: {image_size}")
248
+
249
+ attention_ds = []
250
+ for res in classifier_attention_resolutions.split(","):
251
+ attention_ds.append(image_size // int(res))
252
+
253
+ return EncoderUNetModel(
254
+ image_size=image_size,
255
+ in_channels=3,
256
+ model_channels=classifier_width,
257
+ out_channels=1000,
258
+ num_res_blocks=classifier_depth,
259
+ attention_resolutions=tuple(attention_ds),
260
+ channel_mult=channel_mult,
261
+ use_fp16=classifier_use_fp16,
262
+ num_head_channels=64,
263
+ use_scale_shift_norm=classifier_use_scale_shift_norm,
264
+ resblock_updown=classifier_resblock_updown,
265
+ pool=classifier_pool,
266
+ )
267
+
268
+
269
+ def sr_model_and_diffusion_defaults():
270
+ res = model_and_diffusion_defaults()
271
+ res["large_size"] = 256
272
+ res["small_size"] = 64
273
+ arg_names = inspect.getfullargspec(sr_create_model_and_diffusion)[0]
274
+ for k in res.copy().keys():
275
+ if k not in arg_names:
276
+ del res[k]
277
+ return res
278
+
279
+
280
+ def sr_create_model_and_diffusion(
281
+ large_size,
282
+ small_size,
283
+ class_cond,
284
+ learn_sigma,
285
+ num_channels,
286
+ num_res_blocks,
287
+ num_heads,
288
+ num_head_channels,
289
+ num_heads_upsample,
290
+ attention_resolutions,
291
+ dropout,
292
+ diffusion_steps,
293
+ noise_schedule,
294
+ timestep_respacing,
295
+ use_kl,
296
+ predict_xstart,
297
+ rescale_timesteps,
298
+ rescale_learned_sigmas,
299
+ use_checkpoint,
300
+ use_scale_shift_norm,
301
+ resblock_updown,
302
+ use_fp16,
303
+ ):
304
+ model = sr_create_model(
305
+ large_size,
306
+ small_size,
307
+ num_channels,
308
+ num_res_blocks,
309
+ learn_sigma=learn_sigma,
310
+ class_cond=class_cond,
311
+ use_checkpoint=use_checkpoint,
312
+ attention_resolutions=attention_resolutions,
313
+ num_heads=num_heads,
314
+ num_head_channels=num_head_channels,
315
+ num_heads_upsample=num_heads_upsample,
316
+ use_scale_shift_norm=use_scale_shift_norm,
317
+ dropout=dropout,
318
+ resblock_updown=resblock_updown,
319
+ use_fp16=use_fp16,
320
+ )
321
+ diffusion = create_gaussian_diffusion(
322
+ steps=diffusion_steps,
323
+ learn_sigma=learn_sigma,
324
+ noise_schedule=noise_schedule,
325
+ use_kl=use_kl,
326
+ predict_xstart=predict_xstart,
327
+ rescale_timesteps=rescale_timesteps,
328
+ rescale_learned_sigmas=rescale_learned_sigmas,
329
+ timestep_respacing=timestep_respacing,
330
+ )
331
+ return model, diffusion
332
+
333
+
334
+ def sr_create_model(
335
+ large_size,
336
+ small_size,
337
+ num_channels,
338
+ num_res_blocks,
339
+ learn_sigma,
340
+ class_cond,
341
+ use_checkpoint,
342
+ attention_resolutions,
343
+ num_heads,
344
+ num_head_channels,
345
+ num_heads_upsample,
346
+ use_scale_shift_norm,
347
+ dropout,
348
+ resblock_updown,
349
+ use_fp16,
350
+ ):
351
+ _ = small_size # hack to prevent unused variable
352
+
353
+ if large_size == 512:
354
+ channel_mult = (1, 1, 2, 2, 4, 4)
355
+ elif large_size == 256:
356
+ channel_mult = (1, 1, 2, 2, 4, 4)
357
+ elif large_size == 64:
358
+ channel_mult = (1, 2, 3, 4)
359
+ else:
360
+ raise ValueError(f"unsupported large size: {large_size}")
361
+
362
+ attention_ds = []
363
+ for res in attention_resolutions.split(","):
364
+ attention_ds.append(large_size // int(res))
365
+
366
+ return SuperResModel(
367
+ image_size=large_size,
368
+ in_channels=3,
369
+ model_channels=num_channels,
370
+ out_channels=(3 if not learn_sigma else 6),
371
+ num_res_blocks=num_res_blocks,
372
+ attention_resolutions=tuple(attention_ds),
373
+ dropout=dropout,
374
+ channel_mult=channel_mult,
375
+ num_classes=(NUM_CLASSES if class_cond else None),
376
+ use_checkpoint=use_checkpoint,
377
+ num_heads=num_heads,
378
+ num_head_channels=num_head_channels,
379
+ num_heads_upsample=num_heads_upsample,
380
+ use_scale_shift_norm=use_scale_shift_norm,
381
+ resblock_updown=resblock_updown,
382
+ use_fp16=use_fp16,
383
+ )
384
+
385
+
386
+ def create_gaussian_diffusion(
387
+ *,
388
+ steps=1000,
389
+ learn_sigma=False,
390
+ sigma_small=False,
391
+ noise_schedule="linear",
392
+ use_kl=False,
393
+ predict_xstart=False,
394
+ rescale_timesteps=False,
395
+ rescale_learned_sigmas=False,
396
+ timestep_respacing="",
397
+ ):
398
+ betas = gd.get_named_beta_schedule(noise_schedule, steps)
399
+ if use_kl:
400
+ loss_type = gd.LossType.RESCALED_KL
401
+ elif rescale_learned_sigmas:
402
+ loss_type = gd.LossType.RESCALED_MSE
403
+ else:
404
+ loss_type = gd.LossType.MSE
405
+ if not timestep_respacing:
406
+ timestep_respacing = [steps]
407
+ return SpacedDiffusion(
408
+ use_timesteps=space_timesteps(steps, timestep_respacing),
409
+ betas=betas,
410
+ model_mean_type=(
411
+ gd.ModelMeanType.EPSILON if not predict_xstart else gd.ModelMeanType.START_X
412
+ ),
413
+ model_var_type=(
414
+ (
415
+ gd.ModelVarType.FIXED_LARGE
416
+ if not sigma_small
417
+ else gd.ModelVarType.FIXED_SMALL
418
+ )
419
+ if not learn_sigma
420
+ else gd.ModelVarType.LEARNED_RANGE
421
+ ),
422
+ loss_type=loss_type,
423
+ rescale_timesteps=rescale_timesteps,
424
+ )
425
+
426
+
427
+ def add_dict_to_argparser(parser, default_dict):
428
+ for k, v in default_dict.items():
429
+ v_type = type(v)
430
+ if v is None:
431
+ v_type = str
432
+ elif isinstance(v, bool):
433
+ v_type = str2bool
434
+ parser.add_argument(f"--{k}", default=v, type=v_type)
435
+
436
+
437
+ def args_to_dict(args, keys):
438
+ return {k: getattr(args, k) for k in keys}
439
+
440
+
441
+ def str2bool(v):
442
+ """
443
+ https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse
444
+ """
445
+ if isinstance(v, bool):
446
+ return v
447
+ if v.lower() in ("yes", "true", "t", "y", "1"):
448
+ return True
449
+ elif v.lower() in ("no", "false", "f", "n", "0"):
450
+ return False
451
+ else:
452
+ raise argparse.ArgumentTypeError("boolean value expected")
editing_diffusion/guided_diffusion/guided_diffusion/train_util.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import functools
3
+ import os
4
+
5
+ import blobfile as bf
6
+ import torch as th
7
+ import torch.distributed as dist
8
+ from torch.nn.parallel.distributed import DistributedDataParallel as DDP
9
+ from torch.optim import AdamW
10
+
11
+ from . import dist_util, logger
12
+ from .fp16_util import MixedPrecisionTrainer
13
+ from .nn import update_ema
14
+ from .resample import LossAwareSampler, UniformSampler
15
+
16
+ # For ImageNet experiments, this was a good default value.
17
+ # We found that the lg_loss_scale quickly climbed to
18
+ # 20-21 within the first ~1K steps of training.
19
+ INITIAL_LOG_LOSS_SCALE = 20.0
20
+
21
+
22
+ class TrainLoop:
23
+ def __init__(
24
+ self,
25
+ *,
26
+ model,
27
+ diffusion,
28
+ data,
29
+ batch_size,
30
+ microbatch,
31
+ lr,
32
+ ema_rate,
33
+ log_interval,
34
+ save_interval,
35
+ resume_checkpoint,
36
+ use_fp16=False,
37
+ fp16_scale_growth=1e-3,
38
+ schedule_sampler=None,
39
+ weight_decay=0.0,
40
+ lr_anneal_steps=0,
41
+ ):
42
+ self.model = model
43
+ self.diffusion = diffusion
44
+ self.data = data
45
+ self.batch_size = batch_size
46
+ self.microbatch = microbatch if microbatch > 0 else batch_size
47
+ self.lr = lr
48
+ self.ema_rate = (
49
+ [ema_rate]
50
+ if isinstance(ema_rate, float)
51
+ else [float(x) for x in ema_rate.split(",")]
52
+ )
53
+ self.log_interval = log_interval
54
+ self.save_interval = save_interval
55
+ self.resume_checkpoint = resume_checkpoint
56
+ self.use_fp16 = use_fp16
57
+ self.fp16_scale_growth = fp16_scale_growth
58
+ self.schedule_sampler = schedule_sampler or UniformSampler(diffusion)
59
+ self.weight_decay = weight_decay
60
+ self.lr_anneal_steps = lr_anneal_steps
61
+
62
+ self.step = 0
63
+ self.resume_step = 0
64
+ self.global_batch = self.batch_size * dist.get_world_size()
65
+
66
+ self.sync_cuda = th.cuda.is_available()
67
+
68
+ self._load_and_sync_parameters()
69
+ self.mp_trainer = MixedPrecisionTrainer(
70
+ model=self.model,
71
+ use_fp16=self.use_fp16,
72
+ fp16_scale_growth=fp16_scale_growth,
73
+ )
74
+
75
+ self.opt = AdamW(
76
+ self.mp_trainer.master_params, lr=self.lr, weight_decay=self.weight_decay
77
+ )
78
+ if self.resume_step:
79
+ self._load_optimizer_state()
80
+ # Model was resumed, either due to a restart or a checkpoint
81
+ # being specified at the command line.
82
+ self.ema_params = [
83
+ self._load_ema_parameters(rate) for rate in self.ema_rate
84
+ ]
85
+ else:
86
+ self.ema_params = [
87
+ copy.deepcopy(self.mp_trainer.master_params)
88
+ for _ in range(len(self.ema_rate))
89
+ ]
90
+
91
+ if th.cuda.is_available():
92
+ self.use_ddp = True
93
+ self.ddp_model = DDP(
94
+ self.model,
95
+ device_ids=[dist_util.dev()],
96
+ output_device=dist_util.dev(),
97
+ broadcast_buffers=False,
98
+ bucket_cap_mb=128,
99
+ find_unused_parameters=False,
100
+ )
101
+ else:
102
+ if dist.get_world_size() > 1:
103
+ logger.warn(
104
+ "Distributed training requires CUDA. "
105
+ "Gradients will not be synchronized properly!"
106
+ )
107
+ self.use_ddp = False
108
+ self.ddp_model = self.model
109
+
110
+ def _load_and_sync_parameters(self):
111
+ resume_checkpoint = find_resume_checkpoint() or self.resume_checkpoint
112
+
113
+ if resume_checkpoint:
114
+ self.resume_step = parse_resume_step_from_filename(resume_checkpoint)
115
+ if dist.get_rank() == 0:
116
+ logger.log(f"loading model from checkpoint: {resume_checkpoint}...")
117
+ self.model.load_state_dict(
118
+ dist_util.load_state_dict(
119
+ resume_checkpoint, map_location=dist_util.dev()
120
+ )
121
+ )
122
+
123
+ dist_util.sync_params(self.model.parameters())
124
+
125
+ def _load_ema_parameters(self, rate):
126
+ ema_params = copy.deepcopy(self.mp_trainer.master_params)
127
+
128
+ main_checkpoint = find_resume_checkpoint() or self.resume_checkpoint
129
+ ema_checkpoint = find_ema_checkpoint(main_checkpoint, self.resume_step, rate)
130
+ if ema_checkpoint:
131
+ if dist.get_rank() == 0:
132
+ logger.log(f"loading EMA from checkpoint: {ema_checkpoint}...")
133
+ state_dict = dist_util.load_state_dict(
134
+ ema_checkpoint, map_location=dist_util.dev()
135
+ )
136
+ ema_params = self.mp_trainer.state_dict_to_master_params(state_dict)
137
+
138
+ dist_util.sync_params(ema_params)
139
+ return ema_params
140
+
141
+ def _load_optimizer_state(self):
142
+ main_checkpoint = find_resume_checkpoint() or self.resume_checkpoint
143
+ opt_checkpoint = bf.join(
144
+ bf.dirname(main_checkpoint), f"opt{self.resume_step:06}.pt"
145
+ )
146
+ if bf.exists(opt_checkpoint):
147
+ logger.log(f"loading optimizer state from checkpoint: {opt_checkpoint}")
148
+ state_dict = dist_util.load_state_dict(
149
+ opt_checkpoint, map_location=dist_util.dev()
150
+ )
151
+ self.opt.load_state_dict(state_dict)
152
+
153
+ def run_loop(self):
154
+ while (
155
+ not self.lr_anneal_steps
156
+ or self.step + self.resume_step < self.lr_anneal_steps
157
+ ):
158
+ batch, cond = next(self.data)
159
+ self.run_step(batch, cond)
160
+ if self.step % self.log_interval == 0:
161
+ logger.dumpkvs()
162
+ if self.step % self.save_interval == 0:
163
+ self.save()
164
+ # Run for a finite amount of time in integration tests.
165
+ if os.environ.get("DIFFUSION_TRAINING_TEST", "") and self.step > 0:
166
+ return
167
+ self.step += 1
168
+ # Save the last checkpoint if it wasn't already saved.
169
+ if (self.step - 1) % self.save_interval != 0:
170
+ self.save()
171
+
172
+ def run_step(self, batch, cond):
173
+ self.forward_backward(batch, cond)
174
+ took_step = self.mp_trainer.optimize(self.opt)
175
+ if took_step:
176
+ self._update_ema()
177
+ self._anneal_lr()
178
+ self.log_step()
179
+
180
+ def forward_backward(self, batch, cond):
181
+ self.mp_trainer.zero_grad()
182
+ for i in range(0, batch.shape[0], self.microbatch):
183
+ micro = batch[i : i + self.microbatch].to(dist_util.dev())
184
+ micro_cond = {
185
+ k: v[i : i + self.microbatch].to(dist_util.dev())
186
+ for k, v in cond.items()
187
+ }
188
+ last_batch = (i + self.microbatch) >= batch.shape[0]
189
+ t, weights = self.schedule_sampler.sample(micro.shape[0], dist_util.dev())
190
+
191
+ compute_losses = functools.partial(
192
+ self.diffusion.training_losses,
193
+ self.ddp_model,
194
+ micro,
195
+ t,
196
+ model_kwargs=micro_cond,
197
+ )
198
+
199
+ if last_batch or not self.use_ddp:
200
+ losses = compute_losses()
201
+ else:
202
+ with self.ddp_model.no_sync():
203
+ losses = compute_losses()
204
+
205
+ if isinstance(self.schedule_sampler, LossAwareSampler):
206
+ self.schedule_sampler.update_with_local_losses(
207
+ t, losses["loss"].detach()
208
+ )
209
+
210
+ loss = (losses["loss"] * weights).mean()
211
+ log_loss_dict(
212
+ self.diffusion, t, {k: v * weights for k, v in losses.items()}
213
+ )
214
+ self.mp_trainer.backward(loss)
215
+
216
+ def _update_ema(self):
217
+ for rate, params in zip(self.ema_rate, self.ema_params):
218
+ update_ema(params, self.mp_trainer.master_params, rate=rate)
219
+
220
+ def _anneal_lr(self):
221
+ if not self.lr_anneal_steps:
222
+ return
223
+ frac_done = (self.step + self.resume_step) / self.lr_anneal_steps
224
+ lr = self.lr * (1 - frac_done)
225
+ for param_group in self.opt.param_groups:
226
+ param_group["lr"] = lr
227
+
228
+ def log_step(self):
229
+ logger.logkv("step", self.step + self.resume_step)
230
+ logger.logkv("samples", (self.step + self.resume_step + 1) * self.global_batch)
231
+
232
+ def save(self):
233
+ def save_checkpoint(rate, params):
234
+ state_dict = self.mp_trainer.master_params_to_state_dict(params)
235
+ if dist.get_rank() == 0:
236
+ logger.log(f"saving model {rate}...")
237
+ if not rate:
238
+ filename = f"model{(self.step+self.resume_step):06d}.pt"
239
+ else:
240
+ filename = f"ema_{rate}_{(self.step+self.resume_step):06d}.pt"
241
+ with bf.BlobFile(bf.join(get_blob_logdir(), filename), "wb") as f:
242
+ th.save(state_dict, f)
243
+
244
+ save_checkpoint(0, self.mp_trainer.master_params)
245
+ for rate, params in zip(self.ema_rate, self.ema_params):
246
+ save_checkpoint(rate, params)
247
+
248
+ if dist.get_rank() == 0:
249
+ with bf.BlobFile(
250
+ bf.join(get_blob_logdir(), f"opt{(self.step+self.resume_step):06d}.pt"),
251
+ "wb",
252
+ ) as f:
253
+ th.save(self.opt.state_dict(), f)
254
+
255
+ dist.barrier()
256
+
257
+
258
+ def parse_resume_step_from_filename(filename):
259
+ """
260
+ Parse filenames of the form path/to/modelNNNNNN.pt, where NNNNNN is the
261
+ checkpoint's number of steps.
262
+ """
263
+ split = filename.split("model")
264
+ if len(split) < 2:
265
+ return 0
266
+ split1 = split[-1].split(".")[0]
267
+ try:
268
+ return int(split1)
269
+ except ValueError:
270
+ return 0
271
+
272
+
273
+ def get_blob_logdir():
274
+ # You can change this to be a separate path to save checkpoints to
275
+ # a blobstore or some external drive.
276
+ return logger.get_dir()
277
+
278
+
279
+ def find_resume_checkpoint():
280
+ # On your infrastructure, you may want to override this to automatically
281
+ # discover the latest checkpoint on your blob storage, etc.
282
+ return None
283
+
284
+
285
+ def find_ema_checkpoint(main_checkpoint, step, rate):
286
+ if main_checkpoint is None:
287
+ return None
288
+ filename = f"ema_{rate}_{(step):06d}.pt"
289
+ path = bf.join(bf.dirname(main_checkpoint), filename)
290
+ if bf.exists(path):
291
+ return path
292
+ return None
293
+
294
+
295
+ def log_loss_dict(diffusion, ts, losses):
296
+ for key, values in losses.items():
297
+ logger.logkv_mean(key, values.mean().item())
298
+ # Log the quantiles (four quartiles, in particular).
299
+ for sub_t, sub_loss in zip(ts.cpu().numpy(), values.detach().cpu().numpy()):
300
+ quartile = int(4 * sub_t / diffusion.num_timesteps)
301
+ logger.logkv_mean(f"{key}_q{quartile}", sub_loss)
editing_diffusion/guided_diffusion/guided_diffusion/unet.py ADDED
@@ -0,0 +1,894 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import abstractmethod
2
+
3
+ import math
4
+
5
+ import numpy as np
6
+ import torch as th
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+
10
+ from .fp16_util import convert_module_to_f16, convert_module_to_f32
11
+ from .nn import (
12
+ checkpoint,
13
+ conv_nd,
14
+ linear,
15
+ avg_pool_nd,
16
+ zero_module,
17
+ normalization,
18
+ timestep_embedding,
19
+ )
20
+
21
+
22
+ class AttentionPool2d(nn.Module):
23
+ """
24
+ Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ spacial_dim: int,
30
+ embed_dim: int,
31
+ num_heads_channels: int,
32
+ output_dim: int = None,
33
+ ):
34
+ super().__init__()
35
+ self.positional_embedding = nn.Parameter(
36
+ th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5
37
+ )
38
+ self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
39
+ self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
40
+ self.num_heads = embed_dim // num_heads_channels
41
+ self.attention = QKVAttention(self.num_heads)
42
+
43
+ def forward(self, x):
44
+ b, c, *_spatial = x.shape
45
+ x = x.reshape(b, c, -1) # NC(HW)
46
+ x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
47
+ x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
48
+ x = self.qkv_proj(x)
49
+ x = self.attention(x)
50
+ x = self.c_proj(x)
51
+ return x[:, :, 0]
52
+
53
+
54
+ class TimestepBlock(nn.Module):
55
+ """
56
+ Any module where forward() takes timestep embeddings as a second argument.
57
+ """
58
+
59
+ @abstractmethod
60
+ def forward(self, x, emb):
61
+ """
62
+ Apply the module to `x` given `emb` timestep embeddings.
63
+ """
64
+
65
+
66
+ class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
67
+ """
68
+ A sequential module that passes timestep embeddings to the children that
69
+ support it as an extra input.
70
+ """
71
+
72
+ def forward(self, x, emb):
73
+ for layer in self:
74
+ if isinstance(layer, TimestepBlock):
75
+ x = layer(x, emb)
76
+ else:
77
+ x = layer(x)
78
+ return x
79
+
80
+
81
+ class Upsample(nn.Module):
82
+ """
83
+ An upsampling layer with an optional convolution.
84
+
85
+ :param channels: channels in the inputs and outputs.
86
+ :param use_conv: a bool determining if a convolution is applied.
87
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
88
+ upsampling occurs in the inner-two dimensions.
89
+ """
90
+
91
+ def __init__(self, channels, use_conv, dims=2, out_channels=None):
92
+ super().__init__()
93
+ self.channels = channels
94
+ self.out_channels = out_channels or channels
95
+ self.use_conv = use_conv
96
+ self.dims = dims
97
+ if use_conv:
98
+ self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=1)
99
+
100
+ def forward(self, x):
101
+ assert x.shape[1] == self.channels
102
+ if self.dims == 3:
103
+ x = F.interpolate(
104
+ x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
105
+ )
106
+ else:
107
+ x = F.interpolate(x, scale_factor=2, mode="nearest")
108
+ if self.use_conv:
109
+ x = self.conv(x)
110
+ return x
111
+
112
+
113
+ class Downsample(nn.Module):
114
+ """
115
+ A downsampling layer with an optional convolution.
116
+
117
+ :param channels: channels in the inputs and outputs.
118
+ :param use_conv: a bool determining if a convolution is applied.
119
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
120
+ downsampling occurs in the inner-two dimensions.
121
+ """
122
+
123
+ def __init__(self, channels, use_conv, dims=2, out_channels=None):
124
+ super().__init__()
125
+ self.channels = channels
126
+ self.out_channels = out_channels or channels
127
+ self.use_conv = use_conv
128
+ self.dims = dims
129
+ stride = 2 if dims != 3 else (1, 2, 2)
130
+ if use_conv:
131
+ self.op = conv_nd(
132
+ dims, self.channels, self.out_channels, 3, stride=stride, padding=1
133
+ )
134
+ else:
135
+ assert self.channels == self.out_channels
136
+ self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
137
+
138
+ def forward(self, x):
139
+ assert x.shape[1] == self.channels
140
+ return self.op(x)
141
+
142
+
143
+ class ResBlock(TimestepBlock):
144
+ """
145
+ A residual block that can optionally change the number of channels.
146
+
147
+ :param channels: the number of input channels.
148
+ :param emb_channels: the number of timestep embedding channels.
149
+ :param dropout: the rate of dropout.
150
+ :param out_channels: if specified, the number of out channels.
151
+ :param use_conv: if True and out_channels is specified, use a spatial
152
+ convolution instead of a smaller 1x1 convolution to change the
153
+ channels in the skip connection.
154
+ :param dims: determines if the signal is 1D, 2D, or 3D.
155
+ :param use_checkpoint: if True, use gradient checkpointing on this module.
156
+ :param up: if True, use this block for upsampling.
157
+ :param down: if True, use this block for downsampling.
158
+ """
159
+
160
+ def __init__(
161
+ self,
162
+ channels,
163
+ emb_channels,
164
+ dropout,
165
+ out_channels=None,
166
+ use_conv=False,
167
+ use_scale_shift_norm=False,
168
+ dims=2,
169
+ use_checkpoint=False,
170
+ up=False,
171
+ down=False,
172
+ ):
173
+ super().__init__()
174
+ self.channels = channels
175
+ self.emb_channels = emb_channels
176
+ self.dropout = dropout
177
+ self.out_channels = out_channels or channels
178
+ self.use_conv = use_conv
179
+ self.use_checkpoint = use_checkpoint
180
+ self.use_scale_shift_norm = use_scale_shift_norm
181
+
182
+ self.in_layers = nn.Sequential(
183
+ normalization(channels),
184
+ nn.SiLU(),
185
+ conv_nd(dims, channels, self.out_channels, 3, padding=1),
186
+ )
187
+
188
+ self.updown = up or down
189
+
190
+ if up:
191
+ self.h_upd = Upsample(channels, False, dims)
192
+ self.x_upd = Upsample(channels, False, dims)
193
+ elif down:
194
+ self.h_upd = Downsample(channels, False, dims)
195
+ self.x_upd = Downsample(channels, False, dims)
196
+ else:
197
+ self.h_upd = self.x_upd = nn.Identity()
198
+
199
+ self.emb_layers = nn.Sequential(
200
+ nn.SiLU(),
201
+ linear(
202
+ emb_channels,
203
+ 2 * self.out_channels if use_scale_shift_norm else self.out_channels,
204
+ ),
205
+ )
206
+ self.out_layers = nn.Sequential(
207
+ normalization(self.out_channels),
208
+ nn.SiLU(),
209
+ nn.Dropout(p=dropout),
210
+ zero_module(
211
+ conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)
212
+ ),
213
+ )
214
+
215
+ if self.out_channels == channels:
216
+ self.skip_connection = nn.Identity()
217
+ elif use_conv:
218
+ self.skip_connection = conv_nd(
219
+ dims, channels, self.out_channels, 3, padding=1
220
+ )
221
+ else:
222
+ self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
223
+
224
+ def forward(self, x, emb):
225
+ """
226
+ Apply the block to a Tensor, conditioned on a timestep embedding.
227
+
228
+ :param x: an [N x C x ...] Tensor of features.
229
+ :param emb: an [N x emb_channels] Tensor of timestep embeddings.
230
+ :return: an [N x C x ...] Tensor of outputs.
231
+ """
232
+ return checkpoint(
233
+ self._forward, (x, emb), self.parameters(), self.use_checkpoint
234
+ )
235
+
236
+ def _forward(self, x, emb):
237
+ if self.updown:
238
+ in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
239
+ h = in_rest(x)
240
+ h = self.h_upd(h)
241
+ x = self.x_upd(x)
242
+ h = in_conv(h)
243
+ else:
244
+ h = self.in_layers(x)
245
+ emb_out = self.emb_layers(emb).type(h.dtype)
246
+ while len(emb_out.shape) < len(h.shape):
247
+ emb_out = emb_out[..., None]
248
+ if self.use_scale_shift_norm:
249
+ out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
250
+ scale, shift = th.chunk(emb_out, 2, dim=1)
251
+ h = out_norm(h) * (1 + scale) + shift
252
+ h = out_rest(h)
253
+ else:
254
+ h = h + emb_out
255
+ h = self.out_layers(h)
256
+ return self.skip_connection(x) + h
257
+
258
+
259
+ class AttentionBlock(nn.Module):
260
+ """
261
+ An attention block that allows spatial positions to attend to each other.
262
+
263
+ Originally ported from here, but adapted to the N-d case.
264
+ https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
265
+ """
266
+
267
+ def __init__(
268
+ self,
269
+ channels,
270
+ num_heads=1,
271
+ num_head_channels=-1,
272
+ use_checkpoint=False,
273
+ use_new_attention_order=False,
274
+ ):
275
+ super().__init__()
276
+ self.channels = channels
277
+ if num_head_channels == -1:
278
+ self.num_heads = num_heads
279
+ else:
280
+ assert (
281
+ channels % num_head_channels == 0
282
+ ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"
283
+ self.num_heads = channels // num_head_channels
284
+ self.use_checkpoint = use_checkpoint
285
+ self.norm = normalization(channels)
286
+ self.qkv = conv_nd(1, channels, channels * 3, 1)
287
+ if use_new_attention_order:
288
+ # split qkv before split heads
289
+ self.attention = QKVAttention(self.num_heads)
290
+ else:
291
+ # split heads before split qkv
292
+ self.attention = QKVAttentionLegacy(self.num_heads)
293
+
294
+ self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
295
+
296
+ def forward(self, x):
297
+ return checkpoint(self._forward, (x,), self.parameters(), True)
298
+
299
+ def _forward(self, x):
300
+ b, c, *spatial = x.shape
301
+ x = x.reshape(b, c, -1)
302
+ qkv = self.qkv(self.norm(x))
303
+ h = self.attention(qkv)
304
+ h = self.proj_out(h)
305
+ return (x + h).reshape(b, c, *spatial)
306
+
307
+
308
+ def count_flops_attn(model, _x, y):
309
+ """
310
+ A counter for the `thop` package to count the operations in an
311
+ attention operation.
312
+ Meant to be used like:
313
+ macs, params = thop.profile(
314
+ model,
315
+ inputs=(inputs, timestamps),
316
+ custom_ops={QKVAttention: QKVAttention.count_flops},
317
+ )
318
+ """
319
+ b, c, *spatial = y[0].shape
320
+ num_spatial = int(np.prod(spatial))
321
+ # We perform two matmuls with the same number of ops.
322
+ # The first computes the weight matrix, the second computes
323
+ # the combination of the value vectors.
324
+ matmul_ops = 2 * b * (num_spatial ** 2) * c
325
+ model.total_ops += th.DoubleTensor([matmul_ops])
326
+
327
+
328
+ class QKVAttentionLegacy(nn.Module):
329
+ """
330
+ A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
331
+ """
332
+
333
+ def __init__(self, n_heads):
334
+ super().__init__()
335
+ self.n_heads = n_heads
336
+
337
+ def forward(self, qkv):
338
+ """
339
+ Apply QKV attention.
340
+
341
+ :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
342
+ :return: an [N x (H * C) x T] tensor after attention.
343
+ """
344
+ bs, width, length = qkv.shape
345
+ assert width % (3 * self.n_heads) == 0
346
+ ch = width // (3 * self.n_heads)
347
+ q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
348
+ scale = 1 / math.sqrt(math.sqrt(ch))
349
+ weight = th.einsum(
350
+ "bct,bcs->bts", q * scale, k * scale
351
+ ) # More stable with f16 than dividing afterwards
352
+ weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
353
+ a = th.einsum("bts,bcs->bct", weight, v)
354
+ return a.reshape(bs, -1, length)
355
+
356
+ @staticmethod
357
+ def count_flops(model, _x, y):
358
+ return count_flops_attn(model, _x, y)
359
+
360
+
361
+ class QKVAttention(nn.Module):
362
+ """
363
+ A module which performs QKV attention and splits in a different order.
364
+ """
365
+
366
+ def __init__(self, n_heads):
367
+ super().__init__()
368
+ self.n_heads = n_heads
369
+
370
+ def forward(self, qkv):
371
+ """
372
+ Apply QKV attention.
373
+
374
+ :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
375
+ :return: an [N x (H * C) x T] tensor after attention.
376
+ """
377
+ bs, width, length = qkv.shape
378
+ assert width % (3 * self.n_heads) == 0
379
+ ch = width // (3 * self.n_heads)
380
+ q, k, v = qkv.chunk(3, dim=1)
381
+ scale = 1 / math.sqrt(math.sqrt(ch))
382
+ weight = th.einsum(
383
+ "bct,bcs->bts",
384
+ (q * scale).view(bs * self.n_heads, ch, length),
385
+ (k * scale).view(bs * self.n_heads, ch, length),
386
+ ) # More stable with f16 than dividing afterwards
387
+ weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
388
+ a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
389
+ return a.reshape(bs, -1, length)
390
+
391
+ @staticmethod
392
+ def count_flops(model, _x, y):
393
+ return count_flops_attn(model, _x, y)
394
+
395
+
396
+ class UNetModel(nn.Module):
397
+ """
398
+ The full UNet model with attention and timestep embedding.
399
+
400
+ :param in_channels: channels in the input Tensor.
401
+ :param model_channels: base channel count for the model.
402
+ :param out_channels: channels in the output Tensor.
403
+ :param num_res_blocks: number of residual blocks per downsample.
404
+ :param attention_resolutions: a collection of downsample rates at which
405
+ attention will take place. May be a set, list, or tuple.
406
+ For example, if this contains 4, then at 4x downsampling, attention
407
+ will be used.
408
+ :param dropout: the dropout probability.
409
+ :param channel_mult: channel multiplier for each level of the UNet.
410
+ :param conv_resample: if True, use learned convolutions for upsampling and
411
+ downsampling.
412
+ :param dims: determines if the signal is 1D, 2D, or 3D.
413
+ :param num_classes: if specified (as an int), then this model will be
414
+ class-conditional with `num_classes` classes.
415
+ :param use_checkpoint: use gradient checkpointing to reduce memory usage.
416
+ :param num_heads: the number of attention heads in each attention layer.
417
+ :param num_heads_channels: if specified, ignore num_heads and instead use
418
+ a fixed channel width per attention head.
419
+ :param num_heads_upsample: works with num_heads to set a different number
420
+ of heads for upsampling. Deprecated.
421
+ :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
422
+ :param resblock_updown: use residual blocks for up/downsampling.
423
+ :param use_new_attention_order: use a different attention pattern for potentially
424
+ increased efficiency.
425
+ """
426
+
427
+ def __init__(
428
+ self,
429
+ image_size,
430
+ in_channels,
431
+ model_channels,
432
+ out_channels,
433
+ num_res_blocks,
434
+ attention_resolutions,
435
+ dropout=0,
436
+ channel_mult=(1, 2, 4, 8),
437
+ conv_resample=True,
438
+ dims=2,
439
+ num_classes=None,
440
+ use_checkpoint=False,
441
+ use_fp16=False,
442
+ num_heads=1,
443
+ num_head_channels=-1,
444
+ num_heads_upsample=-1,
445
+ use_scale_shift_norm=False,
446
+ resblock_updown=False,
447
+ use_new_attention_order=False,
448
+ ):
449
+ super().__init__()
450
+
451
+ if num_heads_upsample == -1:
452
+ num_heads_upsample = num_heads
453
+
454
+ self.image_size = image_size
455
+ self.in_channels = in_channels
456
+ self.model_channels = model_channels
457
+ self.out_channels = out_channels
458
+ self.num_res_blocks = num_res_blocks
459
+ self.attention_resolutions = attention_resolutions
460
+ self.dropout = dropout
461
+ self.channel_mult = channel_mult
462
+ self.conv_resample = conv_resample
463
+ self.num_classes = num_classes
464
+ self.use_checkpoint = use_checkpoint
465
+ self.dtype = th.float16 if use_fp16 else th.float32
466
+ self.num_heads = num_heads
467
+ self.num_head_channels = num_head_channels
468
+ self.num_heads_upsample = num_heads_upsample
469
+
470
+ time_embed_dim = model_channels * 4
471
+ self.time_embed = nn.Sequential(
472
+ linear(model_channels, time_embed_dim),
473
+ nn.SiLU(),
474
+ linear(time_embed_dim, time_embed_dim),
475
+ )
476
+
477
+ if self.num_classes is not None:
478
+ self.label_emb = nn.Embedding(num_classes, time_embed_dim)
479
+
480
+ ch = input_ch = int(channel_mult[0] * model_channels)
481
+ self.input_blocks = nn.ModuleList(
482
+ [TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))]
483
+ )
484
+ self._feature_size = ch
485
+ input_block_chans = [ch]
486
+ ds = 1
487
+ for level, mult in enumerate(channel_mult):
488
+ for _ in range(num_res_blocks):
489
+ layers = [
490
+ ResBlock(
491
+ ch,
492
+ time_embed_dim,
493
+ dropout,
494
+ out_channels=int(mult * model_channels),
495
+ dims=dims,
496
+ use_checkpoint=use_checkpoint,
497
+ use_scale_shift_norm=use_scale_shift_norm,
498
+ )
499
+ ]
500
+ ch = int(mult * model_channels)
501
+ if ds in attention_resolutions:
502
+ layers.append(
503
+ AttentionBlock(
504
+ ch,
505
+ use_checkpoint=use_checkpoint,
506
+ num_heads=num_heads,
507
+ num_head_channels=num_head_channels,
508
+ use_new_attention_order=use_new_attention_order,
509
+ )
510
+ )
511
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
512
+ self._feature_size += ch
513
+ input_block_chans.append(ch)
514
+ if level != len(channel_mult) - 1:
515
+ out_ch = ch
516
+ self.input_blocks.append(
517
+ TimestepEmbedSequential(
518
+ ResBlock(
519
+ ch,
520
+ time_embed_dim,
521
+ dropout,
522
+ out_channels=out_ch,
523
+ dims=dims,
524
+ use_checkpoint=use_checkpoint,
525
+ use_scale_shift_norm=use_scale_shift_norm,
526
+ down=True,
527
+ )
528
+ if resblock_updown
529
+ else Downsample(
530
+ ch, conv_resample, dims=dims, out_channels=out_ch
531
+ )
532
+ )
533
+ )
534
+ ch = out_ch
535
+ input_block_chans.append(ch)
536
+ ds *= 2
537
+ self._feature_size += ch
538
+
539
+ self.middle_block = TimestepEmbedSequential(
540
+ ResBlock(
541
+ ch,
542
+ time_embed_dim,
543
+ dropout,
544
+ dims=dims,
545
+ use_checkpoint=use_checkpoint,
546
+ use_scale_shift_norm=use_scale_shift_norm,
547
+ ),
548
+ AttentionBlock(
549
+ ch,
550
+ use_checkpoint=use_checkpoint,
551
+ num_heads=num_heads,
552
+ num_head_channels=num_head_channels,
553
+ use_new_attention_order=use_new_attention_order,
554
+ ),
555
+ ResBlock(
556
+ ch,
557
+ time_embed_dim,
558
+ dropout,
559
+ dims=dims,
560
+ use_checkpoint=use_checkpoint,
561
+ use_scale_shift_norm=use_scale_shift_norm,
562
+ ),
563
+ )
564
+ self._feature_size += ch
565
+
566
+ self.output_blocks = nn.ModuleList([])
567
+ for level, mult in list(enumerate(channel_mult))[::-1]:
568
+ for i in range(num_res_blocks + 1):
569
+ ich = input_block_chans.pop()
570
+ layers = [
571
+ ResBlock(
572
+ ch + ich,
573
+ time_embed_dim,
574
+ dropout,
575
+ out_channels=int(model_channels * mult),
576
+ dims=dims,
577
+ use_checkpoint=use_checkpoint,
578
+ use_scale_shift_norm=use_scale_shift_norm,
579
+ )
580
+ ]
581
+ ch = int(model_channels * mult)
582
+ if ds in attention_resolutions:
583
+ layers.append(
584
+ AttentionBlock(
585
+ ch,
586
+ use_checkpoint=use_checkpoint,
587
+ num_heads=num_heads_upsample,
588
+ num_head_channels=num_head_channels,
589
+ use_new_attention_order=use_new_attention_order,
590
+ )
591
+ )
592
+ if level and i == num_res_blocks:
593
+ out_ch = ch
594
+ layers.append(
595
+ ResBlock(
596
+ ch,
597
+ time_embed_dim,
598
+ dropout,
599
+ out_channels=out_ch,
600
+ dims=dims,
601
+ use_checkpoint=use_checkpoint,
602
+ use_scale_shift_norm=use_scale_shift_norm,
603
+ up=True,
604
+ )
605
+ if resblock_updown
606
+ else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
607
+ )
608
+ ds //= 2
609
+ self.output_blocks.append(TimestepEmbedSequential(*layers))
610
+ self._feature_size += ch
611
+
612
+ self.out = nn.Sequential(
613
+ normalization(ch),
614
+ nn.SiLU(),
615
+ zero_module(conv_nd(dims, input_ch, out_channels, 3, padding=1)),
616
+ )
617
+
618
+ def convert_to_fp16(self):
619
+ """
620
+ Convert the torso of the model to float16.
621
+ """
622
+ self.input_blocks.apply(convert_module_to_f16)
623
+ self.middle_block.apply(convert_module_to_f16)
624
+ self.output_blocks.apply(convert_module_to_f16)
625
+
626
+ def convert_to_fp32(self):
627
+ """
628
+ Convert the torso of the model to float32.
629
+ """
630
+ self.input_blocks.apply(convert_module_to_f32)
631
+ self.middle_block.apply(convert_module_to_f32)
632
+ self.output_blocks.apply(convert_module_to_f32)
633
+
634
+ def forward(self, x, timesteps, y=None):
635
+ """
636
+ Apply the model to an input batch.
637
+
638
+ :param x: an [N x C x ...] Tensor of inputs.
639
+ :param timesteps: a 1-D batch of timesteps.
640
+ :param y: an [N] Tensor of labels, if class-conditional.
641
+ :return: an [N x C x ...] Tensor of outputs.
642
+ """
643
+ assert (y is not None) == (
644
+ self.num_classes is not None
645
+ ), "must specify y if and only if the model is class-conditional"
646
+
647
+ hs = []
648
+ emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
649
+
650
+ if self.num_classes is not None:
651
+ assert y.shape == (x.shape[0],)
652
+ emb = emb + self.label_emb(y)
653
+
654
+ h = x.type(self.dtype)
655
+ for module in self.input_blocks:
656
+ h = module(h, emb)
657
+ hs.append(h)
658
+ h = self.middle_block(h, emb)
659
+ for module in self.output_blocks:
660
+ h = th.cat([h, hs.pop()], dim=1)
661
+ h = module(h, emb)
662
+ h = h.type(x.dtype)
663
+ return self.out(h)
664
+
665
+
666
+ class SuperResModel(UNetModel):
667
+ """
668
+ A UNetModel that performs super-resolution.
669
+
670
+ Expects an extra kwarg `low_res` to condition on a low-resolution image.
671
+ """
672
+
673
+ def __init__(self, image_size, in_channels, *args, **kwargs):
674
+ super().__init__(image_size, in_channels * 2, *args, **kwargs)
675
+
676
+ def forward(self, x, timesteps, low_res=None, **kwargs):
677
+ _, _, new_height, new_width = x.shape
678
+ upsampled = F.interpolate(low_res, (new_height, new_width), mode="bilinear")
679
+ x = th.cat([x, upsampled], dim=1)
680
+ return super().forward(x, timesteps, **kwargs)
681
+
682
+
683
+ class EncoderUNetModel(nn.Module):
684
+ """
685
+ The half UNet model with attention and timestep embedding.
686
+
687
+ For usage, see UNet.
688
+ """
689
+
690
+ def __init__(
691
+ self,
692
+ image_size,
693
+ in_channels,
694
+ model_channels,
695
+ out_channels,
696
+ num_res_blocks,
697
+ attention_resolutions,
698
+ dropout=0,
699
+ channel_mult=(1, 2, 4, 8),
700
+ conv_resample=True,
701
+ dims=2,
702
+ use_checkpoint=False,
703
+ use_fp16=False,
704
+ num_heads=1,
705
+ num_head_channels=-1,
706
+ num_heads_upsample=-1,
707
+ use_scale_shift_norm=False,
708
+ resblock_updown=False,
709
+ use_new_attention_order=False,
710
+ pool="adaptive",
711
+ ):
712
+ super().__init__()
713
+
714
+ if num_heads_upsample == -1:
715
+ num_heads_upsample = num_heads
716
+
717
+ self.in_channels = in_channels
718
+ self.model_channels = model_channels
719
+ self.out_channels = out_channels
720
+ self.num_res_blocks = num_res_blocks
721
+ self.attention_resolutions = attention_resolutions
722
+ self.dropout = dropout
723
+ self.channel_mult = channel_mult
724
+ self.conv_resample = conv_resample
725
+ self.use_checkpoint = use_checkpoint
726
+ self.dtype = th.float16 if use_fp16 else th.float32
727
+ self.num_heads = num_heads
728
+ self.num_head_channels = num_head_channels
729
+ self.num_heads_upsample = num_heads_upsample
730
+
731
+ time_embed_dim = model_channels * 4
732
+ self.time_embed = nn.Sequential(
733
+ linear(model_channels, time_embed_dim),
734
+ nn.SiLU(),
735
+ linear(time_embed_dim, time_embed_dim),
736
+ )
737
+
738
+ ch = int(channel_mult[0] * model_channels)
739
+ self.input_blocks = nn.ModuleList(
740
+ [TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))]
741
+ )
742
+ self._feature_size = ch
743
+ input_block_chans = [ch]
744
+ ds = 1
745
+ for level, mult in enumerate(channel_mult):
746
+ for _ in range(num_res_blocks):
747
+ layers = [
748
+ ResBlock(
749
+ ch,
750
+ time_embed_dim,
751
+ dropout,
752
+ out_channels=int(mult * model_channels),
753
+ dims=dims,
754
+ use_checkpoint=use_checkpoint,
755
+ use_scale_shift_norm=use_scale_shift_norm,
756
+ )
757
+ ]
758
+ ch = int(mult * model_channels)
759
+ if ds in attention_resolutions:
760
+ layers.append(
761
+ AttentionBlock(
762
+ ch,
763
+ use_checkpoint=use_checkpoint,
764
+ num_heads=num_heads,
765
+ num_head_channels=num_head_channels,
766
+ use_new_attention_order=use_new_attention_order,
767
+ )
768
+ )
769
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
770
+ self._feature_size += ch
771
+ input_block_chans.append(ch)
772
+ if level != len(channel_mult) - 1:
773
+ out_ch = ch
774
+ self.input_blocks.append(
775
+ TimestepEmbedSequential(
776
+ ResBlock(
777
+ ch,
778
+ time_embed_dim,
779
+ dropout,
780
+ out_channels=out_ch,
781
+ dims=dims,
782
+ use_checkpoint=use_checkpoint,
783
+ use_scale_shift_norm=use_scale_shift_norm,
784
+ down=True,
785
+ )
786
+ if resblock_updown
787
+ else Downsample(
788
+ ch, conv_resample, dims=dims, out_channels=out_ch
789
+ )
790
+ )
791
+ )
792
+ ch = out_ch
793
+ input_block_chans.append(ch)
794
+ ds *= 2
795
+ self._feature_size += ch
796
+
797
+ self.middle_block = TimestepEmbedSequential(
798
+ ResBlock(
799
+ ch,
800
+ time_embed_dim,
801
+ dropout,
802
+ dims=dims,
803
+ use_checkpoint=use_checkpoint,
804
+ use_scale_shift_norm=use_scale_shift_norm,
805
+ ),
806
+ AttentionBlock(
807
+ ch,
808
+ use_checkpoint=use_checkpoint,
809
+ num_heads=num_heads,
810
+ num_head_channels=num_head_channels,
811
+ use_new_attention_order=use_new_attention_order,
812
+ ),
813
+ ResBlock(
814
+ ch,
815
+ time_embed_dim,
816
+ dropout,
817
+ dims=dims,
818
+ use_checkpoint=use_checkpoint,
819
+ use_scale_shift_norm=use_scale_shift_norm,
820
+ ),
821
+ )
822
+ self._feature_size += ch
823
+ self.pool = pool
824
+ if pool == "adaptive":
825
+ self.out = nn.Sequential(
826
+ normalization(ch),
827
+ nn.SiLU(),
828
+ nn.AdaptiveAvgPool2d((1, 1)),
829
+ zero_module(conv_nd(dims, ch, out_channels, 1)),
830
+ nn.Flatten(),
831
+ )
832
+ elif pool == "attention":
833
+ assert num_head_channels != -1
834
+ self.out = nn.Sequential(
835
+ normalization(ch),
836
+ nn.SiLU(),
837
+ AttentionPool2d(
838
+ (image_size // ds), ch, num_head_channels, out_channels
839
+ ),
840
+ )
841
+ elif pool == "spatial":
842
+ self.out = nn.Sequential(
843
+ nn.Linear(self._feature_size, 2048),
844
+ nn.ReLU(),
845
+ nn.Linear(2048, self.out_channels),
846
+ )
847
+ elif pool == "spatial_v2":
848
+ self.out = nn.Sequential(
849
+ nn.Linear(self._feature_size, 2048),
850
+ normalization(2048),
851
+ nn.SiLU(),
852
+ nn.Linear(2048, self.out_channels),
853
+ )
854
+ else:
855
+ raise NotImplementedError(f"Unexpected {pool} pooling")
856
+
857
+ def convert_to_fp16(self):
858
+ """
859
+ Convert the torso of the model to float16.
860
+ """
861
+ self.input_blocks.apply(convert_module_to_f16)
862
+ self.middle_block.apply(convert_module_to_f16)
863
+
864
+ def convert_to_fp32(self):
865
+ """
866
+ Convert the torso of the model to float32.
867
+ """
868
+ self.input_blocks.apply(convert_module_to_f32)
869
+ self.middle_block.apply(convert_module_to_f32)
870
+
871
+ def forward(self, x, timesteps):
872
+ """
873
+ Apply the model to an input batch.
874
+
875
+ :param x: an [N x C x ...] Tensor of inputs.
876
+ :param timesteps: a 1-D batch of timesteps.
877
+ :return: an [N x K] Tensor of outputs.
878
+ """
879
+ emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
880
+
881
+ results = []
882
+ h = x.type(self.dtype)
883
+ for module in self.input_blocks:
884
+ h = module(h, emb)
885
+ if self.pool.startswith("spatial"):
886
+ results.append(h.type(x.dtype).mean(dim=(2, 3)))
887
+ h = self.middle_block(h, emb)
888
+ if self.pool.startswith("spatial"):
889
+ results.append(h.type(x.dtype).mean(dim=(2, 3)))
890
+ h = th.cat(results, axis=-1)
891
+ return self.out(h)
892
+ else:
893
+ h = h.type(x.dtype)
894
+ return self.out(h)
editing_diffusion/guided_diffusion/model-card.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Overview
2
+
3
+ These are diffusion models and noised image classifiers described in the paper [Diffusion Models Beat GANs on Image Synthesis](https://arxiv.org/abs/2105.05233).
4
+ Included in this release are the following models:
5
+
6
+ * Noisy ImageNet classifiers at resolutions 64x64, 128x128, 256x256, 512x512
7
+ * A class-unconditional ImageNet diffusion model at resolution 256x256
8
+ * Class conditional ImageNet diffusion models at 64x64, 128x128, 256x256, 512x512 resolutions
9
+ * Class-conditional ImageNet upsampling diffusion models: 64x64->256x256, 128x128->512x512
10
+ * Diffusion models trained on three LSUN classes at 256x256 resolution: cat, horse, bedroom
11
+
12
+ # Datasets
13
+
14
+ All of the models we are releasing were either trained on the [ILSVRC 2012 subset of ImageNet](http://www.image-net.org/challenges/LSVRC/2012/) or on single classes of [LSUN](https://arxiv.org/abs/1506.03365).
15
+ Here, we describe characteristics of these datasets which impact model behavior:
16
+
17
+ **LSUN**: This dataset was collected in 2015 using a combination of human labeling (from Amazon Mechanical Turk) and automated data labeling.
18
+ * Each of the three classes we consider contain over a million images.
19
+ * The dataset creators found that the label accuracy was roughly 90% across the entire LSUN dataset when measured by trained experts.
20
+ * Images are scraped from the internet, and LSUN cat images in particular tend to often follow a “meme” format.
21
+ * We found that there are occasionally humans in these photos, including faces, especially within the cat class.
22
+
23
+ **ILSVRC 2012 subset of ImageNet**: This dataset was curated in 2012 and consists of roughly one million images, each belonging to one of 1000 classes.
24
+ * A large portion of the classes in this dataset are animals, plants, and other naturally-occurring objects.
25
+ * Many images contain humans, although usually these humans aren’t reflected by the class label (e.g. the class “Tench, tinca tinca” contains many photos of people holding fish).
26
+
27
+ # Performance
28
+
29
+ These models are intended to generate samples consistent with their training distributions.
30
+ This has been measured in terms of FID, Precision, and Recall.
31
+ These metrics all rely on the representations of a [pre-trained Inception-V3 model](https://arxiv.org/abs/1512.00567),
32
+ which was trained on ImageNet, and so is likely to focus more on the ImageNet classes (such as animals) than on other visual features (such as human faces).
33
+
34
+ Qualitatively, the samples produced by these models often look highly realistic, especially when a diffusion model is combined with a noisy classifier.
35
+
36
+ # Intended Use
37
+
38
+ These models are intended to be used for research purposes only.
39
+ In particular, they can be used as a baseline for generative modeling research, or as a starting point to build off of for such research.
40
+
41
+ These models are not intended to be commercially deployed.
42
+ Additionally, they are not intended to be used to create propaganda or offensive imagery.
43
+
44
+ Before releasing these models, we probed their ability to ease the creation of targeted imagery, since doing so could be potentially harmful.
45
+ We did this either by fine-tuning our ImageNet models on a target LSUN class, or through classifier guidance with publicly available [CLIP models](https://github.com/openai/CLIP).
46
+ * To probe fine-tuning capabilities, we restricted our compute budget to roughly $100 and tried both standard fine-tuning,
47
+ and a diffusion-specific approach where we train a specialized classifier for the LSUN class. The resulting FIDs were significantly worse than publicly available GAN models, indicating that fine-tuning an ImageNet diffusion model does not significantly lower the cost of image generation.
48
+ * To probe guidance with CLIP, we tried two approaches for using pre-trained CLIP models for classifier guidance. Either we fed the noised image to CLIP directly and used its gradients, or we fed the diffusion model's denoised prediction to the CLIP model and differentiated through the whole process. In both cases, we found that it was difficult to recover information from the CLIP model, indicating that these diffusion models are unlikely to make it significantly easier to extract knowledge from CLIP compared to existing GAN models.
49
+
50
+ # Limitations
51
+
52
+ These models sometimes produce highly unrealistic outputs, particularly when generating images containing human faces.
53
+ This may stem from ImageNet's emphasis on non-human objects.
54
+
55
+ While classifier guidance can improve sample quality, it reduces diversity, resulting in some modes of the data distribution being underrepresented.
56
+ This can potentially amplify existing biases in the training dataset such as gender and racial biases.
57
+
58
+ Because ImageNet and LSUN contain images from the internet, they include photos of real people, and the model may have memorized some of the information contained in these photos.
59
+ However, these images are already publicly available, and existing generative models trained on ImageNet have not demonstrated significant leakage of this information.
editing_diffusion/guided_diffusion/scripts/classifier_sample.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Like image_sample.py, but use a noisy image classifier to guide the sampling
3
+ process towards more realistic images.
4
+ """
5
+
6
+ import argparse
7
+ import os
8
+
9
+ import numpy as np
10
+ import torch as th
11
+ import torch.distributed as dist
12
+ import torch.nn.functional as F
13
+
14
+ from guided_diffusion import dist_util, logger
15
+ from guided_diffusion.script_util import (
16
+ NUM_CLASSES,
17
+ model_and_diffusion_defaults,
18
+ classifier_defaults,
19
+ create_model_and_diffusion,
20
+ create_classifier,
21
+ add_dict_to_argparser,
22
+ args_to_dict,
23
+ )
24
+
25
+
26
+ def main():
27
+ args = create_argparser().parse_args()
28
+
29
+ dist_util.setup_dist()
30
+ logger.configure()
31
+
32
+ logger.log("creating model and diffusion...")
33
+ model, diffusion = create_model_and_diffusion(
34
+ **args_to_dict(args, model_and_diffusion_defaults().keys())
35
+ )
36
+ model.load_state_dict(
37
+ dist_util.load_state_dict(args.model_path, map_location="cpu")
38
+ )
39
+ model.to(dist_util.dev())
40
+ if args.use_fp16:
41
+ model.convert_to_fp16()
42
+ model.eval()
43
+
44
+ logger.log("loading classifier...")
45
+ classifier = create_classifier(**args_to_dict(args, classifier_defaults().keys()))
46
+ classifier.load_state_dict(
47
+ dist_util.load_state_dict(args.classifier_path, map_location="cpu")
48
+ )
49
+ classifier.to(dist_util.dev())
50
+ if args.classifier_use_fp16:
51
+ classifier.convert_to_fp16()
52
+ classifier.eval()
53
+
54
+ def cond_fn(x, t, y=None):
55
+ assert y is not None
56
+ with th.enable_grad():
57
+ x_in = x.detach().requires_grad_(True)
58
+ logits = classifier(x_in, t)
59
+ log_probs = F.log_softmax(logits, dim=-1)
60
+ selected = log_probs[range(len(logits)), y.view(-1)]
61
+ return th.autograd.grad(selected.sum(), x_in)[0] * args.classifier_scale
62
+
63
+ def model_fn(x, t, y=None):
64
+ assert y is not None
65
+ return model(x, t, y if args.class_cond else None)
66
+
67
+ logger.log("sampling...")
68
+ all_images = []
69
+ all_labels = []
70
+ while len(all_images) * args.batch_size < args.num_samples:
71
+ model_kwargs = {}
72
+ classes = th.randint(
73
+ low=0, high=NUM_CLASSES, size=(args.batch_size,), device=dist_util.dev()
74
+ )
75
+ model_kwargs["y"] = classes
76
+ sample_fn = (
77
+ diffusion.p_sample_loop if not args.use_ddim else diffusion.ddim_sample_loop
78
+ )
79
+ sample = sample_fn(
80
+ model_fn,
81
+ (args.batch_size, 3, args.image_size, args.image_size),
82
+ clip_denoised=args.clip_denoised,
83
+ model_kwargs=model_kwargs,
84
+ cond_fn=cond_fn,
85
+ device=dist_util.dev(),
86
+ )
87
+ sample = ((sample + 1) * 127.5).clamp(0, 255).to(th.uint8)
88
+ sample = sample.permute(0, 2, 3, 1)
89
+ sample = sample.contiguous()
90
+
91
+ gathered_samples = [th.zeros_like(sample) for _ in range(dist.get_world_size())]
92
+ dist.all_gather(gathered_samples, sample) # gather not supported with NCCL
93
+ all_images.extend([sample.cpu().numpy() for sample in gathered_samples])
94
+ gathered_labels = [th.zeros_like(classes) for _ in range(dist.get_world_size())]
95
+ dist.all_gather(gathered_labels, classes)
96
+ all_labels.extend([labels.cpu().numpy() for labels in gathered_labels])
97
+ logger.log(f"created {len(all_images) * args.batch_size} samples")
98
+
99
+ arr = np.concatenate(all_images, axis=0)
100
+ arr = arr[: args.num_samples]
101
+ label_arr = np.concatenate(all_labels, axis=0)
102
+ label_arr = label_arr[: args.num_samples]
103
+ if dist.get_rank() == 0:
104
+ shape_str = "x".join([str(x) for x in arr.shape])
105
+ out_path = os.path.join(logger.get_dir(), f"samples_{shape_str}.npz")
106
+ logger.log(f"saving to {out_path}")
107
+ np.savez(out_path, arr, label_arr)
108
+
109
+ dist.barrier()
110
+ logger.log("sampling complete")
111
+
112
+
113
+ def create_argparser():
114
+ defaults = dict(
115
+ clip_denoised=True,
116
+ num_samples=10000,
117
+ batch_size=16,
118
+ use_ddim=False,
119
+ model_path="",
120
+ classifier_path="",
121
+ classifier_scale=1.0,
122
+ )
123
+ defaults.update(model_and_diffusion_defaults())
124
+ defaults.update(classifier_defaults())
125
+ parser = argparse.ArgumentParser()
126
+ add_dict_to_argparser(parser, defaults)
127
+ return parser
128
+
129
+
130
+ if __name__ == "__main__":
131
+ main()
editing_diffusion/guided_diffusion/scripts/classifier_train.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Train a noised image classifier on ImageNet.
3
+ """
4
+
5
+ import argparse
6
+ import os
7
+
8
+ import blobfile as bf
9
+ import torch as th
10
+ import torch.distributed as dist
11
+ import torch.nn.functional as F
12
+ from torch.nn.parallel.distributed import DistributedDataParallel as DDP
13
+ from torch.optim import AdamW
14
+
15
+ from guided_diffusion import dist_util, logger
16
+ from guided_diffusion.fp16_util import MixedPrecisionTrainer
17
+ from guided_diffusion.image_datasets import load_data
18
+ from guided_diffusion.resample import create_named_schedule_sampler
19
+ from guided_diffusion.script_util import (
20
+ add_dict_to_argparser,
21
+ args_to_dict,
22
+ classifier_and_diffusion_defaults,
23
+ create_classifier_and_diffusion,
24
+ )
25
+ from guided_diffusion.train_util import parse_resume_step_from_filename, log_loss_dict
26
+
27
+
28
+ def main():
29
+ args = create_argparser().parse_args()
30
+
31
+ dist_util.setup_dist()
32
+ logger.configure()
33
+
34
+ logger.log("creating model and diffusion...")
35
+ model, diffusion = create_classifier_and_diffusion(
36
+ **args_to_dict(args, classifier_and_diffusion_defaults().keys())
37
+ )
38
+ model.to(dist_util.dev())
39
+ if args.noised:
40
+ schedule_sampler = create_named_schedule_sampler(
41
+ args.schedule_sampler, diffusion
42
+ )
43
+
44
+ resume_step = 0
45
+ if args.resume_checkpoint:
46
+ resume_step = parse_resume_step_from_filename(args.resume_checkpoint)
47
+ if dist.get_rank() == 0:
48
+ logger.log(
49
+ f"loading model from checkpoint: {args.resume_checkpoint}... at {resume_step} step"
50
+ )
51
+ model.load_state_dict(
52
+ dist_util.load_state_dict(
53
+ args.resume_checkpoint, map_location=dist_util.dev()
54
+ )
55
+ )
56
+
57
+ # Needed for creating correct EMAs and fp16 parameters.
58
+ dist_util.sync_params(model.parameters())
59
+
60
+ mp_trainer = MixedPrecisionTrainer(
61
+ model=model, use_fp16=args.classifier_use_fp16, initial_lg_loss_scale=16.0
62
+ )
63
+
64
+ model = DDP(
65
+ model,
66
+ device_ids=[dist_util.dev()],
67
+ output_device=dist_util.dev(),
68
+ broadcast_buffers=False,
69
+ bucket_cap_mb=128,
70
+ find_unused_parameters=False,
71
+ )
72
+
73
+ logger.log("creating data loader...")
74
+ data = load_data(
75
+ data_dir=args.data_dir,
76
+ batch_size=args.batch_size,
77
+ image_size=args.image_size,
78
+ class_cond=True,
79
+ random_crop=True,
80
+ )
81
+ if args.val_data_dir:
82
+ val_data = load_data(
83
+ data_dir=args.val_data_dir,
84
+ batch_size=args.batch_size,
85
+ image_size=args.image_size,
86
+ class_cond=True,
87
+ )
88
+ else:
89
+ val_data = None
90
+
91
+ logger.log(f"creating optimizer...")
92
+ opt = AdamW(mp_trainer.master_params, lr=args.lr, weight_decay=args.weight_decay)
93
+ if args.resume_checkpoint:
94
+ opt_checkpoint = bf.join(
95
+ bf.dirname(args.resume_checkpoint), f"opt{resume_step:06}.pt"
96
+ )
97
+ logger.log(f"loading optimizer state from checkpoint: {opt_checkpoint}")
98
+ opt.load_state_dict(
99
+ dist_util.load_state_dict(opt_checkpoint, map_location=dist_util.dev())
100
+ )
101
+
102
+ logger.log("training classifier model...")
103
+
104
+ def forward_backward_log(data_loader, prefix="train"):
105
+ batch, extra = next(data_loader)
106
+ labels = extra["y"].to(dist_util.dev())
107
+
108
+ batch = batch.to(dist_util.dev())
109
+ # Noisy images
110
+ if args.noised:
111
+ t, _ = schedule_sampler.sample(batch.shape[0], dist_util.dev())
112
+ batch = diffusion.q_sample(batch, t)
113
+ else:
114
+ t = th.zeros(batch.shape[0], dtype=th.long, device=dist_util.dev())
115
+
116
+ for i, (sub_batch, sub_labels, sub_t) in enumerate(
117
+ split_microbatches(args.microbatch, batch, labels, t)
118
+ ):
119
+ logits = model(sub_batch, timesteps=sub_t)
120
+ loss = F.cross_entropy(logits, sub_labels, reduction="none")
121
+
122
+ losses = {}
123
+ losses[f"{prefix}_loss"] = loss.detach()
124
+ losses[f"{prefix}_acc@1"] = compute_top_k(
125
+ logits, sub_labels, k=1, reduction="none"
126
+ )
127
+ losses[f"{prefix}_acc@5"] = compute_top_k(
128
+ logits, sub_labels, k=5, reduction="none"
129
+ )
130
+ log_loss_dict(diffusion, sub_t, losses)
131
+ del losses
132
+ loss = loss.mean()
133
+ if loss.requires_grad:
134
+ if i == 0:
135
+ mp_trainer.zero_grad()
136
+ mp_trainer.backward(loss * len(sub_batch) / len(batch))
137
+
138
+ for step in range(args.iterations - resume_step):
139
+ logger.logkv("step", step + resume_step)
140
+ logger.logkv(
141
+ "samples",
142
+ (step + resume_step + 1) * args.batch_size * dist.get_world_size(),
143
+ )
144
+ if args.anneal_lr:
145
+ set_annealed_lr(opt, args.lr, (step + resume_step) / args.iterations)
146
+ forward_backward_log(data)
147
+ mp_trainer.optimize(opt)
148
+ if val_data is not None and not step % args.eval_interval:
149
+ with th.no_grad():
150
+ with model.no_sync():
151
+ model.eval()
152
+ forward_backward_log(val_data, prefix="val")
153
+ model.train()
154
+ if not step % args.log_interval:
155
+ logger.dumpkvs()
156
+ if (
157
+ step
158
+ and dist.get_rank() == 0
159
+ and not (step + resume_step) % args.save_interval
160
+ ):
161
+ logger.log("saving model...")
162
+ save_model(mp_trainer, opt, step + resume_step)
163
+
164
+ if dist.get_rank() == 0:
165
+ logger.log("saving model...")
166
+ save_model(mp_trainer, opt, step + resume_step)
167
+ dist.barrier()
168
+
169
+
170
+ def set_annealed_lr(opt, base_lr, frac_done):
171
+ lr = base_lr * (1 - frac_done)
172
+ for param_group in opt.param_groups:
173
+ param_group["lr"] = lr
174
+
175
+
176
+ def save_model(mp_trainer, opt, step):
177
+ if dist.get_rank() == 0:
178
+ th.save(
179
+ mp_trainer.master_params_to_state_dict(mp_trainer.master_params),
180
+ os.path.join(logger.get_dir(), f"model{step:06d}.pt"),
181
+ )
182
+ th.save(opt.state_dict(), os.path.join(logger.get_dir(), f"opt{step:06d}.pt"))
183
+
184
+
185
+ def compute_top_k(logits, labels, k, reduction="mean"):
186
+ _, top_ks = th.topk(logits, k, dim=-1)
187
+ if reduction == "mean":
188
+ return (top_ks == labels[:, None]).float().sum(dim=-1).mean().item()
189
+ elif reduction == "none":
190
+ return (top_ks == labels[:, None]).float().sum(dim=-1)
191
+
192
+
193
+ def split_microbatches(microbatch, *args):
194
+ bs = len(args[0])
195
+ if microbatch == -1 or microbatch >= bs:
196
+ yield tuple(args)
197
+ else:
198
+ for i in range(0, bs, microbatch):
199
+ yield tuple(x[i : i + microbatch] if x is not None else None for x in args)
200
+
201
+
202
+ def create_argparser():
203
+ defaults = dict(
204
+ data_dir="",
205
+ val_data_dir="",
206
+ noised=True,
207
+ iterations=150000,
208
+ lr=3e-4,
209
+ weight_decay=0.0,
210
+ anneal_lr=False,
211
+ batch_size=4,
212
+ microbatch=-1,
213
+ schedule_sampler="uniform",
214
+ resume_checkpoint="",
215
+ log_interval=10,
216
+ eval_interval=5,
217
+ save_interval=10000,
218
+ )
219
+ defaults.update(classifier_and_diffusion_defaults())
220
+ parser = argparse.ArgumentParser()
221
+ add_dict_to_argparser(parser, defaults)
222
+ return parser
223
+
224
+
225
+ if __name__ == "__main__":
226
+ main()
editing_diffusion/guided_diffusion/scripts/image_nll.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Approximate the bits/dimension for an image model.
3
+ """
4
+
5
+ import argparse
6
+ import os
7
+
8
+ import numpy as np
9
+ import torch.distributed as dist
10
+
11
+ from guided_diffusion import dist_util, logger
12
+ from guided_diffusion.image_datasets import load_data
13
+ from guided_diffusion.script_util import (
14
+ model_and_diffusion_defaults,
15
+ create_model_and_diffusion,
16
+ add_dict_to_argparser,
17
+ args_to_dict,
18
+ )
19
+
20
+
21
+ def main():
22
+ args = create_argparser().parse_args()
23
+
24
+ dist_util.setup_dist()
25
+ logger.configure()
26
+
27
+ logger.log("creating model and diffusion...")
28
+ model, diffusion = create_model_and_diffusion(
29
+ **args_to_dict(args, model_and_diffusion_defaults().keys())
30
+ )
31
+ model.load_state_dict(
32
+ dist_util.load_state_dict(args.model_path, map_location="cpu")
33
+ )
34
+ model.to(dist_util.dev())
35
+ model.eval()
36
+
37
+ logger.log("creating data loader...")
38
+ data = load_data(
39
+ data_dir=args.data_dir,
40
+ batch_size=args.batch_size,
41
+ image_size=args.image_size,
42
+ class_cond=args.class_cond,
43
+ deterministic=True,
44
+ )
45
+
46
+ logger.log("evaluating...")
47
+ run_bpd_evaluation(model, diffusion, data, args.num_samples, args.clip_denoised)
48
+
49
+
50
+ def run_bpd_evaluation(model, diffusion, data, num_samples, clip_denoised):
51
+ all_bpd = []
52
+ all_metrics = {"vb": [], "mse": [], "xstart_mse": []}
53
+ num_complete = 0
54
+ while num_complete < num_samples:
55
+ batch, model_kwargs = next(data)
56
+ batch = batch.to(dist_util.dev())
57
+ model_kwargs = {k: v.to(dist_util.dev()) for k, v in model_kwargs.items()}
58
+ minibatch_metrics = diffusion.calc_bpd_loop(
59
+ model, batch, clip_denoised=clip_denoised, model_kwargs=model_kwargs
60
+ )
61
+
62
+ for key, term_list in all_metrics.items():
63
+ terms = minibatch_metrics[key].mean(dim=0) / dist.get_world_size()
64
+ dist.all_reduce(terms)
65
+ term_list.append(terms.detach().cpu().numpy())
66
+
67
+ total_bpd = minibatch_metrics["total_bpd"]
68
+ total_bpd = total_bpd.mean() / dist.get_world_size()
69
+ dist.all_reduce(total_bpd)
70
+ all_bpd.append(total_bpd.item())
71
+ num_complete += dist.get_world_size() * batch.shape[0]
72
+
73
+ logger.log(f"done {num_complete} samples: bpd={np.mean(all_bpd)}")
74
+
75
+ if dist.get_rank() == 0:
76
+ for name, terms in all_metrics.items():
77
+ out_path = os.path.join(logger.get_dir(), f"{name}_terms.npz")
78
+ logger.log(f"saving {name} terms to {out_path}")
79
+ np.savez(out_path, np.mean(np.stack(terms), axis=0))
80
+
81
+ dist.barrier()
82
+ logger.log("evaluation complete")
83
+
84
+
85
+ def create_argparser():
86
+ defaults = dict(
87
+ data_dir="", clip_denoised=True, num_samples=1000, batch_size=1, model_path=""
88
+ )
89
+ defaults.update(model_and_diffusion_defaults())
90
+ parser = argparse.ArgumentParser()
91
+ add_dict_to_argparser(parser, defaults)
92
+ return parser
93
+
94
+
95
+ if __name__ == "__main__":
96
+ main()
editing_diffusion/guided_diffusion/scripts/image_sample.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generate a large batch of image samples from a model and save them as a large
3
+ numpy array. This can be used to produce samples for FID evaluation.
4
+ """
5
+
6
+ import argparse
7
+ import os
8
+
9
+ import numpy as np
10
+ import torch as th
11
+ import torch.distributed as dist
12
+
13
+ from guided_diffusion import dist_util, logger
14
+ from guided_diffusion.script_util import (
15
+ NUM_CLASSES,
16
+ model_and_diffusion_defaults,
17
+ create_model_and_diffusion,
18
+ add_dict_to_argparser,
19
+ args_to_dict,
20
+ )
21
+
22
+
23
+ def main():
24
+ args = create_argparser().parse_args()
25
+
26
+ dist_util.setup_dist()
27
+ logger.configure()
28
+
29
+ logger.log("creating model and diffusion...")
30
+ model, diffusion = create_model_and_diffusion(
31
+ **args_to_dict(args, model_and_diffusion_defaults().keys())
32
+ )
33
+ model.load_state_dict(
34
+ dist_util.load_state_dict(args.model_path, map_location="cpu")
35
+ )
36
+ model.to(dist_util.dev())
37
+ if args.use_fp16:
38
+ model.convert_to_fp16()
39
+ model.eval()
40
+
41
+ logger.log("sampling...")
42
+ all_images = []
43
+ all_labels = []
44
+ while len(all_images) * args.batch_size < args.num_samples:
45
+ model_kwargs = {}
46
+ if args.class_cond:
47
+ classes = th.randint(
48
+ low=0, high=NUM_CLASSES, size=(args.batch_size,), device=dist_util.dev()
49
+ )
50
+ model_kwargs["y"] = classes
51
+ sample_fn = (
52
+ diffusion.p_sample_loop if not args.use_ddim else diffusion.ddim_sample_loop
53
+ )
54
+ sample = sample_fn(
55
+ model,
56
+ (args.batch_size, 3, args.image_size, args.image_size),
57
+ clip_denoised=args.clip_denoised,
58
+ model_kwargs=model_kwargs,
59
+ )
60
+ sample = ((sample + 1) * 127.5).clamp(0, 255).to(th.uint8)
61
+ sample = sample.permute(0, 2, 3, 1)
62
+ sample = sample.contiguous()
63
+
64
+ gathered_samples = [th.zeros_like(sample) for _ in range(dist.get_world_size())]
65
+ dist.all_gather(gathered_samples, sample) # gather not supported with NCCL
66
+ all_images.extend([sample.cpu().numpy() for sample in gathered_samples])
67
+ if args.class_cond:
68
+ gathered_labels = [
69
+ th.zeros_like(classes) for _ in range(dist.get_world_size())
70
+ ]
71
+ dist.all_gather(gathered_labels, classes)
72
+ all_labels.extend([labels.cpu().numpy() for labels in gathered_labels])
73
+ logger.log(f"created {len(all_images) * args.batch_size} samples")
74
+
75
+ arr = np.concatenate(all_images, axis=0)
76
+ arr = arr[: args.num_samples]
77
+ if args.class_cond:
78
+ label_arr = np.concatenate(all_labels, axis=0)
79
+ label_arr = label_arr[: args.num_samples]
80
+ if dist.get_rank() == 0:
81
+ shape_str = "x".join([str(x) for x in arr.shape])
82
+ out_path = os.path.join(logger.get_dir(), f"samples_{shape_str}.npz")
83
+ logger.log(f"saving to {out_path}")
84
+ if args.class_cond:
85
+ np.savez(out_path, arr, label_arr)
86
+ else:
87
+ np.savez(out_path, arr)
88
+
89
+ dist.barrier()
90
+ logger.log("sampling complete")
91
+
92
+
93
+ def create_argparser():
94
+ defaults = dict(
95
+ clip_denoised=True,
96
+ num_samples=10000,
97
+ batch_size=16,
98
+ use_ddim=False,
99
+ model_path="",
100
+ )
101
+ defaults.update(model_and_diffusion_defaults())
102
+ parser = argparse.ArgumentParser()
103
+ add_dict_to_argparser(parser, defaults)
104
+ return parser
105
+
106
+
107
+ if __name__ == "__main__":
108
+ main()
editing_diffusion/guided_diffusion/scripts/image_train.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Train a diffusion model on images.
3
+ """
4
+
5
+ import argparse
6
+
7
+ from guided_diffusion import dist_util, logger
8
+ from guided_diffusion.image_datasets import load_data
9
+ from guided_diffusion.resample import create_named_schedule_sampler
10
+ from guided_diffusion.script_util import (
11
+ model_and_diffusion_defaults,
12
+ create_model_and_diffusion,
13
+ args_to_dict,
14
+ add_dict_to_argparser,
15
+ )
16
+ from guided_diffusion.train_util import TrainLoop
17
+
18
+
19
+ def main():
20
+ args = create_argparser().parse_args()
21
+
22
+ dist_util.setup_dist()
23
+ logger.configure()
24
+
25
+ logger.log("creating model and diffusion...")
26
+ model, diffusion = create_model_and_diffusion(
27
+ **args_to_dict(args, model_and_diffusion_defaults().keys())
28
+ )
29
+ model.to(dist_util.dev())
30
+ schedule_sampler = create_named_schedule_sampler(args.schedule_sampler, diffusion)
31
+
32
+ logger.log("creating data loader...")
33
+ data = load_data(
34
+ data_dir=args.data_dir,
35
+ batch_size=args.batch_size,
36
+ image_size=args.image_size,
37
+ class_cond=args.class_cond,
38
+ )
39
+
40
+ logger.log("training...")
41
+ TrainLoop(
42
+ model=model,
43
+ diffusion=diffusion,
44
+ data=data,
45
+ batch_size=args.batch_size,
46
+ microbatch=args.microbatch,
47
+ lr=args.lr,
48
+ ema_rate=args.ema_rate,
49
+ log_interval=args.log_interval,
50
+ save_interval=args.save_interval,
51
+ resume_checkpoint=args.resume_checkpoint,
52
+ use_fp16=args.use_fp16,
53
+ fp16_scale_growth=args.fp16_scale_growth,
54
+ schedule_sampler=schedule_sampler,
55
+ weight_decay=args.weight_decay,
56
+ lr_anneal_steps=args.lr_anneal_steps,
57
+ ).run_loop()
58
+
59
+
60
+ def create_argparser():
61
+ defaults = dict(
62
+ data_dir="",
63
+ schedule_sampler="uniform",
64
+ lr=1e-4,
65
+ weight_decay=0.0,
66
+ lr_anneal_steps=0,
67
+ batch_size=1,
68
+ microbatch=-1, # -1 disables microbatches
69
+ ema_rate="0.9999", # comma-separated list of EMA values
70
+ log_interval=10,
71
+ save_interval=10000,
72
+ resume_checkpoint="",
73
+ use_fp16=False,
74
+ fp16_scale_growth=1e-3,
75
+ )
76
+ defaults.update(model_and_diffusion_defaults())
77
+ parser = argparse.ArgumentParser()
78
+ add_dict_to_argparser(parser, defaults)
79
+ return parser
80
+
81
+
82
+ if __name__ == "__main__":
83
+ main()
editing_diffusion/guided_diffusion/scripts/super_res_sample.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generate a large batch of samples from a super resolution model, given a batch
3
+ of samples from a regular model from image_sample.py.
4
+ """
5
+
6
+ import argparse
7
+ import os
8
+
9
+ import blobfile as bf
10
+ import numpy as np
11
+ import torch as th
12
+ import torch.distributed as dist
13
+
14
+ from guided_diffusion import dist_util, logger
15
+ from guided_diffusion.script_util import (
16
+ sr_model_and_diffusion_defaults,
17
+ sr_create_model_and_diffusion,
18
+ args_to_dict,
19
+ add_dict_to_argparser,
20
+ )
21
+
22
+
23
+ def main():
24
+ args = create_argparser().parse_args()
25
+
26
+ dist_util.setup_dist()
27
+ logger.configure()
28
+
29
+ logger.log("creating model...")
30
+ model, diffusion = sr_create_model_and_diffusion(
31
+ **args_to_dict(args, sr_model_and_diffusion_defaults().keys())
32
+ )
33
+ model.load_state_dict(
34
+ dist_util.load_state_dict(args.model_path, map_location="cpu")
35
+ )
36
+ model.to(dist_util.dev())
37
+ if args.use_fp16:
38
+ model.convert_to_fp16()
39
+ model.eval()
40
+
41
+ logger.log("loading data...")
42
+ data = load_data_for_worker(args.base_samples, args.batch_size, args.class_cond)
43
+
44
+ logger.log("creating samples...")
45
+ all_images = []
46
+ while len(all_images) * args.batch_size < args.num_samples:
47
+ model_kwargs = next(data)
48
+ model_kwargs = {k: v.to(dist_util.dev()) for k, v in model_kwargs.items()}
49
+ sample = diffusion.p_sample_loop(
50
+ model,
51
+ (args.batch_size, 3, args.large_size, args.large_size),
52
+ clip_denoised=args.clip_denoised,
53
+ model_kwargs=model_kwargs,
54
+ )
55
+ sample = ((sample + 1) * 127.5).clamp(0, 255).to(th.uint8)
56
+ sample = sample.permute(0, 2, 3, 1)
57
+ sample = sample.contiguous()
58
+
59
+ all_samples = [th.zeros_like(sample) for _ in range(dist.get_world_size())]
60
+ dist.all_gather(all_samples, sample) # gather not supported with NCCL
61
+ for sample in all_samples:
62
+ all_images.append(sample.cpu().numpy())
63
+ logger.log(f"created {len(all_images) * args.batch_size} samples")
64
+
65
+ arr = np.concatenate(all_images, axis=0)
66
+ arr = arr[: args.num_samples]
67
+ if dist.get_rank() == 0:
68
+ shape_str = "x".join([str(x) for x in arr.shape])
69
+ out_path = os.path.join(logger.get_dir(), f"samples_{shape_str}.npz")
70
+ logger.log(f"saving to {out_path}")
71
+ np.savez(out_path, arr)
72
+
73
+ dist.barrier()
74
+ logger.log("sampling complete")
75
+
76
+
77
+ def load_data_for_worker(base_samples, batch_size, class_cond):
78
+ with bf.BlobFile(base_samples, "rb") as f:
79
+ obj = np.load(f)
80
+ image_arr = obj["arr_0"]
81
+ if class_cond:
82
+ label_arr = obj["arr_1"]
83
+ rank = dist.get_rank()
84
+ num_ranks = dist.get_world_size()
85
+ buffer = []
86
+ label_buffer = []
87
+ while True:
88
+ for i in range(rank, len(image_arr), num_ranks):
89
+ buffer.append(image_arr[i])
90
+ if class_cond:
91
+ label_buffer.append(label_arr[i])
92
+ if len(buffer) == batch_size:
93
+ batch = th.from_numpy(np.stack(buffer)).float()
94
+ batch = batch / 127.5 - 1.0
95
+ batch = batch.permute(0, 3, 1, 2)
96
+ res = dict(low_res=batch)
97
+ if class_cond:
98
+ res["y"] = th.from_numpy(np.stack(label_buffer))
99
+ yield res
100
+ buffer, label_buffer = [], []
101
+
102
+
103
+ def create_argparser():
104
+ defaults = dict(
105
+ clip_denoised=True,
106
+ num_samples=10000,
107
+ batch_size=16,
108
+ use_ddim=False,
109
+ base_samples="",
110
+ model_path="",
111
+ )
112
+ defaults.update(sr_model_and_diffusion_defaults())
113
+ parser = argparse.ArgumentParser()
114
+ add_dict_to_argparser(parser, defaults)
115
+ return parser
116
+
117
+
118
+ if __name__ == "__main__":
119
+ main()
editing_diffusion/guided_diffusion/scripts/super_res_train.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Train a super-resolution model.
3
+ """
4
+
5
+ import argparse
6
+
7
+ import torch.nn.functional as F
8
+
9
+ from guided_diffusion import dist_util, logger
10
+ from guided_diffusion.image_datasets import load_data
11
+ from guided_diffusion.resample import create_named_schedule_sampler
12
+ from guided_diffusion.script_util import (
13
+ sr_model_and_diffusion_defaults,
14
+ sr_create_model_and_diffusion,
15
+ args_to_dict,
16
+ add_dict_to_argparser,
17
+ )
18
+ from guided_diffusion.train_util import TrainLoop
19
+
20
+
21
+ def main():
22
+ args = create_argparser().parse_args()
23
+
24
+ dist_util.setup_dist()
25
+ logger.configure()
26
+
27
+ logger.log("creating model...")
28
+ model, diffusion = sr_create_model_and_diffusion(
29
+ **args_to_dict(args, sr_model_and_diffusion_defaults().keys())
30
+ )
31
+ model.to(dist_util.dev())
32
+ schedule_sampler = create_named_schedule_sampler(args.schedule_sampler, diffusion)
33
+
34
+ logger.log("creating data loader...")
35
+ data = load_superres_data(
36
+ args.data_dir,
37
+ args.batch_size,
38
+ large_size=args.large_size,
39
+ small_size=args.small_size,
40
+ class_cond=args.class_cond,
41
+ )
42
+
43
+ logger.log("training...")
44
+ TrainLoop(
45
+ model=model,
46
+ diffusion=diffusion,
47
+ data=data,
48
+ batch_size=args.batch_size,
49
+ microbatch=args.microbatch,
50
+ lr=args.lr,
51
+ ema_rate=args.ema_rate,
52
+ log_interval=args.log_interval,
53
+ save_interval=args.save_interval,
54
+ resume_checkpoint=args.resume_checkpoint,
55
+ use_fp16=args.use_fp16,
56
+ fp16_scale_growth=args.fp16_scale_growth,
57
+ schedule_sampler=schedule_sampler,
58
+ weight_decay=args.weight_decay,
59
+ lr_anneal_steps=args.lr_anneal_steps,
60
+ ).run_loop()
61
+
62
+
63
+ def load_superres_data(data_dir, batch_size, large_size, small_size, class_cond=False):
64
+ data = load_data(
65
+ data_dir=data_dir,
66
+ batch_size=batch_size,
67
+ image_size=large_size,
68
+ class_cond=class_cond,
69
+ )
70
+ for large_batch, model_kwargs in data:
71
+ model_kwargs["low_res"] = F.interpolate(large_batch, small_size, mode="area")
72
+ yield large_batch, model_kwargs
73
+
74
+
75
+ def create_argparser():
76
+ defaults = dict(
77
+ data_dir="",
78
+ schedule_sampler="uniform",
79
+ lr=1e-4,
80
+ weight_decay=0.0,
81
+ lr_anneal_steps=0,
82
+ batch_size=1,
83
+ microbatch=-1,
84
+ ema_rate="0.9999",
85
+ log_interval=10,
86
+ save_interval=10000,
87
+ resume_checkpoint="",
88
+ use_fp16=False,
89
+ fp16_scale_growth=1e-3,
90
+ )
91
+ defaults.update(sr_model_and_diffusion_defaults())
92
+ parser = argparse.ArgumentParser()
93
+ add_dict_to_argparser(parser, defaults)
94
+ return parser
95
+
96
+
97
+ if __name__ == "__main__":
98
+ main()
editing_diffusion/guided_diffusion/setup.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from setuptools import setup
2
+
3
+ setup(
4
+ name="guided-diffusion",
5
+ py_modules=["guided_diffusion"],
6
+ install_requires=["blobfile>=1.0.5", "torch", "tqdm"],
7
+ )
editing_diffusion/main.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from optimization.image_editor import ImageEditor
2
+ from optimization.arguments import get_arguments
3
+
4
+
5
+ if __name__ == "__main__":
6
+ args = get_arguments()
7
+ image_editor = ImageEditor(args)
8
+ image_editor.edit_image_by_prompt()
9
+ # image_editor.reconstruct_image()