Commit ·
556dd64
1
Parent(s): e75b02a
demov1
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+8-19
- CLIP/.gitignoreAdded+10
- CLIP/CLIP.pngAdded
- CLIP/LICENSEAdded+22
- CLIP/MANIFEST.inAdded+1
- CLIP/README.mdAdded+193
- CLIP/clip/__init__.pyAdded+1
- CLIP/clip/bpe_simple_vocab_16e6.txt.gzAdded
- CLIP/clip/clip.pyAdded+221
- CLIP/clip/model.pyAdded+432
- CLIP/clip/simple_tokenizer.pyAdded+132
- CLIP/data/yfcc100m.mdAdded+14
- CLIP/model-card.mdAdded+120
- CLIP/notebooks/Interacting_with_CLIP.ipynbAdded
- CLIP/notebooks/Prompt_Engineering_for_ImageNet.ipynbAdded+1188
- CLIP/requirements.txtAdded+5
- CLIP/setup.pyAdded+21
- CLIP/tests/test_consistency.pyAdded+25
- app.py+395-7
- requirements.txtAdded+15
- steps/temp.txtAdded
- taming-transformers/License.txtAdded+19
- taming-transformers/README.mdAdded+377
- taming-transformers/assets/birddrawnbyachild.pngAdded
- taming-transformers/assets/drin.jpgAdded
- taming-transformers/assets/faceshq.jpgAdded
- taming-transformers/assets/first_stage_mushrooms.pngAdded
- taming-transformers/assets/first_stage_squirrels.pngAdded
- taming-transformers/assets/imagenet.pngAdded
- taming-transformers/assets/lake_in_the_mountains.pngAdded
- taming-transformers/assets/mountain.jpegAdded
- taming-transformers/assets/stormy.jpegAdded
- taming-transformers/assets/sunset_and_ocean.jpgAdded
- taming-transformers/assets/teaser.pngAdded
- taming-transformers/configs/coco_cond_stage.yamlAdded+49
- taming-transformers/configs/custom_vqgan.yamlAdded+43
- taming-transformers/configs/drin_transformer.yamlAdded+77
- taming-transformers/configs/faceshq_transformer.yamlAdded+61
- taming-transformers/configs/faceshq_vqgan.yamlAdded+42
- taming-transformers/configs/imagenet_vqgan.yamlAdded+42
- taming-transformers/configs/imagenetdepth_vqgan.yamlAdded+41
- taming-transformers/configs/sflckr_cond_stage.yamlAdded+43
- taming-transformers/data/ade20k_examples.txtAdded+30
- taming-transformers/data/ade20k_images/ADE_val_00000123.jpgAdded
- taming-transformers/data/ade20k_images/ADE_val_00000125.jpgAdded
- taming-transformers/data/ade20k_images/ADE_val_00000126.jpgAdded
- taming-transformers/data/ade20k_images/ADE_val_00000203.jpgAdded
- taming-transformers/data/ade20k_images/ADE_val_00000262.jpgAdded
- taming-transformers/data/ade20k_images/ADE_val_00000287.jpgAdded
- taming-transformers/data/ade20k_images/ADE_val_00000289.jpgAdded
123456789101112131415161718192021222324252627*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bin.* filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zstandard filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text12345678910111213141516*.bin.* filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tar.gz filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text
12345678910__pycache__/*.py[cod]*$py.class*.egg-info.pytest_cache.ipynb_checkpoints
thumbs.db.DS_Store.idea12345678910111213141516171819202122MIT License
Copyright (c) 2021 OpenAI
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.
1include clip/bpe_simple_vocab_16e6.txt.gz123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193# CLIP
[[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)
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.
## Approach

## Usage
First, [install PyTorch 1.7.1](https://pytorch.org/get-started/locally/) and torchvision, as well as small additional dependencies, and then install this repo as a Python package. On a CUDA GPU machine, the following will do the trick:
```bash$ conda install --yes -c pytorch pytorch=1.7.1 torchvision cudatoolkit=11.0$ pip install ftfy regex tqdm$ pip install git+https://github.com/openai/CLIP.git```
Replace `cudatoolkit=11.0` above with the appropriate CUDA version on your machine or `cpuonly` when installing on a machine without a GPU.
```pythonimport torchimport clipfrom PIL import Image
device = "cuda" if torch.cuda.is_available() else "cpu"model, preprocess = clip.load("ViT-B/32", device=device)
image = preprocess(Image.open("CLIP.png")).unsqueeze(0).to(device)text = clip.tokenize(["a diagram", "a dog", "a cat"]).to(device)
with torch.no_grad(): image_features = model.encode_image(image) text_features = model.encode_text(text) logits_per_image, logits_per_text = model(image, text) probs = logits_per_image.softmax(dim=-1).cpu().numpy()
print("Label probs:", probs) # prints: [[0.9927937 0.00421068 0.00299572]]```
## API
The CLIP module `clip` provides the following methods:
#### `clip.available_models()`
Returns the names of the available CLIP models.
#### `clip.load(name, device=..., jit=False)`
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.
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.
#### `clip.tokenize(text: Union[str, List[str]], context_length=77)`
Returns a LongTensor containing tokenized sequences of given text input(s). This can be used as the input to the model
---
The model returned by `clip.load()` supports the following methods:
#### `model.encode_image(image: Tensor)`
Given a batch of images, returns the image features encoded by the vision portion of the CLIP model.
#### `model.encode_text(text: Tensor)`
Given a batch of text tokens, returns the text features encoded by the language portion of the CLIP model.
#### `model(image: Tensor, text: Tensor)`
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.
## More Examples
### Zero-Shot Prediction
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.
```pythonimport osimport clipimport torchfrom torchvision.datasets import CIFAR100
# Load the modeldevice = "cuda" if torch.cuda.is_available() else "cpu"model, preprocess = clip.load('ViT-B/32', device)
# Download the datasetcifar100 = CIFAR100(root=os.path.expanduser("~/.cache"), download=True, train=False)
# Prepare the inputsimage, class_id = cifar100[3637]image_input = preprocess(image).unsqueeze(0).to(device)text_inputs = torch.cat([clip.tokenize(f"a photo of a {c}") for c in cifar100.classes]).to(device)
# Calculate featureswith torch.no_grad(): image_features = model.encode_image(image_input) text_features = model.encode_text(text_inputs)
# Pick the top 5 most similar labels for the imageimage_features /= image_features.norm(dim=-1, keepdim=True)text_features /= text_features.norm(dim=-1, keepdim=True)similarity = (100.0 * image_features @ text_features.T).softmax(dim=-1)values, indices = similarity[0].topk(5)
# Print the resultprint("\nTop predictions:\n")for value, index in zip(values, indices): print(f"{cifar100.classes[index]:>16s}: {100 * value.item():.2f}%")```
The output will look like the following (the exact numbers may be slightly different depending on the compute device):
```Top predictions:
snake: 65.31% turtle: 12.29% sweet_pepper: 3.83% lizard: 1.88% crocodile: 1.75%```
Note that this example uses the `encode_image()` and `encode_text()` methods that return the encoded features of given inputs.
### Linear-probe evaluation
The example below uses [scikit-learn](https://scikit-learn.org/) to perform logistic regression on image features.
```pythonimport osimport clipimport torch
import numpy as npfrom sklearn.linear_model import LogisticRegressionfrom torch.utils.data import DataLoaderfrom torchvision.datasets import CIFAR100from tqdm import tqdm
# Load the modeldevice = "cuda" if torch.cuda.is_available() else "cpu"model, preprocess = clip.load('ViT-B/32', device)
# Load the datasetroot = os.path.expanduser("~/.cache")train = CIFAR100(root, download=True, train=True, transform=preprocess)test = CIFAR100(root, download=True, train=False, transform=preprocess)
def get_features(dataset): all_features = [] all_labels = [] with torch.no_grad(): for images, labels in tqdm(DataLoader(dataset, batch_size=100)): features = model.encode_image(images.to(device))
all_features.append(features) all_labels.append(labels)
return torch.cat(all_features).cpu().numpy(), torch.cat(all_labels).cpu().numpy()
# Calculate the image featurestrain_features, train_labels = get_features(train)test_features, test_labels = get_features(test)
# Perform logistic regressionclassifier = LogisticRegression(random_state=0, C=0.316, max_iter=1000, verbose=1)classifier.fit(train_features, train_labels)
# Evaluate using the logistic regression classifierpredictions = classifier.predict(test_features)accuracy = np.mean((test_labels == predictions).astype(np.float)) * 100.print(f"Accuracy = {accuracy:.3f}")```
Note that the `C` value should be determined via a hyperparameter sweep using a validation split.1from .clip import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221import hashlibimport osimport urllibimport warningsfrom typing import Union, List
import torchfrom PIL import Imagefrom torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalizefrom tqdm import tqdm
from .model import build_modelfrom .simple_tokenizer import SimpleTokenizer as _Tokenizer
try: from torchvision.transforms import InterpolationMode BICUBIC = InterpolationMode.BICUBICexcept ImportError: BICUBIC = Image.BICUBIC
if torch.__version__.split(".") < ["1", "7", "1"]: warnings.warn("PyTorch version 1.7.1 or higher is recommended")
__all__ = ["available_models", "load", "tokenize"]_tokenizer = _Tokenizer()
_MODELS = { "RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt", "RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt", "RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt", "RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt", "ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt", "ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt",}
def _download(url: str, root: str = os.path.expanduser("~/.cache/clip")): os.makedirs(root, exist_ok=True) filename = os.path.basename(url)
expected_sha256 = url.split("/")[-2] download_target = os.path.join(root, filename)
if os.path.exists(download_target) and not os.path.isfile(download_target): raise RuntimeError(f"{download_target} exists and is not a regular file")
if os.path.isfile(download_target): if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256: return download_target else: warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
with urllib.request.urlopen(url) as source, open(download_target, "wb") as output: with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True) as loop: while True: buffer = source.read(8192) if not buffer: break
output.write(buffer) loop.update(len(buffer))
if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256: raise RuntimeError(f"Model has been downloaded but the SHA256 checksum does not not match")
return download_target
def _transform(n_px): return Compose([ Resize(n_px, interpolation=BICUBIC), CenterCrop(n_px), lambda image: image.convert("RGB"), ToTensor(), Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)), ])
def available_models() -> List[str]: """Returns the names of available CLIP models""" return list(_MODELS.keys())
def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit=False): """Load a CLIP model
Parameters ---------- name : str A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
device : Union[str, torch.device] The device to put the loaded model
jit : bool Whether to load the optimized JIT model or more hackable non-JIT model (default).
Returns ------- model : torch.nn.Module The CLIP model
preprocess : Callable[[PIL.Image], torch.Tensor] A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input """ if name in _MODELS: model_path = _download(_MODELS[name]) elif os.path.isfile(name): model_path = name else: raise RuntimeError(f"Model {name} not found; available models = {available_models()}")
try: # loading JIT archive model = torch.jit.load(model_path, map_location=device if jit else "cpu").eval() state_dict = None except RuntimeError: # loading saved state dict if jit: warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead") jit = False state_dict = torch.load(model_path, map_location="cpu")
if not jit: model = build_model(state_dict or model.state_dict()).to(device) if str(device) == "cpu": model.float() return model, _transform(model.visual.input_resolution)
# patch the device names device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[]) device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
def patch_device(module): try: graphs = [module.graph] if hasattr(module, "graph") else [] except RuntimeError: graphs = []
if hasattr(module, "forward1"): graphs.append(module.forward1.graph)
for graph in graphs: for node in graph.findAllNodes("prim::Constant"): if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"): node.copyAttributes(device_node)
model.apply(patch_device) patch_device(model.encode_image) patch_device(model.encode_text)
# patch dtype to float32 on CPU if str(device) == "cpu": float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[]) float_input = list(float_holder.graph.findNode("aten::to").inputs())[1] float_node = float_input.node()
def patch_float(module): try: graphs = [module.graph] if hasattr(module, "graph") else [] except RuntimeError: graphs = []
if hasattr(module, "forward1"): graphs.append(module.forward1.graph)
for graph in graphs: for node in graph.findAllNodes("aten::to"): inputs = list(node.inputs()) for i in [1, 2]: # dtype can be the second or third argument to aten::to() if inputs[i].node()["value"] == 5: inputs[i].node().copyAttributes(float_node)
model.apply(patch_float) patch_float(model.encode_image) patch_float(model.encode_text)
model.float()
return model, _transform(model.input_resolution.item())
def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = False) -> torch.LongTensor: """ Returns the tokenized representation of given input string(s)
Parameters ---------- texts : Union[str, List[str]] An input string or a list of input strings to tokenize
context_length : int The context length to use; all CLIP models use 77 as the context length
truncate: bool Whether to truncate the text in case its encoding is longer than the context length
Returns ------- A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length] """ if isinstance(texts, str): texts = [texts]
sot_token = _tokenizer.encoder["<|startoftext|>"] eot_token = _tokenizer.encoder["<|endoftext|>"] all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts] result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
for i, tokens in enumerate(all_tokens): if len(tokens) > context_length: if truncate: tokens = tokens[:context_length] tokens[-1] = eot_token else: raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}") result[i, :len(tokens)] = torch.tensor(tokens)
return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432from collections import OrderedDictfrom typing import Tuple, Union
import numpy as npimport torchimport torch.nn.functional as Ffrom torch import nn
class Bottleneck(nn.Module): expansion = 4
def __init__(self, inplanes, planes, stride=1): super().__init__()
# all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1 self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False) self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes)
self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False) self.bn3 = nn.BatchNorm2d(planes * self.expansion)
self.relu = nn.ReLU(inplace=True) self.downsample = None self.stride = stride
if stride > 1 or inplanes != planes * Bottleneck.expansion: # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1 self.downsample = nn.Sequential(OrderedDict([ ("-1", nn.AvgPool2d(stride)), ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)), ("1", nn.BatchNorm2d(planes * self.expansion)) ]))
def forward(self, x: torch.Tensor): identity = x
out = self.relu(self.bn1(self.conv1(x))) out = self.relu(self.bn2(self.conv2(out))) out = self.avgpool(out) out = self.bn3(self.conv3(out))
if self.downsample is not None: identity = self.downsample(x)
out += identity out = self.relu(out) return out
class AttentionPool2d(nn.Module): def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None): super().__init__() self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5) self.k_proj = nn.Linear(embed_dim, embed_dim) self.q_proj = nn.Linear(embed_dim, embed_dim) self.v_proj = nn.Linear(embed_dim, embed_dim) self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim) self.num_heads = num_heads
def forward(self, x): x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC x, _ = F.multi_head_attention_forward( query=x, key=x, value=x, embed_dim_to_check=x.shape[-1], num_heads=self.num_heads, q_proj_weight=self.q_proj.weight, k_proj_weight=self.k_proj.weight, v_proj_weight=self.v_proj.weight, in_proj_weight=None, in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]), bias_k=None, bias_v=None, add_zero_attn=False, dropout_p=0, out_proj_weight=self.c_proj.weight, out_proj_bias=self.c_proj.bias, use_separate_proj_weight=True, training=self.training, need_weights=False )
return x[0]
class ModifiedResNet(nn.Module): """ A ResNet class that is similar to torchvision's but contains the following changes: - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool. - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1 - The final pooling layer is a QKV attention instead of an average pool """
def __init__(self, layers, output_dim, heads, input_resolution=224, width=64): super().__init__() self.output_dim = output_dim self.input_resolution = input_resolution
# the 3-layer stem self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(width // 2) self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(width // 2) self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False) self.bn3 = nn.BatchNorm2d(width) self.avgpool = nn.AvgPool2d(2) self.relu = nn.ReLU(inplace=True)
# residual layers self._inplanes = width # this is a *mutable* variable used during construction self.layer1 = self._make_layer(width, layers[0]) self.layer2 = self._make_layer(width * 2, layers[1], stride=2) self.layer3 = self._make_layer(width * 4, layers[2], stride=2) self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
embed_dim = width * 32 # the ResNet feature dimension self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
def _make_layer(self, planes, blocks, stride=1): layers = [Bottleneck(self._inplanes, planes, stride)]
self._inplanes = planes * Bottleneck.expansion for _ in range(1, blocks): layers.append(Bottleneck(self._inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x): def stem(x): for conv, bn in [(self.conv1, self.bn1), (self.conv2, self.bn2), (self.conv3, self.bn3)]: x = self.relu(bn(conv(x))) x = self.avgpool(x) return x
x = x.type(self.conv1.weight.dtype) x = stem(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.attnpool(x)
return x
class LayerNorm(nn.LayerNorm): """Subclass torch's LayerNorm to handle fp16."""
def forward(self, x: torch.Tensor): orig_type = x.dtype ret = super().forward(x.type(torch.float32)) return ret.type(orig_type)
class QuickGELU(nn.Module): def forward(self, x: torch.Tensor): return x * torch.sigmoid(1.702 * x)
class ResidualAttentionBlock(nn.Module): def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None): super().__init__()
self.attn = nn.MultiheadAttention(d_model, n_head) self.ln_1 = LayerNorm(d_model) self.mlp = nn.Sequential(OrderedDict([ ("c_fc", nn.Linear(d_model, d_model * 4)), ("gelu", QuickGELU()), ("c_proj", nn.Linear(d_model * 4, d_model)) ])) self.ln_2 = LayerNorm(d_model) self.attn_mask = attn_mask
def attention(self, x: torch.Tensor): self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
def forward(self, x: torch.Tensor): x = x + self.attention(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return x
class Transformer(nn.Module): def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None): super().__init__() self.width = width self.layers = layers self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
def forward(self, x: torch.Tensor): return self.resblocks(x)
class VisionTransformer(nn.Module): def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int): super().__init__() self.input_resolution = input_resolution self.output_dim = output_dim self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
scale = width ** -0.5 self.class_embedding = nn.Parameter(scale * torch.randn(width)) self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width)) self.ln_pre = LayerNorm(width)
self.transformer = Transformer(width, layers, heads)
self.ln_post = LayerNorm(width) self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
def forward(self, x: torch.Tensor): x = self.conv1(x) # shape = [*, width, grid, grid] x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] 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] x = x + self.positional_embedding.to(x.dtype) x = self.ln_pre(x)
x = x.permute(1, 0, 2) # NLD -> LND x = self.transformer(x) x = x.permute(1, 0, 2) # LND -> NLD
x = self.ln_post(x[:, 0, :])
if self.proj is not None: x = x @ self.proj
return x
class CLIP(nn.Module): def __init__(self, embed_dim: int, # vision image_resolution: int, vision_layers: Union[Tuple[int, int, int, int], int], vision_width: int, vision_patch_size: int, # text context_length: int, vocab_size: int, transformer_width: int, transformer_heads: int, transformer_layers: int ): super().__init__()
self.context_length = context_length
if isinstance(vision_layers, (tuple, list)): vision_heads = vision_width * 32 // 64 self.visual = ModifiedResNet( layers=vision_layers, output_dim=embed_dim, heads=vision_heads, input_resolution=image_resolution, width=vision_width ) else: vision_heads = vision_width // 64 self.visual = VisionTransformer( input_resolution=image_resolution, patch_size=vision_patch_size, width=vision_width, layers=vision_layers, heads=vision_heads, output_dim=embed_dim )
self.transformer = Transformer( width=transformer_width, layers=transformer_layers, heads=transformer_heads, attn_mask=self.build_attention_mask() )
self.vocab_size = vocab_size self.token_embedding = nn.Embedding(vocab_size, transformer_width) self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width)) self.ln_final = LayerNorm(transformer_width)
self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim)) self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
self.initialize_parameters()
def initialize_parameters(self): nn.init.normal_(self.token_embedding.weight, std=0.02) nn.init.normal_(self.positional_embedding, std=0.01)
if isinstance(self.visual, ModifiedResNet): if self.visual.attnpool is not None: std = self.visual.attnpool.c_proj.in_features ** -0.5 nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std) nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std) nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std) nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]: for name, param in resnet_block.named_parameters(): if name.endswith("bn3.weight"): nn.init.zeros_(param)
proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5) attn_std = self.transformer.width ** -0.5 fc_std = (2 * self.transformer.width) ** -0.5 for block in self.transformer.resblocks: nn.init.normal_(block.attn.in_proj_weight, std=attn_std) nn.init.normal_(block.attn.out_proj.weight, std=proj_std) nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
if self.text_projection is not None: nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
def build_attention_mask(self): # lazily create causal attention mask, with full attention between the vision tokens # pytorch uses additive attention mask; fill with -inf mask = torch.empty(self.context_length, self.context_length) mask.fill_(float("-inf")) mask.triu_(1) # zero out the lower diagonal return mask
@property def dtype(self): return self.visual.conv1.weight.dtype
def encode_image(self, image): return self.visual(image.type(self.dtype))
def encode_text(self, text): x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
x = x + self.positional_embedding.type(self.dtype) x = x.permute(1, 0, 2) # NLD -> LND x = self.transformer(x) x = x.permute(1, 0, 2) # LND -> NLD x = self.ln_final(x).type(self.dtype)
# x.shape = [batch_size, n_ctx, transformer.width] # take features from the eot embedding (eot_token is the highest number in each sequence) x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
return x
def forward(self, image, text): image_features = self.encode_image(image) text_features = self.encode_text(text)
# normalized features image_features = image_features / image_features.norm(dim=-1, keepdim=True) text_features = text_features / text_features.norm(dim=-1, keepdim=True)
# cosine similarity as logits logit_scale = self.logit_scale.exp() logits_per_image = logit_scale * image_features @ text_features.t() logits_per_text = logit_scale * text_features @ image_features.t()
# shape = [global_batch_size, global_batch_size] return logits_per_image, logits_per_text
def convert_weights(model: nn.Module): """Convert applicable model parameters to fp16"""
def _convert_weights_to_fp16(l): if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): l.weight.data = l.weight.data.half() if l.bias is not None: l.bias.data = l.bias.data.half()
if isinstance(l, nn.MultiheadAttention): for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]: tensor = getattr(l, attr) if tensor is not None: tensor.data = tensor.data.half()
for name in ["text_projection", "proj"]: if hasattr(l, name): attr = getattr(l, name) if attr is not None: attr.data = attr.data.half()
model.apply(_convert_weights_to_fp16)
def build_model(state_dict: dict): vit = "visual.proj" in state_dict
if vit: vision_width = state_dict["visual.conv1.weight"].shape[0] vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")]) vision_patch_size = state_dict["visual.conv1.weight"].shape[-1] grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5) image_resolution = vision_patch_size * grid_size else: 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]] vision_layers = tuple(counts) vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0] output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5) vision_patch_size = None assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0] image_resolution = output_width * 32
embed_dim = state_dict["text_projection"].shape[1] context_length = state_dict["positional_embedding"].shape[0] vocab_size = state_dict["token_embedding.weight"].shape[0] transformer_width = state_dict["ln_final.weight"].shape[0] transformer_heads = transformer_width // 64 transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks")))
model = CLIP( embed_dim, image_resolution, vision_layers, vision_width, vision_patch_size, context_length, vocab_size, transformer_width, transformer_heads, transformer_layers )
for key in ["input_resolution", "context_length", "vocab_size"]: if key in state_dict: del state_dict[key]
convert_weights(model) model.load_state_dict(state_dict) return model.eval()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132import gzipimport htmlimport osfrom functools import lru_cache
import ftfyimport regex as re
@lru_cache()def default_bpe(): return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
@lru_cache()def bytes_to_unicode(): """ Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This is a signficant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings. And avoids mapping to whitespace/control characters the bpe code barfs on. """ bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1)) cs = bs[:] n = 0 for b in range(2**8): if b not in bs: bs.append(b) cs.append(2**8+n) n += 1 cs = [chr(n) for n in cs] return dict(zip(bs, cs))
def get_pairs(word): """Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs
def basic_clean(text): text = ftfy.fix_text(text) text = html.unescape(html.unescape(text)) return text.strip()
def whitespace_clean(text): text = re.sub(r'\s+', ' ', text) text = text.strip() return text
class SimpleTokenizer(object): def __init__(self, bpe_path: str = default_bpe()): self.byte_encoder = bytes_to_unicode() self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} merges = gzip.open(bpe_path).read().decode("utf-8").split('\n') merges = merges[1:49152-256-2+1] merges = [tuple(merge.split()) for merge in merges] vocab = list(bytes_to_unicode().values()) vocab = vocab + [v+'</w>' for v in vocab] for merge in merges: vocab.append(''.join(merge)) vocab.extend(['<|startoftext|>', '<|endoftext|>']) self.encoder = dict(zip(vocab, range(len(vocab)))) self.decoder = {v: k for k, v in self.encoder.items()} self.bpe_ranks = dict(zip(merges, range(len(merges)))) self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'} self.pat = re.compile(r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE)
def bpe(self, token): if token in self.cache: return self.cache[token] word = tuple(token[:-1]) + ( token[-1] + '</w>',) pairs = get_pairs(word)
if not pairs: return token+'</w>'
while True: bigram = min(pairs, key = lambda pair: self.bpe_ranks.get(pair, float('inf'))) if bigram not in self.bpe_ranks: break first, second = bigram new_word = [] i = 0 while i < len(word): try: j = word.index(first, i) new_word.extend(word[i:j]) i = j except: new_word.extend(word[i:]) break
if word[i] == first and i < len(word)-1 and word[i+1] == second: new_word.append(first+second) i += 2 else: new_word.append(word[i]) i += 1 new_word = tuple(new_word) word = new_word if len(word) == 1: break else: pairs = get_pairs(word) word = ' '.join(word) self.cache[token] = word return word
def encode(self, text): bpe_tokens = [] text = whitespace_clean(basic_clean(text)).lower() for token in re.findall(self.pat, text): token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8')) bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' ')) return bpe_tokens
def decode(self, tokens): text = ''.join([self.decoder[token] for token in tokens]) text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ') return text1234567891011121314# The YFCC100M Subset
In the paper, we performed a dataset ablation using a subset of the YFCC100M dataset and showed that the performance remained largely similar.
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.
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.
```wget https://openaipublic.azureedge.net/clip/data/yfcc100m_subset_data.tsv.bz2bunzip2 yfcc100m_subset_data.tsv.bz2```
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/).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120# Model Card: CLIP
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.
## Model Details
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.
### Model Date
January 2021
### Model Type
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.
### Model Versions
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.
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.
Please see the paper linked below for further details about their specification.
### Documents
- [Blog Post](https://openai.com/blog/clip/)- [CLIP Paper](https://arxiv.org/abs/2103.00020)
## Model Use
### Intended Use
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.
#### Primary intended uses
The primary intended users of these models are AI researchers.
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.
### Out-of-Scope Use Cases
**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.
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.
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.
## Data
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.
### Data Mission Statement
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.
## Performance and Limitations
### Performance
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:
- Food101- CIFAR10 - CIFAR100 - Birdsnap- SUN397- Stanford Cars- FGVC Aircraft- VOC2007- DTD- Oxford-IIIT Pet dataset- Caltech101- Flowers102- MNIST - SVHN - IIIT5K - Hateful Memes - SST-2- UCF101- Kinetics700- Country211- CLEVR Counting- KITTI Distance- STL-10- RareAct- Flickr30- MSCOCO- ImageNet- ImageNet-A- ImageNet-R- ImageNet Sketch- ObjectNet (ImageNet Overlap)- Youtube-BB- ImageNet-Vid
## Limitations
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.
### Bias and Fairness
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).
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.
## Feedback
### Where to send questions or comments about the model
Please use [this Google Form](https://forms.gle/Uv7afRH5dvY34ZEs9)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "name": "Prompt Engineering for ImageNet.ipynb", "provenance": [], "collapsed_sections": [] }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "accelerator": "GPU", "widgets": { "application/vnd.jupyter.widget-state+json": { "4e3a3f83649f45f8bef3434980634664": { "model_module": "@jupyter-widgets/controls", "model_name": "HBoxModel", "state": { "_view_name": "HBoxView", "_dom_classes": [], "_model_name": "HBoxModel", "_view_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_view_count": null, "_view_module_version": "1.5.0", "box_style": "", "layout": "IPY_MODEL_f066bdb766664c788ba1e9de8d311e22", "_model_module": "@jupyter-widgets/controls", "children": [ "IPY_MODEL_4e7a7427d28a4ae684e0be4548eb9944", "IPY_MODEL_cc9dc019c1334a46b2558ffa6c0dd6e6" ] } }, "f066bdb766664c788ba1e9de8d311e22": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "state": { "_view_name": "LayoutView", "grid_template_rows": null, "right": null, "justify_content": null, "_view_module": "@jupyter-widgets/base", "overflow": null, "_model_module_version": "1.2.0", "_view_count": null, "flex_flow": null, "width": null, "min_width": null, "border": null, "align_items": null, "bottom": null, "_model_module": "@jupyter-widgets/base", "top": null, "grid_column": null, "overflow_y": null, "overflow_x": null, "grid_auto_flow": null, "grid_area": null, "grid_template_columns": null, "flex": null, "_model_name": "LayoutModel", "justify_items": null, "grid_row": null, "max_height": null, "align_content": null, "visibility": null, "align_self": null, "height": null, "min_height": null, "padding": null, "grid_auto_rows": null, "grid_gap": null, "max_width": null, "order": null, "_view_module_version": "1.2.0", "grid_template_areas": null, "object_position": null, "object_fit": null, "grid_auto_columns": null, "margin": null, "display": null, "left": null } }, "4e7a7427d28a4ae684e0be4548eb9944": { "model_module": "@jupyter-widgets/controls", "model_name": "FloatProgressModel", "state": { "_view_name": "ProgressView", "style": "IPY_MODEL_285c877d4f644f3a8a58c4eb5948101c", "_dom_classes": [], "description": "100%", "_model_name": "FloatProgressModel", "bar_style": "success", "max": 1000, "_view_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "value": 1000, "_view_count": null, "_view_module_version": "1.5.0", "orientation": "horizontal", "min": 0, "description_tooltip": null, "_model_module": "@jupyter-widgets/controls", "layout": "IPY_MODEL_075d6545e02e419ca565589eb5ffc318" } }, "cc9dc019c1334a46b2558ffa6c0dd6e6": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "state": { "_view_name": "HTMLView", "style": "IPY_MODEL_53f9106c80e84d5b8c3ec96162d1db98", "_dom_classes": [], "description": "", "_model_name": "HTMLModel", "placeholder": "", "_view_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "value": " 1000/1000 [01:09<00:00, 14.35it/s]", "_view_count": null, "_view_module_version": "1.5.0", "description_tooltip": null, "_model_module": "@jupyter-widgets/controls", "layout": "IPY_MODEL_19c57d99e7c44cbda508ce558fde435d" } }, "285c877d4f644f3a8a58c4eb5948101c": { "model_module": "@jupyter-widgets/controls", "model_name": "ProgressStyleModel", "state": { "_view_name": "StyleView", "_model_name": "ProgressStyleModel", "description_width": "initial", "_view_module": "@jupyter-widgets/base", "_model_module_version": "1.5.0", "_view_count": null, "_view_module_version": "1.2.0", "bar_color": null, "_model_module": "@jupyter-widgets/controls" } }, "075d6545e02e419ca565589eb5ffc318": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "state": { "_view_name": "LayoutView", "grid_template_rows": null, "right": null, "justify_content": null, "_view_module": "@jupyter-widgets/base", "overflow": null, "_model_module_version": "1.2.0", "_view_count": null, "flex_flow": null, "width": null, "min_width": null, "border": null, "align_items": null, "bottom": null, "_model_module": "@jupyter-widgets/base", "top": null, "grid_column": null, "overflow_y": null, "overflow_x": null, "grid_auto_flow": null, "grid_area": null, "grid_template_columns": null, "flex": null, "_model_name": "LayoutModel", "justify_items": null, "grid_row": null, "max_height": null, "align_content": null, "visibility": null, "align_self": null, "height": null, "min_height": null, "padding": null, "grid_auto_rows": null, "grid_gap": null, "max_width": null, "order": null, "_view_module_version": "1.2.0", "grid_template_areas": null, "object_position": null, "object_fit": null, "grid_auto_columns": null, "margin": null, "display": null, "left": null } }, "53f9106c80e84d5b8c3ec96162d1db98": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "state": { "_view_name": "StyleView", "_model_name": "DescriptionStyleModel", "description_width": "", "_view_module": "@jupyter-widgets/base", "_model_module_version": "1.5.0", "_view_count": null, "_view_module_version": "1.2.0", "_model_module": "@jupyter-widgets/controls" } }, "19c57d99e7c44cbda508ce558fde435d": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "state": { "_view_name": "LayoutView", "grid_template_rows": null, "right": null, "justify_content": null, "_view_module": "@jupyter-widgets/base", "overflow": null, "_model_module_version": "1.2.0", "_view_count": null, "flex_flow": null, "width": null, "min_width": null, "border": null, "align_items": null, "bottom": null, "_model_module": "@jupyter-widgets/base", "top": null, "grid_column": null, "overflow_y": null, "overflow_x": null, "grid_auto_flow": null, "grid_area": null, "grid_template_columns": null, "flex": null, "_model_name": "LayoutModel", "justify_items": null, "grid_row": null, "max_height": null, "align_content": null, "visibility": null, "align_self": null, "height": null, "min_height": null, "padding": null, "grid_auto_rows": null, "grid_gap": null, "max_width": null, "order": null, "_view_module_version": "1.2.0", "grid_template_areas": null, "object_position": null, "object_fit": null, "grid_auto_columns": null, "margin": null, "display": null, "left": null } }, "fbb2b937b22049f5987f39f48c652a86": { "model_module": "@jupyter-widgets/controls", "model_name": "HBoxModel", "state": { "_view_name": "HBoxView", "_dom_classes": [], "_model_name": "HBoxModel", "_view_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_view_count": null, "_view_module_version": "1.5.0", "box_style": "", "layout": "IPY_MODEL_0a1b6b76984349ccb36ca2fc4a4a0208", "_model_module": "@jupyter-widgets/controls", "children": [ "IPY_MODEL_c136afb47aa14ac2832093ee415c6f3e", "IPY_MODEL_467a151e73744eccb199fe72aa352e5b" ] } }, "0a1b6b76984349ccb36ca2fc4a4a0208": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "state": { "_view_name": "LayoutView", "grid_template_rows": null, "right": null, "justify_content": null, "_view_module": "@jupyter-widgets/base", "overflow": null, "_model_module_version": "1.2.0", "_view_count": null, "flex_flow": null, "width": null, "min_width": null, "border": null, "align_items": null, "bottom": null, "_model_module": "@jupyter-widgets/base", "top": null, "grid_column": null, "overflow_y": null, "overflow_x": null, "grid_auto_flow": null, "grid_area": null, "grid_template_columns": null, "flex": null, "_model_name": "LayoutModel", "justify_items": null, "grid_row": null, "max_height": null, "align_content": null, "visibility": null, "align_self": null, "height": null, "min_height": null, "padding": null, "grid_auto_rows": null, "grid_gap": null, "max_width": null, "order": null, "_view_module_version": "1.2.0", "grid_template_areas": null, "object_position": null, "object_fit": null, "grid_auto_columns": null, "margin": null, "display": null, "left": null } }, "c136afb47aa14ac2832093ee415c6f3e": { "model_module": "@jupyter-widgets/controls", "model_name": "FloatProgressModel", "state": { "_view_name": "ProgressView", "style": "IPY_MODEL_f6d637c3fc3c46928d023441227130e5", "_dom_classes": [], "description": "100%", "_model_name": "FloatProgressModel", "bar_style": "success", "max": 313, "_view_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "value": 313, "_view_count": null, "_view_module_version": "1.5.0", "orientation": "horizontal", "min": 0, "description_tooltip": null, "_model_module": "@jupyter-widgets/controls", "layout": "IPY_MODEL_029e6eadacb8480193aab52ff073be8f" } }, "467a151e73744eccb199fe72aa352e5b": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "state": { "_view_name": "HTMLView", "style": "IPY_MODEL_30178355f76742898d37966b3875ef0a", "_dom_classes": [], "description": "", "_model_name": "HTMLModel", "placeholder": "", "_view_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "value": " 313/313 [01:26<00:00, 3.62it/s]", "_view_count": null, "_view_module_version": "1.5.0", "description_tooltip": null, "_model_module": "@jupyter-widgets/controls", "layout": "IPY_MODEL_2e62544c03d64d6d92b94fcfaca2fc90" } }, "f6d637c3fc3c46928d023441227130e5": { "model_module": "@jupyter-widgets/controls", "model_name": "ProgressStyleModel", "state": { "_view_name": "StyleView", "_model_name": "ProgressStyleModel", "description_width": "initial", "_view_module": "@jupyter-widgets/base", "_model_module_version": "1.5.0", "_view_count": null, "_view_module_version": "1.2.0", "bar_color": null, "_model_module": "@jupyter-widgets/controls" } }, "029e6eadacb8480193aab52ff073be8f": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "state": { "_view_name": "LayoutView", "grid_template_rows": null, "right": null, "justify_content": null, "_view_module": "@jupyter-widgets/base", "overflow": null, "_model_module_version": "1.2.0", "_view_count": null, "flex_flow": null, "width": null, "min_width": null, "border": null, "align_items": null, "bottom": null, "_model_module": "@jupyter-widgets/base", "top": null, "grid_column": null, "overflow_y": null, "overflow_x": null, "grid_auto_flow": null, "grid_area": null, "grid_template_columns": null, "flex": null, "_model_name": "LayoutModel", "justify_items": null, "grid_row": null, "max_height": null, "align_content": null, "visibility": null, "align_self": null, "height": null, "min_height": null, "padding": null, "grid_auto_rows": null, "grid_gap": null, "max_width": null, "order": null, "_view_module_version": "1.2.0", "grid_template_areas": null, "object_position": null, "object_fit": null, "grid_auto_columns": null, "margin": null, "display": null, "left": null } }, "30178355f76742898d37966b3875ef0a": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "state": { "_view_name": "StyleView", "_model_name": "DescriptionStyleModel", "description_width": "", "_view_module": "@jupyter-widgets/base", "_model_module_version": "1.5.0", "_view_count": null, "_view_module_version": "1.2.0", "_model_module": "@jupyter-widgets/controls" } }, "2e62544c03d64d6d92b94fcfaca2fc90": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "state": { "_view_name": "LayoutView", "grid_template_rows": null, "right": null, "justify_content": null, "_view_module": "@jupyter-widgets/base", "overflow": null, "_model_module_version": "1.2.0", "_view_count": null, "flex_flow": null, "width": null, "min_width": null, "border": null, "align_items": null, "bottom": null, "_model_module": "@jupyter-widgets/base", "top": null, "grid_column": null, "overflow_y": null, "overflow_x": null, "grid_auto_flow": null, "grid_area": null, "grid_template_columns": null, "flex": null, "_model_name": "LayoutModel", "justify_items": null, "grid_row": null, "max_height": null, "align_content": null, "visibility": null, "align_self": null, "height": null, "min_height": null, "padding": null, "grid_auto_rows": null, "grid_gap": null, "max_width": null, "order": null, "_view_module_version": "1.2.0", "grid_template_areas": null, "object_position": null, "object_fit": null, "grid_auto_columns": null, "margin": null, "display": null, "left": null } } } } }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "53N4k0pj_9qL" }, "source": [ "# Preparation for Colab\n", "\n", "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 print the CUDA version of the runtime if it has a GPU, and install PyTorch 1.7.1." ] }, { "cell_type": "code", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "0BpdJkdBssk9", "outputId": "dc75b5f9-17c7-4856-ac79-8047fa609500" }, "source": [ "import subprocess\n", "\n", "CUDA_version = [s for s in subprocess.check_output([\"nvcc\", \"--version\"]).decode(\"UTF-8\").split(\", \") if s.startswith(\"release\")][0].split(\" \")[-1]\n", "print(\"CUDA version:\", CUDA_version)\n", "\n", "if CUDA_version == \"10.0\":\n", " torch_version_suffix = \"+cu100\"\n", "elif CUDA_version == \"10.1\":\n", " torch_version_suffix = \"+cu101\"\n", "elif CUDA_version == \"10.2\":\n", " torch_version_suffix = \"\"\n", "else:\n", " torch_version_suffix = \"+cu110\"" ], "execution_count": 1, "outputs": [ { "output_type": "stream", "text": [ "CUDA version: 10.1\n" ], "name": "stdout" } ] }, { "cell_type": "code", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "RBVr18E5tse8", "outputId": "404230c1-0f78-451d-8816-19d4109d579e" }, "source": [ "! pip install torch==1.7.1{torch_version_suffix} torchvision==0.8.2{torch_version_suffix} -f https://download.pytorch.org/whl/torch_stable.html ftfy regex" ], "execution_count": 2, "outputs": [ { "output_type": "stream", "text": [ "Looking in links: https://download.pytorch.org/whl/torch_stable.html\n", "Collecting torch==1.7.1+cu101\n", "\u001b[?25l Downloading https://download.pytorch.org/whl/cu101/torch-1.7.1%2Bcu101-cp36-cp36m-linux_x86_64.whl (735.4MB)\n", "\u001b[K |████████████████████████████████| 735.4MB 25kB/s \n", "\u001b[?25hCollecting torchvision==0.8.2+cu101\n", "\u001b[?25l Downloading https://download.pytorch.org/whl/cu101/torchvision-0.8.2%2Bcu101-cp36-cp36m-linux_x86_64.whl (12.8MB)\n", "\u001b[K |████████████████████████████████| 12.8MB 248kB/s \n", "\u001b[?25hCollecting ftfy\n", "\u001b[?25l Downloading https://files.pythonhosted.org/packages/ff/e2/3b51c53dffb1e52d9210ebc01f1fb9f2f6eba9b3201fa971fd3946643c71/ftfy-5.8.tar.gz (64kB)\n", "\u001b[K |████████████████████████████████| 71kB 5.6MB/s \n", "\u001b[?25hRequirement already satisfied: regex in /usr/local/lib/python3.6/dist-packages (2019.12.20)\n", "Requirement already satisfied: typing-extensions in /usr/local/lib/python3.6/dist-packages (from torch==1.7.1+cu101) (3.7.4.3)\n", "Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from torch==1.7.1+cu101) (1.19.5)\n", "Requirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from torch==1.7.1+cu101) (0.8)\n", "Requirement already satisfied: pillow>=4.1.1 in /usr/local/lib/python3.6/dist-packages (from torchvision==0.8.2+cu101) (7.0.0)\n", "Requirement already satisfied: wcwidth in /usr/local/lib/python3.6/dist-packages (from ftfy) (0.2.5)\n", "Building wheels for collected packages: ftfy\n", " Building wheel for ftfy (setup.py) ... \u001b[?25l\u001b[?25hdone\n", " Created wheel for ftfy: filename=ftfy-5.8-cp36-none-any.whl size=45613 sha256=73a94b51b7fe03350783d5b9dd638801a904c618d3b0dc7237ce77f401f33404\n", " Stored in directory: /root/.cache/pip/wheels/ba/c0/ef/f28c4da5ac84a4e06ac256ca9182fc34fa57fefffdbc68425b\n", "Successfully built ftfy\n", "Installing collected packages: torch, torchvision, ftfy\n", " Found existing installation: torch 1.7.0+cu101\n", " Uninstalling torch-1.7.0+cu101:\n", " Successfully uninstalled torch-1.7.0+cu101\n", " Found existing installation: torchvision 0.8.1+cu101\n", " Uninstalling torchvision-0.8.1+cu101:\n", " Successfully uninstalled torchvision-0.8.1+cu101\n", "Successfully installed ftfy-5.8 torch-1.7.1+cu101 torchvision-0.8.2+cu101\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "zGm7TwfbDLgu" }, "source": [ "The following command installs the `clip` module from its source:" ] }, { "cell_type": "code", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "QAFjXlGdEMQM", "outputId": "859da71b-00c8-44d1-84d0-7965c20411b4" }, "source": [ "! pip install git+https://github.com/openai/CLIP.git" ], "execution_count": 3, "outputs": [ { "output_type": "stream", "text": [ "Collecting git+https://github.com/openai/CLIP.git\n", " Cloning https://github.com/openai/CLIP.git to /tmp/pip-req-build-ewapt31c\n", " Running command git clone -q https://github.com/openai/CLIP.git /tmp/pip-req-build-ewapt31c\n", "Requirement already satisfied: ftfy in /usr/local/lib/python3.6/dist-packages (from clip==1.0) (5.8)\n", "Requirement already satisfied: regex in /usr/local/lib/python3.6/dist-packages (from clip==1.0) (2019.12.20)\n", "Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from clip==1.0) (4.41.1)\n", "Requirement already satisfied: torch~=1.7.1 in /usr/local/lib/python3.6/dist-packages (from clip==1.0) (1.7.1+cu101)\n", "Requirement already satisfied: torchvision~=0.8.2 in /usr/local/lib/python3.6/dist-packages (from clip==1.0) (0.8.2+cu101)\n", "Requirement already satisfied: wcwidth in /usr/local/lib/python3.6/dist-packages (from ftfy->clip==1.0) (0.2.5)\n", "Requirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from torch~=1.7.1->clip==1.0) (0.8)\n", "Requirement already satisfied: typing-extensions in /usr/local/lib/python3.6/dist-packages (from torch~=1.7.1->clip==1.0) (3.7.4.3)\n", "Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from torch~=1.7.1->clip==1.0) (1.19.5)\n", "Requirement already satisfied: pillow>=4.1.1 in /usr/local/lib/python3.6/dist-packages (from torchvision~=0.8.2->clip==1.0) (7.0.0)\n", "Building wheels for collected packages: clip\n", " Building wheel for clip (setup.py) ... \u001b[?25l\u001b[?25hdone\n", " Created wheel for clip: filename=clip-1.0-cp36-none-any.whl size=1367993 sha256=1839a2f0b015f75579b578ebfa15bcbe8ebab1ff535127c9357c5b26f8473de3\n", " Stored in directory: /tmp/pip-ephem-wheel-cache-jwymwzm4/wheels/79/51/d7/69f91d37121befe21d9c52332e04f592e17d1cabc7319b3e09\n", "Successfully built clip\n", "Installing collected packages: clip\n", "Successfully installed clip-1.0\n" ], "name": "stdout" } ] }, { "cell_type": "code", "metadata": { "id": "C1hkDT38hSaP", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "6cd33e12-aed4-4950-e32f-6f1113eb3ade" }, "source": [ "import numpy as np\n", "import torch\n", "import clip\n", "from tqdm.notebook import tqdm\n", "\n", "print(\"Torch version:\", torch.__version__)" ], "execution_count": 4, "outputs": [ { "output_type": "stream", "text": [ "Torch version: 1.7.1+cu101\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "eFxgLV5HAEEw" }, "source": [ "# Loading the model\n", "\n", "Download and instantiate a CLIP model using the `clip` module that we just installed." ] }, { "cell_type": "code", "metadata": { "id": "uLFS29hnhlY4", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "3148f942-0226-42a3-e5d8-4b9bc6c7c4f8" }, "source": [ "clip.available_models()" ], "execution_count": 5, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "['RN50', 'ViT-B/32']" ] }, "metadata": { "tags": [] }, "execution_count": 5 } ] }, { "cell_type": "code", "metadata": { "id": "cboKZocQlSYX", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "58e644d4-6e23-43b5-964e-1e9e8540d22e" }, "source": [ "model, preprocess = clip.load(\"ViT-B/32\")" ], "execution_count": 6, "outputs": [ { "output_type": "stream", "text": [ "100%|██████████████████████| 353976522/353976522 [00:01<00:00, 188872424.30it/s]\n" ], "name": "stderr" } ] }, { "cell_type": "code", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "IBRVTY9lbGm8", "outputId": "58641dc2-919d-40ae-b71a-7b7b47830f77" }, "source": [ "input_resolution = model.input_resolution.item()\n", "context_length = model.context_length.item()\n", "vocab_size = model.vocab_size.item()\n", "\n", "print(\"Model parameters:\", f\"{np.sum([int(np.prod(p.shape)) for p in model.parameters()]):,}\")\n", "print(\"Input resolution:\", input_resolution)\n", "print(\"Context length:\", context_length)\n", "print(\"Vocab size:\", vocab_size)" ], "execution_count": 7, "outputs": [ { "output_type": "stream", "text": [ "Model parameters: 151,277,313\n", "Input resolution: 224\n", "Context length: 77\n", "Vocab size: 49408\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "LhO3OtOmF8M4" }, "source": [ "# Preparing ImageNet labels and prompts\n", "\n", "The following cell contains the 1,000 labels for the ImageNet dataset, followed by the text templates we'll use as \"prompt engineering\"." ] }, { "cell_type": "code", "metadata": { "id": "R2HbOZrqa0jF" }, "source": [ "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\"]" ], "execution_count": 8, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "eMQSCuBta2G6" }, "source": [ "A subset of these class names are modified from the default ImageNet class names sourced from Anish Athalye's imagenet-simple-labels.\n", "\n", "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", "\n", "Some examples beyond the crane/crane -> construction crane / bird crane issue mentioned in Section 3.1.4 of the paper include:\n", "\n", "- CLIP interprets \"nail\" as \"fingernail\" so we changed the label to \"metal nail\".\n", "- ImageNet kite class refers to the bird of prey, not the flying toy, so we changed \"kite\" to \"kite (bird of prey)\"\n", "- 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\"" ] }, { "cell_type": "code", "metadata": { "id": "toGtcd-Ji_MD", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "46bcc85f-3968-4836-f3c6-e48848e944c4" }, "source": [ "imagenet_templates = [\n", " 'a bad photo of a {}.',\n", " 'a photo of many {}.',\n", " 'a sculpture of a {}.',\n", " 'a photo of the hard to see {}.',\n", " 'a low resolution photo of the {}.',\n", " 'a rendering of a {}.',\n", " 'graffiti of a {}.',\n", " 'a bad photo of the {}.',\n", " 'a cropped photo of the {}.',\n", " 'a tattoo of a {}.',\n", " 'the embroidered {}.',\n", " 'a photo of a hard to see {}.',\n", " 'a bright photo of a {}.',\n", " 'a photo of a clean {}.',\n", " 'a photo of a dirty {}.',\n", " 'a dark photo of the {}.',\n", " 'a drawing of a {}.',\n", " 'a photo of my {}.',\n", " 'the plastic {}.',\n", " 'a photo of the cool {}.',\n", " 'a close-up photo of a {}.',\n", " 'a black and white photo of the {}.',\n", " 'a painting of the {}.',\n", " 'a painting of a {}.',\n", " 'a pixelated photo of the {}.',\n", " 'a sculpture of the {}.',\n", " 'a bright photo of the {}.',\n", " 'a cropped photo of a {}.',\n", " 'a plastic {}.',\n", " 'a photo of the dirty {}.',\n", " 'a jpeg corrupted photo of a {}.',\n", " 'a blurry photo of the {}.',\n", " 'a photo of the {}.',\n", " 'a good photo of the {}.',\n", " 'a rendering of the {}.',\n", " 'a {} in a video game.',\n", " 'a photo of one {}.',\n", " 'a doodle of a {}.',\n", " 'a close-up photo of the {}.',\n", " 'a photo of a {}.',\n", " 'the origami {}.',\n", " 'the {} in a video game.',\n", " 'a sketch of a {}.',\n", " 'a doodle of the {}.',\n", " 'a origami {}.',\n", " 'a low resolution photo of a {}.',\n", " 'the toy {}.',\n", " 'a rendition of the {}.',\n", " 'a photo of the clean {}.',\n", " 'a photo of a large {}.',\n", " 'a rendition of a {}.',\n", " 'a photo of a nice {}.',\n", " 'a photo of a weird {}.',\n", " 'a blurry photo of a {}.',\n", " 'a cartoon {}.',\n", " 'art of a {}.',\n", " 'a sketch of the {}.',\n", " 'a embroidered {}.',\n", " 'a pixelated photo of a {}.',\n", " 'itap of the {}.',\n", " 'a jpeg corrupted photo of the {}.',\n", " 'a good photo of a {}.',\n", " 'a plushie {}.',\n", " 'a photo of the nice {}.',\n", " 'a photo of the small {}.',\n", " 'a photo of the weird {}.',\n", " 'the cartoon {}.',\n", " 'art of the {}.',\n", " 'a drawing of the {}.',\n", " 'a photo of the large {}.',\n", " 'a black and white photo of a {}.',\n", " 'the plushie {}.',\n", " 'a dark photo of a {}.',\n", " 'itap of a {}.',\n", " 'graffiti of the {}.',\n", " 'a toy {}.',\n", " 'itap of my {}.',\n", " 'a photo of a cool {}.',\n", " 'a photo of a small {}.',\n", " 'a tattoo of the {}.',\n", "]\n", "\n", "print(f\"{len(imagenet_classes)} classes, {len(imagenet_templates)} templates\")" ], "execution_count": 9, "outputs": [ { "output_type": "stream", "text": [ "1000 classes, 80 templates\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "aRB5OzgpHwqQ" }, "source": [ "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", "\n", "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", "\n", "1. itap of a {}.\n", "2. a bad photo of the {}.\n", "3. a origami {}.\n", "4. a photo of the large {}.\n", "5. a {} in a video game.\n", "6. art of the {}.\n", "7. a photo of the small {}.\n", "\n", "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." ] }, { "cell_type": "markdown", "metadata": { "id": "4W8ARJVqBJXs" }, "source": [ "# Loading the Images\n", "\n", "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", "\n", "If you have the ImageNet dataset downloaded, you can replace the dataset with the official torchvision loader, e.g.:\n", "\n", "```python\n", "images = torchvision.datasets.ImageNet(\"path/to/imagenet\", split='val', transform=preprocess)\n", "```" ] }, { "cell_type": "code", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "moHR4UlHKsDc", "outputId": "178f6d0d-9a34-4cbc-c9c1-e7ce09927980" }, "source": [ "! pip install git+https://github.com/modestyachts/ImageNetV2_pytorch\n", "\n", "from imagenetv2_pytorch import ImageNetV2Dataset\n", "\n", "images = ImageNetV2Dataset(transform=preprocess)\n", "loader = torch.utils.data.DataLoader(images, batch_size=32, num_workers=16)" ], "execution_count": 10, "outputs": [ { "output_type": "stream", "text": [ "Collecting git+https://github.com/modestyachts/ImageNetV2_pytorch\n", " Cloning https://github.com/modestyachts/ImageNetV2_pytorch to /tmp/pip-req-build-2fnslbyv\n", " Running command git clone -q https://github.com/modestyachts/ImageNetV2_pytorch /tmp/pip-req-build-2fnslbyv\n", "Building wheels for collected packages: imagenetv2-pytorch\n", " Building wheel for imagenetv2-pytorch (setup.py) ... \u001b[?25l\u001b[?25hdone\n", " Created wheel for imagenetv2-pytorch: filename=imagenetv2_pytorch-0.1-cp36-none-any.whl size=2665 sha256=0978fc64026ab86ace52a9f3ebcef53331c43288433173c450a4b5ddcc197f31\n", " Stored in directory: /tmp/pip-ephem-wheel-cache-4eewuaap/wheels/f7/09/0d/03ded955ce95b04c9590b999ae9be076bb5d8f389650aa2147\n", "Successfully built imagenetv2-pytorch\n", "Installing collected packages: imagenetv2-pytorch\n", "Successfully installed imagenetv2-pytorch-0.1\n", "Dataset matched-frequency not found on disk, downloading....\n" ], "name": "stdout" }, { "output_type": "stream", "text": [ "100%|██████████| 1.26G/1.26G [00:35<00:00, 35.7MiB/s]\n" ], "name": "stderr" }, { "output_type": "stream", "text": [ "Extracting....\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "fz6D-F-Wbrtp" }, "source": [ "# Creating zero-shot classifier weights" ] }, { "cell_type": "code", "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 66, "referenced_widgets": [ "4e3a3f83649f45f8bef3434980634664", "f066bdb766664c788ba1e9de8d311e22", "4e7a7427d28a4ae684e0be4548eb9944", "cc9dc019c1334a46b2558ffa6c0dd6e6", "285c877d4f644f3a8a58c4eb5948101c", "075d6545e02e419ca565589eb5ffc318", "53f9106c80e84d5b8c3ec96162d1db98", "19c57d99e7c44cbda508ce558fde435d" ] }, "id": "sRqDoz1Gbsii", "outputId": "5ab6c001-8a5e-42c9-ab46-4477a693229c" }, "source": [ "def zeroshot_classifier(classnames, templates):\n", " with torch.no_grad():\n", " zeroshot_weights = []\n", " for classname in tqdm(classnames):\n", " texts = [template.format(classname) for template in templates] #format with class\n", " texts = clip.tokenize(texts).cuda() #tokenize\n", " class_embeddings = model.encode_text(texts) #embed with text encoder\n", " class_embeddings /= class_embeddings.norm(dim=-1, keepdim=True)\n", " class_embedding = class_embeddings.mean(dim=0)\n", " class_embedding /= class_embedding.norm()\n", " zeroshot_weights.append(class_embedding)\n", " zeroshot_weights = torch.stack(zeroshot_weights, dim=1).cuda()\n", " return zeroshot_weights\n", "\n", "\n", "zeroshot_weights = zeroshot_classifier(imagenet_classes, imagenet_templates)" ], "execution_count": 11, "outputs": [ { "output_type": "display_data", "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "4e3a3f83649f45f8bef3434980634664", "version_minor": 0, "version_major": 2 }, "text/plain": [ "HBox(children=(FloatProgress(value=0.0, max=1000.0), HTML(value='')))" ] }, "metadata": { "tags": [] } }, { "output_type": "stream", "text": [ "\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "1fZo7hG8iJP5" }, "source": [ "# Zero-shot prediction" ] }, { "cell_type": "code", "metadata": { "id": "j4kPSZoShQxN" }, "source": [ "def accuracy(output, target, topk=(1,)):\n", " pred = output.topk(max(topk), 1, True, True)[1].t()\n", " correct = pred.eq(target.view(1, -1).expand_as(pred))\n", " return [float(correct[:k].reshape(-1).float().sum(0, keepdim=True).cpu().numpy()) for k in topk]" ], "execution_count": 12, "outputs": [] }, { "cell_type": "code", "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 100, "referenced_widgets": [ "fbb2b937b22049f5987f39f48c652a86", "0a1b6b76984349ccb36ca2fc4a4a0208", "c136afb47aa14ac2832093ee415c6f3e", "467a151e73744eccb199fe72aa352e5b", "f6d637c3fc3c46928d023441227130e5", "029e6eadacb8480193aab52ff073be8f", "30178355f76742898d37966b3875ef0a", "2e62544c03d64d6d92b94fcfaca2fc90" ] }, "id": "wKJ7YsdlkDXo", "outputId": "90e084fd-86bc-4a52-a06e-61bff7aa86e0" }, "source": [ "with torch.no_grad():\n", " top1, top5, n = 0., 0., 0.\n", " for i, (images, target) in enumerate(tqdm(loader)):\n", " images = images.cuda()\n", " target = target.cuda()\n", " \n", " # predict\n", " image_features = model.encode_image(images)\n", " image_features /= image_features.norm(dim=-1, keepdim=True)\n", " logits = 100. * image_features @ zeroshot_weights\n", "\n", " # measure accuracy\n", " acc1, acc5 = accuracy(logits, target, topk=(1, 5))\n", " top1 += acc1\n", " top5 += acc5\n", " n += images.size(0)\n", "\n", "top1 = (top1 / n) * 100\n", "top5 = (top5 / n) * 100 \n", "\n", "print(f\"Top-1 accuracy: {top1:.2f}\")\n", "print(f\"Top-5 accuracy: {top5:.2f}\")" ], "execution_count": 13, "outputs": [ { "output_type": "display_data", "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "fbb2b937b22049f5987f39f48c652a86", "version_minor": 0, "version_major": 2 }, "text/plain": [ "HBox(children=(FloatProgress(value=0.0, max=313.0), HTML(value='')))" ] }, "metadata": { "tags": [] } }, { "output_type": "stream", "text": [ "\n", "Top-1 accuracy: 55.73\n", "Top-5 accuracy: 83.45\n" ], "name": "stdout" } ] } ]}12345ftfyregextqdmtorchtorchvision123456789101112131415161718192021import os
import pkg_resourcesfrom setuptools import setup, find_packages
setup( name="clip", py_modules=["clip"], version="1.0", description="", author="OpenAI", packages=find_packages(exclude=["tests*"]), install_requires=[ str(r) for r in pkg_resources.parse_requirements( open(os.path.join(os.path.dirname(__file__), "requirements.txt")) ) ], include_package_data=True, extras_require={'dev': ['pytest']},)12345678910111213141516171819202122232425import numpy as npimport pytestimport torchfrom PIL import Image
import clip
@pytest.mark.parametrize('model_name', clip.available_models())def test_consistency(model_name): device = "cpu" jit_model, transform = clip.load(model_name, device=device, jit=True) py_model, _ = clip.load(model_name, device=device, jit=False)
image = transform(Image.open("CLIP.png")).unsqueeze(0).to(device) text = clip.tokenize(["a diagram", "a dog", "a cat"]).to(device)
with torch.no_grad(): logits_per_image, _ = jit_model(image, text) jit_probs = logits_per_image.softmax(dim=-1).cpu().numpy()
logits_per_image, _ = py_model(image, text) py_probs = logits_per_image.softmax(dim=-1).cpu().numpy()
assert np.allclose(jit_probs, py_probs, atol=0.01, rtol=0.1)123456789import gradio as grdef greet(name):return "Hello " + name + "!!"iface = gr.Interface(fn=greet, inputs="text", outputs="text")iface.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397import osos.system('pip freeze')import torchtorch.hub.download_url_to_file('https://heibox.uni-heidelberg.de/d/a7530b09fed84f80a887/files/?p=%2Fconfigs%2Fmodel.yaml&dl=1', 'vqgan_imagenet_f16_16384.yaml')torch.hub.download_url_to_file('https://heibox.uni-heidelberg.de/d/a7530b09fed84f80a887/files/?p=%2Fckpts%2Flast.ckpt&dl=1', 'vqgan_imagenet_f16_16384.ckpt')import argparseimport mathfrom pathlib import Pathimport syssys.path.insert(1, './taming-transformers')from base64 import b64encodefrom omegaconf import OmegaConffrom PIL import Imagefrom taming.models import cond_transformer, vqganimport taming.modulesfrom torch import nn, optimfrom torch.nn import functional as Ffrom torchvision import transformsfrom torchvision.transforms import functional as TFfrom tqdm.notebook import tqdmfrom CLIP import clipimport kornia.augmentation as Kimport numpy as npimport imageiofrom PIL import ImageFile, ImageImageFile.LOAD_TRUNCATED_IMAGES = Trueimport gradio as grimport nvidia_sminvidia_smi.nvmlInit()handle = nvidia_smi.nvmlDeviceGetHandleByIndex(0)# card id 0 hardcoded here, there is also a call to get all available card ids, so we could iteratetorch.hub.download_url_to_file('https://images.pexels.com/photos/158028/bellingrath-gardens-alabama-landscape-scenic-158028.jpeg', 'garden.jpeg')torch.hub.download_url_to_file('https://images.pexels.com/photos/68767/divers-underwater-ocean-swim-68767.jpeg', 'coralreef.jpeg')torch.hub.download_url_to_file('https://images.pexels.com/photos/803975/pexels-photo-803975.jpeg', 'cabin.jpeg')def sinc(x):return torch.where(x != 0, torch.sin(math.pi * x) / (math.pi * x), x.new_ones([]))def lanczos(x, a):cond = torch.logical_and(-a < x, x < a)out = torch.where(cond, sinc(x) * sinc(x/a), x.new_zeros([]))return out / out.sum()def ramp(ratio, width):n = math.ceil(width / ratio + 1)out = torch.empty([n])cur = 0for i in range(out.shape[0]):out[i] = curcur += ratioreturn torch.cat([-out[1:].flip([0]), out])[1:-1]def resample(input, size, align_corners=True):n, c, h, w = input.shapedh, dw = sizeinput = input.view([n * c, 1, h, w])if dh < h:kernel_h = lanczos(ramp(dh / h, 2), 2).to(input.device, input.dtype)pad_h = (kernel_h.shape[0] - 1) // 2input = F.pad(input, (0, 0, pad_h, pad_h), 'reflect')input = F.conv2d(input, kernel_h[None, None, :, None])if dw < w:kernel_w = lanczos(ramp(dw / w, 2), 2).to(input.device, input.dtype)pad_w = (kernel_w.shape[0] - 1) // 2input = F.pad(input, (pad_w, pad_w, 0, 0), 'reflect')input = F.conv2d(input, kernel_w[None, None, None, :])input = input.view([n, c, h, w])return F.interpolate(input, size, mode='bicubic', align_corners=align_corners)class ReplaceGrad(torch.autograd.Function):@staticmethoddef forward(ctx, x_forward, x_backward):ctx.shape = x_backward.shapereturn x_forward@staticmethoddef backward(ctx, grad_in):return None, grad_in.sum_to_size(ctx.shape)replace_grad = ReplaceGrad.applyclass ClampWithGrad(torch.autograd.Function):@staticmethoddef forward(ctx, input, min, max):ctx.min = minctx.max = maxctx.save_for_backward(input)return input.clamp(min, max)@staticmethoddef backward(ctx, grad_in):input, = ctx.saved_tensorsreturn grad_in * (grad_in * (input - input.clamp(ctx.min, ctx.max)) >= 0), None, Noneclamp_with_grad = ClampWithGrad.applydef vector_quantize(x, codebook):d = x.pow(2).sum(dim=-1, keepdim=True) + codebook.pow(2).sum(dim=1) - 2 * x @ codebook.Tindices = d.argmin(-1)x_q = F.one_hot(indices, codebook.shape[0]).to(d.dtype) @ codebookreturn replace_grad(x_q, x)class Prompt(nn.Module):def __init__(self, embed, weight=1., stop=float('-inf')):super().__init__()self.register_buffer('embed', embed)self.register_buffer('weight', torch.as_tensor(weight))self.register_buffer('stop', torch.as_tensor(stop))def forward(self, input):input_normed = F.normalize(input.unsqueeze(1), dim=2)embed_normed = F.normalize(self.embed.unsqueeze(0), dim=2)dists = input_normed.sub(embed_normed).norm(dim=2).div(2).arcsin().pow(2).mul(2)dists = dists * self.weight.sign()return self.weight.abs() * replace_grad(dists, torch.maximum(dists, self.stop)).mean()def parse_prompt(prompt):vals = prompt.rsplit(':', 2)vals = vals + ['', '1', '-inf'][len(vals):]return vals[0], float(vals[1]), float(vals[2])class MakeCutouts(nn.Module):def __init__(self, cut_size, cutn, cut_pow=1.):super().__init__()self.cut_size = cut_sizeself.cutn = cutnself.cut_pow = cut_powself.augs = nn.Sequential(# K.RandomHorizontalFlip(p=0.5),# K.RandomVerticalFlip(p=0.5),# K.RandomSolarize(0.01, 0.01, p=0.7),# K.RandomSharpness(0.3,p=0.4),# K.RandomResizedCrop(size=(self.cut_size,self.cut_size), scale=(0.1,1), ratio=(0.75,1.333), cropping_mode='resample', p=0.5),# K.RandomCrop(size=(self.cut_size,self.cut_size), p=0.5),K.RandomAffine(degrees=15, translate=0.1, p=0.7, padding_mode='border'),K.RandomPerspective(0.7,p=0.7),K.ColorJitter(hue=0.1, saturation=0.1, p=0.7),K.RandomErasing((.1, .4), (.3, 1/.3), same_on_batch=True, p=0.7),)self.noise_fac = 0.1self.av_pool = nn.AdaptiveAvgPool2d((self.cut_size, self.cut_size))self.max_pool = nn.AdaptiveMaxPool2d((self.cut_size, self.cut_size))def forward(self, input):sideY, sideX = input.shape[2:4]max_size = min(sideX, sideY)min_size = min(sideX, sideY, self.cut_size)cutouts = []for _ in range(self.cutn):# size = int(torch.rand([])**self.cut_pow * (max_size - min_size) + min_size)# offsetx = torch.randint(0, sideX - size + 1, ())# offsety = torch.randint(0, sideY - size + 1, ())# cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]# cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))# cutout = transforms.Resize(size=(self.cut_size, self.cut_size))(input)cutout = (self.av_pool(input) + self.max_pool(input))/2cutouts.append(cutout)batch = self.augs(torch.cat(cutouts, dim=0))if self.noise_fac:facs = batch.new_empty([self.cutn, 1, 1, 1]).uniform_(0, self.noise_fac)batch = batch + facs * torch.randn_like(batch)return batchdef load_vqgan_model(config_path, checkpoint_path):config = OmegaConf.load(config_path)if config.model.target == 'taming.models.vqgan.VQModel':model = vqgan.VQModel(**config.model.params)model.eval().requires_grad_(False)model.init_from_ckpt(checkpoint_path)elif config.model.target == 'taming.models.vqgan.GumbelVQ':model = vqgan.GumbelVQ(**config.model.params)model.eval().requires_grad_(False)model.init_from_ckpt(checkpoint_path)elif config.model.target == 'taming.models.cond_transformer.Net2NetTransformer':parent_model = cond_transformer.Net2NetTransformer(**config.model.params)parent_model.eval().requires_grad_(False)parent_model.init_from_ckpt(checkpoint_path)model = parent_model.first_stage_modelelse:raise ValueError(f'unknown model type: {config.model.target}')del model.lossreturn modeldef resize_image(image, out_size):ratio = image.size[0] / image.size[1]area = min(image.size[0] * image.size[1], out_size[0] * out_size[1])size = round((area * ratio)**0.5), round((area / ratio)**0.5)return image.resize(size, Image.LANCZOS)model_name = "vqgan_imagenet_f16_16384"images_interval = 50width = 280height = 280init_image = ""seed = 42args = argparse.Namespace(noise_prompt_seeds=[],noise_prompt_weights=[],size=[width, height],init_image=init_image,init_weight=0.,clip_model='ViT-B/32',vqgan_config=f'{model_name}.yaml',vqgan_checkpoint=f'{model_name}.ckpt',step_size=0.15,cutn=4,cut_pow=1.,display_freq=images_interval,seed=seed,)device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')print('Using device:', device)model = load_vqgan_model(args.vqgan_config, args.vqgan_checkpoint).to(device)perceptor = clip.load(args.clip_model, jit=False)[0].eval().requires_grad_(False).to(device)def inference(text, seed, step_size, max_iterations, width, height, init_image, init_weight, target_images, cutn, cut_pow):torch.cuda.empty_cache()torch.cuda.memory_summary(device=None, abbreviated=False)all_frames = []size=[width, height]texts = textinit_weight=init_weightif init_image:init_image = init_image.nameelse:init_image = ""if target_images:target_images = target_images.nameelse:target_images = ""max_iterations = max_iterationsmodel_names={"vqgan_imagenet_f16_16384": 'ImageNet 16384',"vqgan_imagenet_f16_1024":"ImageNet 1024", 'vqgan_openimages_f16_8192':'OpenImages 8912',"wikiart_1024":"WikiArt 1024", "wikiart_16384":"WikiArt 16384", "coco":"COCO-Stuff", "faceshq":"FacesHQ", "sflckr":"S-FLCKR"}name_model = model_names[model_name]if target_images == "None" or not target_images:target_images = []else:target_images = target_images.split("|")target_images = [image.strip() for image in target_images]texts = [phrase.strip() for phrase in texts.split("|")]if texts == ['']:texts = []from urllib.request import urlopenif texts:print('Using texts:', texts)if target_images:print('Using image prompts:', target_images)if seed is None or seed == -1:seed = torch.seed()else:seed = seedtorch.manual_seed(seed)print('Using seed:', seed)# clock=deepcopy(perceptor.visual.positional_embedding.data)# perceptor.visual.positional_embedding.data = clock/clock.max()# perceptor.visual.positional_embedding.data=clamp_with_grad(clock,0,1)cut_size = perceptor.visual.input_resolutionf = 2**(model.decoder.num_resolutions - 1)make_cutouts = MakeCutouts(cut_size, cutn, cut_pow=cut_pow)toksX, toksY = size[0] // f, size[1] // fsideX, sideY = toksX * f, toksY * fif args.vqgan_checkpoint == 'vqgan_openimages_f16_8192.ckpt':e_dim = 256n_toks = model.quantize.n_embedz_min = model.quantize.embed.weight.min(dim=0).values[None, :, None, None]z_max = model.quantize.embed.weight.max(dim=0).values[None, :, None, None]else:e_dim = model.quantize.e_dimn_toks = model.quantize.n_ez_min = model.quantize.embedding.weight.min(dim=0).values[None, :, None, None]z_max = model.quantize.embedding.weight.max(dim=0).values[None, :, None, None]# z_min = model.quantize.embedding.weight.min(dim=0).values[None, :, None, None]# z_max = model.quantize.embedding.weight.max(dim=0).values[None, :, None, None]# normalize_imagenet = transforms.Normalize(mean=[0.485, 0.456, 0.406],# std=[0.229, 0.224, 0.225])if init_image:if 'http' in init_image:img = Image.open(urlopen(init_image))else:img = Image.open(init_image)pil_image = img.convert('RGB')pil_image = pil_image.resize((sideX, sideY), Image.LANCZOS)pil_tensor = TF.to_tensor(pil_image)z, *_ = model.encode(pil_tensor.to(device).unsqueeze(0) * 2 - 1)else:one_hot = F.one_hot(torch.randint(n_toks, [toksY * toksX], device=device), n_toks).float()# z = one_hot @ model.quantize.embedding.weightif args.vqgan_checkpoint == 'vqgan_openimages_f16_8192.ckpt':z = one_hot @ model.quantize.embed.weightelse:z = one_hot @ model.quantize.embedding.weightz = z.view([-1, toksY, toksX, e_dim]).permute(0, 3, 1, 2)z = torch.rand_like(z)*2z_orig = z.clone()z.requires_grad_(True)opt = optim.Adam([z], lr=step_size)normalize = transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073],std=[0.26862954, 0.26130258, 0.27577711])pMs = []for prompt in texts:txt, weight, stop = parse_prompt(prompt)embed = perceptor.encode_text(clip.tokenize(txt).to(device)).float()pMs.append(Prompt(embed, weight, stop).to(device))for prompt in target_images:path, weight, stop = parse_prompt(prompt)img = Image.open(path)pil_image = img.convert('RGB')img = resize_image(pil_image, (sideX, sideY))batch = make_cutouts(TF.to_tensor(img).unsqueeze(0).to(device))embed = perceptor.encode_image(normalize(batch)).float()pMs.append(Prompt(embed, weight, stop).to(device))for seed, weight in zip(args.noise_prompt_seeds, args.noise_prompt_weights):gen = torch.Generator().manual_seed(seed)embed = torch.empty([1, perceptor.visual.output_dim]).normal_(generator=gen)pMs.append(Prompt(embed, weight).to(device))def synth(z):if args.vqgan_checkpoint == 'vqgan_openimages_f16_8192.ckpt':z_q = vector_quantize(z.movedim(1, 3), model.quantize.embed.weight).movedim(3, 1)else:z_q = vector_quantize(z.movedim(1, 3), model.quantize.embedding.weight).movedim(3, 1)return clamp_with_grad(model.decode(z_q).add(1).div(2), 0, 1)@torch.no_grad()def checkin(i, losses):losses_str = ', '.join(f'{loss.item():g}' for loss in losses)tqdm.write(f'i: {i}, loss: {sum(losses).item():g}, losses: {losses_str}')out = synth(z)# TF.to_pil_image(out[0].cpu()).save('progress.png')# display.display(display.Image('progress.png'))res = nvidia_smi.nvmlDeviceGetUtilizationRates(handle)print(f'gpu: {res.gpu}%, gpu-mem: {res.memory}%')def ascend_txt():# global iout = synth(z)iii = perceptor.encode_image(normalize(make_cutouts(out))).float()result = []if init_weight:result.append(F.mse_loss(z, z_orig) * init_weight / 2)#result.append(F.mse_loss(z, torch.zeros_like(z_orig)) * ((1/torch.tensor(i*2 + 1))*init_weight) / 2)for prompt in pMs:result.append(prompt(iii))img = np.array(out.mul(255).clamp(0, 255)[0].cpu().detach().numpy().astype(np.uint8))[:,:,:]img = np.transpose(img, (1, 2, 0))# imageio.imwrite('./steps/' + str(i) + '.png', np.array(img))img = Image.fromarray(img).convert('RGB')all_frames.append(img)return result, np.array(img)def train(i):opt.zero_grad()lossAll, image = ascend_txt()if i % args.display_freq == 0:checkin(i, lossAll)loss = sum(lossAll)loss.backward()opt.step()with torch.no_grad():z.copy_(z.maximum(z_min).minimum(z_max))return imagei = 0try:with tqdm() as pbar:while True:image = train(i)if i == max_iterations:breaki += 1pbar.update()except KeyboardInterrupt:passwriter = imageio.get_writer('test.mp4', fps=20)for im in all_frames:writer.append_data(np.array(im))writer.close()# all_frames[0].save('out.gif',# save_all=True, append_images=all_frames[1:], optimize=False, duration=80, loop=0)return image, 'test.mp4'def load_image( infilename ) :img = Image.open( infilename )img.load()data = np.asarray( img, dtype="int32" )return datatitle = "VQGAN + CLIP DEMO"description = "Basit ve ingilizce bir tanımlama yazınız."article = "v0.0.1"gr.Interface(inference,[gr.inputs.Textbox(label="Tanımlama"),gr.inputs.Number(default=42, label="seed"),gr.inputs.Slider(minimum=0.1, maximum=0.9, default=0.6, label='step size'),gr.inputs.Slider(minimum=1, maximum=500, default=100, label='max iterations', step=1),gr.inputs.Slider(minimum=200, maximum=600, default=256, label='width', step=1),gr.inputs.Slider(minimum=200, maximum=600, default=256, label='height', step=1),gr.inputs.Image(type="file", label="Başlangıç Görseli (Opsiyonel)", optional=True),gr.inputs.Slider(minimum=0.0, maximum=15.0, default=0.0, label='Başlangıç Weight', step=1.0),gr.inputs.Image(type="file", label="Hedef Görseli (Opsiyonel)", optional=True),gr.inputs.Slider(minimum=1, maximum=40, default=1, label='cutn', step=1),gr.inputs.Slider(minimum=1.0, maximum=40.0, default=1.0, label='cut_pow', step=1.0)],[gr.outputs.Image(type="numpy", label="Üretilen Görsel"),gr.outputs.Video(label="Üretilen Video")],title=title,description=description,article=article,examples=[['a garden by james gurney',42,0.6, 100, 256, 256, 'garden.jpeg', 0.0, 'garden.jpeg',1,1.0],['coral reef city artstationHQ',1000,0.6, 110, 200, 200, 'coralreef.jpeg', 0.0, 'coralreef.jpeg',1,1.0],['a cabin in the mountains unreal engine',98,0.6, 120, 280, 280, 'cabin.jpeg', 0.0, 'cabin.jpeg',1,1.0]],).launch(enable_queue=True,cache_examples=True)
123456789101112131415ftfy regex tqdm omegaconf pytorch-lightningkorniaimageio-ffmpeg einopsgradiotorchtorchvisionPillownumpyimageionvidia_ml_py312345678910111213141516171819Copyright (c) 2020 Patrick Esser and Robin Rombach and Björn Ommer
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OROTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USEOR OTHER DEALINGS IN THE SOFTWARE./123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377# Taming Transformers for High-Resolution Image Synthesis##### CVPR 2021 (Oral)
[**Taming Transformers for High-Resolution Image Synthesis**](https://compvis.github.io/taming-transformers/)<br/>[Patrick Esser](https://github.com/pesser)\*,[Robin Rombach](https://github.com/rromb)\*,[Björn Ommer](https://hci.iwr.uni-heidelberg.de/Staff/bommer)<br/>\* equal contribution
**tl;dr** We combine the efficiancy of convolutional approaches with the expressivity of transformers by introducing a convolutional VQGAN, which learns a codebook of context-rich visual parts, whose composition is modeled with an autoregressive transformer.
[arXiv](https://arxiv.org/abs/2012.09841) | [BibTeX](#bibtex) | [Project Page](https://compvis.github.io/taming-transformers/)
### News- Thanks to [rom1504](https://github.com/rom1504) it is now easy to [train a VQGAN on your own datasets](#training-on-custom-data).- Included a bugfix for the quantizer. For backward compatibility it is disabled by default (which corresponds to always training with `beta=1.0`). Use `legacy=False` in the quantizer config to enable it. Thanks [richcmwang](https://github.com/richcmwang) and [wcshin-git](https://github.com/wcshin-git)!- Our paper received an update: See https://arxiv.org/abs/2012.09841v3 and the corresponding changelog.- Added a pretrained, [1.4B transformer model](https://k00.fr/s511rwcv) trained for class-conditional ImageNet synthesis, which obtains state-of-the-art FID scores among autoregressive approaches and outperforms BigGAN.- Added pretrained, unconditional models on [FFHQ](https://k00.fr/yndvfu95) and [CelebA-HQ](https://k00.fr/2xkmielf).- Added accelerated sampling via caching of keys/values in the self-attention operation, used in `scripts/sample_fast.py`.- Added a checkpoint of a [VQGAN](https://heibox.uni-heidelberg.de/d/2e5662443a6b4307b470/) trained with f8 compression and Gumbel-Quantization. See also our updated [reconstruction notebook](https://colab.research.google.com/github/CompVis/taming-transformers/blob/master/scripts/reconstruction_usage.ipynb). - We added a [colab notebook](https://colab.research.google.com/github/CompVis/taming-transformers/blob/master/scripts/reconstruction_usage.ipynb) which compares two VQGANs and OpenAI's [DALL-E](https://github.com/openai/DALL-E). See also [this section](#more-resources).- We now include an overview of pretrained models in [Tab.1](#overview-of-pretrained-models). We added models for [COCO](#coco) and [ADE20k](#ade20k).- The streamlit demo now supports image completions.- We now include a couple of examples from the D-RIN dataset so you can run the [D-RIN demo](#d-rin) without preparing the dataset first.- You can now jump right into sampling with our [Colab quickstart notebook](https://colab.research.google.com/github/CompVis/taming-transformers/blob/master/scripts/taming-transformers.ipynb).
## RequirementsA suitable [conda](https://conda.io/) environment named `taming` can be createdand activated with:
```conda env create -f environment.yamlconda activate taming```## Overview of pretrained modelsThe following table provides an overview of all models that are currently available. FID scores were evaluated using [torch-fidelity](https://github.com/toshas/torch-fidelity).For reference, we also include a link to the recently released autoencoder of the [DALL-E](https://github.com/openai/DALL-E) model. See the corresponding [colabnotebook](https://colab.research.google.com/github/CompVis/taming-transformers/blob/master/scripts/reconstruction_usage.ipynb)for a comparison and discussion of reconstruction capabilities.
| Dataset | FID vs train | FID vs val | Link | Samples (256x256) | Comments| ------------- | ------------- | ------------- |------------- | ------------- |------------- || FFHQ (f=16) | 9.6 | -- | [ffhq_transformer](https://k00.fr/yndvfu95) | [ffhq_samples](https://k00.fr/j626x093) || CelebA-HQ (f=16) | 10.2 | -- | [celebahq_transformer](https://k00.fr/2xkmielf) | [celebahq_samples](https://k00.fr/j626x093) || ADE20K (f=16) | -- | 35.5 | [ade20k_transformer](https://k00.fr/ot46cksa) | [ade20k_samples.zip](https://heibox.uni-heidelberg.de/f/70bb78cbaf844501b8fb/) [2k] | evaluated on val split (2k images)| COCO-Stuff (f=16) | -- | 20.4 | [coco_transformer](https://k00.fr/2zz6i2ce) | [coco_samples.zip](https://heibox.uni-heidelberg.de/f/a395a9be612f4a7a8054/) [5k] | evaluated on val split (5k images)| ImageNet (cIN) (f=16) | 15.98/15.78/6.59/5.88/5.20 | -- | [cin_transformer](https://k00.fr/s511rwcv) | [cin_samples](https://k00.fr/j626x093) | different decoding hyperparameters | | | | | || || FacesHQ (f=16) | -- | -- | [faceshq_transformer](https://k00.fr/qqfl2do8)| S-FLCKR (f=16) | -- | -- | [sflckr](https://heibox.uni-heidelberg.de/d/73487ab6e5314cb5adba/) | D-RIN (f=16) | -- | -- | [drin_transformer](https://k00.fr/39jcugc5)| | | | | || || VQGAN ImageNet (f=16), 1024 | 10.54 | 7.94 | [vqgan_imagenet_f16_1024](https://heibox.uni-heidelberg.de/d/8088892a516d4e3baf92/) | [reconstructions](https://k00.fr/j626x093) | Reconstruction-FIDs.| VQGAN ImageNet (f=16), 16384 | 7.41 | 4.98 |[vqgan_imagenet_f16_16384](https://heibox.uni-heidelberg.de/d/a7530b09fed84f80a887/) | [reconstructions](https://k00.fr/j626x093) | Reconstruction-FIDs.| VQGAN OpenImages (f=8), 8192, GumbelQuantization | 3.24 | 1.49 |[vqgan_gumbel_f8](https://heibox.uni-heidelberg.de/d/2e5662443a6b4307b470/) | --- | Reconstruction-FIDs.| | | | | || || DALL-E dVAE (f=8), 8192, GumbelQuantization | 33.88 | 32.01 | https://github.com/openai/DALL-E | [reconstructions](https://k00.fr/j626x093) | Reconstruction-FIDs.
## Running pretrained models
The commands below will start a streamlit demo which supports sampling atdifferent resolutions and image completions. To run a non-interactive versionof the sampling process, replace `streamlit run scripts/sample_conditional.py --`by `python scripts/make_samples.py --outdir <path_to_write_samples_to>` andkeep the remaining command line arguments.
To sample from unconditional or class-conditional models, run `python scripts/sample_fast.py -r <path/to/config_and_checkpoint>`.We describe below how to use this script to sample from the ImageNet, FFHQ, and CelebA-HQ models, respectively.
### S-FLCKR
You can also [run this model in a Colabnotebook](https://colab.research.google.com/github/CompVis/taming-transformers/blob/master/scripts/taming-transformers.ipynb),which includes all necessary steps to start sampling.
Download the[2020-11-09T13-31-51_sflckr](https://heibox.uni-heidelberg.de/d/73487ab6e5314cb5adba/)folder and place it into `logs`. Then, run```streamlit run scripts/sample_conditional.py -- -r logs/2020-11-09T13-31-51_sflckr/```
### ImageNet
Download the [2021-04-03T19-39-50_cin_transformer](https://k00.fr/s511rwcv)folder and place it into logs. Sampling from the class-conditional ImageNetmodel does not require any data preparation. To produce 50 samples for each ofthe 1000 classes of ImageNet, with k=600 for top-k sampling, p=0.92 for nucleussampling and temperature t=1.0, run
```python scripts/sample_fast.py -r logs/2021-04-03T19-39-50_cin_transformer/ -n 50 -k 600 -t 1.0 -p 0.92 --batch_size 25 ```
To restrict the model to certain classes, provide them via the `--classes` argument, separated by commas. For example, to sample 50 *ostriches*, *border collies* and *whiskey jugs*, run
```python scripts/sample_fast.py -r logs/2021-04-03T19-39-50_cin_transformer/ -n 50 -k 600 -t 1.0 -p 0.92 --batch_size 25 --classes 9,232,901 ```We recommended to experiment with the autoregressive decoding parameters (top-k, top-p and temperature) for best results.
### FFHQ/CelebA-HQ
Download the [2021-04-23T18-19-01_ffhq_transformer](https://k00.fr/yndvfu95) and [2021-04-23T18-11-19_celebahq_transformer](https://k00.fr/2xkmielf) folders and place them into logs. Again, sampling from these unconditional models does not require any data preparation.To produce 50000 samples, with k=250 for top-k sampling,p=1.0 for nucleus sampling and temperature t=1.0, run
```python scripts/sample_fast.py -r logs/2021-04-23T18-19-01_ffhq_transformer/ ```for FFHQ and
```python scripts/sample_fast.py -r logs/2021-04-23T18-11-19_celebahq_transformer/ ```to sample from the CelebA-HQ model.For both models it can be advantageous to vary the top-k/top-p parameters for sampling.
### FacesHQ
Download [2020-11-13T21-41-45_faceshq_transformer](https://k00.fr/qqfl2do8) andplace it into `logs`. Follow the data preparation steps for[CelebA-HQ](#celeba-hq) and [FFHQ](#ffhq). Run```streamlit run scripts/sample_conditional.py -- -r logs/2020-11-13T21-41-45_faceshq_transformer/```
### D-RIN
Download [2020-11-20T12-54-32_drin_transformer](https://k00.fr/39jcugc5) andplace it into `logs`. To run the demo on a couple of example depth mapsincluded in the repository, run
```streamlit run scripts/sample_conditional.py -- -r logs/2020-11-20T12-54-32_drin_transformer/ --ignore_base_data data="{target: main.DataModuleFromConfig, params: {batch_size: 1, validation: {target: taming.data.imagenet.DRINExamples}}}"```
To run the demo on the complete validation set, first follow the data preparation steps for[ImageNet](#imagenet) and then run```streamlit run scripts/sample_conditional.py -- -r logs/2020-11-20T12-54-32_drin_transformer/```
### COCODownload [2021-01-20T16-04-20_coco_transformer](https://k00.fr/2zz6i2ce) andplace it into `logs`. To run the demo on a couple of example segmentation mapsincluded in the repository, run
```streamlit run scripts/sample_conditional.py -- -r logs/2021-01-20T16-04-20_coco_transformer/ --ignore_base_data data="{target: main.DataModuleFromConfig, params: {batch_size: 1, validation: {target: taming.data.coco.Examples}}}"```
### ADE20kDownload [2020-11-20T21-45-44_ade20k_transformer](https://k00.fr/ot46cksa) andplace it into `logs`. To run the demo on a couple of example segmentation mapsincluded in the repository, run
```streamlit run scripts/sample_conditional.py -- -r logs/2020-11-20T21-45-44_ade20k_transformer/ --ignore_base_data data="{target: main.DataModuleFromConfig, params: {batch_size: 1, validation: {target: taming.data.ade20k.Examples}}}"```
## Training on custom data
Training on your own dataset can be beneficial to get better tokens and hence better images for your domain.Those are the steps to follow to make this work:1. install the repo with `conda env create -f environment.yaml`, `conda activate taming` and `pip install -e .`1. put your .jpg files in a folder `your_folder`2. create 2 text files a `xx_train.txt` and `xx_test.txt` that point to the files in your training and test set respectively (for example `find $(pwd)/your_folder -name "*.jpg" > train.txt`)3. adapt `configs/custom_vqgan.yaml` to point to these 2 files4. run `python main.py --base configs/custom_vqgan.yaml -t True --gpus 0,1` to train on two GPUs. Use `--gpus 0,` (with a trailing comma) to train on a single GPU.
## Data Preparation
### ImageNetThe code will try to download (through [AcademicTorrents](http://academictorrents.com/)) and prepare ImageNet the first time itis used. However, since ImageNet is quite large, this requires a lot of diskspace and time. If you already have ImageNet on your disk, you can speed thingsup by putting the data into`${XDG_CACHE}/autoencoders/data/ILSVRC2012_{split}/data/` (which defaults to`~/.cache/autoencoders/data/ILSVRC2012_{split}/data/`), where `{split}` is oneof `train`/`validation`. It should have the following structure:
```${XDG_CACHE}/autoencoders/data/ILSVRC2012_{split}/data/├── n01440764│ ├── n01440764_10026.JPEG│ ├── n01440764_10027.JPEG│ ├── ...├── n01443537│ ├── n01443537_10007.JPEG│ ├── n01443537_10014.JPEG│ ├── ...├── ...```
If you haven't extracted the data, you can also place`ILSVRC2012_img_train.tar`/`ILSVRC2012_img_val.tar` (or symlinks to them) into`${XDG_CACHE}/autoencoders/data/ILSVRC2012_train/` /`${XDG_CACHE}/autoencoders/data/ILSVRC2012_validation/`, which will then beextracted into above structure without downloading it again. Note that thiswill only happen if neither a folder`${XDG_CACHE}/autoencoders/data/ILSVRC2012_{split}/data/` nor a file`${XDG_CACHE}/autoencoders/data/ILSVRC2012_{split}/.ready` exist. Remove themif you want to force running the dataset preparation again.
You will then need to prepare the depth data using[MiDaS](https://github.com/intel-isl/MiDaS). Create a symlink`data/imagenet_depth` pointing to a folder with two subfolders `train` and`val`, each mirroring the structure of the corresponding ImageNet folderdescribed above and containing a `png` file for each of ImageNet's `JPEG`files. The `png` encodes `float32` depth values obtained from MiDaS as RGBAimages. We provide the script `scripts/extract_depth.py` to generate this data.**Please note** that this script uses [MiDaS via PyTorchHub](https://pytorch.org/hub/intelisl_midas_v2/). When we prepared the data,the hub provided the [MiDaSv2.0](https://github.com/intel-isl/MiDaS/releases/tag/v2) version, but now itprovides a v2.1 version. We haven't tested our models with depth maps obtainedvia v2.1 and if you want to make sure that things work as expected, you mustadjust the script to make sure it explicitly uses[v2.0](https://github.com/intel-isl/MiDaS/releases/tag/v2)!
### CelebA-HQCreate a symlink `data/celebahq` pointing to a folder containing the `.npy`files of CelebA-HQ (instructions to obtain them can be found in the [PGGANrepository](https://github.com/tkarras/progressive_growing_of_gans)).
### FFHQCreate a symlink `data/ffhq` pointing to the `images1024x1024` folder obtainedfrom the [FFHQ repository](https://github.com/NVlabs/ffhq-dataset).
### S-FLCKRUnfortunately, we are not allowed to distribute the images we collected for theS-FLCKR dataset and can therefore only give a description how it was produced.There are many resources on [collecting images from theweb](https://github.com/adrianmrit/flickrdatasets) to get started.We collected sufficiently large images from [flickr](https://www.flickr.com)(see `data/flickr_tags.txt` for a full list of tags used to find images)and various [subreddits](https://www.reddit.com/r/sfwpornnetwork/wiki/network)(see `data/subreddits.txt` for all subreddits that were used).Overall, we collected 107625 images, and split them randomly into 96861training images and 10764 validation images. We then obtained segmentationmasks for each image using [DeepLab v2](https://arxiv.org/abs/1606.00915)trained on [COCO-Stuff](https://arxiv.org/abs/1612.03716). We used a [PyTorchreimplementation](https://github.com/kazuto1011/deeplab-pytorch) and include anexample script for this process in `scripts/extract_segmentation.py`.
### COCOCreate a symlink `data/coco` containing the images from the 2017 split in`train2017` and `val2017`, and their annotations in `annotations`. Files can beobtained from the [COCO webpage](https://cocodataset.org/). In addition, we usethe [Stuff+thing PNG-style annotations on COCO 2017trainval](http://calvin.inf.ed.ac.uk/wp-content/uploads/data/cocostuffdataset/stuffthingmaps_trainval2017.zip)annotations from [COCO-Stuff](https://github.com/nightrome/cocostuff), whichshould be placed under `data/cocostuffthings`.
### ADE20kCreate a symlink `data/ade20k_root` containing the contents of[ADEChallengeData2016.zip](http://data.csail.mit.edu/places/ADEchallenge/ADEChallengeData2016.zip)from the [MIT Scene Parsing Benchmark](http://sceneparsing.csail.mit.edu/).
## Training models
### FacesHQ
Train a VQGAN with```python main.py --base configs/faceshq_vqgan.yaml -t True --gpus 0,```
Then, adjust the checkpoint path of the config key`model.params.first_stage_config.params.ckpt_path` in`configs/faceshq_transformer.yaml` (or download[2020-11-09T13-33-36_faceshq_vqgan](https://k00.fr/uxy5usa9) and place into `logs`, whichcorresponds to the preconfigured checkpoint path), then run```python main.py --base configs/faceshq_transformer.yaml -t True --gpus 0,```
### D-RIN
Train a VQGAN on ImageNet with```python main.py --base configs/imagenet_vqgan.yaml -t True --gpus 0,```
or download a pretrained one from [2020-09-23T17-56-33_imagenet_vqgan](https://k00.fr/u0j2dtac)and place under `logs`. If you trained your own, adjust the path in the configkey `model.params.first_stage_config.params.ckpt_path` of`configs/drin_transformer.yaml`.
Train a VQGAN on Depth Maps of ImageNet with```python main.py --base configs/imagenetdepth_vqgan.yaml -t True --gpus 0,```
or download a pretrained one from [2020-11-03T15-34-24_imagenetdepth_vqgan](https://k00.fr/55rlxs6i)and place under `logs`. If you trained your own, adjust the path in the configkey `model.params.cond_stage_config.params.ckpt_path` of`configs/drin_transformer.yaml`.
To train the transformer, run```python main.py --base configs/drin_transformer.yaml -t True --gpus 0,```
## More Resources### Comparing Different First Stage ModelsThe reconstruction and compression capabilities of different fist stage models can be analyzed in this [colab notebook](https://colab.research.google.com/github/CompVis/taming-transformers/blob/master/scripts/reconstruction_usage.ipynb). In particular, the notebook compares two VQGANs with a downsampling factor of f=16 for each and codebook dimensionality of 1024 and 16384, a VQGAN with f=8 and 8192 codebook entries and the discrete autoencoder of OpenAI's [DALL-E](https://github.com/openai/DALL-E) (which has f=8 and 8192 codebook entries).
### Other- A [video summary](https://www.youtube.com/watch?v=o7dqGcLDf0A&feature=emb_imp_woyt) by [Two Minute Papers](https://www.youtube.com/channel/UCbfYPyITQ-7l4upoX8nvctg).- A [video summary](https://www.youtube.com/watch?v=-wDSDtIAyWQ) by [Gradient Dude](https://www.youtube.com/c/GradientDude/about).- A [weights and biases report summarizing the paper](https://wandb.ai/ayush-thakur/taming-transformer/reports/-Overview-Taming-Transformers-for-High-Resolution-Image-Synthesis---Vmlldzo0NjEyMTY)by [ayulockin](https://github.com/ayulockin).- A [video summary](https://www.youtube.com/watch?v=JfUTd8fjtX8&feature=emb_imp_woyt) by [What's AI](https://www.youtube.com/channel/UCUzGQrN-lyyc0BWTYoJM_Sg).- Take a look at [ak9250's notebook](https://github.com/ak9250/taming-transformers/blob/master/tamingtransformerscolab.ipynb) if you want to run the streamlit demos on Colab.
### Text-to-Image Optimization via CLIPVQGAN has been successfully used as an image generator guided by the [CLIP](https://github.com/openai/CLIP) model, both for pure image generationfrom scratch and image-to-image translation. We recommend the following notebooks/videos/resources:
- [Advadnouns](https://twitter.com/advadnoun/status/1389316507134357506) Patreon and corresponding LatentVision notebooks: https://www.patreon.com/patronizeme - The [notebook]( https://colab.research.google.com/drive/1L8oL-vLJXVcRzCFbPwOoMkPKJ8-aYdPN) of [Rivers Have Wings](https://twitter.com/RiversHaveWings). - A [video](https://www.youtube.com/watch?v=90QDe6DQXF4&t=12s) explanation by [Dot CSV](https://www.youtube.com/channel/UCy5znSnfMsDwaLlROnZ7Qbg) (in Spanish, but English subtitles are available)

Text prompt: *'A bird drawn by a child'*
## Shout-outsThanks to everyone who makes their code and models available. In particular,
- The architecture of our VQGAN is inspired by [Denoising Diffusion Probabilistic Models](https://github.com/hojonathanho/diffusion)- The very hackable transformer implementation [minGPT](https://github.com/karpathy/minGPT)- The good ol' [PatchGAN](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix) and [Learned Perceptual Similarity (LPIPS)](https://github.com/richzhang/PerceptualSimilarity)
## BibTeX
```@misc{esser2020taming, title={Taming Transformers for High-Resolution Image Synthesis}, author={Patrick Esser and Robin Rombach and Björn Ommer}, year={2020}, eprint={2012.09841}, archivePrefix={arXiv}, primaryClass={cs.CV}}```12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849model: base_learning_rate: 4.5e-06 target: taming.models.vqgan.VQSegmentationModel params: embed_dim: 256 n_embed: 1024 image_key: "segmentation" n_labels: 183 ddconfig: double_z: false z_channels: 256 resolution: 256 in_channels: 183 out_ch: 183 ch: 128 ch_mult: - 1 - 1 - 2 - 2 - 4 num_res_blocks: 2 attn_resolutions: - 16 dropout: 0.0
lossconfig: target: taming.modules.losses.segmentation.BCELossWithQuant params: codebook_weight: 1.0
data: target: cutlit.DataModuleFromConfig params: batch_size: 12 train: target: taming.data.coco.CocoImagesAndCaptionsTrain params: size: 296 crop_size: 256 onehot_segmentation: true use_stuffthing: true validation: target: taming.data.coco.CocoImagesAndCaptionsTrain params: size: 256 crop_size: 256 onehot_segmentation: true use_stuffthing: true12345678910111213141516171819202122232425262728293031323334353637383940414243model: base_learning_rate: 4.5e-6 target: taming.models.vqgan.VQModel params: embed_dim: 256 n_embed: 1024 ddconfig: double_z: False z_channels: 256 resolution: 256 in_channels: 3 out_ch: 3 ch: 128 ch_mult: [ 1,1,2,2,4] # num_down = len(ch_mult)-1 num_res_blocks: 2 attn_resolutions: [16] dropout: 0.0
lossconfig: target: taming.modules.losses.vqperceptual.VQLPIPSWithDiscriminator params: disc_conditional: False disc_in_channels: 3 disc_start: 10000 disc_weight: 0.8 codebook_weight: 1.0
data: target: main.DataModuleFromConfig params: batch_size: 5 num_workers: 8 train: target: taming.data.custom.CustomTrain params: training_images_list_file: some/training.txt size: 256 validation: target: taming.data.custom.CustomTest params: test_images_list_file: some/test.txt size: 256
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677model: base_learning_rate: 4.5e-06 target: taming.models.cond_transformer.Net2NetTransformer params: cond_stage_key: depth transformer_config: target: taming.modules.transformer.mingpt.GPT params: vocab_size: 1024 block_size: 512 n_layer: 24 n_head: 16 n_embd: 1024 first_stage_config: target: taming.models.vqgan.VQModel params: ckpt_path: logs/2020-09-23T17-56-33_imagenet_vqgan/checkpoints/last.ckpt embed_dim: 256 n_embed: 1024 ddconfig: double_z: false z_channels: 256 resolution: 256 in_channels: 3 out_ch: 3 ch: 128 ch_mult: - 1 - 1 - 2 - 2 - 4 num_res_blocks: 2 attn_resolutions: - 16 dropout: 0.0 lossconfig: target: taming.modules.losses.DummyLoss cond_stage_config: target: taming.models.vqgan.VQModel params: ckpt_path: logs/2020-11-03T15-34-24_imagenetdepth_vqgan/checkpoints/last.ckpt embed_dim: 256 n_embed: 1024 ddconfig: double_z: false z_channels: 256 resolution: 256 in_channels: 1 out_ch: 1 ch: 128 ch_mult: - 1 - 1 - 2 - 2 - 4 num_res_blocks: 2 attn_resolutions: - 16 dropout: 0.0 lossconfig: target: taming.modules.losses.DummyLoss
data: target: main.DataModuleFromConfig params: batch_size: 2 num_workers: 8 train: target: taming.data.imagenet.RINTrainWithDepth params: size: 256 validation: target: taming.data.imagenet.RINValidationWithDepth params: size: 25612345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061model: base_learning_rate: 4.5e-06 target: taming.models.cond_transformer.Net2NetTransformer params: cond_stage_key: coord transformer_config: target: taming.modules.transformer.mingpt.GPT params: vocab_size: 1024 block_size: 512 n_layer: 24 n_head: 16 n_embd: 1024 first_stage_config: target: taming.models.vqgan.VQModel params: ckpt_path: logs/2020-11-09T13-33-36_faceshq_vqgan/checkpoints/last.ckpt embed_dim: 256 n_embed: 1024 ddconfig: double_z: false z_channels: 256 resolution: 256 in_channels: 3 out_ch: 3 ch: 128 ch_mult: - 1 - 1 - 2 - 2 - 4 num_res_blocks: 2 attn_resolutions: - 16 dropout: 0.0 lossconfig: target: taming.modules.losses.DummyLoss cond_stage_config: target: taming.modules.misc.coord.CoordStage params: n_embed: 1024 down_factor: 16
data: target: main.DataModuleFromConfig params: batch_size: 2 num_workers: 8 train: target: taming.data.faceshq.FacesHQTrain params: size: 256 crop_size: 256 coord: True validation: target: taming.data.faceshq.FacesHQValidation params: size: 256 crop_size: 256 coord: True123456789101112131415161718192021222324252627282930313233343536373839404142model: base_learning_rate: 4.5e-6 target: taming.models.vqgan.VQModel params: embed_dim: 256 n_embed: 1024 ddconfig: double_z: False z_channels: 256 resolution: 256 in_channels: 3 out_ch: 3 ch: 128 ch_mult: [ 1,1,2,2,4] # num_down = len(ch_mult)-1 num_res_blocks: 2 attn_resolutions: [16] dropout: 0.0
lossconfig: target: taming.modules.losses.vqperceptual.VQLPIPSWithDiscriminator params: disc_conditional: False disc_in_channels: 3 disc_start: 30001 disc_weight: 0.8 codebook_weight: 1.0
data: target: main.DataModuleFromConfig params: batch_size: 3 num_workers: 8 train: target: taming.data.faceshq.FacesHQTrain params: size: 256 crop_size: 256 validation: target: taming.data.faceshq.FacesHQValidation params: size: 256 crop_size: 256123456789101112131415161718192021222324252627282930313233343536373839404142model: base_learning_rate: 4.5e-6 target: taming.models.vqgan.VQModel params: embed_dim: 256 n_embed: 1024 ddconfig: double_z: False z_channels: 256 resolution: 256 in_channels: 3 out_ch: 3 ch: 128 ch_mult: [ 1,1,2,2,4] # num_down = len(ch_mult)-1 num_res_blocks: 2 attn_resolutions: [16] dropout: 0.0
lossconfig: target: taming.modules.losses.vqperceptual.VQLPIPSWithDiscriminator params: disc_conditional: False disc_in_channels: 3 disc_start: 250001 disc_weight: 0.8 codebook_weight: 1.0
data: target: main.DataModuleFromConfig params: batch_size: 12 num_workers: 24 train: target: taming.data.imagenet.ImageNetTrain params: config: size: 256 validation: target: taming.data.imagenet.ImageNetValidation params: config: size: 2561234567891011121314151617181920212223242526272829303132333435363738394041model: base_learning_rate: 4.5e-6 target: taming.models.vqgan.VQModel params: embed_dim: 256 n_embed: 1024 image_key: depth ddconfig: double_z: False z_channels: 256 resolution: 256 in_channels: 1 out_ch: 1 ch: 128 ch_mult: [ 1,1,2,2,4] # num_down = len(ch_mult)-1 num_res_blocks: 2 attn_resolutions: [16] dropout: 0.0
lossconfig: target: taming.modules.losses.vqperceptual.VQLPIPSWithDiscriminator params: disc_conditional: False disc_in_channels: 1 disc_start: 50001 disc_weight: 0.75 codebook_weight: 1.0
data: target: main.DataModuleFromConfig params: batch_size: 3 num_workers: 8 train: target: taming.data.imagenet.ImageNetTrainWithDepth params: size: 256 validation: target: taming.data.imagenet.ImageNetValidationWithDepth params: size: 25612345678910111213141516171819202122232425262728293031323334353637383940414243model: base_learning_rate: 4.5e-06 target: taming.models.vqgan.VQSegmentationModel params: embed_dim: 256 n_embed: 1024 image_key: "segmentation" n_labels: 182 ddconfig: double_z: false z_channels: 256 resolution: 256 in_channels: 182 out_ch: 182 ch: 128 ch_mult: - 1 - 1 - 2 - 2 - 4 num_res_blocks: 2 attn_resolutions: - 16 dropout: 0.0
lossconfig: target: taming.modules.losses.segmentation.BCELossWithQuant params: codebook_weight: 1.0
data: target: cutlit.DataModuleFromConfig params: batch_size: 12 train: target: taming.data.sflckr.Examples # adjust params: size: 256 validation: target: taming.data.sflckr.Examples # adjust params: size: 256123456789101112131415161718192021222324252627282930ADE_val_00000636.jpgADE_val_00000126.jpgADE_val_00001412.jpgADE_val_00001845.jpgADE_val_00001200.jpgADE_val_00001578.jpgADE_val_00000880.jpgADE_val_00000875.jpgADE_val_00000123.jpgADE_val_00001209.jpgADE_val_00000203.jpgADE_val_00001851.jpgADE_val_00001583.jpgADE_val_00000287.jpgADE_val_00001947.jpgADE_val_00000262.jpgADE_val_00000603.jpgADE_val_00000125.jpgADE_val_00001698.jpgADE_val_00001966.jpgADE_val_00000532.jpgADE_val_00001177.jpgADE_val_00000734.jpgADE_val_00001498.jpgADE_val_00001766.jpgADE_val_00000303.jpgADE_val_00000509.jpgADE_val_00000573.jpgADE_val_00000289.jpgADE_val_00001388.jpg.gitattributes+8-19
CLIP/.gitignoreAdded+10
CLIP/CLIP.pngAdded

CLIP/LICENSEAdded+22
CLIP/MANIFEST.inAdded+1
CLIP/README.mdAdded+193
CLIP/clip/__init__.pyAdded+1
CLIP/clip/bpe_simple_vocab_16e6.txt.gzAdded
CLIP/clip/clip.pyAdded+221
CLIP/clip/model.pyAdded+432
CLIP/clip/simple_tokenizer.pyAdded+132
CLIP/data/yfcc100m.mdAdded+14
CLIP/model-card.mdAdded+120
CLIP/notebooks/Interacting_with_CLIP.ipynbAdded
CLIP/notebooks/Prompt_Engineering_for_ImageNet.ipynbAdded+1188
CLIP/requirements.txtAdded+5
CLIP/setup.pyAdded+21
CLIP/tests/test_consistency.pyAdded+25
app.py+395-7
requirements.txtAdded+15
steps/temp.txtAdded
taming-transformers/License.txtAdded+19
taming-transformers/README.mdAdded+377
taming-transformers/assets/birddrawnbyachild.pngAdded

taming-transformers/assets/drin.jpgAdded

taming-transformers/assets/faceshq.jpgAdded

taming-transformers/assets/first_stage_mushrooms.pngAdded

taming-transformers/assets/first_stage_squirrels.pngAdded

taming-transformers/assets/imagenet.pngAdded

taming-transformers/assets/lake_in_the_mountains.pngAdded

taming-transformers/assets/mountain.jpegAdded

taming-transformers/assets/stormy.jpegAdded

taming-transformers/assets/sunset_and_ocean.jpgAdded

taming-transformers/assets/teaser.pngAdded

taming-transformers/configs/coco_cond_stage.yamlAdded+49
taming-transformers/configs/custom_vqgan.yamlAdded+43
taming-transformers/configs/drin_transformer.yamlAdded+77
taming-transformers/configs/faceshq_transformer.yamlAdded+61
taming-transformers/configs/faceshq_vqgan.yamlAdded+42
taming-transformers/configs/imagenet_vqgan.yamlAdded+42
taming-transformers/configs/imagenetdepth_vqgan.yamlAdded+41
taming-transformers/configs/sflckr_cond_stage.yamlAdded+43
taming-transformers/data/ade20k_examples.txtAdded+30
taming-transformers/data/ade20k_images/ADE_val_00000123.jpgAdded

taming-transformers/data/ade20k_images/ADE_val_00000125.jpgAdded

taming-transformers/data/ade20k_images/ADE_val_00000126.jpgAdded

taming-transformers/data/ade20k_images/ADE_val_00000203.jpgAdded

taming-transformers/data/ade20k_images/ADE_val_00000262.jpgAdded

taming-transformers/data/ade20k_images/ADE_val_00000287.jpgAdded

taming-transformers/data/ade20k_images/ADE_val_00000289.jpgAdded
