├── fig └── teaser.jpg ├── hfmodels ├── __init__.py ├── swag.py ├── augreg.py └── moco.py ├── sweeps.py ├── CONTRIBUTING.md ├── util ├── lr_sched.py └── misc.py ├── run_configs.py ├── scripts ├── make_yfcc15m_dataset.py └── make_yfcc100m_dataset.py ├── weights.py ├── .gitignore ├── losses.py ├── configs.py ├── CODE_OF_CONDUCT.md ├── clipeval ├── dataset_catalog.json ├── eval_zeroshot.py ├── templates.json └── datasets.py ├── models_citclip.py ├── submitit_citclip.py ├── README.md ├── engine.py ├── main.py └── LICENSE /fig/teaser.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/CiT/HEAD/fig/teaser.jpg -------------------------------------------------------------------------------- /hfmodels/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | from .moco import MoCoModel, MoCoConfig 5 | from .augreg import AugRegModel, AugRegConfig 6 | from .swag import SwagModel, SwagConfig -------------------------------------------------------------------------------- /sweeps.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | """ 5 | pre-configed sweeps. 6 | """ 7 | 8 | import json 9 | 10 | 11 | class alltask_5k_mr005: 12 | batch_size = [1536], "bsz" 13 | max_update = [5000], "s" 14 | refilter = [100], "refilter" 15 | prefilter = [0.45], "" 16 | min_ratio = [0.05], "r" 17 | sublist = [True], "" 18 | val_task = [d for d in json.load(open("clipeval/dataset_catalog.json")).keys()], "" 19 | aug_tag = [True], "" 20 | nodes = [1], "" 21 | ngpus = [1], "" 22 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to CiT 2 | We want to make contributing to this project as easy and transparent as 3 | possible. 4 | 5 | ## Pull Requests 6 | We actively welcome your pull requests. 7 | 8 | 1. Fork the repo and create your branch from `main`. 9 | 2. If you've added code that should be tested, add tests. 10 | 3. If you've changed APIs, update the documentation. 11 | 4. Ensure the test suite passes. 12 | 5. Make sure your code lints. 13 | 6. If you haven't already, complete the Contributor License Agreement ("CLA"). 14 | 15 | ## Contributor License Agreement ("CLA") 16 | In order to accept your pull request, we need you to submit a CLA. You only need 17 | to do this once to work on any of Facebook's open source projects. 18 | 19 | Complete your CLA here: 20 | 21 | ## Issues 22 | We use GitHub issues to track public bugs. Please ensure your description is 23 | clear and has sufficient instructions to be able to reproduce the issue. 24 | 25 | Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe 26 | disclosure of security bugs. In those cases, please go through the process 27 | outlined on that page and do not file a public issue. 28 | 29 | ## License 30 | By contributing to CiT, you agree that your contributions will be licensed 31 | under the LICENSE file in the root directory of this source tree. -------------------------------------------------------------------------------- /util/lr_sched.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # Copyright (c) Meta Platforms, Inc. All Rights Reserved 7 | 8 | import math 9 | 10 | 11 | def adjust_step_learning_rate(optimizer, step, lr, min_lr, warmup_steps, max_update): 12 | """huxu: add supports for steps instead of epoch. 13 | Decay the learning rate with half-cycle cosine after warmup""" 14 | if step < warmup_steps: 15 | lr = lr * step / warmup_steps 16 | else: 17 | lr = min_lr + (lr - min_lr) * 0.5 * \ 18 | (1. + math.cos(math.pi * (step - warmup_steps) / (max_update - warmup_steps))) 19 | for param_group in optimizer.param_groups: 20 | if "lr_scale" in param_group: 21 | param_group["lr"] = lr * param_group["lr_scale"] 22 | else: 23 | param_group["lr"] = lr 24 | return lr 25 | 26 | 27 | def adjust_learning_rate(optimizer, epoch, args): 28 | """Decay the learning rate with half-cycle cosine after warmup""" 29 | if epoch < args.warmup_epochs: 30 | lr = args.lr * epoch / args.warmup_epochs 31 | else: 32 | lr = args.min_lr + (args.lr - args.min_lr) * 0.5 * \ 33 | (1. + math.cos(math.pi * (epoch - args.warmup_epochs) / (args.epochs - args.warmup_epochs))) 34 | for param_group in optimizer.param_groups: 35 | if "lr_scale" in param_group: 36 | param_group["lr"] = lr * param_group["lr_scale"] 37 | else: 38 | param_group["lr"] = lr 39 | return lr -------------------------------------------------------------------------------- /run_configs.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | from configs import Config 5 | 6 | 7 | ########### running ########### 8 | # torchrun --nproc_per_node=8 main.py 9 | 10 | def eval_yfcc15m_in1k_mocob16(): 11 | return Config( 12 | output_dir="yfcc15m_in1k_mocob16", 13 | eval=True, 14 | resume="checkpoint-best.pth", 15 | dataset="yfcc15m_tag", 16 | metadata="data/yfcc15m/yfcc15m_w_tag.pkl", 17 | root="data/yfcc15m", 18 | trainable_weight="head-all", 19 | batch_size=1024, 20 | max_bert_length=32, 21 | max_update=5000, 22 | weight_decay=0.2, 23 | head_weight_decay=1., 24 | eval_steps=500, 25 | curate=100, 26 | min_ratio=0.003, 27 | extra_prompt=True, 28 | aug_tag=True, 29 | nodes=1, ngpus=1, 30 | ) 31 | 32 | 33 | def yfcc15m_in1k_mocob16(): 34 | return Config( 35 | val_task="imagenet", 36 | dataset="yfcc15m_tag", 37 | metadata="data/yfcc15m/yfcc15m_w_tag.pkl", 38 | root="data/yfcc15m", 39 | trainable_weight="head-all", 40 | batch_size=1024, 41 | max_bert_length=32, 42 | max_update=5000, 43 | weight_decay=0.2, 44 | head_weight_decay=1., 45 | eval_steps=500, 46 | curate=100, 47 | min_ratio=0.003, 48 | extra_prompt=True, 49 | aug_tag=True, 50 | nodes=2, ngpus=8, 51 | ) 52 | 53 | 54 | def yfcc100m_in1k_mocob16(): 55 | return Config( 56 | val_task="imagenet", 57 | dataset="yfcc100m_tag", 58 | metadata="data/yfcc100m/yfcc100m_image_ids.pkl", 59 | root="/datasets01/yfcc100m/090517", 60 | trainable_weight="head-all", 61 | batch_size=1024, 62 | max_bert_length=32, 63 | max_update=5000, 64 | weight_decay=0.2, 65 | head_weight_decay=1., 66 | eval_steps=500, 67 | curate=100, 68 | thres=0.7, 69 | sublist=True, 70 | min_ratio=0.01, 71 | extra_prompt=True, 72 | aug_tag=True, 73 | nodes=2, ngpus=8, 74 | ) 75 | -------------------------------------------------------------------------------- /scripts/make_yfcc15m_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # Copyright (c) Meta Platforms, Inc. All Rights Reserved 7 | 8 | 9 | import numpy as np 10 | import pickle 11 | import re 12 | from urllib.parse import unquote 13 | from tqdm import tqdm 14 | 15 | 16 | # Borrowed from SLIP but add tag field to be consistent with LiT: https://lbsn.vgiscience.org/yfcc-introduction/ 17 | 18 | cleanhtml = re.compile('|||||') 19 | cleanurl = re.compile('http\S+|www\S+') 20 | 21 | print('=> loading YFCC image ids') 22 | image_ids = np.load('data/yfcc15m/flickr_unique_ids.npy') 23 | image_ids = set(image_ids) 24 | 25 | print('=> loading CLIP image ids') 26 | clip_ids = set() 27 | with open('data/yfcc15m/yfcc100m_subset_data.tsv') as f: 28 | for l in tqdm(f.readlines()): 29 | row = l.strip().split('\t') 30 | clip_ids.add(int(row[0])) 31 | 32 | print('=> collecting and cleaning subset captions') 33 | captioned = [] 34 | 35 | with open('/datasets01/yfcc100m/090517/yfcc100m_dataset.txt') as f: 36 | for l in tqdm(f): 37 | row = l.strip().split('\t') 38 | if int(row[0]) in image_ids: 39 | if int(row[0]) in clip_ids: 40 | title = unquote(row[8]).replace('+', ' ') 41 | title = re.sub(cleanhtml, '', title) 42 | title = re.sub(cleanurl, '', title) 43 | 44 | desc = unquote(row[9]).replace('+', ' ') 45 | desc = re.sub(cleanhtml, '', desc) 46 | desc = re.sub(cleanurl, '', desc) 47 | 48 | tag = ",".join([row[10].strip(), row[11].strip()]) 49 | tag = unquote(tag).replace('+', ' ') 50 | tag = re.sub(cleanhtml, '', tag) 51 | tag = re.sub(cleanurl, '', tag) 52 | 53 | captioned.append((int(row[0]), title, desc, tag)) 54 | 55 | with open('data/yfcc15m/yfcc15m_w_tag.pkl', 'wb') as f: 56 | pickle.dump(captioned, f) 57 | 58 | print('Total captioned images:', len(captioned)) # 14689580 59 | -------------------------------------------------------------------------------- /weights.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | """ 5 | pre-configed trainable weights. 6 | """ 7 | 8 | 9 | pre_projection_weights = ['logit_scale', 'visual_projection.weight', 'text_projection.weight'] 10 | 11 | # TODO: unify layer selection for all models. 12 | pre_vision_trainable_weights = { 13 | "moco": { 14 | "head": ['moco.head'], 15 | "none": [], 16 | "all": ["[ALL]"] 17 | }, 18 | "augreg": { 19 | "none": [], 20 | "all": ["[ALL]"], 21 | }, 22 | "swag": { 23 | "none": [], 24 | "all": ["[ALL]"], 25 | } 26 | } 27 | 28 | pre_text_trainable_weights = { 29 | "bert": { 30 | "pool": ['pooler.dense.weight', 'pooler.dense.bias'], 31 | "all": ["[ALL]"] 32 | }, 33 | } 34 | 35 | 36 | def _freeze_model(model, trainable_weights): 37 | '''we assume pretrained model has unknown freezing status. 38 | all model must pass through this function. 39 | (e.g.,, MoCo teacher is freezed after pretraining. 40 | [ALL] indicates fully trainable. 41 | ''' 42 | for name, parameter in model.named_parameters(): 43 | for param in trainable_weights: 44 | if name.startswith(param) or param == "[ALL]": 45 | parameter.requires_grad = True 46 | break 47 | else: 48 | parameter.requires_grad = False 49 | 50 | trainable_parameters = [] 51 | for name, parameter in model.named_parameters(): 52 | if parameter.requires_grad: 53 | trainable_parameters.append(name) 54 | print(f"{model.__class__.__name__} trainable weights:", trainable_parameters) 55 | 56 | 57 | def freeze_model(model, args): 58 | assert "-" in args.trainable_weight, "trainable_weight needs format -." 59 | vision_config, text_config = args.trainable_weight.split("-") 60 | vision_trainable_weights = pre_vision_trainable_weights[args.vision_backbone][vision_config] 61 | text_trainable_weights = pre_text_trainable_weights[args.text_backbone][text_config] 62 | _freeze_model(model, pre_projection_weights) 63 | _freeze_model(model.vision_model, vision_trainable_weights) 64 | _freeze_model(model.text_model, text_trainable_weights) 65 | return model 66 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | hfmodels/timm 131 | -------------------------------------------------------------------------------- /losses.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # Copyright (c) Meta Platforms, Inc. All Rights Reserved 7 | 8 | import torch 9 | import torch.nn as nn 10 | import torch.nn.functional as F 11 | import torch.distributed as dist 12 | 13 | from util import misc 14 | 15 | 16 | class AllGather(torch.autograd.Function): 17 | @staticmethod 18 | def forward(ctx, tensor): 19 | output = [torch.empty_like(tensor) for _ in range(misc.get_world_size())] 20 | dist.all_gather(output, tensor) 21 | ctx.rank = misc.get_rank() 22 | ctx.batch_size = tensor.shape[0] 23 | return torch.cat(output, 0) 24 | 25 | @staticmethod 26 | def backward(ctx, grad_output): 27 | return ( 28 | grad_output[ 29 | ctx.batch_size * ctx.rank : ctx.batch_size * (ctx.rank + 1) 30 | ], 31 | None, 32 | ) 33 | 34 | 35 | class CiTCLIPLossGrad(nn.Module): 36 | def forward(self, image_embeds, text_embeds, logit_scale): 37 | # normalized features 38 | image_embeds = F.normalize(image_embeds, dim=-1, p=2) 39 | text_embeds = F.normalize(text_embeds, dim=-1, p=2) 40 | if misc.get_world_size() > 1: 41 | # gather features from all GPUs 42 | image_embeds = AllGather.apply(image_embeds) 43 | text_embeds = AllGather.apply(text_embeds) 44 | 45 | # cosine similarity as logits 46 | logits_per_image = logit_scale * image_embeds @ text_embeds.t() 47 | labels = torch.arange(logits_per_image.size(0), device=image_embeds.device) 48 | loss = F.cross_entropy(logits_per_image, labels) 49 | return loss 50 | 51 | 52 | class CLIPLossGrad(nn.Module): 53 | def forward(self, image_embeds, text_embeds, logit_scale): 54 | image_embeds = F.normalize(image_embeds, dim=-1, p=2) 55 | text_embeds = F.normalize(text_embeds, dim=-1, p=2) 56 | if misc.get_world_size() > 1: 57 | # gather features from all GPUs 58 | image_embeds = AllGather.apply(image_embeds) 59 | text_embeds = AllGather.apply(text_embeds) 60 | 61 | # cosine similarity as logits 62 | logits_per_image = logit_scale * image_embeds @ text_embeds.t() 63 | logits_per_text = logit_scale * text_embeds @ image_embeds.t() 64 | labels = torch.arange(logits_per_image.size(0), device=image_embeds.device) 65 | 66 | loss = (F.cross_entropy(logits_per_image, labels) + \ 67 | F.cross_entropy(logits_per_text, labels)) / 2. 68 | return loss 69 | -------------------------------------------------------------------------------- /scripts/make_yfcc100m_dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # Copyright (c) Meta Platforms, Inc. All Rights Reserved 7 | 8 | 9 | import numpy as np 10 | import pickle 11 | import re 12 | import time 13 | import sqlite3 14 | import webdataset as wds 15 | 16 | from urllib.parse import unquote 17 | from tqdm import tqdm 18 | 19 | 20 | # Borrowed from SLIP but add tag field to be consistent with LiT: https://lbsn.vgiscience.org/yfcc-introduction/ 21 | 22 | def to_pkl(): 23 | cleanhtml = re.compile('|||||') 24 | cleanurl = re.compile('http\S+|www\S+') 25 | 26 | print('=> loading YFCC image ids') 27 | image_ids = np.load('data/yfcc15m/flickr_unique_ids.npy') 28 | image_ids = set(image_ids) 29 | 30 | print('=> loading CLIP image ids') 31 | print('=> collecting and cleaning subset captions') 32 | captioned = [] 33 | valid_image_ids = [] 34 | with open('/datasets01/yfcc100m/090517/yfcc100m_dataset.txt') as f: 35 | for l in tqdm(f): 36 | row = l.strip().split('\t') 37 | if int(row[0]) in image_ids: 38 | title = unquote(row[8]).replace('+', ' ') 39 | title = re.sub(cleanhtml, '', title) 40 | title = re.sub(cleanurl, '', title).strip() 41 | 42 | desc = unquote(row[9]).replace('+', ' ') 43 | desc = re.sub(cleanhtml, '', desc) 44 | desc = re.sub(cleanurl, '', desc).strip() 45 | 46 | tag = ",".join([row[10].strip(), row[11].strip()]) 47 | tag = unquote(tag).replace('+', ' ') 48 | tag = re.sub(cleanhtml, '', tag) 49 | tag = re.sub(cleanurl, '', tag).strip() 50 | if any([len(title) > 0, len(desc) > 0, len(tag) > 0]): 51 | captioned.append((int(row[0]), title, desc, tag)) 52 | valid_image_ids.append(int(row[0])) 53 | 54 | with open('data/yfcc100m/yfcc100m_captioned_w_tag.pkl', 'wb') as f: 55 | pickle.dump(captioned, f) 56 | 57 | with open('data/yfcc100m/yfcc100m_image_ids.pkl', 'wb') as f: 58 | pickle.dump(valid_image_ids, f) 59 | 60 | print('Total captioned images:', len(captioned)) # 94514285 61 | 62 | 63 | def write_json(): 64 | with open('data/yfcc100m/yfcc100m_captioned_w_tag.pkl', 'rb') as f: 65 | captioned = pickle.load(f) 66 | 67 | from collections import defaultdict 68 | repos = defaultdict(dict) 69 | 70 | for idx, (image_id, title, desc, tag) in enumerate(captioned): 71 | index = format(image_id, "0>8d") 72 | repo = index[:2] 73 | z = index[2: 5] 74 | repos[f"{str(repo).zfill(2)}_{str(z).zfill(3)}"][str(image_id).zfill(8)] = {"title": title, "desc": desc, "tag": tag} 75 | 76 | import json 77 | from pathlib import Path 78 | 79 | for repo in repos: 80 | _repo, z = repo.split("_") 81 | Path(f"data/yfcc100m/yfcc100m_captioned_w_tag/{_repo}").mkdir(parents=True, exist_ok=True) 82 | with open(f"data/yfcc100m/yfcc100m_captioned_w_tag/{_repo}/{z}.json", "w") as fw: 83 | json.dump(repos[repo], fw) 84 | 85 | 86 | to_pkl() 87 | write_json() 88 | -------------------------------------------------------------------------------- /hfmodels/swag.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | import torch 5 | 6 | from transformers import ( 7 | PreTrainedModel, 8 | PretrainedConfig, 9 | AutoConfig, 10 | AutoModel, 11 | ) 12 | 13 | from transformers.modeling_outputs import BaseModelOutputWithPooling 14 | 15 | 16 | class SwagConfig(PretrainedConfig): 17 | model_type = "swag" 18 | 19 | def __init__( 20 | self, 21 | config_name="vit_b16", 22 | hidden_size=768, 23 | **kwargs 24 | ): 25 | super().__init__(**kwargs) 26 | self.config_name = config_name 27 | self.hidden_size = hidden_size 28 | 29 | 30 | AutoConfig.register("swag", SwagConfig) 31 | 32 | 33 | class SwagModel(PreTrainedModel): 34 | config_class = SwagConfig 35 | 36 | @classmethod 37 | def from_orig_pretrained(cls, config_name): 38 | swag = torch.hub.load("facebookresearch/swag", model=config_name) 39 | config = SwagConfig(config_name=config_name, hidden_size=swag.hidden_dim) 40 | model = SwagModel(config) 41 | model.swag = swag 42 | return model 43 | 44 | @classmethod 45 | def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): 46 | import os 47 | ckpt_path = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin") 48 | state_dict = torch.load(os.path.join(ckpt_path)) 49 | config = AutoConfig.from_pretrained(pretrained_model_name_or_path) 50 | model = SwagModel(config) 51 | model.load_state_dict(state_dict, strict=True) 52 | return model 53 | 54 | def __init__(self, config): 55 | super().__init__(config) 56 | self.config = config 57 | self.swag = torch.hub.load("facebookresearch/swag", model=config.config_name) 58 | self.post_init() 59 | 60 | def _init_weights(self, module): 61 | self.swag.init_weights() # check existence. 62 | 63 | def forward( 64 | self, 65 | pixel_values=None, 66 | # attention_mask=None, 67 | # head_mask=None, 68 | output_attentions=None, 69 | output_hidden_states=None, 70 | # interpolate_pos_encoding=None, 71 | return_dict=None 72 | ): 73 | # https://github.com/rwightman/pytorch-image-models/blob/e0c4eec4b66dc14ae96097c7b4a7ef2af45ba309/timm/models/vision_transformer.py#L358 74 | # pre_logits is nn.Identity and token means from CLS [:, 0] 75 | sequence_output = self.swag(pixel_values) 76 | pooled_output = sequence_output 77 | 78 | if not return_dict: 79 | return (sequence_output, pooled_output) 80 | 81 | return BaseModelOutputWithPooling( 82 | last_hidden_state=sequence_output, 83 | pooler_output=pooled_output, 84 | hidden_states=None, # encoder_outputs.hidden_states, 85 | attentions=None, # encoder_outputs.attentions, 86 | ) 87 | 88 | 89 | AutoModel.register(SwagConfig, SwagModel) 90 | 91 | 92 | if __name__ == '__main__': 93 | # dump this model for AutoModel: `python -m hfmodels.swag` 94 | models = ["vit_b16", "vit_l16", "vit_h14"] 95 | for model in models: 96 | vision_model = SwagModel.from_orig_pretrained(model) 97 | vision_model.save_pretrained(f"pretrained_models/{model}_swag_hf") 98 | -------------------------------------------------------------------------------- /configs.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | import os 5 | import inspect 6 | 7 | from collections import OrderedDict 8 | 9 | 10 | class Config: 11 | dataset = "yfcc15m_tag" 12 | root = "data/yfcc15m" 13 | metadata = "data/yfcc15m/yfcc15m_w_tag.pkl" 14 | # data adaptation 15 | val_task = "imagenet" 16 | max_sample = None 17 | thres = 0.55 18 | num_workers = 6 19 | 20 | # model 21 | # model = "moco-bert" 22 | max_bert_length = 32 23 | trainable_weight = "head-all" 24 | vision_backbone = "moco" 25 | vision_pretrained = "pretrained_models/moco_hf" 26 | text_backbone = "bert" 27 | text_pretrained = "princeton-nlp/unsup-simcse-bert-base-uncased" 28 | output_root = "runs" 29 | 30 | # training 31 | fp16 = True 32 | lr = 5e-4 33 | warmup_div = 25 34 | min_lr = 1e-5 35 | weight_decay = 0.2 36 | head_weight_decay = 1. 37 | device = "cuda" 38 | dist_eval = False 39 | accum_iter = 1 40 | eval = False 41 | pin_mem = False 42 | resume = None 43 | clip_grad = None 44 | 45 | loss = "CiTCLIPLossGrad" 46 | 47 | curate = 0 48 | 49 | # evaluate 50 | use_template = True 51 | patience = None 52 | eval_steps = 500 53 | seed = 0 54 | dist_on_itp = False 55 | log_dir = None 56 | 57 | def __init__(self, **kwargs): 58 | for key in kwargs: 59 | setattr(self, key, kwargs[key]) 60 | if not hasattr(self, "warmup_steps"): 61 | self.warmup_steps = int(self.max_update / self.warmup_div) # TODO move this to main? 62 | if not hasattr(self, "output_dir"): 63 | self.output_dir = inspect.stack()[1][3] 64 | self.output_dir = os.path.join(self.output_root, self.output_dir) 65 | print("config.output_dir =", self.output_dir) 66 | 67 | def add_cmd_args(self, cmd_args): 68 | for key, value in vars(cmd_args).items(): 69 | if not key.startswith("__") and value is not None: 70 | setattr(self, key, value) 71 | return self 72 | 73 | def __str__(self): 74 | return "\n".join([f"{k}={v}" for k, v in vars(self).items()]) 75 | 76 | 77 | def build_from_sweep_config(sweep_config): 78 | sweep_dict = OrderedDict() 79 | key_to_short = OrderedDict() 80 | key_to_card = OrderedDict() 81 | sweep_name = sweep_config.__name__ 82 | cards = 1 83 | for key, value in vars(sweep_config).items(): 84 | if not key.startswith("__"): 85 | sweep_dict[key] = value[0] if isinstance(value, tuple) else value 86 | cards *= len(sweep_dict[key]) 87 | key_to_card[key] = len(sweep_dict[key]) 88 | key_to_short[key] = value[1] if isinstance(value, tuple) else "" 89 | 90 | all_update_dicts = [] 91 | for sweep_idx in range(cards): 92 | key_to_idx = OrderedDict() 93 | for key in key_to_card: 94 | key_to_idx[key] = sweep_idx % key_to_card[key] 95 | sweep_idx = sweep_idx // key_to_card[key] 96 | update_dict = OrderedDict() 97 | for key, idx in key_to_idx.items(): 98 | update_dict[key] = sweep_dict[key][idx] 99 | update_dict["output_dir"] = "_".join([value+str(update_dict[key]).replace("/", ".") for key, value in key_to_short.items()]) 100 | update_dict["output_dir"] = os.path.join(sweep_name, update_dict["output_dir"]) 101 | all_update_dicts.append(update_dict) 102 | 103 | assert len(all_update_dicts) == cards 104 | return all_update_dicts 105 | -------------------------------------------------------------------------------- /hfmodels/augreg.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | import torch 5 | 6 | 7 | from transformers import ( 8 | PreTrainedModel, 9 | PretrainedConfig, 10 | AutoConfig, 11 | AutoModel, 12 | ) 13 | from transformers.modeling_outputs import BaseModelOutputWithPooling 14 | 15 | import timm 16 | assert timm.__version__ >= "0.4.12", "make sure timm uses augreg checkpoints." 17 | 18 | 19 | class AugRegConfig(PretrainedConfig): 20 | """ 21 | HF or older timm doesn't load augreg weights. 22 | """ 23 | model_type = "augreg" 24 | 25 | def __init__( 26 | self, 27 | config_name="vit_base_patch32_224_in21k", 28 | hidden_size=768, 29 | **kwargs 30 | ): 31 | super().__init__(**kwargs) 32 | self.config_name = config_name 33 | self.hidden_size = hidden_size 34 | 35 | 36 | AutoConfig.register("augreg", AugRegConfig) 37 | 38 | 39 | class AugRegModel(PreTrainedModel): 40 | config_class = AugRegConfig 41 | 42 | @classmethod 43 | def from_orig_pretrained(cls, config_name): 44 | augreg = timm.create_model(config_name, pretrained=True) 45 | config = AugRegConfig(config_name=config_name, hidden_size=augreg.embed_dim) 46 | model = AugRegModel(config) 47 | model.augreg = augreg 48 | return model 49 | 50 | @classmethod 51 | def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): 52 | import os 53 | ckpt_path = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin") 54 | state_dict = torch.load(os.path.join(ckpt_path)) 55 | config = AutoConfig.from_pretrained(pretrained_model_name_or_path) 56 | model = AugRegModel(config) 57 | model.load_state_dict(state_dict, strict=True) 58 | return model 59 | 60 | def __init__(self, config): 61 | super().__init__(config) 62 | self.config = config 63 | self.augreg = timm.create_model(config.config_name, pretrained=False) 64 | self.post_init() 65 | 66 | def _init_weights(self, module): 67 | self.augreg._init_weights(module) 68 | 69 | def forward( 70 | self, 71 | pixel_values=None, 72 | # attention_mask=None, 73 | # head_mask=None, 74 | output_attentions=None, 75 | output_hidden_states=None, 76 | # interpolate_pos_encoding=None, 77 | return_dict=None 78 | ): 79 | # https://github.com/rwightman/pytorch-image-models/blob/e0c4eec4b66dc14ae96097c7b4a7ef2af45ba309/timm/models/vision_transformer.py#L358 80 | # pre_logits is nn.Identity and token means from CLS [:, 0] 81 | sequence_output = self.augreg.forward_features(pixel_values) 82 | pooled_output = sequence_output 83 | 84 | if not return_dict: 85 | return (sequence_output, pooled_output) 86 | 87 | return BaseModelOutputWithPooling( 88 | last_hidden_state=sequence_output, 89 | pooler_output=pooled_output, 90 | hidden_states=None, # encoder_outputs.hidden_states, 91 | attentions=None, # encoder_outputs.attentions, 92 | ) 93 | 94 | 95 | AutoModel.register(AugRegConfig, AugRegModel) 96 | 97 | 98 | if __name__ == '__main__': 99 | # dump this model for AutoModel: `python -m hfmodels.augreg` 100 | models = ["vit_base_patch32_224_in21k", "vit_base_patch16_224_in21k", "vit_large_patch16_224_in21k"] 101 | for model in models: 102 | vision_model = AugRegModel.from_orig_pretrained(model) 103 | vision_model.save_pretrained(f"pretrained_models/{model}_augreg_hf") 104 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to make participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies within all project spaces, and it also applies when 49 | an individual is representing the project or its community in public spaces. 50 | Examples of representing a project or community include using an official 51 | project e-mail address, posting via an official social media account, or acting 52 | as an appointed representative at an online or offline event. Representation of 53 | a project may be further defined and clarified by project maintainers. 54 | 55 | This Code of Conduct also applies outside the project spaces when there is a 56 | reasonable belief that an individual's behavior may have a negative impact on 57 | the project or its community. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported by contacting the project team at . All 63 | complaints will be reviewed and investigated and will result in a response that 64 | is deemed necessary and appropriate to the circumstances. The project team is 65 | obligated to maintain confidentiality with regard to the reporter of an incident. 66 | Further details of specific enforcement policies may be posted separately. 67 | 68 | Project maintainers who do not follow or enforce the Code of Conduct in good 69 | faith may face temporary or permanent repercussions as determined by other 70 | members of the project's leadership. 71 | 72 | ## Attribution 73 | 74 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 75 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 76 | 77 | [homepage]: https://www.contributor-covenant.org 78 | 79 | For answers to common questions about this code of conduct, see 80 | https://www.contributor-covenant.org/faq 81 | -------------------------------------------------------------------------------- /clipeval/dataset_catalog.json: -------------------------------------------------------------------------------- 1 | { 2 | "food101": { 3 | "path": "data/food101", 4 | "type": "imagefolder", 5 | "train": "train", 6 | "test": "test" 7 | }, 8 | "cifar10": { 9 | "path": "data/cifar10", 10 | "type": "special" 11 | }, 12 | "cifar100": { 13 | "path": "data/cifar100", 14 | "type": "special" 15 | }, 16 | "cub200": { 17 | "path": "data/cub200", 18 | "type": "imagefolder", 19 | "train": "train", 20 | "test": "val" 21 | }, 22 | "sun397": { 23 | "path": "data/sun397", 24 | "type": "filelist", 25 | "train": "train", 26 | "test": "test" 27 | }, 28 | "cars": { 29 | "path": "data/cars", 30 | "type": "imagefolder", 31 | "train": "train", 32 | "test": "test" 33 | }, 34 | "aircraft": { 35 | "path": "data/aircraft", 36 | "type": "imagefolder", 37 | "train": "train", 38 | "test": "test" 39 | }, 40 | "dtd": { 41 | "path": "data/dtd", 42 | "type": "imagefolder", 43 | "train": "train", 44 | "test": "test" 45 | }, 46 | "pets": { 47 | "path": "data/pets", 48 | "type": "imagefolder", 49 | "train": "train", 50 | "test": "test" 51 | }, 52 | "caltech101": { 53 | "path": "data/caltech101", 54 | "type": "imagefolder", 55 | "train": "train", 56 | "test": "test" 57 | }, 58 | "flowers": { 59 | "path": "data/flowers", 60 | "type": "imagefolder", 61 | "train": "train", 62 | "test": "test" 63 | }, 64 | "mnist": { 65 | "path": "data/mnist", 66 | "type": "special" 67 | }, 68 | "fer2013": { 69 | "path": "data/fer2013", 70 | "type": "imagefolder", 71 | "train": "train", 72 | "test": "test" 73 | }, 74 | "stl10": { 75 | "path": "data/stl10", 76 | "type": "special" 77 | }, 78 | "eurosat": { 79 | "path": "data/eurosat", 80 | "type": "imagefolder", 81 | "train": "train", 82 | "test": "val" 83 | }, 84 | "resisc45": { 85 | "path": "data/resisc45", 86 | "type": "imagefolder", 87 | "train": "train", 88 | "test": "test" 89 | }, 90 | "gtsrb": { 91 | "path": "data/gtsrb", 92 | "type": "imagefolder", 93 | "train": "train", 94 | "test": "test" 95 | }, 96 | "kitti_distance": { 97 | "path": "data/kitti_distance", 98 | "type": "imagefolder", 99 | "train": "train", 100 | "test": "val" 101 | }, 102 | "country211": { 103 | "path": "data/country211", 104 | "type": "imagefolder", 105 | "train": "train", 106 | "test": "test" 107 | }, 108 | "patch_camelyon": { 109 | "path": "data/patch_camelyon", 110 | "type": "imagefolder", 111 | "train": "train", 112 | "test": "val" 113 | }, 114 | "ucf101_frames": { 115 | "path": "data/ucf101_frames", 116 | "type": "imagefolder", 117 | "train": "train", 118 | "test": "val" 119 | }, 120 | "kinetics700_frames": { 121 | "path": "data/k700", 122 | "type": "imagefolder", 123 | "train": "train_images", 124 | "test": "val_images" 125 | }, 126 | "clevr_counts": { 127 | "path": "data/clevr_counts", 128 | "type": "filelist", 129 | "train": "train", 130 | "test": "val" 131 | }, 132 | "hateful_memes": { 133 | "path": "data/hateful_memes", 134 | "type": "imagefolder", 135 | "train": "train", 136 | "test": "dev" 137 | }, 138 | "rendered_sst2": { 139 | "path": "data/rendered_sst2", 140 | "type": "imagefolder", 141 | "train": "train", 142 | "test": "test" 143 | }, 144 | "imagenet": { 145 | "path": "data/imagenet_full_size/", 146 | "type": "imagefolder", 147 | "train": "train", 148 | "test": "val" 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /models_citclip.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | import torch 5 | 6 | from transformers import VisionTextDualEncoderModel 7 | 8 | 9 | class CiTCLIPVisionTextDualEncoderModel(VisionTextDualEncoderModel): 10 | '''a hf model wrapper to support forward with either or both image/text. 11 | note that HF impl. uses an artificial pooler that most pre-trained models (e.g., ViT) don't have. 12 | # LiT directly uses [CLS] token for both vision and language. 13 | text: https://github.com/google-research/vision_transformer/blob/16fc24d2734f34b0a7b16212a4386c41fe662cb4/vit_jax/models_lit.py#L62 14 | vision: https://github.com/google-research/vision_transformer/blob/16fc24d2734f34b0a7b16212a4386c41fe662cb4/vit_jax/models_vit.py#L283 15 | configs of LiT: https://github.com/google-research/vision_transformer/blob/16fc24d2734f34b0a7b16212a4386c41fe662cb4/vit_jax/configs/models.py#L319 16 | ''' 17 | 18 | def forward( 19 | self, 20 | input_ids=None, 21 | pixel_values=None, 22 | attention_mask=None, 23 | position_ids=None, 24 | return_loss=None, 25 | token_type_ids=None, 26 | output_attentions=None, 27 | output_hidden_states=None, 28 | return_dict=None, 29 | skip_text_projection=False, 30 | split=1, 31 | **kwargs, 32 | ): 33 | image_embeds, text_embeds = None, None 34 | if pixel_values is not None: 35 | if split > 1: # TODO: test if can merge these two branch. 36 | vision_outputs = [] 37 | for splitted_pixel_values in torch.split(pixel_values, pixel_values.size(0) // split): 38 | vision_outputs.append( 39 | self.vision_model( 40 | pixel_values=splitted_pixel_values, 41 | output_attentions=output_attentions, 42 | output_hidden_states=output_hidden_states, 43 | return_dict=return_dict, 44 | )[1] 45 | ) 46 | image_embeds = torch.cat(vision_outputs, dim=0) 47 | else: 48 | vision_outputs = self.vision_model( 49 | pixel_values=pixel_values, 50 | output_attentions=output_attentions, 51 | output_hidden_states=output_hidden_states, 52 | return_dict=return_dict, 53 | ) 54 | image_embeds = vision_outputs[1] # pooler_output 55 | image_embeds = self.visual_projection(image_embeds) 56 | 57 | if input_ids is not None: 58 | text_outputs = self.text_model( 59 | input_ids=input_ids, 60 | attention_mask=attention_mask, 61 | token_type_ids=token_type_ids, 62 | position_ids=position_ids, 63 | output_attentions=output_attentions, 64 | output_hidden_states=output_hidden_states, 65 | return_dict=return_dict, 66 | ) 67 | # SimCSE uses pooler as tanh as in HF. 68 | text_embeds = text_outputs[1] # pooler_output 69 | if not skip_text_projection: 70 | text_embeds = self.text_projection(text_embeds) 71 | 72 | # cosine similarity as logits 73 | logit_scale = self.logit_scale.exp() 74 | return {"text_embeds": text_embeds, "image_embeds": image_embeds, "logit_scale": logit_scale} 75 | 76 | 77 | def build_model(args): 78 | import os 79 | import hfmodels 80 | 81 | from transformers import AutoTokenizer 82 | 83 | os.environ["TOKENIZERS_PARALLELISM"] = "false" 84 | 85 | print(f"creating model: {args.vision_backbone}-{args.text_backbone}") 86 | 87 | model = CiTCLIPVisionTextDualEncoderModel.from_vision_text_pretrained( # VisionTextDualEncoderModel 88 | args.vision_pretrained, # we dump simclr/moco into HF format. 89 | args.text_pretrained, # all text models are in HF. # vision_model= ... your own model is not HF format. 90 | projection_dim=args.projection_dim if hasattr(args, "projection_dim") else 512 91 | ) 92 | tokenizer = AutoTokenizer.from_pretrained(args.text_pretrained, use_fast=True) 93 | return model, tokenizer 94 | -------------------------------------------------------------------------------- /hfmodels/moco.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | import torch 5 | import sys 6 | sys.path.append("moco-v3") # repo path to moco-v3 7 | 8 | from transformers import ( 9 | PreTrainedModel, 10 | PretrainedConfig, 11 | AutoConfig, 12 | AutoModel, 13 | ) 14 | 15 | from torch import nn 16 | from transformers.modeling_outputs import BaseModelOutputWithPooling 17 | from vits import vit_base 18 | from functools import partial 19 | from moco.builder import MoCo_ViT 20 | from collections import OrderedDict 21 | 22 | 23 | class MoCoConfig(PretrainedConfig): 24 | """ 25 | refer `https://github.com/huggingface/transformers/blob/v4.15.0/src/transformers/models/vit/configuration_vit.py#L29` 26 | `model_type` only has three choices. 27 | https://github.com/huggingface/transformers/blob/05fa1a7ac17bb7aa07b9e0c1e138ecb31a28bbfe/src/transformers/models/vision_text_dual_encoder/configuration_vision_text_dual_encoder.py#L94 28 | how to make sure `hidden_size` match checkpoint ? 29 | """ 30 | model_type = "moco" 31 | 32 | def __init__( 33 | self, 34 | config_name="vit_base_patch16", 35 | hidden_size=256, 36 | **kwargs 37 | ): 38 | super().__init__(**kwargs) 39 | self.config_name = config_name 40 | self.hidden_size = hidden_size 41 | 42 | 43 | AutoConfig.register("moco", MoCoConfig) 44 | 45 | 46 | class MoCoModel(PreTrainedModel): 47 | config_class = MoCoConfig 48 | 49 | @classmethod 50 | def from_orig_pretrained(cls, ckpt_dir): 51 | """load from original checkpoint; used to save a HF checkpoint, see main.""" 52 | config = MoCoConfig(hidden_size=256) 53 | model = MoCoModel(config) 54 | print("loading weights from", ckpt_dir) 55 | ckpt = torch.load(ckpt_dir, map_location='cpu') 56 | state_dict = OrderedDict() 57 | for k, v in ckpt['state_dict'].items(): 58 | k = k.replace('module.', '') 59 | for prefix in ["momentum_encoder", "predictor"]: 60 | if k.startswith(prefix): 61 | break 62 | else: 63 | state_dict[k.replace("base_encoder.", "")] = v 64 | model.moco.load_state_dict(state_dict, strict=True) 65 | model.eval() 66 | return model 67 | 68 | @classmethod 69 | def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): 70 | import os 71 | ckpt_path = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin") 72 | state_dict = torch.load(os.path.join(ckpt_path)) 73 | config = AutoConfig.from_pretrained(pretrained_model_name_or_path) 74 | model = MoCoModel(config) 75 | model.load_state_dict(state_dict, strict=True) 76 | return model 77 | 78 | def __init__(self, config, add_pooling_layer=True): 79 | super().__init__(config) 80 | self.config = config 81 | self.moco = MoCo_ViT( 82 | partial(vit_base, stop_grad_conv1=True), 83 | 256, 4096, 0.2 84 | ).base_encoder 85 | self.post_init() 86 | 87 | def _init_weights(self, m): 88 | # borrowed from mae 89 | if isinstance(m, nn.Linear): 90 | # we use xavier_uniform following official JAX ViT: 91 | torch.nn.init.xavier_uniform_(m.weight) 92 | if isinstance(m, nn.Linear) and m.bias is not None: 93 | nn.init.constant_(m.bias, 0) 94 | elif isinstance(m, nn.LayerNorm): 95 | nn.init.constant_(m.bias, 0) 96 | nn.init.constant_(m.weight, 1.0) 97 | 98 | def forward( 99 | self, 100 | pixel_values=None, 101 | # attention_mask=None, 102 | # head_mask=None, 103 | output_attentions=None, 104 | output_hidden_states=None, 105 | # interpolate_pos_encoding=None, 106 | return_dict=None 107 | ): 108 | encoder_outputs = self.moco(pixel_values) 109 | sequence_output = encoder_outputs.unsqueeze(1) 110 | pooled_output = encoder_outputs 111 | if not return_dict: 112 | return (sequence_output, pooled_output) # + encoder_outputs[1:] 113 | 114 | return BaseModelOutputWithPooling( 115 | last_hidden_state=sequence_output, 116 | pooler_output=encoder_outputs, 117 | hidden_states=None, # encoder_outputs.hidden_states, 118 | attentions=None, # encoder_outputs.attentions, 119 | ) 120 | 121 | 122 | AutoModel.register(MoCoConfig, MoCoModel) 123 | 124 | 125 | if __name__ == '__main__': 126 | # dump this model for AutoModel: `python -m hfmodels.moco` 127 | vision_model = MoCoModel.from_orig_pretrained("pretrained_models/moco/vit-b-300ep.pth.tar") 128 | vision_model.save_pretrained("pretrained_models/moco_hf") 129 | -------------------------------------------------------------------------------- /clipeval/eval_zeroshot.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # Copyright (c) Meta Platforms, Inc. All Rights Reserved 7 | 8 | import torch 9 | import json 10 | import os 11 | 12 | from sklearn import metrics 13 | 14 | 15 | def load_metadata(metadir="clipeval"): 16 | with open(os.path.join(metadir, 'dataset_catalog.json')) as f: 17 | catalog = json.load(f) 18 | 19 | with open(os.path.join(metadir, 'templates.json')) as f: 20 | all_templates = json.load(f) 21 | 22 | with open(os.path.join(metadir, 'labels.json')) as f: 23 | all_labels = json.load(f) 24 | return catalog, all_templates, all_labels 25 | 26 | 27 | def evaluate(d, val_loader, templates, labels, model, tokenizer, max_bert_length, classnorm=False): 28 | print('Evaluating {}'.format(d)) 29 | 30 | is_acc = d not in ['aircraft', 'pets', 'caltech101', 'flowers', 'kinetics700_frames', 'hateful_memes'] 31 | 32 | acc_or_outputs = validate_zeroshot(val_loader, templates, labels, model, tokenizer, is_acc, max_bert_length, classnorm) 33 | 34 | if d in ['aircraft', 'pets', 'caltech101', 'flowers']: 35 | metric = mean_per_class(*acc_or_outputs) 36 | elif d == 'kinetics700_frames': 37 | top1, top5 = accuracy(*acc_or_outputs, topk=(1, 5)) 38 | metric = (top1 + top5) / 2 39 | metric = metric.item() 40 | elif d == 'hateful_memes': 41 | metric = roc_auc(*acc_or_outputs) 42 | else: 43 | metric = acc_or_outputs 44 | 45 | return metric 46 | 47 | 48 | @torch.no_grad() 49 | def build_text_features(templates, labels, model, tokenizer, max_bert_length=77, skip_text_projection=False, classnorm=False): 50 | # (huxu) TODO: add device 51 | text_features = [] 52 | for label in labels: 53 | if isinstance(label, list): 54 | texts = [t.format(l) for t in templates for l in label] 55 | else: 56 | texts = [t.format(label) for t in templates] 57 | 58 | texts = tokenizer(texts, padding=True, truncation=True, max_length=max_bert_length, return_tensors="pt") 59 | for key in texts: 60 | texts[key] = texts[key].to(next(model.parameters()).device, non_blocking=True) 61 | # texts = texts.view(-1, max_bert_length).contiguous() 62 | class_embeddings = model(**texts, skip_text_projection=skip_text_projection)["text_embeds"] 63 | class_embeddings = class_embeddings / class_embeddings.norm(dim=-1, keepdim=True) 64 | class_embeddings = class_embeddings.mean(dim=0) 65 | text_features.append(class_embeddings) 66 | text_features = torch.stack(text_features, dim=0) 67 | mean, std = None, None 68 | if classnorm: 69 | mean, std = text_features.mean(dim=0)[None, :], text_features.std(dim=0)[None, :] 70 | text_features = (text_features - mean) / std 71 | text_features = text_features / text_features.norm(dim=-1, keepdim=True) 72 | return text_features, mean, std 73 | 74 | 75 | @torch.no_grad() 76 | def validate_zeroshot(val_loader, templates, labels, model, tokenizer, is_acc, max_bert_length, classnorm=False): 77 | # switch to evaluate mode 78 | model.cuda() 79 | model.eval() 80 | 81 | total_top1 = 0 82 | total_images = 0 83 | 84 | all_outputs = [] 85 | all_targets = [] 86 | 87 | text_features = None 88 | 89 | for samples in val_loader: 90 | if text_features is None: 91 | print('=> encoding captions') 92 | text_features, mean, std = build_text_features(templates, labels, model, tokenizer, max_bert_length, classnorm=classnorm) 93 | 94 | if isinstance(samples, tuple) or isinstance(samples, list): 95 | images, target = samples[0], samples[1] 96 | elif isinstance(samples, dict): 97 | images, target = samples["pixel_values"], samples["targets"] 98 | else: 99 | raise ValueError("unknown sample type", type(samples)) 100 | 101 | images = images.cuda(non_blocking=True) 102 | target = target.cuda(non_blocking=True) 103 | 104 | # encode images 105 | image_features = model(pixel_values=images)["image_embeds"] 106 | 107 | if classnorm: 108 | image_features = (image_features - mean) / std 109 | 110 | image_features = image_features / image_features.norm(dim=-1, keepdim=True) 111 | # cosine similarity as logits 112 | logits_per_image = image_features @ text_features.t() 113 | logits_per_image = logits_per_image.cpu() 114 | target = target.cpu() 115 | if is_acc: 116 | # measure accuracy and record loss 117 | pred = logits_per_image.argmax(dim=1) 118 | correct = pred.eq(target).sum() 119 | total_top1 += correct.item() 120 | total_images += images.size(0) 121 | else: 122 | all_outputs.append(logits_per_image) 123 | all_targets.append(target) 124 | 125 | if is_acc: 126 | return 100 * total_top1 / total_images 127 | else: 128 | return torch.cat(all_outputs), torch.cat(all_targets) 129 | 130 | 131 | def accuracy(output, target, topk=(1,)): 132 | """Computes the accuracy over the k top predictions for the specified values of k""" 133 | with torch.no_grad(): 134 | maxk = max(topk) 135 | batch_size = target.size(0) 136 | 137 | _, pred = output.topk(maxk, 1, True, True) 138 | pred = pred.t() 139 | correct = pred.eq(target.reshape(1, -1).expand_as(pred)) 140 | 141 | res = [] 142 | for k in topk: 143 | correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True) 144 | res.append(correct_k.mul_(100.0 / batch_size)) 145 | return res 146 | 147 | 148 | def mean_per_class(outputs, targets): 149 | pred = outputs.argmax(1) 150 | confusion_matrix = metrics.confusion_matrix(targets, pred) 151 | per_classes = confusion_matrix.diagonal() / confusion_matrix.sum(axis=1) 152 | 153 | return 100 * per_classes.mean() 154 | 155 | 156 | def roc_auc(outputs, targets): 157 | pos_score = outputs[:, 1] - outputs[:, 0] 158 | metric = metrics.roc_auc_score(targets, pos_score) 159 | 160 | return 100 * metric 161 | 162 | 163 | if __name__ == '__main__': 164 | logits = torch.randn(128, 10) 165 | targets = torch.randint(size=(128,), low=0, high=10) 166 | 167 | evaluate("imagenet", logits, targets) 168 | -------------------------------------------------------------------------------- /submitit_citclip.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # -------------------------------------------------------- 7 | # A script to run multinode training with submitit. 8 | # -------------------------------------------------------- 9 | # Copyright (c) Meta Platforms, Inc. All Rights Reserved 10 | 11 | import argparse 12 | import os 13 | import uuid 14 | from pathlib import Path 15 | 16 | import submitit 17 | 18 | 19 | def parse_args(): 20 | parser = argparse.ArgumentParser("Submitit for adaptation") 21 | parser.add_argument("sweep", type=str, help="name of a sweep.") 22 | parser.add_argument("--ngpus", default=1, type=int, help="Number of gpus to request on each node") 23 | parser.add_argument("--nodes", default=1, type=int, help="Number of nodes to request") 24 | parser.add_argument("--resume", default=None, type=str, help="resume a checkpoint.") 25 | parser.add_argument("--timeout", default=4320, type=int, help="Duration of the job") 26 | parser.add_argument("--job_dir", default="", type=str, help="Job dir. Leave empty for automatic.") 27 | 28 | parser.add_argument("--partition", default="learnlab", type=str, help="Partition where to submit") 29 | parser.add_argument('--comment', default="", type=str, help="Comment to pass to scheduler") 30 | 31 | args = parser.parse_args() 32 | return args 33 | 34 | 35 | def get_shared_folder() -> Path: 36 | user = os.getenv("USER") 37 | if Path("/checkpoint/").is_dir(): 38 | p = Path(f"/checkpoint/{user}/adaclip") 39 | p.mkdir(exist_ok=True) 40 | return p 41 | raise RuntimeError("No shared folder available") 42 | 43 | 44 | def get_init_file(): 45 | # Init file must not exist, but it's parent dir must exist. 46 | os.makedirs(str(get_shared_folder()), exist_ok=True) 47 | init_file = get_shared_folder() / f"{uuid.uuid4().hex}_init" 48 | if init_file.exists(): 49 | os.remove(str(init_file)) 50 | return init_file 51 | 52 | 53 | class Trainer(object): 54 | def __init__(self, args): 55 | self.args = args 56 | self.args.config.dist_url = get_init_file().as_uri() 57 | 58 | def __call__(self): 59 | self._setup_gpu_args() 60 | import main 61 | main.main(self.args.config) 62 | 63 | def checkpoint(self): 64 | import os 65 | import submitit 66 | 67 | self.args.config.dist_url = get_init_file().as_uri() 68 | checkpoint_file = os.path.join(self.args.config.output_dir, "checkpoint-last.pth") 69 | if os.path.exists(checkpoint_file): 70 | self.args.config.resume = checkpoint_file 71 | print("Requeuing ", self.args) 72 | empty_trainer = type(self)(self.args) 73 | return submitit.helpers.DelayedSubmission(empty_trainer) 74 | 75 | def _setup_gpu_args(self): 76 | import submitit 77 | import os 78 | from pathlib import Path 79 | 80 | job_env = submitit.JobEnvironment() 81 | if self.args.ngpus >= 1: 82 | # self.args.config.seed += job_env.global_rank 83 | # assert 'SLURM_PROCID' in os.environ: 84 | self.args.config.local_rank = job_env.local_rank 85 | self.args.config.rank = job_env.global_rank 86 | self.args.config.world_size = job_env.num_tasks 87 | print(f"Process group: {job_env.num_tasks} tasks, rank: {job_env.global_rank}") 88 | 89 | 90 | def main(args): 91 | if args.job_dir == "": 92 | args.job_dir = get_shared_folder() 93 | 94 | assert args.job_dir != "" 95 | 96 | args.job_dir = Path(args.job_dir) / "%j" 97 | 98 | # Note that the folder will depend on the job_id, to easily track experiments 99 | executor = submitit.AutoExecutor(folder=args.job_dir, slurm_max_num_timeout=30) 100 | 101 | num_gpus_per_node = args.ngpus 102 | nodes = args.nodes 103 | timeout_min = args.timeout 104 | 105 | partition = args.partition 106 | kwargs = {} 107 | kwargs['slurm_constraint'] = 'volta32gb' 108 | if args.comment: 109 | kwargs['slurm_comment'] = args.comment 110 | 111 | executor.update_parameters( 112 | mem_gb= 160 * num_gpus_per_node, # if "yfcccc12m" not in args.config.output_dir else 120 * num_gpus_per_node, 113 | gpus_per_node=num_gpus_per_node, 114 | tasks_per_node=num_gpus_per_node, 115 | cpus_per_task=7, 116 | nodes=nodes, 117 | timeout_min=timeout_min, 118 | # Below are cluster dependent parameters 119 | slurm_partition=partition, 120 | slurm_signal_delay_s=120, 121 | **kwargs 122 | ) 123 | 124 | executor.update_parameters(name=os.path.basename(args.config.output_dir)) 125 | trainer = Trainer(args) 126 | job = executor.submit(trainer) 127 | 128 | print("Submitted job_id:", job.job_id, "@", str(args.job_dir).replace("%j", job.job_id)) 129 | 130 | 131 | def submit(): 132 | args = parse_args() 133 | import sweeps 134 | import run_configs 135 | import configs 136 | 137 | from copy import deepcopy 138 | if hasattr(sweeps, args.sweep): 139 | print(f"sweeping {args.sweep} in `sweeps.py`") 140 | sweep_config = getattr(sweeps, args.sweep) 141 | all_update_dicts = configs.build_from_sweep_config(sweep_config) 142 | for update_dict in all_update_dicts: 143 | _args = deepcopy(args) 144 | config = configs.Config(**update_dict) 145 | if args.resume is not None: 146 | config.resume = args.resume 147 | setattr(_args, "config", config) 148 | 149 | if hasattr(config, "ngpus"): 150 | _args.ngpus = config.ngpus 151 | 152 | if hasattr(config, "nodes"): 153 | _args.nodes = config.nodes 154 | 155 | _args.job_dir = config.output_dir 156 | main(_args) 157 | elif hasattr(run_configs, args.sweep): 158 | print(f"launch {args.sweep} in `run_configs.py`") 159 | config = getattr(run_configs, args.sweep)() 160 | _args = deepcopy(args) 161 | if args.resume is not None: 162 | config.resume = args.resume 163 | setattr(_args, "config", config) 164 | 165 | if hasattr(config, "ngpus"): 166 | _args.ngpus = config.ngpus 167 | 168 | if hasattr(config, "nodes"): 169 | _args.nodes = config.nodes 170 | 171 | _args.job_dir = config.output_dir 172 | main(_args) 173 | 174 | 175 | if __name__ == "__main__": 176 | submit() 177 | -------------------------------------------------------------------------------- /clipeval/templates.json: -------------------------------------------------------------------------------- 1 | { 2 | "food101": [ 3 | "a photo of {}, a type of food." 4 | ], 5 | "cifar10": [ 6 | "a photo of a {}.", 7 | "a blurry photo of a {}.", 8 | "a black and white photo of a {}.", 9 | "a low contrast photo of a {}.", 10 | "a high contrast photo of a {}.", 11 | "a bad photo of a {}.", 12 | "a good photo of a {}.", 13 | "a photo of a small {}.", 14 | "a photo of a big {}.", 15 | "a photo of the {}.", 16 | "a blurry photo of the {}.", 17 | "a black and white photo of the {}.", 18 | "a low contrast photo of the {}.", 19 | "a high contrast photo of the {}.", 20 | "a bad photo of the {}.", 21 | "a good photo of the {}.", 22 | "a photo of the small {}.", 23 | "a photo of the big {}." 24 | ], 25 | "cifar100": [ 26 | "a photo of a {}.", 27 | "a blurry photo of a {}.", 28 | "a black and white photo of a {}.", 29 | "a low contrast photo of a {}.", 30 | "a high contrast photo of a {}.", 31 | "a bad photo of a {}.", 32 | "a good photo of a {}.", 33 | "a photo of a small {}.", 34 | "a photo of a big {}.", 35 | "a photo of the {}.", 36 | "a blurry photo of the {}.", 37 | "a black and white photo of the {}.", 38 | "a low contrast photo of the {}.", 39 | "a high contrast photo of the {}.", 40 | "a bad photo of the {}.", 41 | "a good photo of the {}.", 42 | "a photo of the small {}.", 43 | "a photo of the big {}." 44 | ], 45 | "birdsnap": [ 46 | "a photo of a {}, a type of bird." 47 | ], 48 | "cub200": [ 49 | "a photo of a {}, a type of bird." 50 | ], 51 | "imagenet": [ 52 | "itap of a {}.", 53 | "a bad photo of the {}.", 54 | "a origami {}.", 55 | "a photo of the large {}.", 56 | "a {} in a video game.", 57 | "art of the {}.", 58 | "a photo of the small {}." 59 | ], 60 | "rendered_sst2": [ 61 | "a {} review of a movie." 62 | ], 63 | "hateful_memes": [ 64 | "a {}." 65 | ], 66 | "clevr_counts": [ 67 | "a photo of {} objects." 68 | ], 69 | "kinetics700_frames": [ 70 | "a photo of {}.", 71 | "a photo of a person {}.", 72 | "a photo of a person using {}.", 73 | "a photo of a person doing {}.", 74 | "a photo of a person during {}.", 75 | "a photo of a person performing {}.", 76 | "a photo of a person practicing {}.", 77 | "a video of {}.", 78 | "a video of a person {}.", 79 | "a video of a person using {}.", 80 | "a video of a person doing {}.", 81 | "a video of a person during {}.", 82 | "a video of a person performing {}.", 83 | "a video of a person practicing {}.", 84 | "a example of {}.", 85 | "a example of a person {}.", 86 | "a example of a person using {}.", 87 | "a example of a person doing {}.", 88 | "a example of a person during {}.", 89 | "a example of a person performing {}.", 90 | "a example of a person practicing {}.", 91 | "a demonstration of {}.", 92 | "a demonstration of a person {}.", 93 | "a demonstration of a person using {}.", 94 | "a demonstration of a person doing {}.", 95 | "a demonstration of a person during {}.", 96 | "a demonstration of a person performing {}.", 97 | "a demonstration of a person practicing {}." 98 | ], 99 | "ucf101_frames": [ 100 | "a photo of a person {}.", 101 | "a video of a person {}.", 102 | "a example of a person {}.", 103 | "a demonstration of a person {}.", 104 | "a photo of the person {}.", 105 | "a video of the person {}.", 106 | "a example of the person {}.", 107 | "a demonstration of the person {}.", 108 | "a photo of a person using {}.", 109 | "a video of a person using {}.", 110 | "a example of a person using {}.", 111 | "a demonstration of a person using {}.", 112 | "a photo of the person using {}.", 113 | "a video of the person using {}.", 114 | "a example of the person using {}.", 115 | "a demonstration of the person using {}.", 116 | "a photo of a person doing {}.", 117 | "a video of a person doing {}.", 118 | "a example of a person doing {}.", 119 | "a demonstration of a person doing {}.", 120 | "a photo of the person doing {}.", 121 | "a video of the person doing {}.", 122 | "a example of the person doing {}.", 123 | "a demonstration of the person doing {}.", 124 | "a photo of a person during {}.", 125 | "a video of a person during {}.", 126 | "a example of a person during {}.", 127 | "a demonstration of a person during {}.", 128 | "a photo of the person during {}.", 129 | "a video of the person during {}.", 130 | "a example of the person during {}.", 131 | "a demonstration of the person during {}.", 132 | "a photo of a person performing {}.", 133 | "a video of a person performing {}.", 134 | "a example of a person performing {}.", 135 | "a demonstration of a person performing {}.", 136 | "a photo of the person performing {}.", 137 | "a video of the person performing {}.", 138 | "a example of the person performing {}.", 139 | "a demonstration of the person performing {}.", 140 | "a photo of a person practicing {}.", 141 | "a video of a person practicing {}.", 142 | "a example of a person practicing {}.", 143 | "a demonstration of a person practicing {}.", 144 | "a photo of the person practicing {}.", 145 | "a video of the person practicing {}.", 146 | "a example of the person practicing {}.", 147 | "a demonstration of the person practicing {}." 148 | ], 149 | "patch_camelyon": [ 150 | "this is a photo of {}" 151 | ], 152 | "country211": [ 153 | "a photo i took in {}.", 154 | "a photo i took while visiting {}.", 155 | "a photo from my home country of {}.", 156 | "a photo from my visit to {}.", 157 | "a photo showing the country of {}." 158 | ], 159 | "kitti_distance": [ 160 | "{}" 161 | ], 162 | "gtsrb": [ 163 | "a zoomed in photo of a \"{}\" traffic sign.", 164 | "a centered photo of a \"{}\" traffic sign.", 165 | "a close up photo of a \"{}\" traffic sign." 166 | ], 167 | "resisc45": [ 168 | "satellite imagery of {}.", 169 | "aerial imagery of {}.", 170 | "satellite photo of {}.", 171 | "aerial photo of {}.", 172 | "satellite view of {}.", 173 | "aerial view of {}.", 174 | "satellite imagery of a {}.", 175 | "aerial imagery of a {}.", 176 | "satellite photo of a {}.", 177 | "aerial photo of a {}.", 178 | "satellite view of a {}.", 179 | "aerial view of a {}.", 180 | "satellite imagery of the {}.", 181 | "aerial imagery of the {}.", 182 | "satellite photo of the {}.", 183 | "aerial photo of the {}.", 184 | "satellite view of the {}.", 185 | "aerial view of the {}." 186 | ], 187 | "eurosat": [ 188 | "a centered satellite photo of {}.", 189 | "a centered satellite photo of a {}.", 190 | "a centered satellite photo of the {}." 191 | ], 192 | "stl10": [ 193 | "a photo of a {}.", 194 | "a photo of the {}." 195 | ], 196 | "fer2013": [ 197 | "a photo of a {} looking face.", 198 | "a photo of a face showing the emotion: {}.", 199 | "a photo of a face looking {}.", 200 | "a face that looks {}.", 201 | "they look {}.", 202 | "look at how {} they are." 203 | ], 204 | "mnist": [ 205 | "a photo of the number: \"{}\"." 206 | ], 207 | "flowers": [ 208 | "a photo of a {}, a type of flower." 209 | ], 210 | "caltech101": [ 211 | "a photo of a {}.", 212 | "a painting of a {}.", 213 | "a plastic {}.", 214 | "a sculpture of a {}.", 215 | "a sketch of a {}.", 216 | "a tattoo of a {}.", 217 | "a toy {}.", 218 | "a rendition of a {}.", 219 | "a embroidered {}.", 220 | "a cartoon {}.", 221 | "a {} in a video game.", 222 | "a plushie {}.", 223 | "a origami {}.", 224 | "art of a {}.", 225 | "graffiti of a {}.", 226 | "a drawing of a {}.", 227 | "a doodle of a {}.", 228 | "a photo of the {}.", 229 | "a painting of the {}.", 230 | "the plastic {}.", 231 | "a sculpture of the {}.", 232 | "a sketch of the {}.", 233 | "a tattoo of the {}.", 234 | "the toy {}.", 235 | "a rendition of the {}.", 236 | "the embroidered {}.", 237 | "the cartoon {}.", 238 | "the {} in a video game.", 239 | "the plushie {}.", 240 | "the origami {}.", 241 | "art of the {}.", 242 | "graffiti of the {}.", 243 | "a drawing of the {}.", 244 | "a doodle of the {}." 245 | ], 246 | "pets": [ 247 | "a photo of a {}, a type of pet." 248 | ], 249 | "dtd": [ 250 | "a photo of a {} texture.", 251 | "a photo of a {} pattern.", 252 | "a photo of a {} thing.", 253 | "a photo of a {} object.", 254 | "a photo of the {} texture.", 255 | "a photo of the {} pattern.", 256 | "a photo of the {} thing.", 257 | "a photo of the {} object." 258 | ], 259 | "voc2007": [ 260 | "a photo of a {}." 261 | ], 262 | "aircraft": [ 263 | "a photo of a {}, a type of aircraft.", 264 | "a photo of the {}, a type of aircraft." 265 | ], 266 | "cars": [ 267 | "a photo of a {}.", 268 | "a photo of the {}.", 269 | "a photo of my {}.", 270 | "i love my {}!", 271 | "a photo of my dirty {}.", 272 | "a photo of my clean {}.", 273 | "a photo of my new {}.", 274 | "a photo of my old {}." 275 | ], 276 | "sun397": [ 277 | "a photo of a {}.", 278 | "a photo of the {}." 279 | ] 280 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## CiT: Curation in Training 2 | 3 | This repository contains the code for paper [CiT: Curation in Training for Effective Vision-Language Data](https://arxiv.org/abs/2301.02241). For the first time, CiT curates/optimizes training data during (pre-)training a CLIP-style model, archieves better scaling law and beats human's offline data filtering (for potential downstream tasks). 4 | 5 | ```bibtex 6 | @inproceedings{xu2023cit, 7 | title={CiT: Curation in Training for Effective Vision-Language Data}, 8 | author={Hu Xu, Saining Xie, Po-Yao Huang, Licheng Yu, Russell Howes, Gargi Ghosh, Luke Zettlemoyer and Christoph Feichtenhofer}, 9 | journal={arXiv preprint arXiv:2301.02241}, 10 | year={2023} 11 | } 12 | ``` 13 | 14 | ## Updates 15 | * 01/17/2023: release YFCC100M for ImageNet(-1K). 16 | * 01/05/2023: initial release. 17 | 18 | 19 | ## Quick Links 20 | 21 | - [Overview](#overview) 22 | - [Getting Started](#getting-started) 23 | - [Prepare Vision Encoders](#prepare-vision-encoders) 24 | - [Download Pretrained CiT](#download-pretrained-cit) 25 | - [Use CiT with PyTorch](#use-cit-with-pytorch) 26 | - [Use CiT with Huggingface](#use-cit-with-huggingface) 27 | - [Model List](#model-list) 28 | - [Evaluation](#evaluation) 29 | - [Train CiT](#train-cit) 30 | - [Training](#training) 31 | - [Bugs or Questions?](#bugs-or-questions) 32 | - [Citation](#citation) 33 | - [Reference](#reference) 34 | 35 | ## Overview 36 | 37 | This paper trades generality for efficiency and presents Curation in Training (CiT), a simple and efficient vision-text learning algorithm that couples a data objective into training. CiT automatically yields quality data to speed-up contrastive image-text training and alleviates the need for an offline data filtering pipeline, allowing broad data sources (including raw image-text pairs from the web). CiT contains two loops: an outer loop curating the training data and an inner loop consuming the curated training data. The text encoder connects the two loops. Given metadata for tasks of interest, e.g., class names, and a large pool of image-text pairs, CiT alternatively selects relevant training data from the pool by measuring the similarity of their text embeddings and embeddings of the metadata. 38 | 39 | ![](fig/teaser.jpg) 40 | 41 | ## Getting Started 42 | 43 | This code is developed with minimal requirements in mind (tested under Python 3.9.7, PyTorch 1.10.2 and Transformers 4.19.2). All models are built under [Transformers](https://github.com/huggingface/transformers)'s [VisionTextDualEncoder](https://huggingface.co/docs/transformers/model_doc/vision-text-dual-encoder) to allow potential extension to other pre-trained models. 44 | 45 | ```bash 46 | pip install transformers==4.19.2 47 | ``` 48 | 49 | ### Prepare Vision Encoders 50 | CiT paper uses pre-trained vision encoders such as [MoCo-v3](https://github.com/facebookresearch/moco-v3), AugReg (Timm `>=0.4.12`, older version doesn't contain AugReg checkpoints) and [SWAG](https://github.com/facebookresearch/SWAG). They are not available in [Huggingface Transformers](https://github.com/huggingface/transformers) at the moment. 51 | 52 | First, clone or install 3rd party repos: 53 | ```bash 54 | git clone https://github.com/facebookresearch/moco-v3.git # moco-v3 55 | cd hfmodels && git clone -b v0.5.4 https://github.com/rwightman/pytorch-image-models.git # AugReg from timm as a local copy. 56 | cd .. 57 | ``` 58 | Note it is recommended to have different copies of timm with local imports since MoCo-v3 and AugReg models may ask for different versions (and timm is NOT backward/forward compatible). SWAG is from torch hub so we don't need to do anything. 59 | 60 | **Training only** 61 | To download checkpoints of pre-trained vision encoders: 62 | ```bash 63 | cd pretrained_models && wget https://dl.fbaipublicfiles.com/moco-v3/vit-b-300ep/vit-b-300ep.pth.tar # moco-v3 64 | cd .. 65 | ``` 66 | Checkpoints for AugReg (timm) or SWAG (torch hub) should be automatically downloaded. 67 | 68 | Lastly, launch the follow commands to convert these 3rd party models into huggingface models for training. 69 | 70 | ```bash 71 | python -m hfmodels.moco 72 | python -m hfmodels.augreg 73 | python -m hfmodels.swag 74 | ``` 75 | You should find them in `pretrained_models`. 76 | 77 | ### Download Pretrained CiT 78 | ```bash 79 | wget https://dl.fbaipublicfiles.com/MMPT/cit/yfcc15m_in1k_mocob16.tar 80 | tar xvf yfcc15m_in1k_mocob16.tar # expected in pretrained_models/yfcc15m_in1k_mocob16 81 | ``` 82 | Check [Model List](#model-list) for other models. 83 | 84 | ### Use CiT with PyTorch 85 | For transparency on pytorch, you can use the following code to load CiT pre-trained models (similar to resuming a training in `main.py`): 86 | 87 | ```python 88 | import torch 89 | import run_configs 90 | 91 | from torch.nn import functional as F 92 | from models_citclip import build_model 93 | 94 | config_name = "yfcc15m_in1k_mocob16" 95 | args = getattr(run_configs, config_name)() 96 | model, tokenizer = build_model(args) 97 | 98 | state_dict = torch.load(f"pretrained_models/{config_name}/pytorch_model.bin", map_location='cpu') 99 | model.load_state_dict(state_dict) 100 | model.eval() 101 | 102 | inputs = tokenizer(["a photo of dog"], padding="max_length", truncation=True, max_length=args.max_bert_length, return_tensors="pt") 103 | inputs["pixel_values"] = torch.randn(1, 3, 224, 224) 104 | with torch.no_grad(): 105 | outputs = model(**inputs) 106 | image_embeds = F.normalize(outputs["image_embeds"], dim=-1, p=2) 107 | text_embeds = F.normalize(outputs["text_embeds"], dim=-1, p=2) 108 | cosine = image_embeds @ text_embeds.t() 109 | print(cosine.item()) 110 | ``` 111 | 112 | ### Use CiT with Huggingface 113 | Please run the following to load checkpoints (Huggingface Transformer compatible). Hosting checkpoints in huggingface coming soon. 114 | 115 | ```python 116 | import torch 117 | 118 | import hfmodels 119 | import run_configs 120 | 121 | from torch.nn import functional as F 122 | from transformers import AutoModel, AutoTokenizer 123 | 124 | 125 | config_name = "yfcc15m_in1k_mocob16" 126 | args = getattr(run_configs, config_name)() 127 | 128 | model = AutoModel.from_pretrained(f"pretrained_models/{config_name}") 129 | tokenizer = AutoTokenizer.from_pretrained(args.text_pretrained) # TODO: we didn't save tokenizer, so read the original. 130 | 131 | inputs = tokenizer(["a photo of dog"], padding="max_length", truncation=True, max_length=args.max_bert_length, return_tensors="pt") 132 | inputs["pixel_values"] = torch.randn(1, 3, 224, 224) 133 | 134 | with torch.no_grad(): 135 | outputs = model(**inputs) 136 | image_embeds = F.normalize(outputs.image_embeds, dim=-1, p=2) 137 | text_embeds = F.normalize(outputs.text_embeds, dim=-1, p=2) 138 | cosine = image_embeds @ text_embeds.t() 139 | 140 | print(cosine.item()) 141 | print(outputs.logits_per_image.item()) # this is multiplied by logit_scale by HF. 142 | ``` 143 | 144 | 145 | ## Model List 146 | Our released models are listed as following. You can import these models by the following Get Started/Evaluation section. 147 | | Model | Table in Paper | 148 | |:-------------------------------|:--------:| 149 | | [cit/yfcc15m_in1k_mocob16](https://dl.fbaipublicfiles.com/MMPT/cit/yfcc15m_in1k_mocob16.tar) | Table 4 | 150 | | [cit/yfcc100m_in1k_mocob16](https://dl.fbaipublicfiles.com/MMPT/cit/yfcc100m_in1k_mocob16.tar) | Table 4 | 151 | 152 | More models coming soon. 153 | 154 | ## Evaluation 155 | Evaluate on IN-1K: 156 | 157 | ```bash 158 | python main.py yfcc15m_in1k_mocob16 --resume pretrained_models/yfcc15m_in1k_mocob16 --eval 159 | ``` 160 | 161 | Evaluate on 26 tasks: 162 | ```bash 163 | python main.py eval_yfcc15m_in1k_mocob16 --resume pretrained_models/yfcc15m_in1k_mocob16 --eval 164 | # or via submitit: 165 | python submitit_citclip.py eval_yfcc15m_in1k_mocob16 166 | ``` 167 | 168 | ### Training 169 | 170 | **Data** 171 | Preprocess YFCC15M can be done as follows: 172 | ```bash 173 | mkdir -p data/yfcc15m 174 | # follow https://github.com/facebookresearch/SLIP to download and compile a list of downloaded images to data/yfcc15m/flickr_unique_ids.npy 175 | # copy YFCC15M (https://github.com/openai/CLIP/blob/main/data/yfcc100m.md) to `data/yfcc15m/yfcc100m_subset_data.tsv` 176 | python scripts/make_yfcc15m_dataset.py 177 | ``` 178 | 179 | Preprocessing YFCC100M (too big to fit all in CPU memory): 180 | ```bash 181 | mkdir -p data/yfcc100m 182 | python scripts/make_yfcc100m_dataset.py 183 | ``` 184 | 185 | **Training scripts** 186 | 187 | Every config is written as a native python function/class to record the args and neither bash args or mixed programming languages nor python config (eg, versioning OmegaConf or yaml). 188 | Check example configs in `run_configs.py`, e.g., 189 | 190 | ```bash 191 | python main.py yfcc15m_in1k_mocob16 # a local training of the default setup in the paper on YFCC15M on a single GPU. 192 | torchrun --nproc_per_node=8 main.py yfcc15m_in1k_mocob16 # on a local node with 8 GPUs. 193 | python submitit_citclip.py yfcc15m_in1k_mocob16 # submit the SLURM job with 16 GPUs (nodes=2 and ngpus=8). `conda install -c conda-forge submitit` or `pip install submitit` 194 | ``` 195 | 196 | **Single GPU Training** 197 | coming soon 198 | 199 | ## Curated Dataset 200 | As a side benefit, CiT made a dataset (as a textbook). 201 | 202 | **YFCC100M for ImageNet** 203 | You can find this dataset [here](https://dl.fbaipublicfiles.com/MMPT/cit/yfcc100m_for_in.tar.gz), with `{image ids}_{text key}` as keys and times of this pair used in CiT training as values. 204 | 205 | ## Bugs or questions? 206 | 207 | If you have any questions related to the code or the paper, feel free to email Hu Xu (`huxu@meta.com`). 208 | 209 | ## TODO 210 | 211 | - [] integrated downloading with huggingface and pytorch hub 212 | 213 | ## Citation 214 | 215 | Please cite our paper if CiT contributes in your work: 216 | 217 | ```bibtex 218 | @inproceedings{xu2023cit, 219 | title={CiT: Curation in Training for Effective Vision-Language Data}, 220 | author={Hu Xu, Saining Xie, Po-Yao Huang, Licheng Yu, Russell Howes, Gargi Ghosh, Luke Zettlemoyer and Christoph Feichtenhofer}, 221 | journal={arXiv preprint arXiv:2301.02241}, 222 | year={2023} 223 | } 224 | ``` 225 | 226 | ## Reference 227 | 228 | The codebase is developed from [MAE](https://github.com/facebookresearch/mae), [SLIP](https://github.com/facebookresearch/SLIP) repos and [Huggingface Transformers](https://github.com/huggingface/transformers). 229 | 230 | 231 | ## License 232 | 233 | The majority of CiT is licensed under CC-BY-NC, however portions of the project are available under separate license terms: https://github.com/facebookresearch/slip is licensed under the MIT license and https://huggingface.co/docs/transformers/index is licensed under the Apache 2.0 license. 234 | -------------------------------------------------------------------------------- /clipeval/datasets.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # Copyright (c) Meta Platforms, Inc. All Rights Reserved 7 | 8 | import json 9 | import os 10 | import pickle 11 | import zipfile 12 | 13 | import numpy as np 14 | import torch 15 | import random 16 | 17 | from PIL import Image, ImageFile 18 | from torchvision import datasets as t_datasets 19 | 20 | 21 | ImageFile.LOAD_TRUNCATED_IMAGES = True 22 | 23 | 24 | def pil_loader(path): 25 | # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835) 26 | with open(path, 'rb') as f: 27 | img = Image.open(f) 28 | return img.convert('RGB') 29 | 30 | 31 | def yfcc_loader(root, index): 32 | index = format(index, "0>8d") 33 | repo = index[:2] 34 | z = index[2: 5] 35 | file_img = index[5:] + '.jpg' 36 | path_zip = os.path.join(root, 'images', repo, z) + '.zip' 37 | with zipfile.ZipFile(path_zip, 'r') as myzip: 38 | img = Image.open(myzip.open(file_img)) 39 | return img.convert('RGB') 40 | 41 | 42 | def aug_tag(tag): 43 | delims = [" ", ",", ";", "/", "\n"] 44 | delim = random.choice(delims)[0] 45 | segs = [seg.strip() for seg in tag.split(",") if len(seg.strip()) > 0] 46 | random.shuffle(segs) 47 | tag = delim.join(segs) 48 | return tag 49 | 50 | 51 | class ImageCaptionDatasetBase(torch.utils.data.Dataset): 52 | def __init__(self, args, dataset, root, metadata, task_example_ids=None, with_vision=True, with_text=True, max_sample=None): 53 | self.with_vision = with_vision 54 | self.with_text = with_text 55 | self.dataset = dataset 56 | self.root = root 57 | if hasattr(args, "aug_tag"): 58 | self.aug_tag = args.aug_tag 59 | if self.dataset in ["yfcc100m_tag"]: 60 | self.json_root = os.path.join(os.path.dirname(metadata), "yfcc100m_captioned_w_tag") 61 | self.samples = [] 62 | if task_example_ids is not None: 63 | if isinstance(task_example_ids, list): 64 | self.samples.extend(task_example_ids) 65 | else: 66 | self.samples.extend(list(task_example_ids)) 67 | print(f"apply task filter with {len(self.samples)} examples.") 68 | else: 69 | with open(metadata, 'rb') as f: 70 | samples = pickle.load(f) 71 | self.samples.extend(samples) 72 | if max_sample is not None and len(self.samples) >= max_sample: 73 | self.samples = self.samples[:max_sample] 74 | elif self.dataset in ['yfcc15m_tag', 'yfcc15m']: 75 | with open(metadata, 'rb') as f: 76 | samples = pickle.load(f) 77 | self.samples = [] 78 | if task_example_ids is not None: 79 | if isinstance(task_example_ids, list): 80 | # build the index of sample and follow the list order. 81 | image_id_to_sample = {} 82 | for image_id, title, desc, tag in samples: 83 | title, desc, tag = title.strip(), desc.strip(), tag.strip() 84 | if len(title) > 0: 85 | image_id_to_sample["_".join([str(image_id).zfill(8), "title"])] = {"image_id": image_id, "title": title} 86 | if len(desc) > 0: 87 | image_id_to_sample["_".join([str(image_id).zfill(8), "desc"])] = {"image_id": image_id, "desc": desc} 88 | if "tag" in self.dataset and len(tag) > 0: 89 | image_id_to_sample["_".join([str(image_id).zfill(8), "tag"])] = {"image_id": image_id, "tag": tag} 90 | for image_key in task_example_ids: 91 | if max_sample is not None and len(self.samples) >= max_sample: 92 | break 93 | image_id, field = image_key.split("_") 94 | image_id = image_id.zfill(8) 95 | image_key = "_".join([image_id, field]) 96 | self.samples.append(image_id_to_sample[image_key]) 97 | else: 98 | for image_id, title, desc, tag in samples: 99 | title, desc, tag = title.strip(), desc.strip(), tag.strip() 100 | if str(image_id).zfill(8) + "_title" in task_example_ids and len(title) > 0: 101 | self.samples.append({"image_id": image_id, "title": title}) 102 | if str(image_id).zfill(8) + "_desc" in task_example_ids and len(desc) > 0: 103 | self.samples.append({"image_id": image_id, "desc": desc}) 104 | if "tag" in self.dataset and str(image_id).zfill(8) + "_tag" in task_example_ids and len(tag) > 0: 105 | self.samples.append({"image_id": image_id, "tag": tag}) 106 | if max_sample is not None and len(self.samples) >= max_sample: 107 | break 108 | print(f"apply task filter with {len(self.samples)} examples.") 109 | else: 110 | for image_id, title, desc, tag in samples: 111 | title, desc, tag = title.strip(), desc.strip(), tag.strip() 112 | rec = {} 113 | if len(title) > 0: 114 | rec["title"] = title 115 | if len(desc) > 0: 116 | rec["desc"] = desc 117 | if "tag" in self.dataset and len(tag) > 0: 118 | rec["tag"] = tag 119 | if len(rec) > 0: 120 | rec["image_id"] = image_id 121 | self.samples.append(rec) 122 | if max_sample is not None and len(self.samples) >= max_sample: 123 | break 124 | else: 125 | raise ValueError(f"unknown dataset {self.dataset}") 126 | 127 | def get_raw_item(self, i): 128 | if self.dataset in ["yfcc100m_tag"]: 129 | sample = self.samples[i] 130 | if isinstance(sample, str): 131 | index, key = sample.split("_") 132 | else: 133 | index = sample 134 | index = format(index, "0>8d") 135 | img = yfcc_loader(self.root, int(index)) if self.with_vision else None 136 | if self.with_text: 137 | repo = index[:2] 138 | z = index[2: 5] 139 | with open(f"{self.json_root}/{repo}/{z}.json") as fr: 140 | repo_z = json.load(fr) 141 | rec = repo_z[str(index).zfill(8)] 142 | if not isinstance(sample, str): 143 | key = random.choice([key for key in rec if len(rec[key]) > 0]) 144 | index = "_".join([str(index).zfill(8), key]) 145 | if key == "tag" and (hasattr(self, "aug_tag") and self.aug_tag): 146 | caption = aug_tag(rec[key]) 147 | else: 148 | caption = rec[key] 149 | elif self.dataset in ['yfcc15m_tag', 'yfcc15m']: 150 | rec = self.samples[i] 151 | index = rec["image_id"] 152 | img = yfcc_loader(self.root, index) if self.with_vision else None 153 | if self.with_text: 154 | key = random.choice([_key for _key in rec if _key != "image_id"]) 155 | index = "_".join([str(index).zfill(8), key]) 156 | if key == "tag" and hasattr(self, "aug_tag"): 157 | caption = aug_tag(rec[key]) 158 | else: 159 | caption = rec[key] 160 | else: 161 | raise ValueError(f"unknown dataset {self.dataset}") 162 | return index, img, caption 163 | 164 | def __getitem__(self, i): 165 | raise NotImplementedError 166 | 167 | def __len__(self): 168 | return len(self.samples) 169 | 170 | 171 | class ImageCaptionDatasetCLIP(ImageCaptionDatasetBase): 172 | def __init__(self, args, dataset, root, metadata, task_example_ids, transform=None, tokenizer=None, max_bert_length=77, with_vision=True, with_text=True, max_sample=None): 173 | super().__init__(args, dataset, root, metadata, task_example_ids, with_vision, with_text, max_sample) 174 | self.max_bert_length = max_bert_length 175 | self.transform = transform 176 | self.tokenizer = tokenizer 177 | 178 | def __getitem__(self, i): 179 | index, img, caption = self.get_raw_item(i) 180 | result = {"image_ids": index} 181 | # apply transformation 182 | if img is not None and self.transform is not None: 183 | img = self.transform(img) 184 | result["pixel_values"] = img 185 | 186 | # tokenize caption 187 | if caption is not None and self.tokenizer is not None: 188 | inputs = self.tokenizer(caption, padding="max_length", truncation=True, max_length=self.max_bert_length, return_tensors="pt") 189 | for key in inputs: 190 | inputs[key] = inputs[key][0] 191 | result.update(**inputs) 192 | result["captions"] = caption 193 | return result 194 | 195 | 196 | class FileListDataset(torch.utils.data.Dataset): 197 | def __init__(self, images, labels, transform=None, target_transform=None): 198 | self.transform = transform 199 | self.target_transform = target_transform 200 | self.images = np.load(images) 201 | self.labels = np.load(labels) 202 | 203 | def __getitem__(self, index): 204 | img = pil_loader(self.images[index]) 205 | target = self.labels[index] 206 | 207 | if self.transform is not None: 208 | img = self.transform(img) 209 | 210 | if self.target_transform is not None: 211 | target = self.target_transform(target) 212 | 213 | return img, target 214 | 215 | def __len__(self): 216 | return len(self.images) 217 | 218 | 219 | def get_downstream_dataset(catalog, name, is_train, transform): 220 | entry = catalog[name] 221 | root = entry['path'] 222 | if entry['type'] == 'imagefolder': 223 | dataset = t_datasets.ImageFolder(os.path.join(root, entry['train'] if is_train else entry['test']), 224 | transform=transform) 225 | elif entry['type'] == 'special': 226 | if name == 'cifar10': 227 | dataset = t_datasets.CIFAR10(root, train=is_train, 228 | transform=transform, download=True) 229 | elif name == 'cifar100': 230 | dataset = t_datasets.CIFAR100(root, train=is_train, 231 | transform=transform, download=True) 232 | elif name == 'stl10': 233 | dataset = t_datasets.STL10(root, split='train' if is_train else 'test', 234 | transform=transform, download=True) 235 | elif name == 'mnist': 236 | dataset = t_datasets.MNIST(root, train=is_train, 237 | transform=transform, download=True) 238 | elif entry['type'] == 'filelist': 239 | path = entry['train'] if is_train else entry['test'] 240 | val_images = os.path.join(root, path + '_images.npy') 241 | val_labels = os.path.join(root, path + '_labels.npy') 242 | if name == 'clevr_counts': 243 | target_transform = lambda x: ['count_10', 'count_3', 'count_4', 'count_5', 'count_6', 'count_7', 'count_8', 'count_9'].index(x) 244 | else: 245 | target_transform = None 246 | dataset = FileListDataset(val_images, val_labels, transform, target_transform) 247 | else: 248 | raise Exception('Unknown dataset') 249 | 250 | return dataset 251 | -------------------------------------------------------------------------------- /engine.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # -------------------------------------------------------- 7 | # References: 8 | # DeiT: https://github.com/facebookresearch/deit 9 | # BEiT: https://github.com/microsoft/unilm/tree/master/beit 10 | # -------------------------------------------------------- 11 | # Copyright (c) Meta Platforms, Inc. All Rights Reserved 12 | 13 | import math 14 | import sys 15 | import json 16 | 17 | import torch 18 | 19 | import util.misc as misc 20 | import util.lr_sched as lr_sched 21 | 22 | from typing import Iterable 23 | from collections import defaultdict 24 | 25 | 26 | def to_device(samples, device, args): 27 | inputs = {} 28 | for key in samples: 29 | if key not in ["image_ids", "captions", "__key__"]: 30 | inputs[key] = samples[key].to(device, non_blocking=True) 31 | if key == "pixel_values" and inputs[key].dtype == torch.uint8: 32 | from main import get_mean_std 33 | # inmem data. normalize it. 34 | inputs[key] = inputs[key].to(torch.float32).div_(255.) # b, 3, 224, 224 35 | mean, std = get_mean_std(args) 36 | mean = torch.as_tensor(mean, device=inputs[key].device)[None, :, None, None] 37 | std = torch.as_tensor(std, device=inputs[key].device)[None, :, None, None] 38 | inputs[key] = inputs[key].sub_(mean).div_(std) 39 | return inputs 40 | 41 | 42 | @torch.no_grad() 43 | def evaluate(args, model, val_transform, tokenizer): 44 | from clipeval import datasets, eval_zeroshot 45 | 46 | catalog, all_templates, all_labels = eval_zeroshot.load_metadata("clipeval") 47 | 48 | if args.val_task is None or args.val_task in ["mt", "imagenet21k", "imagenet1k"]: # infer val_task for multitasking. 49 | val_task = "imagenet" 50 | else: 51 | val_task = args.val_task 52 | 53 | metrics = {} 54 | for d in catalog: # assume multitask on CLIP suite by default and early stop if IN only. 55 | if not args.eval and d != val_task: # training only eval on val_task. 56 | continue 57 | if args.eval and args.val_task not in ["mt", "imagenet21k", "imagenet1k"] and d != val_task: 58 | continue 59 | val_dataset = datasets.get_downstream_dataset( 60 | catalog, d, is_train=False, transform=val_transform) 61 | templates = all_templates[d] 62 | labels = all_labels[d] 63 | 64 | if args.val_task not in ["mt", "imagenet21k", "imagenet1k"] and (hasattr(args, "extra_prompt") and args.extra_prompt) and d == "imagenet": # not eval MT in LiT setup. 65 | templates.extend(["A photo of a {}", "{}"]) # see LiT page 16. 66 | 67 | val_loader = torch.utils.data.DataLoader( 68 | val_dataset, batch_size=args.batch_size//2, shuffle=False, 69 | num_workers=args.num_workers, pin_memory=False, drop_last=False) 70 | 71 | if not args.use_template: 72 | templates = ["{}"] 73 | 74 | metric = eval_zeroshot.evaluate(d, val_loader, templates, labels, model, tokenizer, args.max_bert_length, False) 75 | metrics[d] = metric 76 | if args.eval: 77 | json_str = json.dumps({"task": d, "acc": metric}) 78 | misc.print_json(args.output_dir, json_str) 79 | return metrics if len(metrics) > 1 else metrics[val_task] # be compatible for ImageNet only evaluation. 80 | 81 | 82 | def append_dataset(dataset, batch, mask_selector, batch_size): 83 | if "pixel_values" in batch: 84 | assert batch["pixel_values"].dtype == torch.uint8 85 | if mask_selector.sum().item() == 0: 86 | return 87 | assert len(dataset[-1]["image_ids"]) <= batch_size 88 | if len(dataset[-1]["image_ids"]) == batch_size: 89 | dataset.append(defaultdict(list)) 90 | batch_len = len(batch["image_ids"]) 91 | for key in batch: 92 | assert batch_len == len(batch[key]) 93 | for ix, selected in enumerate(mask_selector): 94 | if selected: 95 | dataset[-1][key].append(batch[key][ix]) 96 | 97 | while len(dataset[-1]["image_ids"]) >= batch_size: 98 | last_batch = dataset[-1] 99 | new_batch = {} 100 | for key in last_batch: 101 | value = last_batch[key] 102 | if len(value) >= batch_size: 103 | last_batch[key] = value[:batch_size] 104 | if torch.is_tensor(value[0]): 105 | last_batch[key] = torch.stack(last_batch[key]) 106 | if len(value) > batch_size: 107 | new_batch[key] = value[batch_size:] 108 | if new_batch: 109 | dataset.append(new_batch) 110 | else: 111 | return 112 | 113 | 114 | def train_one_epoch(model: torch.nn.Module, model_without_ddp, criterion: torch.nn.Module, tokenizer, 115 | data_loader: Iterable, data_loader_val: Iterable, val_transform, best_acc, optimizer: torch.optim.Optimizer, 116 | device: torch.device, epoch: int, step, loss_scaler, eff_batch_size, max_norm: float = 0, 117 | # mixup_fn: Optional[Mixup] = None, 118 | log_writer=None, 119 | args=None): 120 | model.train(True) 121 | 122 | metric_logger = misc.MetricLogger(delimiter=" ") 123 | metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}')) 124 | header = 'Epoch: [{}]'.format(epoch) 125 | print_freq = 20 126 | accum_iter = args.accum_iter 127 | 128 | optimizer.zero_grad() 129 | 130 | # assuming data_loader is either a real dataloader or inmem as a list of batches? 131 | for data_iter_step, samples in enumerate(metric_logger.log_every(data_loader, print_freq, header, args.max_update)): 132 | if step[0] > args.max_update: 133 | break 134 | 135 | # we use a per iteration (instead of per epoch) lr scheduler 136 | if data_iter_step % accum_iter == 0: 137 | lr_sched.adjust_step_learning_rate(optimizer, step[0], args.lr, args.min_lr, args.warmup_steps, args.max_update) 138 | 139 | inputs = to_device(samples, device, args) 140 | 141 | with torch.cuda.amp.autocast(enabled=args.fp16): 142 | outputs = model(**inputs) 143 | loss = criterion(**outputs) 144 | 145 | loss_value = loss.item() 146 | 147 | if not math.isfinite(loss_value): 148 | print("Loss is {}, stopping training".format(loss_value)) 149 | sys.exit(1) 150 | 151 | loss /= accum_iter 152 | update_grad = (data_iter_step + 1) % accum_iter == 0 153 | loss_scaler(loss, optimizer, clip_grad=max_norm, 154 | parameters=model.parameters(), create_graph=False, 155 | update_grad=update_grad) 156 | 157 | if update_grad: 158 | step[0] += 1 159 | optimizer.zero_grad() 160 | 161 | torch.cuda.synchronize() 162 | 163 | metric_logger.update(loss=loss_value) 164 | min_lr = 10. 165 | max_lr = 0. 166 | for group in optimizer.param_groups: 167 | min_lr = min(min_lr, group["lr"]) 168 | max_lr = max(max_lr, group["lr"]) 169 | 170 | metric_logger.update(lr=max_lr) 171 | 172 | loss_value_reduce = misc.all_reduce_mean(loss_value) 173 | if log_writer is not None: 174 | log_writer.add_scalar('lr', max_lr, step[0]) 175 | log_writer.add_scalar('loss', loss_value_reduce, step[0]) 176 | 177 | if step[0] and step[0] % args.eval_steps == 0: 178 | metric = evaluate(args, model, val_transform, tokenizer) 179 | json_str = json.dumps({"step": step[0], "acc": metric, "seen": eff_batch_size * step[0]}) 180 | misc.print_json(args.output_dir, json_str) 181 | if log_writer is not None: 182 | log_writer.add_scalar('acc', metric, step[0]) 183 | 184 | if isinstance(data_loader, list) or (hasattr(data_loader, "dataset") and isinstance(data_loader.dataset, torch.utils.data.IterableDataset)): 185 | misc.save_model( 186 | args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer, 187 | loss_scaler=loss_scaler, epoch=0, epoch_name="last", best_acc=best_acc[0], step=step[0]) 188 | if metric > best_acc[0]: 189 | best_acc[0] = metric 190 | misc.save_model( 191 | args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer, 192 | loss_scaler=loss_scaler, epoch=step[0], epoch_name="best", best_acc=best_acc[0], step=step[0]) 193 | model.train(True) 194 | 195 | if step[0] and curate_condition(step[0], args): 196 | break 197 | 198 | # gather the stats from all processes 199 | metric_logger.synchronize_between_processes() 200 | print("Averaged stats:", metric_logger) 201 | return {k: meter.global_avg for k, meter in metric_logger.meters.items()} 202 | 203 | 204 | def curate_condition(step, args): 205 | if args.curate and step % args.curate == 0: 206 | return True 207 | else: 208 | return False 209 | 210 | 211 | def curate_scheduler(step, args): 212 | return args.curate 213 | 214 | 215 | def max_sim(logits, thres): 216 | logits, idx = logits.max(dim=-1) 217 | return logits > thres, idx 218 | 219 | 220 | ratio = 1.0 221 | thres = None 222 | 223 | 224 | def thres_scheduler(step, args): 225 | return args.thres 226 | 227 | 228 | def while_condition(example_ids, step, args): 229 | if hasattr(args, "inmem") and args.inmem: 230 | return len(example_ids) < curate_scheduler(step, args) or (len(example_ids) == curate_scheduler(step, args) and len(example_ids[-1]["image_ids"]) < args.batch_size) 231 | else: 232 | return len(example_ids) < (curate_scheduler(step, args) * args.batch_size) 233 | 234 | 235 | @torch.no_grad() 236 | def iterative_classcurate(step, device, producer_iter, model, tokenizer, args): 237 | model.eval() 238 | from clipeval import eval_zeroshot 239 | 240 | catalog, all_templates, all_labels = eval_zeroshot.load_metadata("clipeval") 241 | if args.val_task == "mt": 242 | labels = set() 243 | for d in catalog: 244 | for label in all_labels[d]: 245 | if isinstance(label, list): 246 | for _label in label: 247 | labels.add(_label) 248 | else: 249 | labels.add(label) 250 | labels = list(labels) 251 | elif args.val_task == "imagenet21k": 252 | labels = set() 253 | with open("clipeval/imagenet21k_wordnet_lemmas.txt", "r") as fr: 254 | for line in fr: 255 | labels.add(line.strip()) 256 | labels = list(labels) 257 | else: 258 | d = args.val_task # infer catalog_subsets 259 | labels = all_labels[d] 260 | 261 | templates = ["{}"] if not (hasattr(args, "templatefilter") and args.templatefilter) else all_templates[args.val_task] # no templates for now. 262 | 263 | labels_emb = [] 264 | with torch.cuda.amp.autocast(): 265 | labels_emb, _, _ = eval_zeroshot.build_text_features( 266 | templates, labels, model, tokenizer, args.max_bert_length, skip_text_projection=True) 267 | labels_emb = labels_emb.t().to(torch.float32) 268 | if hasattr(args, "sublist") and args.sublist: 269 | example_ids = [] 270 | else: 271 | example_ids = set() 272 | total_example = 0 273 | global thres 274 | thres = thres_scheduler(step[0], args) 275 | while while_condition(example_ids, step[0], args): 276 | samples = next(producer_iter) 277 | image_ids = samples["image_ids"] 278 | total_example += len(image_ids) 279 | if hasattr(args, "skip_step") and step[0] < args.skip_step: 280 | mask_selector = torch.ones((len(image_ids),), dtype=torch.bool) 281 | else: 282 | inputs = to_device(samples, device, args) 283 | with torch.cuda.amp.autocast(): 284 | text_embeds = model(**inputs, skip_text_projection=False if hasattr(args, "project_emb") else True)["text_embeds"] 285 | text_embeds = text_embeds.to(torch.float32) 286 | text_embeds = text_embeds / text_embeds.norm(dim=-1, keepdim=True) 287 | logits = torch.matmul(text_embeds, labels_emb).cpu() 288 | mask_selector, class_idx = max_sim(logits, thres) 289 | batch_ratio = float(mask_selector.sum() / len(mask_selector)) 290 | if hasattr(args, "min_ratio") and batch_ratio < args.min_ratio: 291 | # use topr logic. 292 | max_logits, class_idx = logits.max(dim=-1) 293 | _, idx = max_logits.topk(dim=-1, k=int(args.min_ratio * logits.size(0))) 294 | mask_selector = torch.zeros_like(max_logits, dtype=torch.bool) 295 | mask_selector[idx] = True 296 | if mask_selector.sum() > 0: 297 | assert len(mask_selector.size()) == 1 and len(image_ids) == mask_selector.size(0) 298 | filtered_image_ids = [image_ids[_idx] for _idx in range(len(image_ids)) if mask_selector[_idx]] 299 | for image_id_field in filtered_image_ids: 300 | if hasattr(args, "sublist") and args.sublist: 301 | example_ids.append(image_id_field) 302 | else: 303 | example_ids.add(image_id_field) 304 | 305 | global ratio 306 | ratio = len(example_ids) / total_example 307 | misc.print_json(args.output_dir, json.dumps({"step": step[0], "ratio": ratio, "thres": thres})) 308 | model.train() 309 | return example_ids 310 | -------------------------------------------------------------------------------- /util/misc.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # -------------------------------------------------------- 7 | # References: 8 | # DeiT: https://github.com/facebookresearch/deit 9 | # BEiT: https://github.com/microsoft/unilm/tree/master/beit 10 | # -------------------------------------------------------- 11 | # Copyright (c) Meta Platforms, Inc. All Rights Reserved 12 | 13 | import builtins 14 | import datetime 15 | import os 16 | import time 17 | from collections import defaultdict, deque 18 | from pathlib import Path 19 | 20 | import torch 21 | import torch.distributed as dist 22 | from torch._six import inf 23 | 24 | 25 | class SmoothedValue(object): 26 | """Track a series of values and provide access to smoothed values over a 27 | window or the global series average. 28 | """ 29 | 30 | def __init__(self, window_size=20, fmt=None): 31 | if fmt is None: 32 | fmt = "{median:.4f} ({global_avg:.4f})" 33 | self.deque = deque(maxlen=window_size) 34 | self.total = 0.0 35 | self.count = 0 36 | self.fmt = fmt 37 | 38 | def update(self, value, n=1): 39 | self.deque.append(value) 40 | self.count += n 41 | self.total += value * n 42 | 43 | def synchronize_between_processes(self): 44 | """ 45 | Warning: does not synchronize the deque! 46 | """ 47 | if not is_dist_avail_and_initialized(): 48 | return 49 | t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda') 50 | dist.barrier() 51 | dist.all_reduce(t) 52 | t = t.tolist() 53 | self.count = int(t[0]) 54 | self.total = t[1] 55 | 56 | @property 57 | def median(self): 58 | d = torch.tensor(list(self.deque)) 59 | return d.median().item() 60 | 61 | @property 62 | def avg(self): 63 | d = torch.tensor(list(self.deque), dtype=torch.float32) 64 | return d.mean().item() 65 | 66 | @property 67 | def global_avg(self): 68 | return self.total / self.count 69 | 70 | @property 71 | def max(self): 72 | return max(self.deque) 73 | 74 | @property 75 | def value(self): 76 | return self.deque[-1] 77 | 78 | def __str__(self): 79 | return self.fmt.format( 80 | median=self.median, 81 | avg=self.avg, 82 | global_avg=self.global_avg, 83 | max=self.max, 84 | value=self.value) 85 | 86 | 87 | class MetricLogger(object): 88 | def __init__(self, delimiter="\t"): 89 | self.meters = defaultdict(SmoothedValue) 90 | self.delimiter = delimiter 91 | 92 | def update(self, **kwargs): 93 | for k, v in kwargs.items(): 94 | if v is None: 95 | continue 96 | if isinstance(v, torch.Tensor): 97 | v = v.item() 98 | assert isinstance(v, (float, int)) 99 | self.meters[k].update(v) 100 | 101 | def __getattr__(self, attr): 102 | if attr in self.meters: 103 | return self.meters[attr] 104 | if attr in self.__dict__: 105 | return self.__dict__[attr] 106 | raise AttributeError("'{}' object has no attribute '{}'".format( 107 | type(self).__name__, attr)) 108 | 109 | def __str__(self): 110 | loss_str = [] 111 | for name, meter in self.meters.items(): 112 | loss_str.append( 113 | "{}: {}".format(name, str(meter)) 114 | ) 115 | return self.delimiter.join(loss_str) 116 | 117 | def synchronize_between_processes(self): 118 | for meter in self.meters.values(): 119 | meter.synchronize_between_processes() 120 | 121 | def add_meter(self, name, meter): 122 | self.meters[name] = meter 123 | 124 | def log_every(self, iterable, print_freq, header=None, max_update=None): 125 | i = 0 126 | if not header: 127 | header = '' 128 | start_time = time.time() 129 | end = time.time() 130 | iter_time = SmoothedValue(fmt='{avg:.4f}') 131 | data_time = SmoothedValue(fmt='{avg:.4f}') 132 | if hasattr(iterable, "dataset") and isinstance(iterable.dataset, torch.utils.data.IterableDataset): 133 | len_iter = max_update 134 | else: 135 | len_iter = len(iterable) 136 | 137 | space_fmt = ':' + str(len(str(len_iter))) + 'd' 138 | log_msg = [ 139 | header, 140 | '[{0' + space_fmt + '}/{1}]', 141 | 'eta: {eta}', 142 | '{meters}', 143 | 'time: {time}', 144 | 'data: {data}' 145 | ] 146 | if torch.cuda.is_available(): 147 | log_msg.append('max mem: {memory:.0f}') 148 | log_msg = self.delimiter.join(log_msg) 149 | MB = 1024.0 * 1024.0 150 | for obj in iterable: 151 | data_time.update(time.time() - end) 152 | yield obj 153 | iter_time.update(time.time() - end) 154 | if i % print_freq == 0 or i == len_iter - 1: 155 | eta_seconds = iter_time.global_avg * (len_iter - i) 156 | eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) 157 | if torch.cuda.is_available(): 158 | print(log_msg.format( 159 | i, len_iter, eta=eta_string, 160 | meters=str(self), 161 | time=str(iter_time), data=str(data_time), 162 | memory=torch.cuda.max_memory_allocated() / MB)) 163 | else: 164 | print(log_msg.format( 165 | i, len_iter, eta=eta_string, 166 | meters=str(self), 167 | time=str(iter_time), data=str(data_time))) 168 | i += 1 169 | end = time.time() 170 | total_time = time.time() - start_time 171 | total_time_str = str(datetime.timedelta(seconds=int(total_time))) 172 | print('{} Total time: {} ({:.4f} s / it)'.format( 173 | header, total_time_str, total_time / len_iter)) 174 | 175 | 176 | def setup_for_distributed(is_master): 177 | """ 178 | This function disables printing when not in master process 179 | """ 180 | builtin_print = builtins.print 181 | 182 | def print(*args, **kwargs): 183 | force = kwargs.pop('force', False) 184 | force = force or (get_world_size() > 8) 185 | if is_master or force: 186 | now = datetime.datetime.now() 187 | builtin_print('[{}] '.format(now), end='') # print with time stamp 188 | builtin_print(*args, **kwargs) 189 | 190 | builtins.print = print 191 | 192 | 193 | def is_dist_avail_and_initialized(): 194 | if not dist.is_available(): 195 | return False 196 | if not dist.is_initialized(): 197 | return False 198 | return True 199 | 200 | 201 | def get_world_size(): 202 | if not is_dist_avail_and_initialized(): 203 | return 1 204 | return dist.get_world_size() 205 | 206 | 207 | def get_rank(): 208 | if not is_dist_avail_and_initialized(): 209 | return 0 210 | return dist.get_rank() 211 | 212 | 213 | def is_main_process(): 214 | return get_rank() == 0 215 | 216 | 217 | def save_on_master(*args, **kwargs): 218 | if is_main_process(): 219 | torch.save(*args, **kwargs) 220 | 221 | 222 | def init_distributed_mode(args): 223 | if args.dist_on_itp: 224 | args.rank = int(os.environ['OMPI_COMM_WORLD_RANK']) 225 | args.world_size = int(os.environ['OMPI_COMM_WORLD_SIZE']) 226 | args.gpu = int(os.environ['OMPI_COMM_WORLD_LOCAL_RANK']) 227 | args.dist_url = "tcp://%s:%s" % (os.environ['MASTER_ADDR'], os.environ['MASTER_PORT']) 228 | os.environ['LOCAL_RANK'] = str(args.gpu) 229 | os.environ['RANK'] = str(args.rank) 230 | os.environ['WORLD_SIZE'] = str(args.world_size) 231 | # ["RANK", "WORLD_SIZE", "MASTER_ADDR", "MASTER_PORT", "LOCAL_RANK"] 232 | elif 'RANK' in os.environ and 'WORLD_SIZE' in os.environ: 233 | args.rank = int(os.environ["RANK"]) 234 | args.world_size = int(os.environ['WORLD_SIZE']) 235 | args.gpu = int(os.environ['LOCAL_RANK']) 236 | elif 'SLURM_PROCID' in os.environ: 237 | args.rank = int(os.environ['SLURM_PROCID']) 238 | args.gpu = args.rank % torch.cuda.device_count() 239 | else: 240 | print('Not using distributed mode') 241 | setup_for_distributed(is_master=True) # hack 242 | args.distributed = False 243 | return 244 | 245 | args.distributed = True 246 | 247 | torch.cuda.set_device(args.gpu) 248 | args.dist_backend = 'nccl' 249 | print('| distributed init (rank {}): {}, gpu {}'.format( 250 | args.rank, args.dist_url, args.gpu), flush=True) 251 | torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url, 252 | world_size=args.world_size, rank=args.rank) 253 | torch.distributed.barrier() 254 | setup_for_distributed(args.rank == 0) 255 | 256 | 257 | class NativeScalerWithGradNormCount: 258 | state_dict_key = "amp_scaler" 259 | 260 | def __init__(self, fp16=True): 261 | self._scaler = torch.cuda.amp.GradScaler(enabled=fp16) 262 | 263 | def __call__(self, loss, optimizer, clip_grad=None, parameters=None, create_graph=False, update_grad=True): 264 | self._scaler.scale(loss).backward(create_graph=create_graph) 265 | if update_grad: 266 | if clip_grad is not None: 267 | assert parameters is not None 268 | self._scaler.unscale_(optimizer) # unscale the gradients of optimizer's assigned params in-place 269 | norm = torch.nn.utils.clip_grad_norm_(parameters, clip_grad) 270 | else: 271 | self._scaler.unscale_(optimizer) 272 | norm = get_grad_norm_(parameters) 273 | self._scaler.step(optimizer) 274 | self._scaler.update() 275 | else: 276 | norm = None 277 | return norm 278 | 279 | def state_dict(self): 280 | return self._scaler.state_dict() 281 | 282 | def load_state_dict(self, state_dict): 283 | self._scaler.load_state_dict(state_dict) 284 | 285 | 286 | def get_grad_norm_(parameters, norm_type: float = 2.0) -> torch.Tensor: 287 | if isinstance(parameters, torch.Tensor): 288 | parameters = [parameters] 289 | parameters = [p for p in parameters if p.grad is not None] 290 | norm_type = float(norm_type) 291 | if len(parameters) == 0: 292 | return torch.tensor(0.) 293 | device = parameters[0].grad.device 294 | if norm_type == inf: 295 | total_norm = max(p.grad.detach().abs().max().to(device) for p in parameters) 296 | else: 297 | total_norm = torch.norm(torch.stack([torch.norm(p.grad.detach(), norm_type).to(device) for p in parameters]), norm_type) 298 | return total_norm 299 | 300 | 301 | def save_model(args, epoch, epoch_name, model, model_without_ddp, optimizer, loss_scaler, best_val_loss=None, best_acc=None, step=None): 302 | output_dir = Path(args.output_dir) 303 | if loss_scaler is not None: 304 | checkpoint_paths = [output_dir / ('checkpoint-%s.pth' % epoch_name)] 305 | for checkpoint_path in checkpoint_paths: 306 | to_save = { 307 | 'model': model_without_ddp.state_dict(), 308 | 'optimizer': optimizer.state_dict(), 309 | 'epoch': epoch, 310 | 'scaler': loss_scaler.state_dict(), 311 | 'args': args, 312 | 'best_val_loss': best_val_loss, 313 | 'best_acc': best_acc, 314 | 'step': step, 315 | } 316 | 317 | save_on_master(to_save, checkpoint_path) 318 | else: 319 | client_state = {'epoch': epoch, 'best_val_loss': best_val_loss, 'best_acc': best_acc, 'step': step} 320 | model.save_checkpoint(save_dir=args.output_dir, tag="checkpoint-%s" % epoch_name, client_state=client_state) 321 | 322 | 323 | def load_model(args, model_without_ddp, optimizer, loss_scaler): 324 | if args.resume: 325 | start_epoch, best_val_loss = None, None 326 | if args.resume.startswith('https'): 327 | checkpoint = torch.hub.load_state_dict_from_url( 328 | args.resume, map_location='cpu', check_hash=True) 329 | else: 330 | checkpoint = torch.load(args.resume, map_location='cpu') 331 | model_without_ddp.load_state_dict(checkpoint['model']) 332 | print("Resume checkpoint %s" % args.resume) 333 | if 'optimizer' in checkpoint and 'epoch' in checkpoint and not (hasattr(args, 'eval') and args.eval): 334 | optimizer.load_state_dict(checkpoint['optimizer']) 335 | start_epoch = checkpoint['epoch'] + 1 336 | if 'scaler' in checkpoint: 337 | loss_scaler.load_state_dict(checkpoint['scaler']) 338 | print("With optim & sched!") 339 | best_val_loss = checkpoint['best_val_loss'] if 'best_val_loss' in checkpoint else None 340 | best_acc = checkpoint['best_acc'] if 'best_acc' in checkpoint else 0. 341 | if isinstance(best_acc, list): # TODO: be backward compatible; remove this line before release; 342 | best_acc = best_acc[0] 343 | step = checkpoint['step'] if 'step' in checkpoint else 0 344 | return start_epoch, best_val_loss, best_acc, step 345 | 346 | 347 | 348 | def all_reduce_mean(x): 349 | world_size = get_world_size() 350 | if world_size > 1: 351 | x_reduce = torch.tensor(x).cuda() 352 | dist.all_reduce(x_reduce) 353 | x_reduce /= world_size 354 | return x_reduce.item() 355 | else: 356 | return x 357 | 358 | 359 | def print_json(output_dir, json_str, mode="a"): 360 | print(json_str) 361 | if output_dir and is_main_process(): 362 | with open(os.path.join(output_dir, "log.txt"), mode=mode, encoding="utf-8") as f: 363 | f.write(json_str + "\n") -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. 2 | # All rights reserved. 3 | 4 | # This source code is licensed under the license found in the 5 | # LICENSE file in the root directory of this source tree. 6 | # -------------------------------------------------------- 7 | # References: 8 | # DeiT: https://github.com/facebookresearch/deit 9 | # BEiT: https://github.com/microsoft/unilm/tree/master/beit 10 | # -------------------------------------------------------- 11 | # Copyright (c) Meta Platforms, Inc. All Rights Reserved 12 | 13 | import argparse 14 | import datetime 15 | import numpy as np 16 | import os 17 | import time 18 | import json 19 | from pathlib import Path 20 | 21 | import torch 22 | import torch.backends.cudnn as cudnn 23 | from collections import defaultdict 24 | 25 | import losses 26 | 27 | import util.misc as misc 28 | 29 | from util.misc import NativeScalerWithGradNormCount as NativeScaler 30 | 31 | from models_citclip import build_model 32 | from engine import train_one_epoch, evaluate, iterative_classcurate 33 | from weights import freeze_model 34 | 35 | 36 | def get_mean_std(args): 37 | if "augreg" in args.vision_backbone or "augreg" in args.vision_pretrained: 38 | mean = [0.5, 0.5, 0.5] 39 | std = [0.5, 0.5, 0.5] 40 | else: 41 | mean = [0.485, 0.456, 0.406] 42 | std = [0.229, 0.224, 0.225] 43 | return mean, std 44 | 45 | 46 | def get_val_transform(args): 47 | """moved from SLIP's eval_zeroshot.py""" 48 | import torchvision.transforms as transforms 49 | mean, std = get_mean_std(args) 50 | print(args.vision_backbone, "val_normalizer", mean, std) 51 | return transforms.Compose([ 52 | transforms.Resize(256), 53 | transforms.CenterCrop(224), 54 | lambda x: x.convert('RGB'), 55 | transforms.ToTensor(), 56 | transforms.Normalize(mean=mean, std=std) 57 | ]) 58 | 59 | 60 | def get_train_transform(args): 61 | import torchvision.transforms as transforms 62 | trans = [transforms.RandomResizedCrop(224, scale=(0.5, 1.0))] 63 | if hasattr(args, "inmem") and args.inmem: # use in-mem training / no dataloader for consumer dataset. 64 | from torchvision.transforms.functional import pil_to_tensor 65 | trans.append(pil_to_tensor) 66 | else: 67 | trans.append(transforms.ToTensor()) 68 | mean, std = get_mean_std(args) 69 | print(args.vision_backbone, "train_normalizer", mean, std) 70 | trans.append(transforms.Normalize(mean=mean, std=std)) 71 | return transforms.Compose(trans) 72 | 73 | 74 | def build_dataset(args, tokenizer): 75 | from clipeval import datasets 76 | train_transform = get_train_transform(args) 77 | train_task_example_ids = None 78 | if hasattr(args, "pcurate") or (args.val_task is not None and args.curate == 0): # no validation for full yfcc15m training (same as SLIP/CLIP). 79 | thres = args.pcurate if hasattr(args, "pcurate") else args.thres 80 | if args.dataset in ["yfcc15m_tag"]: 81 | task_meta = torch.load(f"data/CLIP/{args.dataset}/{args.val_task}_ub_{args.dataset}_simcse{thres}_{args.max_bert_length}.pt") 82 | if hasattr(args, "sublist") and args.sublist: 83 | train_task_example_ids = task_meta["example_ids"] 84 | else: 85 | train_task_example_ids = set(task_meta["example_ids"]) 86 | print("train_task_example_ids_key", len(train_task_example_ids)) 87 | else: 88 | task_meta = torch.load(f"data/CLIP/CLIP_eval/{args.val_task}_ub_{args.dataset}_simcse{thres}.pt") 89 | if hasattr(args, "sublist") and args.sublist: 90 | train_task_example_ids = task_meta["example_ids"] 91 | else: 92 | train_task_example_ids = set(task_meta["example_ids"]) 93 | print("train_task_example_ids", len(train_task_example_ids)) 94 | tar_files = None 95 | train_dataset = datasets.ImageCaptionDatasetCLIP( 96 | args, args.dataset, args.root, args.metadata, train_task_example_ids, 97 | train_transform, tokenizer, args.max_bert_length, max_sample=args.max_sample 98 | ) 99 | return train_dataset, None, train_transform, tar_files 100 | 101 | 102 | def producer_collator(batch_list): 103 | result = defaultdict(list) 104 | for item in batch_list: 105 | for key in item: 106 | if key not in ["__key__"]: 107 | result[key].append(item[key]) 108 | for key in result: 109 | if key not in ["image_ids", "__key__", "captions"]: 110 | result[key] = torch.stack(result[key]) 111 | return result 112 | 113 | 114 | def main(args): 115 | misc.init_distributed_mode(args) 116 | 117 | print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__)))) 118 | print("{}".format(args).replace(', ', ',\n')) 119 | 120 | device = torch.device(args.device) 121 | 122 | # fix the seed for reproducibility 123 | seed = args.seed + misc.get_rank() 124 | torch.manual_seed(seed) 125 | np.random.seed(seed) 126 | 127 | cudnn.benchmark = True 128 | 129 | model, tokenizer = build_model(args) 130 | model = freeze_model(model, args) 131 | model.to(device) 132 | dataset_train, dataset_val, train_transform, tar_files = build_dataset(args, tokenizer) 133 | val_transform = get_val_transform(args) 134 | 135 | num_tasks = misc.get_world_size() 136 | global_rank = misc.get_rank() 137 | sampler_train = torch.utils.data.DistributedSampler( 138 | dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True 139 | ) if not isinstance(dataset_train, torch.utils.data.IterableDataset) else None 140 | if args.dist_eval: 141 | if len(dataset_val) % num_tasks != 0: 142 | print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. ' 143 | 'This will slightly alter validation results as extra duplicate entries are added to achieve ' 144 | 'equal num of samples per-process.') 145 | sampler_val = torch.utils.data.DistributedSampler( 146 | dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=True) # shuffle=True to reduce monitor bias 147 | else: 148 | sampler_val = None if dataset_val is None else torch.utils.data.SequentialSampler(dataset_val) 149 | 150 | if global_rank == 0 and args.log_dir is not None and not args.eval: 151 | from torch.utils.tensorboard import SummaryWriter 152 | os.makedirs(args.log_dir, exist_ok=True) 153 | log_writer = SummaryWriter(log_dir=args.log_dir) 154 | else: 155 | log_writer = None 156 | 157 | model_without_ddp = model 158 | n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) 159 | print("Model = %s" % str(model_without_ddp)) 160 | print('number of params (M): %.2f' % (n_parameters / 1.e6)) 161 | 162 | eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size() 163 | 164 | if args.lr is None: # only base_lr is specified 165 | args.lr = args.blr * eff_batch_size / 256 166 | 167 | print("base lr: %.2e" % (args.lr * 256 / eff_batch_size)) 168 | print("actual lr: %.2e" % args.lr) 169 | 170 | print("accumulate grad iterations: %d" % args.accum_iter) 171 | print("effective batch size: %d" % eff_batch_size) 172 | if not isinstance(dataset_train, torch.utils.data.IterableDataset): 173 | print("len(dataset)", len(dataset_train)) 174 | else: 175 | print("cannot estimate len of torch.utils.data.IterableDataset.") 176 | 177 | if args.distributed: 178 | find_unused = False 179 | model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=find_unused) 180 | model_without_ddp = model.module 181 | 182 | # https://github.com/rwightman/pytorch-image-models/blob/fd360ac951a179474917f4b2d21db8669bf87f68/timm/models/vision_transformer.py#L407 183 | no_weight_decay_list = {'pos_embed', 'cls_token', 'dist_token'} # THIS DOESN'T MATTER YET as we frozen all. 184 | head_weight_decay_list = {"visual_projection", "text_projection"} 185 | 186 | p_wd, p_no_wd = [], [] 187 | p_head_wd = [] 188 | # only apply 1-dim no decay for now. 189 | for n, p in model.named_parameters(): 190 | if not p.requires_grad: 191 | continue # frozen weights 192 | if p.ndim == 1 or n in no_weight_decay_list: 193 | p_no_wd.append(p) 194 | elif hasattr(args, "no_wd_emb") and isinstance(p, torch.nn.Embedding): 195 | p_no_wd.append(p) 196 | elif hasattr(args, "no_wd_ln") and isinstance(p, torch.nn.LayerNorm): 197 | p_no_wd.append(p) 198 | elif hasattr(args, "head_weight_decay") and [True for _part in head_weight_decay_list if _part in n]: 199 | p_head_wd.append(p) 200 | else: 201 | p_wd.append(p) 202 | 203 | param_groups = [{"params": p_wd, "weight_decay": args.weight_decay}, 204 | {"params": p_no_wd, "weight_decay": 0.}] 205 | 206 | if p_head_wd: 207 | param_groups.append({"params": p_head_wd, "weight_decay": args.head_weight_decay}) 208 | 209 | optimizer = torch.optim.AdamW(param_groups, lr=args.lr, eps=1e-8) 210 | loss_scaler = NativeScaler(args.fp16) 211 | 212 | start_epoch, best_acc, step = 0, [0.], [0] 213 | if args.resume: 214 | if args.resume.endswith(".pth"): # a pytorch checkpoint for resuming training. 215 | if args.resume.startswith("checkpoint"): 216 | args.resume = os.path.join(args.output_dir, args.resume) 217 | start_epoch, _, best_acc, step = misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler) 218 | best_acc, step = [best_acc], [step if step is not None else 0] 219 | 220 | if isinstance(dataset_train, torch.utils.data.IterableDataset): 221 | # random from step to avoid dupped train. 222 | dataset_train.start_shard_id = step[0] % dataset_train.num_shards 223 | print("resuming", args.resume, "from step", step[0], "with best_acc", best_acc[0]) 224 | else: 225 | print("assuming a huggingface transformer pretrained model (no optimizer states).") 226 | from models_citclip import CiTCLIPVisionTextDualEncoderModel 227 | metric = evaluate(args, model, val_transform, tokenizer) 228 | model = CiTCLIPVisionTextDualEncoderModel.from_pretrained(args.resume) 229 | if args.eval: 230 | metric = evaluate(args, model, val_transform, tokenizer) 231 | json_str = json.dumps({"step": step[0], "acc": metric, "seen": eff_batch_size * step[0]}) 232 | print(json_str) 233 | exit(0) 234 | 235 | criterion = getattr(losses, args.loss)().to(device) 236 | 237 | print("criterion = %s" % str(criterion)) 238 | 239 | if args.curate is not None and args.curate > 1: 240 | curate_batch_size = args.batch_size * 2 241 | 242 | dataset_train.with_vision = True if hasattr(args, "inmem") and args.inmem else False 243 | data_loader_producer = torch.utils.data.DataLoader( 244 | dataset_train, sampler=sampler_train, 245 | batch_size=curate_batch_size, 246 | num_workers=args.num_workers, 247 | pin_memory=args.pin_mem, 248 | drop_last=True, 249 | collate_fn=producer_collator, 250 | persistent_workers=True 251 | ) 252 | 253 | def producer_fn(epoch): 254 | while True: 255 | data_loader_producer.sampler.set_epoch(epoch) 256 | for batch in data_loader_producer: 257 | yield batch 258 | epoch += 1 259 | 260 | producer_iter = iter(producer_fn(start_epoch)) 261 | 262 | else: 263 | data_loader_train = torch.utils.data.DataLoader( 264 | dataset_train, sampler=sampler_train, 265 | batch_size=args.batch_size, 266 | num_workers=args.num_workers, 267 | pin_memory=args.pin_mem, 268 | drop_last=True, 269 | ) 270 | 271 | data_loader_val = None if dataset_val is None else torch.utils.data.DataLoader( 272 | dataset_val, sampler=sampler_val, 273 | batch_size=args.batch_size, 274 | num_workers=args.num_workers, 275 | pin_memory=args.pin_mem, 276 | drop_last=False 277 | ) 278 | 279 | import math 280 | 281 | if not isinstance(dataset_train, torch.utils.data.IterableDataset) and not args.curate: 282 | epochs = math.ceil(args.max_update / (len(dataset_train) // eff_batch_size)) 283 | print(f"Start training for {args.max_update} steps / {epochs} epochs") 284 | else: 285 | epochs = 1000000 # a big number to allow infinity run on iterativedataset. 286 | print(f"Start training for {args.max_update} steps on torch.utils.data.IterableDataset or curate dataset, the checkpoint is stateless.") 287 | start_time = time.time() 288 | for epoch in range(start_epoch, epochs): 289 | if step[0] >= args.max_update: 290 | break 291 | 292 | if args.curate is not None and (args.curate > 0 and step[0] % args.curate == 0): 293 | curate_cls = iterative_classcurate 294 | all_example_ids = curate_cls(step, device, producer_iter, model, tokenizer, args) 295 | print(len(all_example_ids), "after curate", args.curate * args.batch_size, "expected") 296 | if hasattr(args, "inmem") and args.inmem: 297 | data_loader_train = all_example_ids 298 | else: 299 | if hasattr(args, "sublist") and args.sublist: 300 | assert isinstance(all_example_ids, list) 301 | all_example_ids = all_example_ids[:args.curate * args.batch_size] 302 | else: 303 | all_example_ids = set(list(all_example_ids)[:args.curate * args.batch_size]) 304 | assert len(all_example_ids) == args.curate * args.batch_size 305 | from clipeval import datasets 306 | dataset_train = datasets.ImageCaptionDatasetCLIP(args, 307 | args.dataset, args.root, args.metadata, all_example_ids, 308 | train_transform, tokenizer, args.max_bert_length, max_sample=args.max_sample 309 | ) 310 | data_loader_train = torch.utils.data.DataLoader( 311 | dataset_train, shuffle=True, # just a local sampler. 312 | batch_size=args.batch_size, 313 | num_workers=args.num_workers, 314 | pin_memory=args.pin_mem, 315 | drop_last=True, 316 | ) 317 | 318 | if hasattr(data_loader_train, "sampler") and isinstance(data_loader_train.sampler, torch.utils.data.DistributedSampler): 319 | data_loader_train.sampler.set_epoch(epoch) 320 | 321 | train_stats = train_one_epoch( 322 | model, model_without_ddp, criterion, tokenizer, data_loader_train, data_loader_val, val_transform, best_acc, 323 | optimizer, device, epoch, step, loss_scaler, eff_batch_size, 324 | args.clip_grad, 325 | log_writer=log_writer, 326 | args=args 327 | ) 328 | 329 | if not isinstance(dataset_train, torch.utils.data.IterableDataset): 330 | misc.save_model( 331 | args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer, 332 | loss_scaler=loss_scaler, epoch=epoch, epoch_name="last", best_acc=best_acc[0], step=step[0]) 333 | else: 334 | misc.save_model( 335 | args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer, 336 | loss_scaler=loss_scaler, epoch=0, epoch_name="last", best_acc=best_acc[0], step=step[0]) 337 | 338 | # if log_writer is not None: 339 | # log_writer.finish() 340 | args.resume = os.path.join(args.output_dir, "checkpoint-best.pth") 341 | if os.path.isfile(args.resume): 342 | misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler) 343 | 344 | metric = evaluate(args, model, val_transform, tokenizer) 345 | json_str = json.dumps({"step": step[0], "acc": metric, "seen": eff_batch_size * step[0]}) 346 | print(json_str) 347 | 348 | total_time = time.time() - start_time 349 | total_time_str = str(datetime.timedelta(seconds=int(total_time))) 350 | print('Training time {}'.format(total_time_str)) 351 | 352 | 353 | def parse_args(): 354 | '''see configs.py or sweep.py (we only allow pre-defined config).''' 355 | parser = argparse.ArgumentParser(description='CiTCLIP', add_help=False) 356 | parser.add_argument('config_name', type=str, help='see configs.py') 357 | parser.add_argument('--world_size', default=1, type=int) 358 | parser.add_argument('--local_rank', default=-1, type=int) 359 | parser.add_argument('--dist_on_itp', action='store_true') 360 | parser.add_argument('--dist_url', default='env://') 361 | parser.add_argument('--resume', default=None, type=str) 362 | parser.add_argument('--eval', default=None, action='store_true') 363 | 364 | cmd_args = parser.parse_args() 365 | 366 | import run_configs 367 | config = getattr(run_configs, cmd_args.config_name)().add_cmd_args(cmd_args) 368 | return config 369 | 370 | 371 | if __name__ == '__main__': 372 | args = parse_args() 373 | if args.output_dir: 374 | Path(args.output_dir).mkdir(parents=True, exist_ok=True) 375 | main(args) 376 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | Section 1 -- Definitions. 71 | 72 | a. Adapted Material means material subject to Copyright and Similar 73 | Rights that is derived from or based upon the Licensed Material 74 | and in which the Licensed Material is translated, altered, 75 | arranged, transformed, or otherwise modified in a manner requiring 76 | permission under the Copyright and Similar Rights held by the 77 | Licensor. For purposes of this Public License, where the Licensed 78 | Material is a musical work, performance, or sound recording, 79 | Adapted Material is always produced where the Licensed Material is 80 | synched in timed relation with a moving image. 81 | 82 | b. Adapter's License means the license You apply to Your Copyright 83 | and Similar Rights in Your contributions to Adapted Material in 84 | accordance with the terms and conditions of this Public License. 85 | 86 | c. Copyright and Similar Rights means copyright and/or similar rights 87 | closely related to copyright including, without limitation, 88 | performance, broadcast, sound recording, and Sui Generis Database 89 | Rights, without regard to how the rights are labeled or 90 | categorized. For purposes of this Public License, the rights 91 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 92 | Rights. 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. NonCommercial means not primarily intended for or directed towards 116 | commercial advantage or monetary compensation. For purposes of 117 | this Public License, the exchange of the Licensed Material for 118 | other material subject to Copyright and Similar Rights by digital 119 | file-sharing or similar means is NonCommercial provided there is 120 | no payment of monetary compensation in connection with the 121 | exchange. 122 | 123 | j. Share means to provide material to the public by any means or 124 | process that requires permission under the Licensed Rights, such 125 | as reproduction, public display, public performance, distribution, 126 | dissemination, communication, or importation, and to make material 127 | available to the public including in ways that members of the 128 | public may access the material from a place and at a time 129 | individually chosen by them. 130 | 131 | k. Sui Generis Database Rights means rights other than copyright 132 | resulting from Directive 96/9/EC of the European Parliament and of 133 | the Council of 11 March 1996 on the legal protection of databases, 134 | as amended and/or succeeded, as well as other essentially 135 | equivalent rights anywhere in the world. 136 | 137 | l. You means the individual or entity exercising the Licensed Rights 138 | under this Public License. Your has a corresponding meaning. 139 | 140 | Section 2 -- Scope. 141 | 142 | a. License grant. 143 | 144 | 1. Subject to the terms and conditions of this Public License, 145 | the Licensor hereby grants You a worldwide, royalty-free, 146 | non-sublicensable, non-exclusive, irrevocable license to 147 | exercise the Licensed Rights in the Licensed Material to: 148 | 149 | a. reproduce and Share the Licensed Material, in whole or 150 | in part, for NonCommercial purposes only; and 151 | 152 | b. produce, reproduce, and Share Adapted Material for 153 | NonCommercial purposes only. 154 | 155 | 2. Exceptions and Limitations. For the avoidance of doubt, where 156 | Exceptions and Limitations apply to Your use, this Public 157 | License does not apply, and You do not need to comply with 158 | its terms and conditions. 159 | 160 | 3. Term. The term of this Public License is specified in Section 161 | 6(a). 162 | 163 | 4. Media and formats; technical modifications allowed. The 164 | Licensor authorizes You to exercise the Licensed Rights in 165 | all media and formats whether now known or hereafter created, 166 | and to make technical modifications necessary to do so. The 167 | Licensor waives and/or agrees not to assert any right or 168 | authority to forbid You from making technical modifications 169 | necessary to exercise the Licensed Rights, including 170 | technical modifications necessary to circumvent Effective 171 | Technological Measures. For purposes of this Public License, 172 | simply making modifications authorized by this Section 2(a) 173 | (4) never produces Adapted Material. 174 | 175 | 5. Downstream recipients. 176 | 177 | a. Offer from the Licensor -- Licensed Material. Every 178 | recipient of the Licensed Material automatically 179 | receives an offer from the Licensor to exercise the 180 | Licensed Rights under the terms and conditions of this 181 | Public License. 182 | 183 | b. No downstream restrictions. You may not offer or impose 184 | any additional or different terms or conditions on, or 185 | apply any Effective Technological Measures to, the 186 | Licensed Material if doing so restricts exercise of the 187 | Licensed Rights by any recipient of the Licensed 188 | Material. 189 | 190 | 6. No endorsement. Nothing in this Public License constitutes or 191 | may be construed as permission to assert or imply that You 192 | are, or that Your use of the Licensed Material is, connected 193 | with, or sponsored, endorsed, or granted official status by, 194 | the Licensor or others designated to receive attribution as 195 | provided in Section 3(a)(1)(A)(i). 196 | 197 | b. Other rights. 198 | 199 | 1. Moral rights, such as the right of integrity, are not 200 | licensed under this Public License, nor are publicity, 201 | privacy, and/or other similar personality rights; however, to 202 | the extent possible, the Licensor waives and/or agrees not to 203 | assert any such rights held by the Licensor to the limited 204 | extent necessary to allow You to exercise the Licensed 205 | Rights, but not otherwise. 206 | 207 | 2. Patent and trademark rights are not licensed under this 208 | Public License. 209 | 210 | 3. To the extent possible, the Licensor waives any right to 211 | collect royalties from You for the exercise of the Licensed 212 | Rights, whether directly or through a collecting society 213 | under any voluntary or waivable statutory or compulsory 214 | licensing scheme. In all other cases the Licensor expressly 215 | reserves any right to collect such royalties, including when 216 | the Licensed Material is used other than for NonCommercial 217 | purposes. 218 | 219 | Section 3 -- License Conditions. 220 | 221 | Your exercise of the Licensed Rights is expressly made subject to the 222 | following conditions. 223 | 224 | a. Attribution. 225 | 226 | 1. If You Share the Licensed Material (including in modified 227 | form), You must: 228 | 229 | a. retain the following if it is supplied by the Licensor 230 | with the Licensed Material: 231 | 232 | i. identification of the creator(s) of the Licensed 233 | Material and any others designated to receive 234 | attribution, in any reasonable manner requested by 235 | the Licensor (including by pseudonym if 236 | designated); 237 | 238 | ii. a copyright notice; 239 | 240 | iii. a notice that refers to this Public License; 241 | 242 | iv. a notice that refers to the disclaimer of 243 | warranties; 244 | 245 | v. a URI or hyperlink to the Licensed Material to the 246 | extent reasonably practicable; 247 | 248 | b. indicate if You modified the Licensed Material and 249 | retain an indication of any previous modifications; and 250 | 251 | c. indicate the Licensed Material is licensed under this 252 | Public License, and include the text of, or the URI or 253 | hyperlink to, this Public License. 254 | 255 | 2. You may satisfy the conditions in Section 3(a)(1) in any 256 | reasonable manner based on the medium, means, and context in 257 | which You Share the Licensed Material. For example, it may be 258 | reasonable to satisfy the conditions by providing a URI or 259 | hyperlink to a resource that includes the required 260 | information. 261 | 262 | 3. If requested by the Licensor, You must remove any of the 263 | information required by Section 3(a)(1)(A) to the extent 264 | reasonably practicable. 265 | 266 | 4. If You Share Adapted Material You produce, the Adapter's 267 | License You apply must not prevent recipients of the Adapted 268 | Material from complying with this Public License. 269 | 270 | Section 4 -- Sui Generis Database Rights. 271 | 272 | Where the Licensed Rights include Sui Generis Database Rights that 273 | apply to Your use of the Licensed Material: 274 | 275 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 276 | to extract, reuse, reproduce, and Share all or a substantial 277 | portion of the contents of the database for NonCommercial purposes 278 | only; 279 | 280 | b. if You include all or a substantial portion of the database 281 | contents in a database in which You have Sui Generis Database 282 | Rights, then the database in which You have Sui Generis Database 283 | Rights (but not its individual contents) is Adapted Material; and 284 | 285 | c. You must comply with the conditions in Section 3(a) if You Share 286 | all or a substantial portion of the contents of the database. 287 | 288 | For the avoidance of doubt, this Section 4 supplements and does not 289 | replace Your obligations under this Public License where the Licensed 290 | Rights include other Copyright and Similar Rights. 291 | 292 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 293 | 294 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 295 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 296 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 297 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 298 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 299 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 300 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 301 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 302 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 303 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 304 | 305 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 306 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 307 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 308 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 309 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 310 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 311 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 312 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 313 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 314 | 315 | c. The disclaimer of warranties and limitation of liability provided 316 | above shall be interpreted in a manner that, to the extent 317 | possible, most closely approximates an absolute disclaimer and 318 | waiver of all liability. 319 | 320 | Section 6 -- Term and Termination. 321 | 322 | a. This Public License applies for the term of the Copyright and 323 | Similar Rights licensed here. However, if You fail to comply with 324 | this Public License, then Your rights under this Public License 325 | terminate automatically. 326 | 327 | b. Where Your right to use the Licensed Material has terminated under 328 | Section 6(a), it reinstates: 329 | 330 | 1. automatically as of the date the violation is cured, provided 331 | it is cured within 30 days of Your discovery of the 332 | violation; or 333 | 334 | 2. upon express reinstatement by the Licensor. 335 | 336 | For the avoidance of doubt, this Section 6(b) does not affect any 337 | right the Licensor may have to seek remedies for Your violations 338 | of this Public License. 339 | 340 | c. For the avoidance of doubt, the Licensor may also offer the 341 | Licensed Material under separate terms or conditions or stop 342 | distributing the Licensed Material at any time; however, doing so 343 | will not terminate this Public License. 344 | 345 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 346 | License. 347 | 348 | Section 7 -- Other Terms and Conditions. 349 | 350 | a. The Licensor shall not be bound by any additional or different 351 | terms or conditions communicated by You unless expressly agreed. 352 | 353 | b. Any arrangements, understandings, or agreements regarding the 354 | Licensed Material not stated herein are separate from and 355 | independent of the terms and conditions of this Public License. 356 | 357 | Section 8 -- Interpretation. 358 | 359 | a. For the avoidance of doubt, this Public License does not, and 360 | shall not be interpreted to, reduce, limit, restrict, or impose 361 | conditions on any use of the Licensed Material that could lawfully 362 | be made without permission under this Public License. 363 | 364 | b. To the extent possible, if any provision of this Public License is 365 | deemed unenforceable, it shall be automatically reformed to the 366 | minimum extent necessary to make it enforceable. If the provision 367 | cannot be reformed, it shall be severed from this Public License 368 | without affecting the enforceability of the remaining terms and 369 | conditions. 370 | 371 | c. No term or condition of this Public License will be waived and no 372 | failure to comply consented to unless expressly agreed to by the 373 | Licensor. 374 | 375 | d. Nothing in this Public License constitutes or may be interpreted 376 | as a limitation upon, or waiver of, any privileges and immunities 377 | that apply to the Licensor or You, including from the legal 378 | processes of any jurisdiction or authority. 379 | 380 | ======================================================================= 381 | 382 | Creative Commons is not a party to its public 383 | licenses. Notwithstanding, Creative Commons may elect to apply one of 384 | its public licenses to material it publishes and in those instances 385 | will be considered the “Licensor.” The text of the Creative Commons 386 | public licenses is dedicated to the public domain under the CC0 Public 387 | Domain Dedication. Except for the limited purpose of indicating that 388 | material is shared under a Creative Commons public license or as 389 | otherwise permitted by the Creative Commons policies published at 390 | creativecommons.org/policies, Creative Commons does not authorize the 391 | use of the trademark "Creative Commons" or any other trademark or logo 392 | of Creative Commons without its prior written consent including, 393 | without limitation, in connection with any unauthorized modifications 394 | to any of its public licenses or any other arrangements, 395 | understandings, or agreements concerning use of licensed material. For 396 | the avoidance of doubt, this paragraph does not form part of the 397 | public licenses. 398 | 399 | Creative Commons may be contacted at creativecommons.org. --------------------------------------------------------------------------------