Moyao001 commited on
Commit
bd4eea7
·
verified ·
1 Parent(s): fd1d3dc

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. CCEdit-main/src/clip/.github/workflows/test.yml +33 -0
  2. CCEdit-main/src/clip/.gitignore +10 -0
  3. CCEdit-main/src/clip/LICENSE +22 -0
  4. CCEdit-main/src/clip/MANIFEST.in +1 -0
  5. CCEdit-main/src/clip/README.md +199 -0
  6. CCEdit-main/src/clip/clip.egg-info/PKG-INFO +16 -0
  7. CCEdit-main/src/clip/clip.egg-info/SOURCES.txt +15 -0
  8. CCEdit-main/src/clip/clip.egg-info/dependency_links.txt +1 -0
  9. CCEdit-main/src/clip/clip.egg-info/requires.txt +9 -0
  10. CCEdit-main/src/clip/clip.egg-info/top_level.txt +1 -0
  11. CCEdit-main/src/clip/clip/model.py +436 -0
  12. CCEdit-main/src/clip/data/yfcc100m.md +14 -0
  13. CCEdit-main/src/clip/hubconf.py +42 -0
  14. CCEdit-main/src/clip/model-card.md +120 -0
  15. CCEdit-main/src/clip/notebooks/Interacting_with_CLIP.ipynb +0 -0
  16. CCEdit-main/src/clip/notebooks/Prompt_Engineering_for_ImageNet.ipynb +1107 -0
  17. CCEdit-main/src/clip/requirements.txt +6 -0
  18. CCEdit-main/src/clip/setup.py +21 -0
  19. CCEdit-main/src/clip/tests/test_consistency.py +25 -0
  20. CCEdit-main/src/pnp-diffusers/README.md +60 -0
  21. CCEdit-main/src/pnp-diffusers/config_pnp.yaml +19 -0
  22. CCEdit-main/src/pnp-diffusers/pnp_utils.py +153 -0
  23. CCEdit-main/src/pnp-diffusers/preprocess.py +216 -0
  24. CCEdit-main/src/pnp-diffusers/requirements.txt +7 -0
  25. CCEdit-main/src/sdata/LICENSE +21 -0
  26. CCEdit-main/src/sdata/examples/configs/example.yaml +31 -0
  27. CCEdit-main/src/sdata/examples/image_simple.py +37 -0
  28. CCEdit-main/src/sdata/requirements_pt1.txt +13 -0
  29. CCEdit-main/src/sdata/sdata.egg-info/PKG-INFO +4 -0
  30. CCEdit-main/src/sdata/sdata.egg-info/SOURCES.txt +19 -0
  31. CCEdit-main/src/sdata/sdata.egg-info/dependency_links.txt +1 -0
  32. CCEdit-main/src/sdata/sdata.egg-info/top_level.txt +1 -0
  33. CCEdit-main/src/sdata/sdata/__init__.py +14 -0
  34. CCEdit-main/src/sdata/sdata/__pycache__/__init__.cpython-39.pyc +0 -0
  35. CCEdit-main/src/sdata/sdata/__pycache__/custom_datapipes.cpython-39.pyc +0 -0
  36. CCEdit-main/src/sdata/sdata/__pycache__/datapipeline.cpython-39.pyc +0 -0
  37. CCEdit-main/src/sdata/sdata/__pycache__/dataset.cpython-39.pyc +0 -0
  38. CCEdit-main/src/sdata/sdata/__pycache__/dummy.cpython-39.pyc +0 -0
  39. CCEdit-main/src/sdata/sdata/datapipeline.py +536 -0
  40. CCEdit-main/src/sdata/sdata/filters/__init__.py +12 -0
  41. CCEdit-main/src/sdata/sdata/filters/__pycache__/__init__.cpython-39.pyc +0 -0
  42. CCEdit-main/src/sdata/sdata/filters/__pycache__/base.cpython-39.pyc +0 -0
  43. CCEdit-main/src/sdata/sdata/filters/__pycache__/metadata_filters.cpython-39.pyc +0 -0
  44. CCEdit-main/src/sdata/sdata/filters/base.py +64 -0
  45. CCEdit-main/src/sdata/sdata/filters/metadata_filters.py +104 -0
  46. CCEdit-main/src/sdata/sdata/mappers/__init__.py +15 -0
  47. CCEdit-main/src/sdata/sdata/mappers/__pycache__/__init__.cpython-39.pyc +0 -0
  48. CCEdit-main/src/sdata/sdata/mappers/__pycache__/base.cpython-39.pyc +0 -0
  49. CCEdit-main/src/sdata/sdata/mappers/__pycache__/batched_mappers.cpython-39.pyc +0 -0
  50. CCEdit-main/src/sdata/sdata/mappers/__pycache__/sample_mappers.cpython-39.pyc +0 -0
CCEdit-main/src/clip/.github/workflows/test.yml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: test
2
+ on:
3
+ push:
4
+ branches:
5
+ - main
6
+ pull_request:
7
+ branches:
8
+ - main
9
+ jobs:
10
+ CLIP-test:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ matrix:
14
+ python-version: [3.8]
15
+ pytorch-version: [1.7.1, 1.9.1, 1.10.1]
16
+ include:
17
+ - python-version: 3.8
18
+ pytorch-version: 1.7.1
19
+ torchvision-version: 0.8.2
20
+ - python-version: 3.8
21
+ pytorch-version: 1.9.1
22
+ torchvision-version: 0.10.1
23
+ - python-version: 3.8
24
+ pytorch-version: 1.10.1
25
+ torchvision-version: 0.11.2
26
+ steps:
27
+ - uses: conda-incubator/setup-miniconda@v2
28
+ - run: conda install -n test python=${{ matrix.python-version }} pytorch=${{ matrix.pytorch-version }} torchvision=${{ matrix.torchvision-version }} cpuonly -c pytorch
29
+ - uses: actions/checkout@v2
30
+ - run: echo "$CONDA/envs/test/bin" >> $GITHUB_PATH
31
+ - run: pip install pytest
32
+ - run: pip install .
33
+ - run: pytest
CCEdit-main/src/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
CCEdit-main/src/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
+
CCEdit-main/src/clip/MANIFEST.in ADDED
@@ -0,0 +1 @@
 
 
1
+ include clip/bpe_simple_vocab_16e6.txt.gz
CCEdit-main/src/clip/README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/) (or later) 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(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.
194
+
195
+
196
+ ## See Also
197
+
198
+ * [OpenCLIP](https://github.com/mlfoundations/open_clip): includes larger and independently trained CLIP models up to ViT-G/14
199
+ * [Hugging Face implementation of CLIP](https://huggingface.co/docs/transformers/model_doc/clip): for easier integration with the HF ecosystem
CCEdit-main/src/clip/clip.egg-info/PKG-INFO ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.2
2
+ Name: clip
3
+ Version: 1.0
4
+ Author: OpenAI
5
+ License-File: LICENSE
6
+ Requires-Dist: ftfy
7
+ Requires-Dist: packaging
8
+ Requires-Dist: regex
9
+ Requires-Dist: tqdm
10
+ Requires-Dist: torch
11
+ Requires-Dist: torchvision
12
+ Provides-Extra: dev
13
+ Requires-Dist: pytest; extra == "dev"
14
+ Dynamic: author
15
+ Dynamic: provides-extra
16
+ Dynamic: requires-dist
CCEdit-main/src/clip/clip.egg-info/SOURCES.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ setup.py
5
+ clip/__init__.py
6
+ clip/bpe_simple_vocab_16e6.txt.gz
7
+ clip/clip.py
8
+ clip/model.py
9
+ clip/simple_tokenizer.py
10
+ clip.egg-info/PKG-INFO
11
+ clip.egg-info/SOURCES.txt
12
+ clip.egg-info/dependency_links.txt
13
+ clip.egg-info/requires.txt
14
+ clip.egg-info/top_level.txt
15
+ tests/test_consistency.py
CCEdit-main/src/clip/clip.egg-info/dependency_links.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
CCEdit-main/src/clip/clip.egg-info/requires.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ ftfy
2
+ packaging
3
+ regex
4
+ tqdm
5
+ torch
6
+ torchvision
7
+
8
+ [dev]
9
+ pytest
CCEdit-main/src/clip/clip.egg-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ clip
CCEdit-main/src/clip/clip/model.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ self.relu1 = nn.ReLU(inplace=True)
20
+
21
+ self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
22
+ self.bn2 = nn.BatchNorm2d(planes)
23
+ self.relu2 = nn.ReLU(inplace=True)
24
+
25
+ self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
26
+
27
+ self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
28
+ self.bn3 = nn.BatchNorm2d(planes * self.expansion)
29
+ self.relu3 = nn.ReLU(inplace=True)
30
+
31
+ self.downsample = None
32
+ self.stride = stride
33
+
34
+ if stride > 1 or inplanes != planes * Bottleneck.expansion:
35
+ # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
36
+ self.downsample = nn.Sequential(OrderedDict([
37
+ ("-1", nn.AvgPool2d(stride)),
38
+ ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
39
+ ("1", nn.BatchNorm2d(planes * self.expansion))
40
+ ]))
41
+
42
+ def forward(self, x: torch.Tensor):
43
+ identity = x
44
+
45
+ out = self.relu1(self.bn1(self.conv1(x)))
46
+ out = self.relu2(self.bn2(self.conv2(out)))
47
+ out = self.avgpool(out)
48
+ out = self.bn3(self.conv3(out))
49
+
50
+ if self.downsample is not None:
51
+ identity = self.downsample(x)
52
+
53
+ out += identity
54
+ out = self.relu3(out)
55
+ return out
56
+
57
+
58
+ class AttentionPool2d(nn.Module):
59
+ def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
60
+ super().__init__()
61
+ self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
62
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
63
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
64
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
65
+ self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
66
+ self.num_heads = num_heads
67
+
68
+ def forward(self, x):
69
+ x = x.flatten(start_dim=2).permute(2, 0, 1) # NCHW -> (HW)NC
70
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
71
+ x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
72
+ x, _ = F.multi_head_attention_forward(
73
+ query=x[:1], key=x, value=x,
74
+ embed_dim_to_check=x.shape[-1],
75
+ num_heads=self.num_heads,
76
+ q_proj_weight=self.q_proj.weight,
77
+ k_proj_weight=self.k_proj.weight,
78
+ v_proj_weight=self.v_proj.weight,
79
+ in_proj_weight=None,
80
+ in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
81
+ bias_k=None,
82
+ bias_v=None,
83
+ add_zero_attn=False,
84
+ dropout_p=0,
85
+ out_proj_weight=self.c_proj.weight,
86
+ out_proj_bias=self.c_proj.bias,
87
+ use_separate_proj_weight=True,
88
+ training=self.training,
89
+ need_weights=False
90
+ )
91
+ return x.squeeze(0)
92
+
93
+
94
+ class ModifiedResNet(nn.Module):
95
+ """
96
+ A ResNet class that is similar to torchvision's but contains the following changes:
97
+ - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
98
+ - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
99
+ - The final pooling layer is a QKV attention instead of an average pool
100
+ """
101
+
102
+ def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
103
+ super().__init__()
104
+ self.output_dim = output_dim
105
+ self.input_resolution = input_resolution
106
+
107
+ # the 3-layer stem
108
+ self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
109
+ self.bn1 = nn.BatchNorm2d(width // 2)
110
+ self.relu1 = nn.ReLU(inplace=True)
111
+ self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
112
+ self.bn2 = nn.BatchNorm2d(width // 2)
113
+ self.relu2 = nn.ReLU(inplace=True)
114
+ self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
115
+ self.bn3 = nn.BatchNorm2d(width)
116
+ self.relu3 = nn.ReLU(inplace=True)
117
+ self.avgpool = nn.AvgPool2d(2)
118
+
119
+ # residual layers
120
+ self._inplanes = width # this is a *mutable* variable used during construction
121
+ self.layer1 = self._make_layer(width, layers[0])
122
+ self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
123
+ self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
124
+ self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
125
+
126
+ embed_dim = width * 32 # the ResNet feature dimension
127
+ self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
128
+
129
+ def _make_layer(self, planes, blocks, stride=1):
130
+ layers = [Bottleneck(self._inplanes, planes, stride)]
131
+
132
+ self._inplanes = planes * Bottleneck.expansion
133
+ for _ in range(1, blocks):
134
+ layers.append(Bottleneck(self._inplanes, planes))
135
+
136
+ return nn.Sequential(*layers)
137
+
138
+ def forward(self, x):
139
+ def stem(x):
140
+ x = self.relu1(self.bn1(self.conv1(x)))
141
+ x = self.relu2(self.bn2(self.conv2(x)))
142
+ x = self.relu3(self.bn3(self.conv3(x)))
143
+ x = self.avgpool(x)
144
+ return x
145
+
146
+ x = x.type(self.conv1.weight.dtype)
147
+ x = stem(x)
148
+ x = self.layer1(x)
149
+ x = self.layer2(x)
150
+ x = self.layer3(x)
151
+ x = self.layer4(x)
152
+ x = self.attnpool(x)
153
+
154
+ return x
155
+
156
+
157
+ class LayerNorm(nn.LayerNorm):
158
+ """Subclass torch's LayerNorm to handle fp16."""
159
+
160
+ def forward(self, x: torch.Tensor):
161
+ orig_type = x.dtype
162
+ ret = super().forward(x.type(torch.float32))
163
+ return ret.type(orig_type)
164
+
165
+
166
+ class QuickGELU(nn.Module):
167
+ def forward(self, x: torch.Tensor):
168
+ return x * torch.sigmoid(1.702 * x)
169
+
170
+
171
+ class ResidualAttentionBlock(nn.Module):
172
+ def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
173
+ super().__init__()
174
+
175
+ self.attn = nn.MultiheadAttention(d_model, n_head)
176
+ self.ln_1 = LayerNorm(d_model)
177
+ self.mlp = nn.Sequential(OrderedDict([
178
+ ("c_fc", nn.Linear(d_model, d_model * 4)),
179
+ ("gelu", QuickGELU()),
180
+ ("c_proj", nn.Linear(d_model * 4, d_model))
181
+ ]))
182
+ self.ln_2 = LayerNorm(d_model)
183
+ self.attn_mask = attn_mask
184
+
185
+ def attention(self, x: torch.Tensor):
186
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
187
+ return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
188
+
189
+ def forward(self, x: torch.Tensor):
190
+ x = x + self.attention(self.ln_1(x))
191
+ x = x + self.mlp(self.ln_2(x))
192
+ return x
193
+
194
+
195
+ class Transformer(nn.Module):
196
+ def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
197
+ super().__init__()
198
+ self.width = width
199
+ self.layers = layers
200
+ self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
201
+
202
+ def forward(self, x: torch.Tensor):
203
+ return self.resblocks(x)
204
+
205
+
206
+ class VisionTransformer(nn.Module):
207
+ def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
208
+ super().__init__()
209
+ self.input_resolution = input_resolution
210
+ self.output_dim = output_dim
211
+ self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
212
+
213
+ scale = width ** -0.5
214
+ self.class_embedding = nn.Parameter(scale * torch.randn(width))
215
+ self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
216
+ self.ln_pre = LayerNorm(width)
217
+
218
+ self.transformer = Transformer(width, layers, heads)
219
+
220
+ self.ln_post = LayerNorm(width)
221
+ self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
222
+
223
+ def forward(self, x: torch.Tensor):
224
+ x = self.conv1(x) # shape = [*, width, grid, grid]
225
+ x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
226
+ x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
227
+ 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]
228
+ x = x + self.positional_embedding.to(x.dtype)
229
+ x = self.ln_pre(x)
230
+
231
+ x = x.permute(1, 0, 2) # NLD -> LND
232
+ x = self.transformer(x)
233
+ x = x.permute(1, 0, 2) # LND -> NLD
234
+
235
+ x = self.ln_post(x[:, 0, :])
236
+
237
+ if self.proj is not None:
238
+ x = x @ self.proj
239
+
240
+ return x
241
+
242
+
243
+ class CLIP(nn.Module):
244
+ def __init__(self,
245
+ embed_dim: int,
246
+ # vision
247
+ image_resolution: int,
248
+ vision_layers: Union[Tuple[int, int, int, int], int],
249
+ vision_width: int,
250
+ vision_patch_size: int,
251
+ # text
252
+ context_length: int,
253
+ vocab_size: int,
254
+ transformer_width: int,
255
+ transformer_heads: int,
256
+ transformer_layers: int
257
+ ):
258
+ super().__init__()
259
+
260
+ self.context_length = context_length
261
+
262
+ if isinstance(vision_layers, (tuple, list)):
263
+ vision_heads = vision_width * 32 // 64
264
+ self.visual = ModifiedResNet(
265
+ layers=vision_layers,
266
+ output_dim=embed_dim,
267
+ heads=vision_heads,
268
+ input_resolution=image_resolution,
269
+ width=vision_width
270
+ )
271
+ else:
272
+ vision_heads = vision_width // 64
273
+ self.visual = VisionTransformer(
274
+ input_resolution=image_resolution,
275
+ patch_size=vision_patch_size,
276
+ width=vision_width,
277
+ layers=vision_layers,
278
+ heads=vision_heads,
279
+ output_dim=embed_dim
280
+ )
281
+
282
+ self.transformer = Transformer(
283
+ width=transformer_width,
284
+ layers=transformer_layers,
285
+ heads=transformer_heads,
286
+ attn_mask=self.build_attention_mask()
287
+ )
288
+
289
+ self.vocab_size = vocab_size
290
+ self.token_embedding = nn.Embedding(vocab_size, transformer_width)
291
+ self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
292
+ self.ln_final = LayerNorm(transformer_width)
293
+
294
+ self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
295
+ self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
296
+
297
+ self.initialize_parameters()
298
+
299
+ def initialize_parameters(self):
300
+ nn.init.normal_(self.token_embedding.weight, std=0.02)
301
+ nn.init.normal_(self.positional_embedding, std=0.01)
302
+
303
+ if isinstance(self.visual, ModifiedResNet):
304
+ if self.visual.attnpool is not None:
305
+ std = self.visual.attnpool.c_proj.in_features ** -0.5
306
+ nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
307
+ nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
308
+ nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
309
+ nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
310
+
311
+ for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
312
+ for name, param in resnet_block.named_parameters():
313
+ if name.endswith("bn3.weight"):
314
+ nn.init.zeros_(param)
315
+
316
+ proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
317
+ attn_std = self.transformer.width ** -0.5
318
+ fc_std = (2 * self.transformer.width) ** -0.5
319
+ for block in self.transformer.resblocks:
320
+ nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
321
+ nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
322
+ nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
323
+ nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
324
+
325
+ if self.text_projection is not None:
326
+ nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
327
+
328
+ def build_attention_mask(self):
329
+ # lazily create causal attention mask, with full attention between the vision tokens
330
+ # pytorch uses additive attention mask; fill with -inf
331
+ mask = torch.empty(self.context_length, self.context_length)
332
+ mask.fill_(float("-inf"))
333
+ mask.triu_(1) # zero out the lower diagonal
334
+ return mask
335
+
336
+ @property
337
+ def dtype(self):
338
+ return self.visual.conv1.weight.dtype
339
+
340
+ def encode_image(self, image):
341
+ return self.visual(image.type(self.dtype))
342
+
343
+ def encode_text(self, text):
344
+ x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
345
+
346
+ x = x + self.positional_embedding.type(self.dtype)
347
+ x = x.permute(1, 0, 2) # NLD -> LND
348
+ x = self.transformer(x)
349
+ x = x.permute(1, 0, 2) # LND -> NLD
350
+ x = self.ln_final(x).type(self.dtype)
351
+
352
+ # x.shape = [batch_size, n_ctx, transformer.width]
353
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
354
+ x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
355
+
356
+ return x
357
+
358
+ def forward(self, image, text):
359
+ image_features = self.encode_image(image)
360
+ text_features = self.encode_text(text)
361
+
362
+ # normalized features
363
+ image_features = image_features / image_features.norm(dim=1, keepdim=True)
364
+ text_features = text_features / text_features.norm(dim=1, keepdim=True)
365
+
366
+ # cosine similarity as logits
367
+ logit_scale = self.logit_scale.exp()
368
+ logits_per_image = logit_scale * image_features @ text_features.t()
369
+ logits_per_text = logits_per_image.t()
370
+
371
+ # shape = [global_batch_size, global_batch_size]
372
+ return logits_per_image, logits_per_text
373
+
374
+
375
+ def convert_weights(model: nn.Module):
376
+ """Convert applicable model parameters to fp16"""
377
+
378
+ def _convert_weights_to_fp16(l):
379
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
380
+ l.weight.data = l.weight.data.half()
381
+ if l.bias is not None:
382
+ l.bias.data = l.bias.data.half()
383
+
384
+ if isinstance(l, nn.MultiheadAttention):
385
+ for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
386
+ tensor = getattr(l, attr)
387
+ if tensor is not None:
388
+ tensor.data = tensor.data.half()
389
+
390
+ for name in ["text_projection", "proj"]:
391
+ if hasattr(l, name):
392
+ attr = getattr(l, name)
393
+ if attr is not None:
394
+ attr.data = attr.data.half()
395
+
396
+ model.apply(_convert_weights_to_fp16)
397
+
398
+
399
+ def build_model(state_dict: dict):
400
+ vit = "visual.proj" in state_dict
401
+
402
+ if vit:
403
+ vision_width = state_dict["visual.conv1.weight"].shape[0]
404
+ vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
405
+ vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
406
+ grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
407
+ image_resolution = vision_patch_size * grid_size
408
+ else:
409
+ 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]]
410
+ vision_layers = tuple(counts)
411
+ vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
412
+ output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
413
+ vision_patch_size = None
414
+ assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
415
+ image_resolution = output_width * 32
416
+
417
+ embed_dim = state_dict["text_projection"].shape[1]
418
+ context_length = state_dict["positional_embedding"].shape[0]
419
+ vocab_size = state_dict["token_embedding.weight"].shape[0]
420
+ transformer_width = state_dict["ln_final.weight"].shape[0]
421
+ transformer_heads = transformer_width // 64
422
+ transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith("transformer.resblocks")))
423
+
424
+ model = CLIP(
425
+ embed_dim,
426
+ image_resolution, vision_layers, vision_width, vision_patch_size,
427
+ context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
428
+ )
429
+
430
+ for key in ["input_resolution", "context_length", "vocab_size"]:
431
+ if key in state_dict:
432
+ del state_dict[key]
433
+
434
+ convert_weights(model)
435
+ model.load_state_dict(state_dict)
436
+ return model.eval()
CCEdit-main/src/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
+ ```bash
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/).
CCEdit-main/src/clip/hubconf.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from clip.clip import tokenize as _tokenize, load as _load, available_models as _available_models
2
+ import re
3
+ import string
4
+
5
+ dependencies = ["torch", "torchvision", "ftfy", "regex", "tqdm"]
6
+
7
+ # For compatibility (cannot include special characters in function name)
8
+ model_functions = { model: re.sub(f'[{string.punctuation}]', '_', model) for model in _available_models()}
9
+
10
+ def _create_hub_entrypoint(model):
11
+ def entrypoint(**kwargs):
12
+ return _load(model, **kwargs)
13
+
14
+ entrypoint.__doc__ = f"""Loads the {model} CLIP model
15
+
16
+ Parameters
17
+ ----------
18
+ device : Union[str, torch.device]
19
+ The device to put the loaded model
20
+
21
+ jit : bool
22
+ Whether to load the optimized JIT model or more hackable non-JIT model (default).
23
+
24
+ download_root: str
25
+ path to download the model files; by default, it uses "~/.cache/clip"
26
+
27
+ Returns
28
+ -------
29
+ model : torch.nn.Module
30
+ The {model} CLIP model
31
+
32
+ preprocess : Callable[[PIL.Image], torch.Tensor]
33
+ A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
34
+ """
35
+ return entrypoint
36
+
37
+ def tokenize():
38
+ return _tokenize
39
+
40
+ _entrypoints = {model_functions[model]: _create_hub_entrypoint(model) for model in _available_models()}
41
+
42
+ globals().update(_entrypoints)
CCEdit-main/src/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, and in January 2022, the RN50x64 and ViT-L/14 models were released. Lastly, the ViT-L/14@336px model was released in April 2022.
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)
CCEdit-main/src/clip/notebooks/Interacting_with_CLIP.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
CCEdit-main/src/clip/notebooks/Prompt_Engineering_for_ImageNet.ipynb ADDED
@@ -0,0 +1,1107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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<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<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
+ "from pkg_resources import packaging\n",
592
+ "\n",
593
+ "print(\"Torch version:\", torch.__version__)\n"
594
+ ],
595
+ "execution_count": 2,
596
+ "outputs": [
597
+ {
598
+ "output_type": "stream",
599
+ "text": [
600
+ "Torch version: 1.9.0+cu102\n"
601
+ ],
602
+ "name": "stdout"
603
+ }
604
+ ]
605
+ },
606
+ {
607
+ "cell_type": "markdown",
608
+ "metadata": {
609
+ "id": "eFxgLV5HAEEw"
610
+ },
611
+ "source": [
612
+ "# Loading the model\n",
613
+ "\n",
614
+ "Download and instantiate a CLIP model using the `clip` module that we just installed."
615
+ ]
616
+ },
617
+ {
618
+ "cell_type": "code",
619
+ "metadata": {
620
+ "id": "uLFS29hnhlY4",
621
+ "colab": {
622
+ "base_uri": "https://localhost:8080/"
623
+ },
624
+ "outputId": "09abb234-693e-4efb-953f-e1847ba95758"
625
+ },
626
+ "source": [
627
+ "clip.available_models()"
628
+ ],
629
+ "execution_count": 3,
630
+ "outputs": [
631
+ {
632
+ "output_type": "execute_result",
633
+ "data": {
634
+ "text/plain": [
635
+ "['RN50', 'RN101', 'RN50x4', 'RN50x16', 'ViT-B/32', 'ViT-B/16']"
636
+ ]
637
+ },
638
+ "metadata": {
639
+ "tags": []
640
+ },
641
+ "execution_count": 3
642
+ }
643
+ ]
644
+ },
645
+ {
646
+ "cell_type": "code",
647
+ "metadata": {
648
+ "id": "cboKZocQlSYX",
649
+ "colab": {
650
+ "base_uri": "https://localhost:8080/"
651
+ },
652
+ "outputId": "240acdd0-ca62-45db-8418-9e4ef73e8aff"
653
+ },
654
+ "source": [
655
+ "model, preprocess = clip.load(\"ViT-B/32\")"
656
+ ],
657
+ "execution_count": 4,
658
+ "outputs": [
659
+ {
660
+ "output_type": "stream",
661
+ "text": [
662
+ "100%|███████████████████████████████████████| 338M/338M [00:05<00:00, 63.6MiB/s]\n"
663
+ ],
664
+ "name": "stderr"
665
+ }
666
+ ]
667
+ },
668
+ {
669
+ "cell_type": "code",
670
+ "metadata": {
671
+ "colab": {
672
+ "base_uri": "https://localhost:8080/"
673
+ },
674
+ "id": "IBRVTY9lbGm8",
675
+ "outputId": "785019a1-1f40-45b0-e349-b0d4ec3173bf"
676
+ },
677
+ "source": [
678
+ "input_resolution = model.visual.input_resolution\n",
679
+ "context_length = model.context_length\n",
680
+ "vocab_size = model.vocab_size\n",
681
+ "\n",
682
+ "print(\"Model parameters:\", f\"{np.sum([int(np.prod(p.shape)) for p in model.parameters()]):,}\")\n",
683
+ "print(\"Input resolution:\", input_resolution)\n",
684
+ "print(\"Context length:\", context_length)\n",
685
+ "print(\"Vocab size:\", vocab_size)"
686
+ ],
687
+ "execution_count": 5,
688
+ "outputs": [
689
+ {
690
+ "output_type": "stream",
691
+ "text": [
692
+ "Model parameters: 151,277,313\n",
693
+ "Input resolution: 224\n",
694
+ "Context length: 77\n",
695
+ "Vocab size: 49408\n"
696
+ ],
697
+ "name": "stdout"
698
+ }
699
+ ]
700
+ },
701
+ {
702
+ "cell_type": "markdown",
703
+ "metadata": {
704
+ "id": "LhO3OtOmF8M4"
705
+ },
706
+ "source": [
707
+ "# Preparing ImageNet labels and prompts\n",
708
+ "\n",
709
+ "The following cell contains the 1,000 labels for the ImageNet dataset, followed by the text templates we'll use as \"prompt engineering\"."
710
+ ]
711
+ },
712
+ {
713
+ "cell_type": "code",
714
+ "metadata": {
715
+ "id": "R2HbOZrqa0jF"
716
+ },
717
+ "source": [
718
+ "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\"]"
719
+ ],
720
+ "execution_count": 6,
721
+ "outputs": []
722
+ },
723
+ {
724
+ "cell_type": "markdown",
725
+ "metadata": {
726
+ "id": "eMQSCuBta2G6"
727
+ },
728
+ "source": [
729
+ "A subset of these class names are modified from the default ImageNet class names sourced from Anish Athalye's imagenet-simple-labels.\n",
730
+ "\n",
731
+ "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",
732
+ "\n",
733
+ "Some examples beyond the crane/crane -> construction crane / bird crane issue mentioned in Section 3.1.4 of the paper include:\n",
734
+ "\n",
735
+ "- CLIP interprets \"nail\" as \"fingernail\" so we changed the label to \"metal nail\".\n",
736
+ "- ImageNet kite class refers to the bird of prey, not the flying toy, so we changed \"kite\" to \"kite (bird of prey)\"\n",
737
+ "- 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\""
738
+ ]
739
+ },
740
+ {
741
+ "cell_type": "code",
742
+ "metadata": {
743
+ "id": "toGtcd-Ji_MD",
744
+ "colab": {
745
+ "base_uri": "https://localhost:8080/"
746
+ },
747
+ "outputId": "b6eb0753-2bee-4144-abe3-fbd23f35f555"
748
+ },
749
+ "source": [
750
+ "imagenet_templates = [\n",
751
+ " 'a bad photo of a {}.',\n",
752
+ " 'a photo of many {}.',\n",
753
+ " 'a sculpture of a {}.',\n",
754
+ " 'a photo of the hard to see {}.',\n",
755
+ " 'a low resolution photo of the {}.',\n",
756
+ " 'a rendering of a {}.',\n",
757
+ " 'graffiti of a {}.',\n",
758
+ " 'a bad photo of the {}.',\n",
759
+ " 'a cropped photo of the {}.',\n",
760
+ " 'a tattoo of a {}.',\n",
761
+ " 'the embroidered {}.',\n",
762
+ " 'a photo of a hard to see {}.',\n",
763
+ " 'a bright photo of a {}.',\n",
764
+ " 'a photo of a clean {}.',\n",
765
+ " 'a photo of a dirty {}.',\n",
766
+ " 'a dark photo of the {}.',\n",
767
+ " 'a drawing of a {}.',\n",
768
+ " 'a photo of my {}.',\n",
769
+ " 'the plastic {}.',\n",
770
+ " 'a photo of the cool {}.',\n",
771
+ " 'a close-up photo of a {}.',\n",
772
+ " 'a black and white photo of the {}.',\n",
773
+ " 'a painting of the {}.',\n",
774
+ " 'a painting of a {}.',\n",
775
+ " 'a pixelated photo of the {}.',\n",
776
+ " 'a sculpture of the {}.',\n",
777
+ " 'a bright photo of the {}.',\n",
778
+ " 'a cropped photo of a {}.',\n",
779
+ " 'a plastic {}.',\n",
780
+ " 'a photo of the dirty {}.',\n",
781
+ " 'a jpeg corrupted photo of a {}.',\n",
782
+ " 'a blurry photo of the {}.',\n",
783
+ " 'a photo of the {}.',\n",
784
+ " 'a good photo of the {}.',\n",
785
+ " 'a rendering of the {}.',\n",
786
+ " 'a {} in a video game.',\n",
787
+ " 'a photo of one {}.',\n",
788
+ " 'a doodle of a {}.',\n",
789
+ " 'a close-up photo of the {}.',\n",
790
+ " 'a photo of a {}.',\n",
791
+ " 'the origami {}.',\n",
792
+ " 'the {} in a video game.',\n",
793
+ " 'a sketch of a {}.',\n",
794
+ " 'a doodle of the {}.',\n",
795
+ " 'a origami {}.',\n",
796
+ " 'a low resolution photo of a {}.',\n",
797
+ " 'the toy {}.',\n",
798
+ " 'a rendition of the {}.',\n",
799
+ " 'a photo of the clean {}.',\n",
800
+ " 'a photo of a large {}.',\n",
801
+ " 'a rendition of a {}.',\n",
802
+ " 'a photo of a nice {}.',\n",
803
+ " 'a photo of a weird {}.',\n",
804
+ " 'a blurry photo of a {}.',\n",
805
+ " 'a cartoon {}.',\n",
806
+ " 'art of a {}.',\n",
807
+ " 'a sketch of the {}.',\n",
808
+ " 'a embroidered {}.',\n",
809
+ " 'a pixelated photo of a {}.',\n",
810
+ " 'itap of the {}.',\n",
811
+ " 'a jpeg corrupted photo of the {}.',\n",
812
+ " 'a good photo of a {}.',\n",
813
+ " 'a plushie {}.',\n",
814
+ " 'a photo of the nice {}.',\n",
815
+ " 'a photo of the small {}.',\n",
816
+ " 'a photo of the weird {}.',\n",
817
+ " 'the cartoon {}.',\n",
818
+ " 'art of the {}.',\n",
819
+ " 'a drawing of the {}.',\n",
820
+ " 'a photo of the large {}.',\n",
821
+ " 'a black and white photo of a {}.',\n",
822
+ " 'the plushie {}.',\n",
823
+ " 'a dark photo of a {}.',\n",
824
+ " 'itap of a {}.',\n",
825
+ " 'graffiti of the {}.',\n",
826
+ " 'a toy {}.',\n",
827
+ " 'itap of my {}.',\n",
828
+ " 'a photo of a cool {}.',\n",
829
+ " 'a photo of a small {}.',\n",
830
+ " 'a tattoo of the {}.',\n",
831
+ "]\n",
832
+ "\n",
833
+ "print(f\"{len(imagenet_classes)} classes, {len(imagenet_templates)} templates\")"
834
+ ],
835
+ "execution_count": 7,
836
+ "outputs": [
837
+ {
838
+ "output_type": "stream",
839
+ "text": [
840
+ "1000 classes, 80 templates\n"
841
+ ],
842
+ "name": "stdout"
843
+ }
844
+ ]
845
+ },
846
+ {
847
+ "cell_type": "markdown",
848
+ "metadata": {
849
+ "id": "aRB5OzgpHwqQ"
850
+ },
851
+ "source": [
852
+ "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",
853
+ "\n",
854
+ "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",
855
+ "\n",
856
+ "1. itap of a {}.\n",
857
+ "2. a bad photo of the {}.\n",
858
+ "3. a origami {}.\n",
859
+ "4. a photo of the large {}.\n",
860
+ "5. a {} in a video game.\n",
861
+ "6. art of the {}.\n",
862
+ "7. a photo of the small {}.\n",
863
+ "\n",
864
+ "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."
865
+ ]
866
+ },
867
+ {
868
+ "cell_type": "markdown",
869
+ "metadata": {
870
+ "id": "4W8ARJVqBJXs"
871
+ },
872
+ "source": [
873
+ "# Loading the Images\n",
874
+ "\n",
875
+ "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",
876
+ "\n",
877
+ "If you have the ImageNet dataset downloaded, you can replace the dataset with the official torchvision loader, e.g.:\n",
878
+ "\n",
879
+ "```python\n",
880
+ "images = torchvision.datasets.ImageNet(\"path/to/imagenet\", split='val', transform=preprocess)\n",
881
+ "```"
882
+ ]
883
+ },
884
+ {
885
+ "cell_type": "code",
886
+ "metadata": {
887
+ "colab": {
888
+ "base_uri": "https://localhost:8080/"
889
+ },
890
+ "id": "moHR4UlHKsDc",
891
+ "outputId": "40731297-edc7-4cd0-be75-ed426c8fb005"
892
+ },
893
+ "source": [
894
+ "! pip install git+https://github.com/modestyachts/ImageNetV2_pytorch\n",
895
+ "\n",
896
+ "from imagenetv2_pytorch import ImageNetV2Dataset\n",
897
+ "\n",
898
+ "images = ImageNetV2Dataset(transform=preprocess)\n",
899
+ "loader = torch.utils.data.DataLoader(images, batch_size=32, num_workers=2)"
900
+ ],
901
+ "execution_count": 8,
902
+ "outputs": [
903
+ {
904
+ "output_type": "stream",
905
+ "text": [
906
+ "Collecting git+https://github.com/modestyachts/ImageNetV2_pytorch\n",
907
+ " Cloning https://github.com/modestyachts/ImageNetV2_pytorch to /tmp/pip-req-build-0kih0kn2\n",
908
+ " Running command git clone -q https://github.com/modestyachts/ImageNetV2_pytorch /tmp/pip-req-build-0kih0kn2\n",
909
+ "Building wheels for collected packages: imagenetv2-pytorch\n",
910
+ " Building wheel for imagenetv2-pytorch (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
911
+ " Created wheel for imagenetv2-pytorch: filename=imagenetv2_pytorch-0.1-py3-none-any.whl size=2663 sha256=ac31e0ed9c61afc5e0271eed315d3a82844a79ae64f8ce43fc1c98928cec129f\n",
912
+ " Stored in directory: /tmp/pip-ephem-wheel-cache-745b5n1m/wheels/ab/ee/f4/73bce5c7f68d28ce632ef33ae87ce60aaca021eb2b3b31a6fa\n",
913
+ "Successfully built imagenetv2-pytorch\n",
914
+ "Installing collected packages: imagenetv2-pytorch\n",
915
+ "Successfully installed imagenetv2-pytorch-0.1\n",
916
+ "Dataset matched-frequency not found on disk, downloading....\n"
917
+ ],
918
+ "name": "stdout"
919
+ },
920
+ {
921
+ "output_type": "stream",
922
+ "text": [
923
+ "100%|██████████| 1.26G/1.26G [01:02<00:00, 20.2MiB/s]\n"
924
+ ],
925
+ "name": "stderr"
926
+ },
927
+ {
928
+ "output_type": "stream",
929
+ "text": [
930
+ "Extracting....\n"
931
+ ],
932
+ "name": "stdout"
933
+ }
934
+ ]
935
+ },
936
+ {
937
+ "cell_type": "markdown",
938
+ "metadata": {
939
+ "id": "fz6D-F-Wbrtp"
940
+ },
941
+ "source": [
942
+ "# Creating zero-shot classifier weights"
943
+ ]
944
+ },
945
+ {
946
+ "cell_type": "code",
947
+ "metadata": {
948
+ "colab": {
949
+ "base_uri": "https://localhost:8080/",
950
+ "height": 67,
951
+ "referenced_widgets": [
952
+ "66a1639713ae441d8a9b873381f9d774",
953
+ "610b775178c645e2b4663b77cc0c67b6",
954
+ "412dd15f0d8542f5ab2730f8616fb582",
955
+ "5e6315f36b4e4eeea5c6294b024e0c97",
956
+ "085d5388abda4202bfa66d0c088452f8",
957
+ "f75124b64aa147c693c67a78f8e3a231",
958
+ "6e5676a054874243b55fc6d120a07d01",
959
+ "dc6d1416c01a4047935ee15c3fd2eb1c"
960
+ ]
961
+ },
962
+ "id": "sRqDoz1Gbsii",
963
+ "outputId": "312b8ebf-3961-4903-d8cb-3b7a94cc97b6"
964
+ },
965
+ "source": [
966
+ "def zeroshot_classifier(classnames, templates):\n",
967
+ " with torch.no_grad():\n",
968
+ " zeroshot_weights = []\n",
969
+ " for classname in tqdm(classnames):\n",
970
+ " texts = [template.format(classname) for template in templates] #format with class\n",
971
+ " texts = clip.tokenize(texts).cuda() #tokenize\n",
972
+ " class_embeddings = model.encode_text(texts) #embed with text encoder\n",
973
+ " class_embeddings /= class_embeddings.norm(dim=-1, keepdim=True)\n",
974
+ " class_embedding = class_embeddings.mean(dim=0)\n",
975
+ " class_embedding /= class_embedding.norm()\n",
976
+ " zeroshot_weights.append(class_embedding)\n",
977
+ " zeroshot_weights = torch.stack(zeroshot_weights, dim=1).cuda()\n",
978
+ " return zeroshot_weights\n",
979
+ "\n",
980
+ "\n",
981
+ "zeroshot_weights = zeroshot_classifier(imagenet_classes, imagenet_templates)"
982
+ ],
983
+ "execution_count": 9,
984
+ "outputs": [
985
+ {
986
+ "output_type": "display_data",
987
+ "data": {
988
+ "application/vnd.jupyter.widget-view+json": {
989
+ "model_id": "66a1639713ae441d8a9b873381f9d774",
990
+ "version_minor": 0,
991
+ "version_major": 2
992
+ },
993
+ "text/plain": [
994
+ "HBox(children=(FloatProgress(value=0.0, max=1000.0), HTML(value='')))"
995
+ ]
996
+ },
997
+ "metadata": {
998
+ "tags": []
999
+ }
1000
+ },
1001
+ {
1002
+ "output_type": "stream",
1003
+ "text": [
1004
+ "\n"
1005
+ ],
1006
+ "name": "stdout"
1007
+ }
1008
+ ]
1009
+ },
1010
+ {
1011
+ "cell_type": "markdown",
1012
+ "metadata": {
1013
+ "id": "1fZo7hG8iJP5"
1014
+ },
1015
+ "source": [
1016
+ "# Zero-shot prediction"
1017
+ ]
1018
+ },
1019
+ {
1020
+ "cell_type": "code",
1021
+ "metadata": {
1022
+ "id": "j4kPSZoShQxN"
1023
+ },
1024
+ "source": [
1025
+ "def accuracy(output, target, topk=(1,)):\n",
1026
+ " pred = output.topk(max(topk), 1, True, True)[1].t()\n",
1027
+ " correct = pred.eq(target.view(1, -1).expand_as(pred))\n",
1028
+ " return [float(correct[:k].reshape(-1).float().sum(0, keepdim=True).cpu().numpy()) for k in topk]"
1029
+ ],
1030
+ "execution_count": 10,
1031
+ "outputs": []
1032
+ },
1033
+ {
1034
+ "cell_type": "code",
1035
+ "metadata": {
1036
+ "colab": {
1037
+ "base_uri": "https://localhost:8080/",
1038
+ "height": 102,
1039
+ "referenced_widgets": [
1040
+ "84f80a7f3e764346969a347b0f71b24e",
1041
+ "392656f01b2945f3bd7903783ed8cc96",
1042
+ "8e47a435519b4ce090879b4be2f61f99",
1043
+ "41b1ed6b0a9745c1a595377670b15ff4",
1044
+ "179b8ae1eb7f4a828f953e889b141725",
1045
+ "d8708e8414fd44f4abd6590c9b57996f",
1046
+ "800e30f5b4f24475a2b0046da0703631",
1047
+ "8764308b948745f1a677332fd21fcaf0"
1048
+ ]
1049
+ },
1050
+ "id": "wKJ7YsdlkDXo",
1051
+ "outputId": "ab824854-38e4-4d37-ad40-2a7ce3c5fd43"
1052
+ },
1053
+ "source": [
1054
+ "with torch.no_grad():\n",
1055
+ " top1, top5, n = 0., 0., 0.\n",
1056
+ " for i, (images, target) in enumerate(tqdm(loader)):\n",
1057
+ " images = images.cuda()\n",
1058
+ " target = target.cuda()\n",
1059
+ " \n",
1060
+ " # predict\n",
1061
+ " image_features = model.encode_image(images)\n",
1062
+ " image_features /= image_features.norm(dim=-1, keepdim=True)\n",
1063
+ " logits = 100. * image_features @ zeroshot_weights\n",
1064
+ "\n",
1065
+ " # measure accuracy\n",
1066
+ " acc1, acc5 = accuracy(logits, target, topk=(1, 5))\n",
1067
+ " top1 += acc1\n",
1068
+ " top5 += acc5\n",
1069
+ " n += images.size(0)\n",
1070
+ "\n",
1071
+ "top1 = (top1 / n) * 100\n",
1072
+ "top5 = (top5 / n) * 100 \n",
1073
+ "\n",
1074
+ "print(f\"Top-1 accuracy: {top1:.2f}\")\n",
1075
+ "print(f\"Top-5 accuracy: {top5:.2f}\")"
1076
+ ],
1077
+ "execution_count": 11,
1078
+ "outputs": [
1079
+ {
1080
+ "output_type": "display_data",
1081
+ "data": {
1082
+ "application/vnd.jupyter.widget-view+json": {
1083
+ "model_id": "84f80a7f3e764346969a347b0f71b24e",
1084
+ "version_minor": 0,
1085
+ "version_major": 2
1086
+ },
1087
+ "text/plain": [
1088
+ "HBox(children=(FloatProgress(value=0.0, max=313.0), HTML(value='')))"
1089
+ ]
1090
+ },
1091
+ "metadata": {
1092
+ "tags": []
1093
+ }
1094
+ },
1095
+ {
1096
+ "output_type": "stream",
1097
+ "text": [
1098
+ "\n",
1099
+ "Top-1 accuracy: 55.93\n",
1100
+ "Top-5 accuracy: 83.36\n"
1101
+ ],
1102
+ "name": "stdout"
1103
+ }
1104
+ ]
1105
+ }
1106
+ ]
1107
+ }
CCEdit-main/src/clip/requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ftfy
2
+ packaging
3
+ regex
4
+ tqdm
5
+ torch
6
+ torchvision
CCEdit-main/src/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
+ )
CCEdit-main/src/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)
CCEdit-main/src/pnp-diffusers/README.md ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Plug-and-Play Diffusion Features for Text-Driven Image-to-Image Translation (CVPR 2023)
2
+
3
+ ## [<a href="https://pnp-diffusion.github.io/" target="_blank">Project Page</a>]
4
+
5
+ [![arXiv](https://img.shields.io/badge/arXiv-PnP-b31b1b.svg)](https://arxiv.org/abs/2211.12572) [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/hysts/PnP-diffusion-features) <a href="https://replicate.com/arielreplicate/plug_and_play_image_translation"><img src="https://replicate.com/arielreplicate/plug_and_play_image_translation/badge"></a> [![TI2I](https://img.shields.io/badge/benchmarks-TI2I-blue)](https://www.dropbox.com/sh/8giw0uhfekft47h/AAAF1frwakVsQocKczZZSX6La?dl=0)
6
+
7
+ ![teaser](assets/teaser.png)
8
+
9
+
10
+ **To plug-and-play diffusion features, please follow these steps:**
11
+
12
+ 1. [Setup](#setup)
13
+ 2. [Latent extraction](#latent-extraction)
14
+ 3. [Running PnP](#running-pnp)
15
+
16
+
17
+ ## Setup
18
+
19
+ Create the environment and install the dependencies by running:
20
+
21
+ ```
22
+ conda create -n pnp-diffusers python=3.9
23
+ conda activate pnp-diffusers
24
+ pip install -r requirements.txt
25
+ ```
26
+
27
+
28
+ ## Latent Extraction
29
+
30
+ We first compute the intermediate noisy latents of the structure guidance image. To do that, run:
31
+
32
+ ```
33
+ python preprocess.py --data_path <path_to_guidance_image> --inversion_prompt <inversion_prompt>
34
+ ```
35
+
36
+ where `<inversion_prompt>` should describe the content of the guidance image. The intermediate noisy latents will be saved under the path `latents_forward/<image_name>`, where `<image_name>` is the filename of the provided guidance image.
37
+
38
+
39
+ ## Running PnP
40
+
41
+ Run the following command for applying PnP on the structure guidance image:
42
+
43
+ ```
44
+ python pnp.py --config_path <pnp_config_path>
45
+ ```
46
+
47
+ where `<pnp_config_path>` is a path to a yaml config file. The config includes fields for providing the guidance image path, the PnP output path, translation prompt, guidance scale, PnP feature and self-attention injection thresholds, and additional hyperparameters. See an example config in `config_pnp.yaml`.
48
+
49
+
50
+ ## Citation
51
+ ```
52
+ @InProceedings{Tumanyan_2023_CVPR,
53
+ author = {Tumanyan, Narek and Geyer, Michal and Bagon, Shai and Dekel, Tali},
54
+ title = {Plug-and-Play Diffusion Features for Text-Driven Image-to-Image Translation},
55
+ booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)},
56
+ month = {June},
57
+ year = {2023},
58
+ pages = {1921-1930}
59
+ }
60
+ ```
CCEdit-main/src/pnp-diffusers/config_pnp.yaml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # general
2
+ seed: 1
3
+ device: 'cuda'
4
+ output_path: 'PNP-results/horse'
5
+
6
+ # data
7
+ image_path: 'data/horse.jpg'
8
+ latents_path: 'latents_forward'
9
+
10
+ # diffusion
11
+ sd_version: '2.1'
12
+ guidance_scale: 7.5
13
+ n_timesteps: 50
14
+ prompt: a photo of a pink toy horse on the beach
15
+ negative_prompt: ugly, blurry, black, low res, unrealistic
16
+
17
+ # pnp injection thresholds, ∈ [0, 1]
18
+ pnp_attn_t: 0.5
19
+ pnp_f_t: 0.8
CCEdit-main/src/pnp-diffusers/pnp_utils.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import os
3
+ import random
4
+ import numpy as np
5
+
6
+ def seed_everything(seed):
7
+ torch.manual_seed(seed)
8
+ torch.cuda.manual_seed(seed)
9
+ random.seed(seed)
10
+ np.random.seed(seed)
11
+
12
+ def register_time(model, t):
13
+ conv_module = model.unet.up_blocks[1].resnets[1]
14
+ setattr(conv_module, 't', t)
15
+ down_res_dict = {0: [0, 1], 1: [0, 1], 2: [0, 1]}
16
+ up_res_dict = {1: [0, 1, 2], 2: [0, 1, 2], 3: [0, 1, 2]}
17
+ for res in up_res_dict:
18
+ for block in up_res_dict[res]:
19
+ module = model.unet.up_blocks[res].attentions[block].transformer_blocks[0].attn1
20
+ setattr(module, 't', t)
21
+ for res in down_res_dict:
22
+ for block in down_res_dict[res]:
23
+ module = model.unet.down_blocks[res].attentions[block].transformer_blocks[0].attn1
24
+ setattr(module, 't', t)
25
+ module = model.unet.mid_block.attentions[0].transformer_blocks[0].attn1
26
+ setattr(module, 't', t)
27
+
28
+
29
+ def load_source_latents_t(t, latents_path):
30
+ latents_t_path = os.path.join(latents_path, f'noisy_latents_{t}.pt')
31
+ assert os.path.exists(latents_t_path), f'Missing latents at t {t} path {latents_t_path}'
32
+ latents = torch.load(latents_t_path)
33
+ return latents
34
+
35
+ def register_attention_control_efficient(model, injection_schedule):
36
+ def sa_forward(self):
37
+ to_out = self.to_out
38
+ if type(to_out) is torch.nn.modules.container.ModuleList:
39
+ to_out = self.to_out[0]
40
+ else:
41
+ to_out = self.to_out
42
+
43
+ def forward(x, encoder_hidden_states=None, attention_mask=None):
44
+ batch_size, sequence_length, dim = x.shape
45
+ h = self.heads
46
+
47
+ is_cross = encoder_hidden_states is not None
48
+ encoder_hidden_states = encoder_hidden_states if is_cross else x
49
+ if not is_cross and self.injection_schedule is not None and (
50
+ self.t in self.injection_schedule or self.t == 1000):
51
+ q = self.to_q(x)
52
+ k = self.to_k(encoder_hidden_states)
53
+
54
+ source_batch_size = int(q.shape[0] // 3)
55
+ # inject unconditional
56
+ q[source_batch_size:2 * source_batch_size] = q[:source_batch_size]
57
+ k[source_batch_size:2 * source_batch_size] = k[:source_batch_size]
58
+ # inject conditional
59
+ q[2 * source_batch_size:] = q[:source_batch_size]
60
+ k[2 * source_batch_size:] = k[:source_batch_size]
61
+
62
+ q = self.head_to_batch_dim(q)
63
+ k = self.head_to_batch_dim(k)
64
+ else:
65
+ q = self.to_q(x)
66
+ k = self.to_k(encoder_hidden_states)
67
+ q = self.head_to_batch_dim(q)
68
+ k = self.head_to_batch_dim(k)
69
+
70
+ v = self.to_v(encoder_hidden_states)
71
+ v = self.head_to_batch_dim(v)
72
+
73
+ sim = torch.einsum("b i d, b j d -> b i j", q, k) * self.scale
74
+
75
+ if attention_mask is not None:
76
+ attention_mask = attention_mask.reshape(batch_size, -1)
77
+ max_neg_value = -torch.finfo(sim.dtype).max
78
+ attention_mask = attention_mask[:, None, :].repeat(h, 1, 1)
79
+ sim.masked_fill_(~attention_mask, max_neg_value)
80
+
81
+ # attention, what we cannot get enough of
82
+ attn = sim.softmax(dim=-1)
83
+ out = torch.einsum("b i j, b j d -> b i d", attn, v)
84
+ out = self.batch_to_head_dim(out)
85
+
86
+ return to_out(out)
87
+
88
+ return forward
89
+
90
+ res_dict = {1: [1, 2], 2: [0, 1, 2], 3: [0, 1, 2]} # we are injecting attention in blocks 4 - 11 of the decoder, so not in the first block of the lowest resolution
91
+ for res in res_dict:
92
+ for block in res_dict[res]:
93
+ module = model.unet.up_blocks[res].attentions[block].transformer_blocks[0].attn1
94
+ module.forward = sa_forward(module)
95
+ setattr(module, 'injection_schedule', injection_schedule)
96
+
97
+
98
+ def register_conv_control_efficient(model, injection_schedule):
99
+ def conv_forward(self):
100
+ def forward(input_tensor, temb):
101
+ hidden_states = input_tensor
102
+
103
+ hidden_states = self.norm1(hidden_states)
104
+ hidden_states = self.nonlinearity(hidden_states)
105
+
106
+ if self.upsample is not None:
107
+ # upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
108
+ if hidden_states.shape[0] >= 64:
109
+ input_tensor = input_tensor.contiguous()
110
+ hidden_states = hidden_states.contiguous()
111
+ input_tensor = self.upsample(input_tensor)
112
+ hidden_states = self.upsample(hidden_states)
113
+ elif self.downsample is not None:
114
+ input_tensor = self.downsample(input_tensor)
115
+ hidden_states = self.downsample(hidden_states)
116
+
117
+ hidden_states = self.conv1(hidden_states)
118
+
119
+ if temb is not None:
120
+ temb = self.time_emb_proj(self.nonlinearity(temb))[:, :, None, None]
121
+
122
+ if temb is not None and self.time_embedding_norm == "default":
123
+ hidden_states = hidden_states + temb
124
+
125
+ hidden_states = self.norm2(hidden_states)
126
+
127
+ if temb is not None and self.time_embedding_norm == "scale_shift":
128
+ scale, shift = torch.chunk(temb, 2, dim=1)
129
+ hidden_states = hidden_states * (1 + scale) + shift
130
+
131
+ hidden_states = self.nonlinearity(hidden_states)
132
+
133
+ hidden_states = self.dropout(hidden_states)
134
+ hidden_states = self.conv2(hidden_states)
135
+ if self.injection_schedule is not None and (self.t in self.injection_schedule or self.t == 1000):
136
+ source_batch_size = int(hidden_states.shape[0] // 3)
137
+ # inject unconditional
138
+ hidden_states[source_batch_size:2 * source_batch_size] = hidden_states[:source_batch_size]
139
+ # inject conditional
140
+ hidden_states[2 * source_batch_size:] = hidden_states[:source_batch_size]
141
+
142
+ if self.conv_shortcut is not None:
143
+ input_tensor = self.conv_shortcut(input_tensor)
144
+
145
+ output_tensor = (input_tensor + hidden_states) / self.output_scale_factor
146
+
147
+ return output_tensor
148
+
149
+ return forward
150
+
151
+ conv_module = model.unet.up_blocks[1].resnets[1]
152
+ conv_module.forward = conv_forward(conv_module)
153
+ setattr(conv_module, 'injection_schedule', injection_schedule)
CCEdit-main/src/pnp-diffusers/preprocess.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import CLIPTextModel, CLIPTokenizer, logging
2
+ from diffusers import AutoencoderKL, UNet2DConditionModel, DDIMScheduler
3
+
4
+ # suppress partial model loading warning
5
+ logging.set_verbosity_error()
6
+
7
+ import os
8
+ from PIL import Image
9
+ from tqdm import tqdm, trange
10
+ import torch
11
+ import torch.nn as nn
12
+ import argparse
13
+ from pathlib import Path
14
+ from pnp_utils import *
15
+ import torchvision.transforms as T
16
+
17
+
18
+ def get_timesteps(scheduler, num_inference_steps, strength, device):
19
+ # get the original timestep using init_timestep
20
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
21
+
22
+ t_start = max(num_inference_steps - init_timestep, 0)
23
+ timesteps = scheduler.timesteps[t_start:]
24
+
25
+ return timesteps, num_inference_steps - t_start
26
+
27
+
28
+ class Preprocess(nn.Module):
29
+ def __init__(self, device, sd_version='2.0', hf_key=None):
30
+ super().__init__()
31
+
32
+ self.device = device
33
+ self.sd_version = sd_version
34
+ self.use_depth = False
35
+
36
+ print(f'[INFO] loading stable diffusion...')
37
+ if hf_key is not None:
38
+ print(f'[INFO] using hugging face custom model key: {hf_key}')
39
+ model_key = hf_key
40
+ elif self.sd_version == '2.1':
41
+ model_key = "stabilityai/stable-diffusion-2-1-base"
42
+ elif self.sd_version == '2.0':
43
+ model_key = "stabilityai/stable-diffusion-2-base"
44
+ elif self.sd_version == '1.5':
45
+ model_key = "runwayml/stable-diffusion-v1-5"
46
+ elif self.sd_version == 'depth':
47
+ model_key = "stabilityai/stable-diffusion-2-depth"
48
+ self.use_depth = True
49
+ else:
50
+ raise ValueError(f'Stable-diffusion version {self.sd_version} not supported.')
51
+
52
+ # Create model
53
+ self.vae = AutoencoderKL.from_pretrained(model_key, subfolder="vae", revision="fp16",
54
+ torch_dtype=torch.float16).to(self.device)
55
+ self.tokenizer = CLIPTokenizer.from_pretrained(model_key, subfolder="tokenizer")
56
+ self.text_encoder = CLIPTextModel.from_pretrained(model_key, subfolder="text_encoder", revision="fp16",
57
+ torch_dtype=torch.float16).to(self.device)
58
+ self.unet = UNet2DConditionModel.from_pretrained(model_key, subfolder="unet", revision="fp16",
59
+ torch_dtype=torch.float16).to(self.device)
60
+ self.scheduler = DDIMScheduler.from_pretrained(model_key, subfolder="scheduler")
61
+ print(f'[INFO] loaded stable diffusion!')
62
+
63
+ self.inversion_func = self.ddim_inversion
64
+
65
+ @torch.no_grad()
66
+ def get_text_embeds(self, prompt, negative_prompt, device="cuda"):
67
+ text_input = self.tokenizer(prompt, padding='max_length', max_length=self.tokenizer.model_max_length,
68
+ truncation=True, return_tensors='pt')
69
+ text_embeddings = self.text_encoder(text_input.input_ids.to(device))[0]
70
+ uncond_input = self.tokenizer(negative_prompt, padding='max_length', max_length=self.tokenizer.model_max_length,
71
+ return_tensors='pt')
72
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(device))[0]
73
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
74
+ return text_embeddings
75
+
76
+ @torch.no_grad()
77
+ def decode_latents(self, latents):
78
+ with torch.autocast(device_type='cuda', dtype=torch.float32):
79
+ latents = 1 / 0.18215 * latents
80
+ imgs = self.vae.decode(latents).sample
81
+ imgs = (imgs / 2 + 0.5).clamp(0, 1)
82
+ return imgs
83
+
84
+ def load_img(self, image_path):
85
+ image_pil = T.Resize(512)(Image.open(image_path).convert("RGB"))
86
+ image = T.ToTensor()(image_pil).unsqueeze(0).to(device)
87
+ return image
88
+
89
+ @torch.no_grad()
90
+ def encode_imgs(self, imgs):
91
+ with torch.autocast(device_type='cuda', dtype=torch.float32):
92
+ imgs = 2 * imgs - 1
93
+ posterior = self.vae.encode(imgs).latent_dist
94
+ latents = posterior.mean * 0.18215
95
+ return latents
96
+
97
+ @torch.no_grad()
98
+ def ddim_inversion(self, cond, latent, save_path, save_latents=True,
99
+ timesteps_to_save=None):
100
+ timesteps = reversed(self.scheduler.timesteps)
101
+ with torch.autocast(device_type='cuda', dtype=torch.float32):
102
+ for i, t in enumerate(tqdm(timesteps)):
103
+ cond_batch = cond.repeat(latent.shape[0], 1, 1)
104
+
105
+ alpha_prod_t = self.scheduler.alphas_cumprod[t]
106
+ alpha_prod_t_prev = (
107
+ self.scheduler.alphas_cumprod[timesteps[i - 1]]
108
+ if i > 0 else self.scheduler.final_alpha_cumprod
109
+ )
110
+
111
+ mu = alpha_prod_t ** 0.5
112
+ mu_prev = alpha_prod_t_prev ** 0.5
113
+ sigma = (1 - alpha_prod_t) ** 0.5
114
+ sigma_prev = (1 - alpha_prod_t_prev) ** 0.5
115
+
116
+ eps = self.unet(latent, t, encoder_hidden_states=cond_batch).sample
117
+
118
+ pred_x0 = (latent - sigma_prev * eps) / mu_prev
119
+ latent = mu * pred_x0 + sigma * eps
120
+ if save_latents:
121
+ torch.save(latent, os.path.join(save_path, f'noisy_latents_{t}.pt'))
122
+ torch.save(latent, os.path.join(save_path, f'noisy_latents_{t}.pt'))
123
+ return latent
124
+
125
+ @torch.no_grad()
126
+ def ddim_sample(self, x, cond, save_path, save_latents=False, timesteps_to_save=None):
127
+ timesteps = self.scheduler.timesteps
128
+ with torch.autocast(device_type='cuda', dtype=torch.float32):
129
+ for i, t in enumerate(tqdm(timesteps)):
130
+ cond_batch = cond.repeat(x.shape[0], 1, 1)
131
+ alpha_prod_t = self.scheduler.alphas_cumprod[t]
132
+ alpha_prod_t_prev = (
133
+ self.scheduler.alphas_cumprod[timesteps[i + 1]]
134
+ if i < len(timesteps) - 1
135
+ else self.scheduler.final_alpha_cumprod
136
+ )
137
+ mu = alpha_prod_t ** 0.5
138
+ sigma = (1 - alpha_prod_t) ** 0.5
139
+ mu_prev = alpha_prod_t_prev ** 0.5
140
+ sigma_prev = (1 - alpha_prod_t_prev) ** 0.5
141
+
142
+ eps = self.unet(x, t, encoder_hidden_states=cond_batch).sample
143
+
144
+ pred_x0 = (x - sigma * eps) / mu
145
+ x = mu_prev * pred_x0 + sigma_prev * eps
146
+
147
+ if save_latents:
148
+ torch.save(x, os.path.join(save_path, f'noisy_latents_{t}.pt'))
149
+ return x
150
+
151
+ @torch.no_grad()
152
+ def extract_latents(self, num_steps, data_path, save_path, timesteps_to_save,
153
+ inversion_prompt='', extract_reverse=False):
154
+ self.scheduler.set_timesteps(num_steps)
155
+
156
+ cond = self.get_text_embeds(inversion_prompt, "")[1].unsqueeze(0)
157
+ image = self.load_img(data_path)
158
+ latent = self.encode_imgs(image)
159
+
160
+ inverted_x = self.inversion_func(cond, latent, save_path, save_latents=not extract_reverse,
161
+ timesteps_to_save=timesteps_to_save)
162
+ latent_reconstruction = self.ddim_sample(inverted_x, cond, save_path, save_latents=extract_reverse,
163
+ timesteps_to_save=timesteps_to_save)
164
+ rgb_reconstruction = self.decode_latents(latent_reconstruction)
165
+
166
+ return rgb_reconstruction # , latent_reconstruction
167
+
168
+
169
+ def run(opt):
170
+ # timesteps to save
171
+ if opt.sd_version == '2.1':
172
+ model_key = "stabilityai/stable-diffusion-2-1-base"
173
+ elif opt.sd_version == '2.0':
174
+ model_key = "stabilityai/stable-diffusion-2-base"
175
+ elif opt.sd_version == '1.5':
176
+ model_key = "runwayml/stable-diffusion-v1-5"
177
+ elif opt.sd_version == 'depth':
178
+ model_key = "stabilityai/stable-diffusion-2-depth"
179
+ toy_scheduler = DDIMScheduler.from_pretrained(model_key, subfolder="scheduler")
180
+ toy_scheduler.set_timesteps(opt.save_steps)
181
+ timesteps_to_save, num_inference_steps = get_timesteps(toy_scheduler, num_inference_steps=opt.save_steps,
182
+ strength=1.0,
183
+ device=device)
184
+
185
+ seed_everything(opt.seed)
186
+
187
+ extraction_path_prefix = "_reverse" if opt.extract_reverse else "_forward"
188
+ save_path = os.path.join(opt.save_dir + extraction_path_prefix, os.path.splitext(os.path.basename(opt.data_path))[0])
189
+ os.makedirs(save_path, exist_ok=True)
190
+
191
+ model = Preprocess(device, sd_version=opt.sd_version, hf_key=None)
192
+ recon_image = model.extract_latents(data_path=opt.data_path,
193
+ num_steps=opt.steps,
194
+ save_path=save_path,
195
+ timesteps_to_save=timesteps_to_save,
196
+ inversion_prompt=opt.inversion_prompt,
197
+ extract_reverse=opt.extract_reverse)
198
+
199
+ T.ToPILImage()(recon_image[0]).save(os.path.join(save_path, f'recon.jpg'))
200
+
201
+
202
+ if __name__ == "__main__":
203
+ device = 'cuda'
204
+ parser = argparse.ArgumentParser()
205
+ parser.add_argument('--data_path', type=str,
206
+ default='data/horse.jpg')
207
+ parser.add_argument('--save_dir', type=str, default='latents')
208
+ parser.add_argument('--sd_version', type=str, default='2.1', choices=['1.5', '2.0', '2.1'],
209
+ help="stable diffusion version")
210
+ parser.add_argument('--seed', type=int, default=1)
211
+ parser.add_argument('--steps', type=int, default=999)
212
+ parser.add_argument('--save-steps', type=int, default=1000)
213
+ parser.add_argument('--inversion_prompt', type=str, default='')
214
+ parser.add_argument('--extract-reverse', default=False, action='store_true', help="extract features during the denoising process")
215
+ opt = parser.parse_args()
216
+ run(opt)
CCEdit-main/src/pnp-diffusers/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ torch==2.0.1
2
+ torchvision==0.15.2
3
+ numpy==1.25.0
4
+ diffusers==0.17.1
5
+ xformers==0.0.20
6
+ transformers==4.30.2
7
+ accelerate==0.20.3
CCEdit-main/src/sdata/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023 StabilityAI
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.
CCEdit-main/src/sdata/examples/configs/example.yaml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset:
2
+ urls:
3
+ # USER: adapt this path the root of your custom dataset
4
+ - "/path/to/data"
5
+ pipeline_config:
6
+ shardshuffle: 10000
7
+ sample_shuffle: 1000 # USER: you might wanna adapt depending on your available RAM
8
+
9
+ decoders:
10
+ - "pil"
11
+
12
+ postprocessors:
13
+ - target: sdata.mappers.TorchVisionImageTransforms
14
+ params:
15
+ key: 'jpg' # USER: you might wanna adapt this for your custom dataset
16
+ transforms:
17
+ - target: torchvision.transforms.Resize
18
+ params:
19
+ size: 256
20
+ interpolation: 3
21
+ - target: torchvision.transforms.ToTensor
22
+ - target: sdata.mappers.Rescaler
23
+
24
+ - target: sdata.mappers.AddOriginalImageSizeAsTupleAndCropToSquare
25
+ params:
26
+ h_key: height # USER: you might wanna adapt this for your custom dataset
27
+ w_key: width # USER: you might wanna adapt this for your custom dataset
28
+
29
+ loader:
30
+ batch_size: 64
31
+ num_workers: 6
CCEdit-main/src/sdata/examples/image_simple.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import List
3
+
4
+ import torch
5
+ from omegaconf import OmegaConf
6
+ import numpy as np
7
+
8
+ from sdata import create_dataset, create_loader
9
+
10
+ num_it = 100
11
+ max_vis = 3
12
+
13
+ if __name__ == "__main__":
14
+ filedir = os.path.realpath(os.path.dirname(__file__))
15
+ config_path = os.path.join(filedir, "configs", "example.yaml")
16
+ config = OmegaConf.load(config_path)
17
+
18
+ # build config
19
+ datapipeline = create_dataset(**config.dataset)
20
+
21
+ # build loader
22
+ loader = create_loader(datapipeline, **config.loader)
23
+
24
+ print(f"Yielding {num_it} batches")
25
+
26
+ for i, batch in enumerate(loader):
27
+ if i >= num_it:
28
+ break
29
+
30
+ for key in batch:
31
+ if isinstance(batch[key], (torch.Tensor, np.ndarray)):
32
+ print(key, batch[key].shape)
33
+ elif isinstance(batch[key], (List)):
34
+ print(key)
35
+ print(batch[key][:max_vis])
36
+
37
+ print("ciao")
CCEdit-main/src/sdata/requirements_pt1.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ omegaconf
2
+ einops
3
+ fire
4
+ tqdm
5
+ webdataset>=0.2.33
6
+ --extra-index-url https://download.pytorch.org/whl/cu117
7
+ torch==1.13.1
8
+ torchdata==0.5.1
9
+ torchaudio==0.13.1
10
+ torchvision==0.14.1+cu117
11
+ torchmetrics
12
+ opencv-python==4.6.0.66
13
+ -e .
CCEdit-main/src/sdata/sdata.egg-info/PKG-INFO ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Metadata-Version: 2.2
2
+ Name: sdata
3
+ Version: 0.0.1
4
+ License-File: LICENSE
CCEdit-main/src/sdata/sdata.egg-info/SOURCES.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LICENSE
2
+ README.md
3
+ setup.py
4
+ sdata/__init__.py
5
+ sdata/custom_datapipes.py
6
+ sdata/datapipeline.py
7
+ sdata/dataset.py
8
+ sdata/dummy.py
9
+ sdata.egg-info/PKG-INFO
10
+ sdata.egg-info/SOURCES.txt
11
+ sdata.egg-info/dependency_links.txt
12
+ sdata.egg-info/top_level.txt
13
+ sdata/filters/__init__.py
14
+ sdata/filters/base.py
15
+ sdata/filters/metadata_filters.py
16
+ sdata/mappers/__init__.py
17
+ sdata/mappers/base.py
18
+ sdata/mappers/batched_mappers.py
19
+ sdata/mappers/sample_mappers.py
CCEdit-main/src/sdata/sdata.egg-info/dependency_links.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
CCEdit-main/src/sdata/sdata.egg-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ sdata
CCEdit-main/src/sdata/sdata/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .dataset import create_dataset, create_loader
2
+ from .datapipeline import warn_and_continue
3
+ from . import mappers, filters
4
+ from .dummy import create_dummy_dataset
5
+
6
+
7
+ __all__ = [
8
+ "filters",
9
+ "mappers",
10
+ "create_loader",
11
+ "create_dataset",
12
+ "warn_and_continue",
13
+ "create_dummy_dataset",
14
+ ]
CCEdit-main/src/sdata/sdata/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (423 Bytes). View file
 
CCEdit-main/src/sdata/sdata/__pycache__/custom_datapipes.cpython-39.pyc ADDED
Binary file (13 kB). View file
 
CCEdit-main/src/sdata/sdata/__pycache__/datapipeline.cpython-39.pyc ADDED
Binary file (14.7 kB). View file
 
CCEdit-main/src/sdata/sdata/__pycache__/dataset.cpython-39.pyc ADDED
Binary file (6.31 kB). View file
 
CCEdit-main/src/sdata/sdata/__pycache__/dummy.cpython-39.pyc ADDED
Binary file (1.46 kB). View file
 
CCEdit-main/src/sdata/sdata/datapipeline.py ADDED
@@ -0,0 +1,536 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import os
3
+ from typing import Callable, Optional, Union, List, Any, Dict
4
+ import re
5
+ from packaging import version
6
+ from operator import itemgetter
7
+ import functools
8
+ import time
9
+ import warnings
10
+ import threading
11
+
12
+
13
+ from omegaconf import ListConfig, DictConfig
14
+ import torchdata
15
+ import torch.distributed as dist
16
+
17
+ from torch.utils.data.datapipes.iter import IterableWrapper, FileOpener
18
+ from torchdata.datapipes.iter import IterKeyZipper
19
+ import webdataset as wds
20
+
21
+ from .custom_datapipes import (
22
+ CustomShardExpanderIterDataPipe,
23
+ SplitByWorker,
24
+ PrefixResampler,
25
+ TarArchiveLoaderAndCloser,
26
+ SeedSetter,
27
+ Dataset2SamplesConverter,
28
+ _is_stream_handle,
29
+ )
30
+
31
+ class TimeoutError(Exception):
32
+ pass
33
+
34
+
35
+ def timeout_wrapper(func):
36
+ def wrapper(*args, **kwargs):
37
+ if (
38
+ "SDATA_MAX_EXC_TIME" not in os.environ
39
+ or not os.environ["SDATA_MAX_EXC_TIME"]
40
+ ):
41
+ res = func(*args, **kwargs)
42
+ del args
43
+ del kwargs
44
+ return res
45
+
46
+ timeout = float(os.environ["SDATA_MAX_EXC_TIME"])
47
+
48
+ result = [None]
49
+ exception = [None]
50
+ event = threading.Event()
51
+
52
+ def wrapped_func():
53
+ try:
54
+ result[0] = func(*args, **kwargs)
55
+ except Exception as e:
56
+ exception[0] = e
57
+ finally:
58
+ event.set()
59
+
60
+ thread = threading.Thread(target=wrapped_func)
61
+ thread.start()
62
+ event.wait(timeout)
63
+
64
+ if not event.is_set():
65
+ raise TimeoutError(
66
+ f"Function call timed out (longer than {timeout } secs)."
67
+ )
68
+
69
+ thread.join()
70
+
71
+ if exception[0] is not None:
72
+ raise exception[0]
73
+
74
+ del thread
75
+ del exception
76
+ del wrapped_func
77
+ del event
78
+ del args
79
+ del kwargs
80
+
81
+ return result[0]
82
+
83
+ return wrapper
84
+
85
+
86
+ def warn_and_continue(exn):
87
+ """Call in an exception handler to ignore any exception, isssue a warning, and continue."""
88
+ print(exn)
89
+ warnings.warn(repr(exn))
90
+ time.sleep(0.05)
91
+ return True
92
+
93
+
94
+ def time_measure(name: str = "function"):
95
+ def wrapper(fn):
96
+ def measure_time(*args, **kwargs):
97
+ start = time.perf_counter()
98
+ r = fn(*args, **kwargs)
99
+ end = time.perf_counter()
100
+ if "SDATA_PROFILE" in os.environ and os.environ["SDATA_PROFILE"]:
101
+ if r is None:
102
+ return r
103
+ try:
104
+ if isinstance(r, Dict):
105
+ r[f"{name}-time"] = end - start
106
+ else:
107
+ args[1][f"{name}-time"] = end - start
108
+
109
+ except Exception as e:
110
+ print(f"Exception raised when measuring time for {name}")
111
+ raise e
112
+
113
+ del args
114
+ del kwargs
115
+
116
+ return r
117
+
118
+ return measure_time
119
+
120
+ return wrapper
121
+
122
+
123
+ def instantiate(config: Union[Dict, DictConfig]) -> Any:
124
+ if not "target" in config:
125
+ if config == "__is_first_stage__":
126
+ return None
127
+ elif config == "__is_unconditional__":
128
+ return None
129
+ raise KeyError("Expected key `target` to instantiate.")
130
+ return create_obj(config["target"])(**config.get("params", dict()))
131
+
132
+
133
+ def make_callable(config):
134
+ return functools.partial(
135
+ create_obj(config["target"]), **config.get("params", dict())
136
+ )
137
+
138
+
139
+ def create_obj(string: str, reload: bool = False, invalidate_cache: bool = True) -> Any:
140
+ module, cls = string.rsplit(".", 1)
141
+ if invalidate_cache:
142
+ importlib.invalidate_caches()
143
+ if reload:
144
+ module_imp = importlib.import_module(module)
145
+ importlib.reload(module_imp)
146
+ return getattr(importlib.import_module(module, package=None), cls)
147
+
148
+
149
+ class KeyPassThroughDecoder(wds.Decoder):
150
+ def __init__(self, *args, passthrough_keys=None, **kwargs):
151
+ super().__init__(*args, **kwargs)
152
+ self.passthrough_keys = passthrough_keys
153
+ if self.passthrough_keys is None:
154
+ self.passthrough_keys = []
155
+
156
+ def decode1(self, key, data):
157
+ # if data is a stream handle, we need to read all the content before decoding
158
+ if _is_stream_handle(data):
159
+ ds = data
160
+ # The behavior of .read can differ between streams (e.g. HTTPResponse), hence this is used instead
161
+ data = b"".join(data)
162
+ ds.close()
163
+
164
+ key = "." + key
165
+ for f in self.handlers:
166
+ result = f(key, data)
167
+ if isinstance(result, wds.autodecode.Continue):
168
+ key, data = result.key, result.data
169
+ continue
170
+ if result is not None:
171
+ del data
172
+ return result
173
+ return data
174
+
175
+ @timeout_wrapper
176
+ @time_measure(name="KeyPassThroughDecoder")
177
+ def decode(self, sample):
178
+ """Decode an entire sample.
179
+
180
+ :param sample: the sample, a dictionary of key value pairs
181
+ """
182
+ result = {}
183
+ assert isinstance(sample, dict), sample
184
+ for k, v in list(sample.items()):
185
+ if k[0] == "_":
186
+ if isinstance(v, bytes):
187
+ v = v.decode("utf-8")
188
+ result[k] = v
189
+ continue
190
+ if self.only is not None and k not in self.only:
191
+ result[k] = v
192
+ continue
193
+ assert v is not None
194
+ if self.partial:
195
+ if isinstance(v, bytes) or k in self.passthrough_keys:
196
+ result[k] = self.decode1(k, v)
197
+ else:
198
+ result[k] = v
199
+ else:
200
+ assert (
201
+ isinstance(v, bytes) or k in self.passthrough_keys
202
+ ), f"key: {k}; passthrough_keys: {self.passthrough_keys}"
203
+ result[k] = self.decode1(k, v)
204
+ return result
205
+
206
+
207
+ def tarfilter(x):
208
+ ret = x.endswith(".tar")
209
+ del x
210
+ return ret
211
+
212
+
213
+ def grouper(x):
214
+ key = x[0].split("/")[-1].split(".")[0]
215
+ del x
216
+ return key
217
+
218
+
219
+ def tuple_grouper(x):
220
+ key = x[0][0].split("/")[-1].split(".")[0]
221
+ del x
222
+ return key
223
+
224
+
225
+ def merge_samples(s1, s2, meta_urls):
226
+ s1_files = [os.path.splitext(s[0])[1] for s in s1]
227
+ meta_key_list = [mk for mk in meta_urls if mk in s2[0][0]]
228
+ if len(meta_key_list) == 0:
229
+ raise ValueError(
230
+ f"no matching meta key found for the following file(s): {os.path.splitext(s2[0][0])[0]}"
231
+ )
232
+ elif len(meta_key_list) > 1:
233
+ raise ValueError(
234
+ f"More than one matching meta key found for the following file(s): {os.path.splitext(s2[0][0])[0]}"
235
+ )
236
+
237
+ meta_key = meta_key_list[0]
238
+ outs2 = [
239
+ s
240
+ if os.path.splitext(s[0])[1] not in s1_files
241
+ else (os.path.splitext(s[0])[0] + meta_key + os.path.splitext(s[0])[1], s[1])
242
+ for s in s2
243
+ ]
244
+ del s2
245
+ return list(s1) + outs2
246
+
247
+
248
+ def merge_them(u1, u2):
249
+ # concat lists: these lists should contain all tarfiles from the same prefix but
250
+ # with different filenames
251
+ return u1[1] + [
252
+ u2,
253
+ ]
254
+
255
+
256
+ def identity(x):
257
+ return True
258
+
259
+
260
+ def map_to_tuple(x):
261
+ return (
262
+ os.path.join(os.path.split(x)[0], os.path.splitext(os.path.split(x)[1])[0]),
263
+ [
264
+ x,
265
+ ],
266
+ )
267
+
268
+
269
+ def filter_with_meta_set(x, meta_set):
270
+ return itemgetter(0)(x) in meta_set
271
+
272
+
273
+ def get_ref_key(x, suffix):
274
+ return os.path.splitext(x.replace("_" + suffix, ""))[0]
275
+
276
+
277
+ def list_files_in_datapipe(
278
+ urls: Union[List, ListConfig],
279
+ is_braceexpand: bool,
280
+ tar_sampler: Callable = identity,
281
+ ) -> torchdata.datapipes.iter.IterDataPipe:
282
+ """
283
+
284
+ :param datapipe:
285
+ :param is_braceexpand:
286
+ :return:
287
+ """
288
+ datapipe = IterableWrapper(urls)
289
+
290
+ if version.parse(torchdata.__version__) >= version.parse("0.6.0"):
291
+ if is_braceexpand:
292
+ datapipe = CustomShardExpanderIterDataPipe(datapipe)
293
+ else:
294
+ datapipe = datapipe.list_files(recursive=True).filter(tarfilter)
295
+ else:
296
+ if is_braceexpand:
297
+ datapipe = CustomShardExpanderIterDataPipe(datapipe)
298
+ else:
299
+ datapipe = datapipe.list_files(recursive=True).filter(tarfilter)
300
+
301
+ datapipe = datapipe.filter(tar_sampler)
302
+
303
+ return datapipe
304
+
305
+
306
+ class StableDataPipeline(wds.DataPipeline, wds.compat.FluidInterface):
307
+ """
308
+ Central class for reading data from tars on local fs and building samples based on consecutive files with the same keys
309
+ """
310
+
311
+ def __init__(
312
+ self,
313
+ urls: Union[List[str], str, ListConfig],
314
+ meta_urls: Optional[Union[List[str], str]] = None,
315
+ metadata_buffer_size: Union[int, None] = 10000,
316
+ repeat: int = None,
317
+ shardshuffle: int = 10000,
318
+ sample_shuffle: int = 1,
319
+ resample_prefixes: bool = False,
320
+ prefix_probs: Optional[List[float]] = None,
321
+ split_data_by_worker: bool = True,
322
+ tar_sampler: Optional[Union[DictConfig, Dict, Callable]] = identity,
323
+ handler: Union[Callable, DictConfig] = wds.reraise_exception,
324
+ debug: bool = False,
325
+ n_shards: int = 100000,
326
+ ):
327
+ """
328
+
329
+ :param urls: folders to load the shards from, can be a list of different prefoxes for dataset mixing
330
+ :param meta_urls: can be used for aligned metadata files stored as tars
331
+ :param metadata_buffer_size:
332
+ :param repeat: number of repetitions in the training data. Default is None which means looping perpetually.
333
+ :param shardshuffle: Shuffle buffer size for shard shuffling. size 1 means no shufflin. Default is 10k.
334
+ :param sample_shuffle: Shuffle buffer for sample-level-shuffling. Default is 1 which means no shuffling
335
+ :param resample_prefixes: Whether to resample when different prefixes are in the entire dataset.
336
+ This can be useful in combination with prefix probs when training on merged datasets of non-equal size.
337
+ :param prefix_probs: list containing resampling probabilities for every prefix in `urls`
338
+ :param split_data_by_worker: Whether to split shards across worker threads for num_workers > 0
339
+ :param handler: handler for handling exceptions as in webdataset
340
+ """
341
+ super().__init__()
342
+
343
+ if isinstance(urls, (List, ListConfig, list)):
344
+ pass
345
+ elif isinstance(urls, str):
346
+ urls = [urls]
347
+ else:
348
+ raise TypeError(
349
+ "urls need to be path to a S3 prefix or list of paths to more than one prefixes"
350
+ )
351
+
352
+ if isinstance(handler, (DictConfig, Dict)):
353
+ handler = make_callable(handler)
354
+
355
+
356
+ # get some information abt fs where shards live in and the way shards are specified
357
+ is_braceexpand = any(["{" in u for u in urls])
358
+
359
+ if is_braceexpand:
360
+ brace_expansion = re.compile(r"\{[0-9]+\.\.[0-9]+\}")
361
+ assert all(len(re.findall(brace_expansion, u)) == 1 for u in urls), (
362
+ "Specifiying tars in listed prefixes should be consistent. "
363
+ "It should be either braceexpand notation or just using some "
364
+ "base prefix. If this still fails, you might have some urls with "
365
+ "multiple or malformed braceexpands."
366
+ )
367
+
368
+ if isinstance(tar_sampler, (Dict, dict, DictConfig)):
369
+ tar_sampler = instantiate(tar_sampler)
370
+
371
+ main_datapipe = list_files_in_datapipe(
372
+ urls,
373
+ is_braceexpand=is_braceexpand,
374
+ tar_sampler=tar_sampler,
375
+ ).map(fn=map_to_tuple)
376
+
377
+ if meta_urls:
378
+ print(
379
+ f"Zipping together {len(meta_urls)} meta datapipes with the following suffixes {meta_urls} "
380
+ f"and adding this to the main datapipes "
381
+ )
382
+
383
+ if isinstance(meta_urls, str):
384
+ meta_urls = [meta_urls]
385
+
386
+ meta_urls_base = [os.path.split(m) for m in urls]
387
+ # meta_urls = [[os.path.join(m[0], os.path.splitext(m[1])[0]+f"_{suffix}"+os.path.splitext(m[1])[1]) for m in meta_urls_base] for suffix in meta_urls]
388
+ meta_files = [
389
+ [os.path.join(m[0] + f"_{suffix}", m[1]) for m in meta_urls_base]
390
+ for suffix in meta_urls
391
+ ]
392
+
393
+ for suffix, meta_url_collection in zip(meta_urls, meta_files):
394
+ # this is the meta data which will be added to the man data
395
+ meta_datapipe = list_files_in_datapipe(
396
+ meta_url_collection,
397
+ is_braceexpand=is_braceexpand,
398
+ tar_sampler=tar_sampler,
399
+ )
400
+ # filter out non-exisiting shards
401
+ meta_set = set([get_ref_key(pth, suffix) for pth in meta_datapipe])
402
+ main_datapipe = main_datapipe.filter(
403
+ functools.partial(filter_with_meta_set, meta_set=meta_set)
404
+ )
405
+
406
+ # cycle in side branch to avoid exhausting after iterating over the entire dataset
407
+ meta_datapipe = meta_datapipe.cycle()
408
+ # merging always based on filenames where the metadata shards are expected to have <main_shard_id>.tar,
409
+ # e.g. for a main shard "0000.tar" and an optical flow metadatashard we'd have "0000.tar" for the metadata shard
410
+ # and the resulting key would be /path/to/prefix/0000
411
+ main_datapipe = IterKeyZipper(
412
+ main_datapipe,
413
+ ref_datapipe=meta_datapipe,
414
+ key_fn=itemgetter(0),
415
+ ref_key_fn=functools.partial(get_ref_key, suffix=suffix),
416
+ keep_key=True,
417
+ merge_fn=merge_them,
418
+ buffer_size=metadata_buffer_size,
419
+ )
420
+ # main_datapipe = main_datapipe
421
+
422
+ # start shuffling accross shards for the first time to mix different datasets
423
+ # (can be the same for all workers, just as an additional shuffled initialization)
424
+ if shardshuffle > 1 and not resample_prefixes and len(urls) > 1:
425
+ # back to datapipes. We further apply a map to remove the key, so that the result is the sames than
426
+ # for the prefix subsampler
427
+ main_datapipe = main_datapipe.shuffle(buffer_size=n_shards).map(
428
+ fn=itemgetter(1)
429
+ )
430
+ elif resample_prefixes:
431
+ main_datapipe = PrefixResampler(
432
+ main_datapipe.shuffle(buffer_size=n_shards),
433
+ ps=prefix_probs,
434
+ prefixes=urls,
435
+ is_braceexpand=is_braceexpand,
436
+ custom_seeding=split_data_by_worker,
437
+ debug=debug
438
+ )
439
+ else:
440
+ main_datapipe = main_datapipe.map(itemgetter(1))
441
+
442
+ if not resample_prefixes:
443
+ shardshuffle = max(shardshuffle, 1)
444
+ main_datapipe = main_datapipe.shuffle(buffer_size=shardshuffle)
445
+
446
+ main_datapipe = main_datapipe.sharding_filter()
447
+
448
+ # after this operation datapipes in the distinct processes contain different tars
449
+ if dist.is_available() and dist.is_initialized():
450
+ # after this operation datapipes in the distinct processes contain different tars
451
+
452
+ global_rank = dist.get_rank()
453
+ world_size = dist.get_world_size()
454
+ main_datapipe.apply_sharding(world_size, global_rank)
455
+ print("#" * 100)
456
+ print(f"distributing shards for worker with global rank {global_rank}")
457
+ print("#" * 100)
458
+
459
+ else:
460
+ print(
461
+ f"torch distributed not used, not applying sharding in {self.__class__.__name__}"
462
+ )
463
+
464
+ if split_data_by_worker:
465
+ print("Distributing shards across the worker threads in every process")
466
+ main_datapipe = SplitByWorker(
467
+ datapipe=main_datapipe, debug=debug
468
+ )
469
+ else:
470
+ main_datapipe = SeedSetter(main_datapipe, debug=debug)
471
+
472
+ main_datapipe = main_datapipe.cycle(count=repeat)
473
+
474
+ # unzip before loading, since here we can be sure that all shards are distributed and shuffled
475
+ # aligned with their corresponding metadata shards
476
+ meta_len = len(meta_urls) if meta_urls else 0
477
+ main_datapipe, *meta_datapipes = main_datapipe.unzip(
478
+ sequence_length=meta_len + 1
479
+ )
480
+
481
+
482
+ # regular fileopener
483
+ main_datapipe = FileOpener(main_datapipe, mode="b")
484
+ meta_datapipes = [FileOpener(m, mode="b") for m in meta_datapipes]
485
+
486
+ # adapted TarLoader which closes open tarfile handles after exceeding them
487
+ # main_datapipe = TarArchiveLoaderAndCloser(datapipe=main_datapipe).groupby(grouper)
488
+ #
489
+ main_datapipe = TarArchiveLoaderAndCloser(
490
+ datapipe=main_datapipe, handler=handler
491
+ ).groupby(grouper)
492
+ meta_datapipes = [
493
+ TarArchiveLoaderAndCloser(datapipe=m, handler=handler).groupby(grouper)
494
+ for m in meta_datapipes
495
+ ]
496
+
497
+ # zip again, this time we're searching based on the same keys
498
+ for meta_dp in meta_datapipes:
499
+ # here we da
500
+ main_datapipe = IterKeyZipper(
501
+ main_datapipe,
502
+ ref_datapipe=meta_dp,
503
+ key_fn=tuple_grouper,
504
+ merge_fn=functools.partial(merge_samples, meta_urls=meta_urls),
505
+ buffer_size=metadata_buffer_size,
506
+ )
507
+
508
+ if sample_shuffle > 0:
509
+ main_datapipe = main_datapipe.shuffle(buffer_size=sample_shuffle)
510
+
511
+ main_datapipe = Dataset2SamplesConverter(main_datapipe, handler=handler)
512
+ self.append(main_datapipe)
513
+ # self.append(dataset2samples(handler=handler))
514
+
515
+ def decode(
516
+ self,
517
+ *args,
518
+ pre=None,
519
+ post=None,
520
+ only=None,
521
+ partial=False,
522
+ passthrough_keys=None,
523
+ handler=wds.reraise_exception,
524
+ ):
525
+ handlers = [
526
+ wds.autodecode.ImageHandler(x) if isinstance(x, str) else x for x in args
527
+ ]
528
+ decoder = KeyPassThroughDecoder(
529
+ handlers,
530
+ passthrough_keys=passthrough_keys,
531
+ pre=pre,
532
+ post=post,
533
+ only=only,
534
+ partial=partial,
535
+ )
536
+ return self.map(decoder, handler=handler)
CCEdit-main/src/sdata/sdata/filters/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .base import AbstractFilter, LambdaFilter
2
+ from .metadata_filters import (
3
+ SimpleSizeFilter,
4
+ SimpleKeyFilter,
5
+ )
6
+
7
+ __all__ = [
8
+ "AbstractFilter",
9
+ "SimpleSizeFilter",
10
+ "SimpleKeyFilter",
11
+ "LambdaFilter"
12
+ ]
CCEdit-main/src/sdata/sdata/filters/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (346 Bytes). View file
 
CCEdit-main/src/sdata/sdata/filters/__pycache__/base.cpython-39.pyc ADDED
Binary file (2.3 kB). View file
 
CCEdit-main/src/sdata/sdata/filters/__pycache__/metadata_filters.cpython-39.pyc ADDED
Binary file (4.23 kB). View file
 
CCEdit-main/src/sdata/sdata/filters/base.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import abstractmethod
2
+ from typing import Dict, Union, List, Optional, Callable
3
+
4
+ from omegaconf import ListConfig, DictConfig
5
+
6
+ from ..datapipeline import time_measure, make_callable
7
+
8
+
9
+ class AbstractFilter:
10
+ def __init__(
11
+ self,
12
+ exclude_keys: Optional[Union[List[str], ListConfig, str]] = None,
13
+ verbose: bool = False,
14
+ ):
15
+ if not exclude_keys:
16
+ exclude_keys = []
17
+
18
+ if isinstance(exclude_keys, str):
19
+ exclude_keys = [exclude_keys]
20
+ self.exclude_keys = exclude_keys
21
+
22
+ self.verbose = verbose
23
+
24
+ def skip_this_sample(self, sample: Dict) -> bool:
25
+ res = any(map(lambda x: x in sample["__url__"], self.exclude_keys))
26
+ del sample
27
+ return res
28
+
29
+ @abstractmethod
30
+ def __call__(self, sample: Dict) -> bool:
31
+ raise NotImplementedError("AbstractFilter should not be called but overwritten")
32
+
33
+
34
+ class LambdaFilter(AbstractFilter):
35
+ def __init__(
36
+ self,
37
+ keys: Union[str, List[str], ListConfig],
38
+ fn: Union[Dict, DictConfig, Callable],
39
+ *args,
40
+ **kwargs
41
+ ):
42
+ super().__init__(*args, **kwargs)
43
+ if isinstance(keys, str):
44
+ keys = [keys]
45
+
46
+ self.keys = keys
47
+
48
+ if isinstance(fn, Union[Dict, DictConfig]):
49
+ fn = make_callable(fn)
50
+
51
+ self.fn = fn
52
+
53
+ @time_measure("LambdaMapper")
54
+ def __call__(self, sample: Dict) -> bool:
55
+ if self.skip_this_sample(sample):
56
+ del sample
57
+ return True
58
+
59
+ let_pass = True
60
+ for key in self.keys:
61
+ let_pass &= self.fn(sample[key])
62
+
63
+ del sample
64
+ return let_pass
CCEdit-main/src/sdata/sdata/filters/metadata_filters.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Optional, List, Union, Tuple
2
+
3
+ from omegaconf import DictConfig
4
+
5
+ from .base import AbstractFilter
6
+ from sdata.datapipeline import time_measure, timeout_wrapper
7
+
8
+
9
+ class SimpleKeyFilter(AbstractFilter):
10
+ def __init__(self, keys: Union[str, List[str]], *args, **kwargs):
11
+ super().__init__(*args, **kwargs)
12
+ if isinstance(keys, str):
13
+ keys = [keys]
14
+
15
+ self.keys = set(keys)
16
+
17
+ @timeout_wrapper
18
+ @time_measure("SimpleKeyFilter")
19
+ def __call__(self, sample: Dict) -> bool:
20
+ try:
21
+ if self.skip_this_sample(sample):
22
+ return True
23
+ result = all(map(lambda x: x in sample, self.keys))
24
+ del sample
25
+ return result
26
+ except Exception as e:
27
+ print(f"{e.__class__.__name__} in {self.__class__.__name__}: {e}")
28
+ return False
29
+
30
+
31
+ class SimpleSizeFilter(AbstractFilter):
32
+ def __init__(
33
+ self,
34
+ size: Union[int, Tuple[int, int], List[int]],
35
+ mode: str = "min",
36
+ strict: Optional[Union[bool, Dict]] = None,
37
+ width_key: str = "original_width",
38
+ height_key: str = "original_height",
39
+ *args,
40
+ **kwargs,
41
+ ):
42
+ """
43
+ Simple size filter based on metadata which is already decoded
44
+ :param size: The desired min or max size
45
+ :param mode: either to filter out all above a min size (min) or all below a max size (max)
46
+ :param key: indicates the field in the sample, the field should be a dict
47
+ :param subkeys: list of strings defining subkeys for nested dict, i.e. ['foo','bar'] would result
48
+ in sample[self.key]['foo']['bar'] being the entry in a nested dict, where the size information sits
49
+ :param strict: whether to return True or False when the key is not present
50
+ :param width_key: the width key at the final level in the metadata dict i.e. for key='json',
51
+ subkeys=['foo','bar'] and width_key = 'original_width', the entry sample['json']['foo']['bar']['original_width']
52
+ would be used
53
+ :param height_key: same as above but with width
54
+ """
55
+ super().__init__(*args, **kwargs)
56
+ if isinstance(size, int):
57
+ size = [size, size]
58
+
59
+ self.size = size
60
+
61
+ if mode == "min":
62
+ self.relation = self.filter_min
63
+ else:
64
+ self.relation = self.filter_max
65
+
66
+ self.strict = strict
67
+ if not isinstance(self.strict, (bool, dict, DictConfig)):
68
+ raise TypeError(
69
+ f"strict in {self.__class__.__name__} should be bool or Dict"
70
+ )
71
+
72
+ self.height_key = height_key
73
+ self.width_key = width_key
74
+
75
+ def filter_min(self, height: int, width: int) -> bool:
76
+ return height >= self.size[0] and width >= self.size[1]
77
+
78
+ def filter_max(self, height: int, width: int) -> bool:
79
+ return height <= self.size[0] and width <= self.size[1]
80
+
81
+ @timeout_wrapper
82
+ @time_measure("SimpleSizeFilter")
83
+ def __call__(self, sample: Dict) -> bool:
84
+ try:
85
+ if self.skip_this_sample(sample):
86
+ return True
87
+ # get height and width
88
+ original_width = sample[self.width_key]
89
+ original_height = sample[self.height_key]
90
+
91
+ result = self.relation(original_height, original_width)
92
+ return result
93
+ except Exception as e:
94
+ if isinstance(self.strict, bool):
95
+ return not self.strict
96
+ elif isinstance(self.strict, (dict, DictConfig)):
97
+ url = sample["__url__"]
98
+ key = [k for k in self.strict if k in url][0]
99
+ result = not self.strict[key]
100
+ return result
101
+ else:
102
+ raise TypeError(
103
+ f"strict in {self.__class__.__name__} should be bool or Dict"
104
+ )
CCEdit-main/src/sdata/sdata/mappers/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .base import AbstractMapper
2
+ from .batched_mappers import BatchedEinopsTransform
3
+ from .sample_mappers import (
4
+ TorchVisionImageTransforms,
5
+ Rescaler,
6
+ AddOriginalImageSizeAsTupleAndCropToSquare,
7
+ )
8
+
9
+ __all__ = [
10
+ "AbstractMapper",
11
+ "AddOriginalImageSizeAsTupleAndCropToSquare",
12
+ "BatchedEinopsTransform",
13
+ "TorchVisionImageTransforms",
14
+ "Rescaler",
15
+ ]
CCEdit-main/src/sdata/sdata/mappers/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (444 Bytes). View file
 
CCEdit-main/src/sdata/sdata/mappers/__pycache__/base.cpython-39.pyc ADDED
Binary file (2.35 kB). View file
 
CCEdit-main/src/sdata/sdata/mappers/__pycache__/batched_mappers.cpython-39.pyc ADDED
Binary file (1.31 kB). View file
 
CCEdit-main/src/sdata/sdata/mappers/__pycache__/sample_mappers.cpython-39.pyc ADDED
Binary file (5.5 kB). View file