├── figures ├── diagram.png ├── test_cgqa.png ├── architecture.png ├── test_mit-states.png └── test_ut-zap50k.png ├── word embedding ├── cgqa_word2vec_obj.save ├── cgqa_word2vec_attr.save ├── mit-states_ft+w2v_attr.save ├── mit-states_ft+w2v_obj.save ├── ut-zap50k_fasttext_obj.save └── ut-zap50k_fasttext_attr.save ├── configs ├── cgqa │ └── CANet.yml ├── mit-states │ └── CANet.yml └── ut-zap50k │ └── CANet.yml ├── utils ├── reorganize_utzap.py └── utils.py ├── config_model.py ├── model ├── image_extractor.py ├── word_embedding.py ├── CANet.py └── common.py ├── flags.py ├── test.py ├── README.md ├── train.py ├── data └── dataset.py └── LICENSE /figures/diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wqshmzh/CANet-CZSL/HEAD/figures/diagram.png -------------------------------------------------------------------------------- /figures/test_cgqa.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wqshmzh/CANet-CZSL/HEAD/figures/test_cgqa.png -------------------------------------------------------------------------------- /figures/architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wqshmzh/CANet-CZSL/HEAD/figures/architecture.png -------------------------------------------------------------------------------- /figures/test_mit-states.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wqshmzh/CANet-CZSL/HEAD/figures/test_mit-states.png -------------------------------------------------------------------------------- /figures/test_ut-zap50k.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wqshmzh/CANet-CZSL/HEAD/figures/test_ut-zap50k.png -------------------------------------------------------------------------------- /word embedding/cgqa_word2vec_obj.save: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wqshmzh/CANet-CZSL/HEAD/word embedding/cgqa_word2vec_obj.save -------------------------------------------------------------------------------- /word embedding/cgqa_word2vec_attr.save: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wqshmzh/CANet-CZSL/HEAD/word embedding/cgqa_word2vec_attr.save -------------------------------------------------------------------------------- /word embedding/mit-states_ft+w2v_attr.save: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wqshmzh/CANet-CZSL/HEAD/word embedding/mit-states_ft+w2v_attr.save -------------------------------------------------------------------------------- /word embedding/mit-states_ft+w2v_obj.save: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wqshmzh/CANet-CZSL/HEAD/word embedding/mit-states_ft+w2v_obj.save -------------------------------------------------------------------------------- /word embedding/ut-zap50k_fasttext_obj.save: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wqshmzh/CANet-CZSL/HEAD/word embedding/ut-zap50k_fasttext_obj.save -------------------------------------------------------------------------------- /word embedding/ut-zap50k_fasttext_attr.save: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wqshmzh/CANet-CZSL/HEAD/word embedding/ut-zap50k_fasttext_attr.save -------------------------------------------------------------------------------- /configs/cgqa/CANet.yml: -------------------------------------------------------------------------------- 1 | --- 2 | dataset: 3 | dataset: cgqa 4 | splitname: compositional-split-natural 5 | train_only: true 6 | model_params: 7 | emb_type: word2vec 8 | nhiddenlayers: 0 9 | nlayer: 2 10 | alpha: 0.4 11 | 12 | training: 13 | batch_size: 256 14 | lr: 5.0e-05 15 | lrg: 5.0e-06 # Learning rete for image backbone if fine-tune the backbone 16 | cosine_scale: 0.05 17 | max_epochs: 1000 18 | test_batch_size: 2048 19 | update_image_features: false # Fine tune the image backbone? 20 | update_word_features: true 21 | -------------------------------------------------------------------------------- /configs/mit-states/CANet.yml: -------------------------------------------------------------------------------- 1 | --- 2 | dataset: 3 | dataset: mit-states 4 | splitname: compositional-split-natural 5 | train_only: true 6 | model_params: 7 | emb_type: ft+w2v 8 | nhiddenlayers: 0 9 | nlayer: 2 10 | alpha: 0.2 11 | 12 | training: 13 | batch_size: 256 14 | lr: 5.0e-05 15 | lrg: 5.0e-06 # Learning rete for image backbone if fine-tune the backbone 16 | cosine_scale: 0.05 17 | max_epochs: 800 18 | test_batch_size: 2048 19 | update_image_features: false # Fine tune the image backbone? 20 | update_word_features: true 21 | -------------------------------------------------------------------------------- /configs/ut-zap50k/CANet.yml: -------------------------------------------------------------------------------- 1 | --- 2 | dataset: 3 | dataset: ut-zap50k 4 | splitname: compositional-split-natural 5 | train_only: true 6 | model_params: 7 | emb_type: fasttext 8 | nhiddenlayers: 0 9 | nlayer: 2 10 | alpha: 0.4 11 | 12 | training: 13 | batch_size: 256 14 | lr: 5.0e-05 15 | lrg: 5.0e-06 # Learning rete for image backbone if fine-tune the backbone 16 | cosine_scale: 0.02 17 | max_epochs: 500 18 | test_batch_size: 2048 19 | update_image_features: false # Fine tune the image backbone? 20 | update_word_features: true 21 | -------------------------------------------------------------------------------- /utils/reorganize_utzap.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Facebook, Inc. and its 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 | """ 8 | Reorganize the UT-Zappos dataset to resemble the MIT-States dataset 9 | root/attr_obj/img1.jpg 10 | root/attr_obj/img2.jpg 11 | root/attr_obj/img3.jpg 12 | ... 13 | """ 14 | 15 | import os 16 | import torch 17 | import shutil 18 | import tqdm 19 | 20 | DATA_FOLDER= 'I:/Datasets' 21 | 22 | root = DATA_FOLDER+'/ut-zap50k' 23 | os.makedirs(root+'/images',exist_ok=True) 24 | 25 | data = torch.load(root+'/metadata_compositional-split-natural.t7') 26 | for instance in tqdm.tqdm(data): 27 | image, attr, obj = instance['_image'], instance['attr'], instance['obj'] 28 | old_file = '%s/%s'%(root, image) 29 | new_dir = '%s/images/%s_%s/'%(root, attr, obj) 30 | os.makedirs(new_dir, exist_ok=True) 31 | shutil.move(old_file, new_dir) -------------------------------------------------------------------------------- /config_model.py: -------------------------------------------------------------------------------- 1 | import torch.optim as optim 2 | from model.image_extractor import get_image_extractor 3 | from model.CANet import CANet 4 | 5 | def configure_model(args, dataset, train=True): 6 | image_extractor = None 7 | if args.update_image_features: 8 | if args.rank == 0: print('> Initialize feature extractor <{}>'.format(args.image_extractor)) 9 | image_extractor = get_image_extractor(args, arch=args.image_extractor, pretrained=True) 10 | if not args.extract_feature_vectors: 11 | import torch.nn as nn 12 | image_extractor = nn.Sequential(*list(image_extractor.children())[:-1]) 13 | image_extractor = image_extractor.to(args.device) 14 | 15 | print('> Initialize model ') 16 | model = CANet(dataset, args).to(args.device) 17 | 18 | # configuring optimizer 19 | if train: 20 | print('> Initialize optimizer ') 21 | model_params = [param for _, param in model.named_parameters() if param.requires_grad] 22 | optim_params = [{'params':model_params}] 23 | if args.update_image_features: 24 | ie_parameters = [param for _, param in image_extractor.named_parameters()] 25 | optim_params.append({'params': ie_parameters, 'lr': args.lrg}) 26 | optimizer = optim.Adam(optim_params, lr=args.lr, weight_decay=args.wd) 27 | return image_extractor, model, optimizer 28 | else: 29 | return image_extractor, model -------------------------------------------------------------------------------- /model/image_extractor.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Image feature extractor 3 | ''' 4 | import torch 5 | import torch.nn as nn 6 | from torchvision import models 7 | from torchvision.models.resnet import ResNet, BasicBlock 8 | 9 | class ResNet18_conv(ResNet): 10 | def __init__(self): 11 | super(ResNet18_conv, self).__init__(BasicBlock, [2, 2, 2, 2]) 12 | 13 | def forward(self, x): 14 | # change forward here 15 | x = self.conv1(x) 16 | x = self.bn1(x) 17 | x = self.relu(x) 18 | x = self.maxpool(x) 19 | 20 | x = self.layer1(x) 21 | x = self.layer2(x) 22 | x = self.layer3(x) 23 | x = self.layer4(x) 24 | 25 | return x 26 | 27 | def get_image_extractor(arch='resnet18', pretrained=True, feature_dim=None): 28 | ''' 29 | Inputs 30 | arch: Base architecture 31 | pretrained: Bool, Imagenet weights 32 | feature_dim: Int, output feature dimension 33 | checkpoint: String, not implemented 34 | Returns 35 | Pytorch model 36 | ''' 37 | 38 | if arch == 'resnet18': 39 | model = models.resnet18(pretrained=pretrained) 40 | if feature_dim is None: 41 | model.fc = nn.Sequential() 42 | else: 43 | model.fc = nn.Linear(512, feature_dim) 44 | 45 | elif arch == 'resnet50': 46 | model = models.resnet50(pretrained = pretrained) 47 | if feature_dim is None: 48 | model.fc = nn.Sequential() 49 | else: 50 | model.fc = nn.Linear(2048, feature_dim) 51 | 52 | elif arch == 'resnet152': 53 | model = models.resnet152(pretrained = pretrained) 54 | if feature_dim is None: 55 | model.fc = nn.Sequential() 56 | else: 57 | model.fc = nn.Linear(2048, feature_dim) 58 | 59 | elif arch == 'vgg16': 60 | model = models.vgg16(pretrained = pretrained) 61 | modules = list(model.classifier.children())[:-3] 62 | model.classifier=torch.nn.Sequential(*modules) 63 | if feature_dim is not None: 64 | model.classifier[3]=torch.nn.Linear(4096,feature_dim) 65 | 66 | return model -------------------------------------------------------------------------------- /utils/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | from os.path import join as ospj 3 | import torch 4 | import random 5 | import shutil 6 | import sys 7 | import yaml 8 | import numpy as np 9 | from typing import TypeVar 10 | 11 | def seed_torch(seed=0): 12 | random.seed(seed) 13 | os.environ['PYTHONHASHSEED'] = str(seed) 14 | np.random.seed(seed) 15 | torch.manual_seed(seed) 16 | torch.cuda.manual_seed(seed) 17 | torch.cuda.manual_seed_all(seed) 18 | torch.backends.cudnn.deterministic = True 19 | torch.backends.cudnn.benchmark = False 20 | torch.backends.cudnn.enabled = False 21 | torch.backends.cuda.matmul.allow_tf32 = False 22 | 23 | def chunks(l, n): 24 | """Yield successive n-sized chunks from l.""" 25 | for i in range(0, len(l), n): 26 | yield l[i:i + n] 27 | 28 | def get_norm_values(norm_family = 'imagenet'): 29 | ''' 30 | Inputs 31 | norm_family: String of norm_family 32 | Returns 33 | mean, std : tuple of 3 channel values 34 | ''' 35 | if norm_family == 'imagenet': 36 | mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225] 37 | else: 38 | raise ValueError('Incorrect normalization family') 39 | return mean, std 40 | 41 | def save_args(args, log_path, argfile): 42 | shutil.copy('train.py', log_path) 43 | modelfiles = ospj(log_path, 'models') 44 | try: 45 | shutil.copy(argfile, log_path) 46 | except: 47 | print('Config exists') 48 | try: 49 | shutil.copytree('models/', modelfiles) 50 | except: 51 | print('Already exists') 52 | with open(ospj(log_path,'args_all.yaml'),'w') as f: 53 | yaml.dump(args, f, default_flow_style=False, allow_unicode=True) 54 | with open(ospj(log_path, 'args.txt'), 'w') as f: 55 | f.write('\n'.join(sys.argv[1:])) 56 | 57 | class UnNormalizer: 58 | ''' 59 | Unnormalize a given tensor using mean and std of a dataset family 60 | Inputs 61 | norm_family: String, dataset 62 | tensor: Torch tensor 63 | Outputs 64 | tensor: Unnormalized tensor 65 | ''' 66 | def __init__(self, norm_family = 'imagenet'): 67 | self.mean, self.std = get_norm_values(norm_family=norm_family) 68 | self.mean, self.std = torch.Tensor(self.mean).view(1, 3, 1, 1), torch.Tensor(self.std).view(1, 3, 1, 1) 69 | 70 | def __call__(self, tensor): 71 | return (tensor * self.std) + self.mean 72 | 73 | def load_args(filename, args): 74 | with open(filename, 'r') as stream: 75 | data_loaded = yaml.safe_load(stream) 76 | for key, group in data_loaded.items(): 77 | for key, val in group.items(): 78 | setattr(args, key, val) 79 | -------------------------------------------------------------------------------- /flags.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) 3 | 4 | # Program parameters 5 | parser.add_argument('--dataset', default='ut-zap50k', help='mit-states|ut-zap50k|cgqa') # YOU HAVE TO CHOOSE A DATASET 6 | parser.add_argument('--splitname', default='compositional-split-natural', help="dataset split") 7 | parser.add_argument('--image_extractor', default = 'resnet18', help = 'image feature extractor') 8 | parser.add_argument('--norm_family', default = 'imagenet', help = 'Normalization values from dataset') 9 | parser.add_argument('--test_set', type=str, help='val|test mode') 10 | parser.add_argument('--test_batch_size', type=int, default=32, help="Batch size at test/eval time") 11 | parser.add_argument('--cpu_eval', action='store_true', help='Perform test on cpu') 12 | parser.add_argument('--train_split', default='normal', help='How to split training set: normal-no split|obj|attr') 13 | 14 | # Training hyperparameters 15 | parser.add_argument('--train', type=bool, help='Training or evaluation?') 16 | parser.add_argument('--topk', type=int, default=1,help="Compute topk accuracy") 17 | parser.add_argument('--num_workers', type=int, default=16,help="Number of workers") 18 | parser.add_argument('--batch_size', type=int, default=256,help="Training batch size") 19 | parser.add_argument('--lr', type=float, default=5e-5, help="Learning rate") 20 | parser.add_argument('--lrg', type=float, default=1e-3, help="Learning rate for feature extractor") 21 | parser.add_argument('--wd', type=float, default=5e-5, help="Weight decay") 22 | parser.add_argument('--save_every', type=int, default=1,help="Frequency of snapshots in epochs") 23 | parser.add_argument('--eval_val_every', type=int, default=1,help="Frequency of eval in epochs") 24 | parser.add_argument('--max_epochs', type=int, default=800,help="Max number of epochs") 25 | 26 | # Model common parameters 27 | parser.add_argument('--emb_dim', type=int, default=300, help='dimension of shared embedding space') 28 | parser.add_argument('--nlayers', type=int, default=2, help='Layers in the image embedder') 29 | parser.add_argument('--bias', type=float, default=1e3, help='Bias value for unseen concepts') 30 | parser.add_argument('--update_image_features', action = 'store_true', default=False, help='Whether update image features extracted from vision models such as ResNet') 31 | parser.add_argument('--update_word_features', action = 'store_true', default=True, help='Whether update word features extracted from NLP models') 32 | parser.add_argument('--emb_type', default='fasttext', help='gl+w2v|ft+w2v|ft+gl|ft+w2v+gl|glove|word2vec|fasttext, name of embeddings to use for initializing the primitives') 33 | parser.add_argument('--composition', default='mlp_add', help='add|mul|mlp|mlp_add, how to compose primitives') 34 | parser.add_argument('--relu', action='store_true', default=False, help='Use relu in the last MLP layer') 35 | parser.add_argument('--dropout', action='store_true', default=False, help='Use dropout') 36 | parser.add_argument('--norm', action='store_true', default=False, help='Use normalization') 37 | parser.add_argument('--train_only', default=True, help='Optimize only for train pairs') 38 | parser.add_argument('--cosine_scale', type=float, default=20, help="Scale for cosine similarity") 39 | parser.add_argument('--nhiddenlayers', type=int, default=0, help='Num of hidden layers of attr adapter') 40 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | # Torch imports 2 | import torch 3 | import numpy as np 4 | # Python imports 5 | import tqdm 6 | from tqdm import tqdm 7 | import os 8 | from os.path import join as ospj 9 | # Local imports 10 | from data import dataset as dset 11 | from model.common import Evaluator 12 | from utils.utils import load_args 13 | from config_model import configure_model 14 | from flags import parser 15 | 16 | def main(): 17 | args = parser.parse_args() 18 | args.dataset = 'ut-zap50k' # Choose from ut-zap50k | mit-states | cgqa 19 | args.main_root = os.path.dirname(__file__) 20 | args.data_root = '/root/datasets' 21 | device = 0 # Your GPU order. If you don't have a GPU, ignore this. 22 | 23 | # Get arguments and start logging 24 | print('> Initialize parameters') 25 | config_path = ospj(args.main_root, 'configs', args.dataset, 'CANet.yml') 26 | if os.path.exists(config_path): 27 | load_args(config_path, args) 28 | print(' Load parameter values from file {}'.format(config_path)) 29 | else: 30 | print(' No yml file found. Keep default parameter values in flags.py') 31 | 32 | if torch.cuda.is_available(): 33 | args.device = 'cuda:{}'.format(device) 34 | else: 35 | args.device = 'cpu' 36 | print('> Choose device: {}'.format(args.device)) 37 | 38 | # Get dataset 39 | print('> Load dataset') 40 | args.phase = 'test' 41 | testset = dset.CompositionDataset( 42 | args=args, 43 | root=os.path.join(args.data_root, args.dataset), 44 | phase=args.phase, 45 | split=args.splitname, 46 | model =args.image_extractor, 47 | update_image_features = args.update_image_features, 48 | ) 49 | testloader = torch.utils.data.DataLoader( 50 | testset, 51 | batch_size=args.test_batch_size, 52 | shuffle=False, 53 | num_workers=args.num_workers) 54 | 55 | # Get model and optimizer 56 | args.train = False 57 | image_extractor, model = configure_model(args, testset, train=args.train) 58 | print(model) 59 | 60 | # load saved model 61 | print('> Load saved trained model') 62 | save_path = os.path.join(args.main_root, 'saved model') 63 | if os.path.exists(save_path): 64 | checkpoint = torch.load(ospj(save_path, 'saved_{}.t7'.format(args.dataset)), map_location=args.device) 65 | else: 66 | print(' No saved model found in local disk. Please run train.py to train the model first') 67 | return 68 | if image_extractor: 69 | try: 70 | image_extractor.load_state_dict(checkpoint['image_extractor']) 71 | image_extractor.eval() 72 | except: 73 | print(' No saved image extractor in checkpoint file') 74 | model.load_state_dict(checkpoint['net']) 75 | model.eval() 76 | 77 | print('> Initialize evaluator') 78 | evaluator = Evaluator(testset, args) 79 | 80 | with torch.no_grad(): 81 | test(image_extractor, model, testloader, evaluator, args) 82 | 83 | def test(image_extractor, model, testloader, evaluator, args): 84 | if image_extractor: 85 | image_extractor.eval() 86 | 87 | model.eval() 88 | 89 | all_attr_gt, all_obj_gt, all_pair_gt, all_pred = [], [], [], [] 90 | 91 | for _, data in tqdm(enumerate(testloader), total=len(testloader), desc='Testing'): 92 | data = [d.to(args.device) for d in data] 93 | if image_extractor: 94 | data[0] = image_extractor(data[0]) 95 | _, predictions = model.val_forward(data) 96 | attr_truth, obj_truth, pair_truth = data[1], data[2], data[3] 97 | all_pred.append(predictions) 98 | all_attr_gt.append(attr_truth) 99 | all_obj_gt.append(obj_truth) 100 | all_pair_gt.append(pair_truth) 101 | 102 | all_attr_gt, all_obj_gt, all_pair_gt = torch.cat(all_attr_gt).to('cpu'), torch.cat(all_obj_gt).to( 103 | 'cpu'), torch.cat(all_pair_gt).to('cpu') 104 | 105 | all_pred_dict = {} 106 | # Gather values as dict of (attr, obj) as key and list of predictions as values 107 | for k in all_pred[0].keys(): 108 | all_pred_dict[k] = torch.cat( 109 | [all_pred[i][k].to('cpu') for i in range(len(all_pred))]) 110 | 111 | # Calculate best unseen accuracy 112 | results = evaluator.score_model(all_pred_dict, all_obj_gt, bias=args.bias, topk=args.topk) 113 | stats = evaluator.evaluate_predictions(results, all_attr_gt, all_obj_gt, all_pair_gt, all_pred_dict, 114 | topk=args.topk) 115 | 116 | attr_acc = stats['closed_attr_match'] 117 | obj_acc = stats['closed_obj_match'] 118 | seen_acc = stats['best_seen'] 119 | unseen_acc = stats['best_unseen'] 120 | HM = stats['best_hm'] 121 | AUC = stats['AUC'] 122 | print('|----Test Finished: Attr Acc: {:.2f}% | Obj Acc: {:.2f}% | Seen Acc: {:.2f}% | Unseen Acc: {:.2f}% | HM: {:.2f}% | AUC: {:.2f}'.\ 123 | format(attr_acc*100, obj_acc*100, seen_acc*100, unseen_acc*100, HM*100, AUC*100)) 124 | 125 | if __name__ == '__main__': 126 | print('======== Welcome! ========') 127 | print('> Program start') 128 | main() 129 | print('=== Program terminated ===') 130 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Conditional Attribute Network CANet 2 | 3 | This is the pytorch code for the paper: 4 | 5 | > **Title:** Learning Conditional Attributes for Compositional Zero-Shot Learning
6 | > **Authors:** Qingsheng Wang, Lingqiao Liu, Chenchen Jing, et.al.
7 | > **Publication:** IEEE Conference on Computer Vision and Pattern Recognition (CVPR) 2023
8 | > **Published Paper:** https://arxiv.org/abs/2305.17940 9 | 10 |

11 | 12 |

13 | 14 |

15 | 16 |

17 | 18 | If you find this work interesting please cite 19 | 20 | ``` 21 | @inproceedings{wang2023learning, 22 | title={Learning Conditional Attributes for Compositional Zero-Shot Learning}, 23 | author={Qingsheng Wang, Lingqiao Liu, Chenchen Jing, Hao Chen, Guoqiang Liang, Peng Wang, Chunhua Shen}, 24 | booktitle={CVPR}, 25 | year={2023} 26 | } 27 | ``` 28 | 29 | All code was implemented using Python 3.10 and Pytorch 1.12 on Ubuntu. 30 | 31 | ## 1. Data Preparation 32 | 33 | UT-Zappos50K: 34 | 35 | MIT-States: 36 | 37 | C-GQA: 38 | 39 | 1. Download datasets UT-Zappos50K, MIT-States, and C-GQA and unzip them into a dataset folder, e.g., /home/XXX/datasets. Rename the dataset folder names as **ut-zap50k**, **mit-states**, and **cgqa**. 40 | 2. Download data splits for UT-Zappos50K and MIT-States at 41 | 3. We provide the resnet18 feature vectors for all three datasets: 42 | 43 | Google Drive: 44 | 45 | Baidu Netdisk: 46 | 47 | Place the "resnet18_feature_vectors.t7" into each of the dataset main path. 48 | 5. Unzip the downloaded file **compositional_split_natural.tar.gz** and place the sub-folders **mit-states** and **ut-zap50k** into the corresponding dataset folder. Note that the cgqa dataset zip file contains its own data split. 49 | 6. Now, we have the following folder structure for the three datasets: 50 | 51 | ```python 52 | > /home/XXX 53 | > datasets 54 | > ut-zap50k # can also be mit-states or cgqa 55 | - metadata_compositional-split-natural.t7 56 | - resnet18_feature_vectors.t7 57 | > compositional-split-natural 58 | - test_pairs.txt 59 | - train_pairs.txt 60 | - val_pairs.txt 61 | # ===Create this empty folder manually for UT-Zappos50K===# 62 | > images 63 | # ======Only UT-Zappos50K has the following folders=======# 64 | > Boots 65 | > Sandals 66 | > Shoes 67 | > Slippers 68 | ``` 69 | 70 | 7. Run **/utils/reorganize_utzap.py** to reorganize images in UT-Zappos50K, where set **DATA_FOLDER='/home/XXX/datasets'** in line 20. 71 | 8. (Optional) Delete sub-folders **Boots**, **Sandals**, **Shoes**, and **Slippers** in the folder **ut-zap50k** if you want to save some disk space. 72 | 73 | ## 2. Inference 74 | 75 | We provide the trained parameters for all three datasets: 76 | 77 | Google Drive: 78 | 79 | Baidu Netdisk: 80 | 81 | 1. Download all trained parameters into the manually created folder **saved model**. Now we have the folder structure: 82 | 83 | ``` 84 | > CANet-CZSL-master 85 | > ... 86 | > model 87 | > saved model 88 | - saved_cgqa.t7 89 | - saved_mit-states.t7 90 | - saved_ut-zap50k.t7 91 | > utils 92 | > ... 93 | ``` 94 | 95 | 2. Open **test.py**, you have to specify some arguments before running this code: **args.dataset**, **args.data_root**, and **device** in lines 18-21. 96 | 3. Run this code. If you run the code for the first time, you will get a file **resnet18_feature_vectors.t7** in each dataset folder. This file contains visual embeddings of all images extracted by resnet-18 without any image augmentation. In this way, all visual embeddings are retrieved by image filename rather than being computed every time and thus reducing inference time significantly. You will get exactly the same results reported in the paper if everything sets (Results in the paper are rounded). 97 | 98 | UT-Zappos50K: 99 |

100 | 101 |

102 | 103 | MIT-States: 104 |

105 | 106 |

107 | 108 | C-GQA: 109 |

110 | 111 |

112 | 113 | *Warning: If you were using an older version pytorch, you would get slightly different results because the pre-trained parameters of the image backbone are different from the lasted version pytorch.* 114 | 115 | ## 3. Training 116 | 117 | You can train the model from scratch. 118 | 119 | 1. You can edit configurations for different runs in **flags.py** and **configs/dataset name 120 | CANet.yml**. The file **flags.py** defines some of the shared hyper-parameters and the *.yml files define dataset-specific hyper-parameters. 121 | 122 | 2. Open **model/word_embedding.py** and set the global variable **DATA_FOLDER = '/home/XXX/word_embedding/'** in line 4 to tell where you save these pre-trained word embeddings. 123 | 124 | 3. Open **train.py** and set **args.dataset**, **args.data_root**, and **device** in lines 34-37 before your training. 125 | 126 | You will notice that a folder named **logs** is created automatically after starting the training. This folder contains the saved checkpoint model, best model, tensorboard file, and all history results in a csv file. 127 | 128 | ## Acknowledgement 129 | 130 | This code package is based on the CZSL library at . We show our deep appreciation for their contribution. 131 | -------------------------------------------------------------------------------- /model/word_embedding.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import numpy as np 3 | 4 | DATA_FOLDER = '/home/D/wangqs/word embeddings/' 5 | 6 | def load_word_embeddings(vocab, args): 7 | if args.emb_type == 'glove': 8 | embeds = load_glove_embeddings(vocab) 9 | elif args.emb_type == 'fasttext': 10 | embeds = load_fasttext_embeddings(vocab) 11 | elif args.emb_type == 'word2vec': 12 | embeds = load_word2vec_embeddings(vocab) 13 | elif args.emb_type == 'ft+w2v': 14 | embeds1 = load_fasttext_embeddings(vocab) 15 | embeds2 = load_word2vec_embeddings(vocab) 16 | embeds = torch.cat([embeds1, embeds2], dim = 1) 17 | print(' Combined embedding shape is ', embeds.shape) 18 | elif args.emb_type == 'ft+gl': 19 | embeds1 = load_fasttext_embeddings(vocab) 20 | embeds2 = load_glove_embeddings(vocab) 21 | embeds = torch.cat([embeds1, embeds2], dim = 1) 22 | print(' Combined embedding shape is ', embeds.shape) 23 | elif args.emb_type == 'ft+ft': 24 | embeds1 = load_fasttext_embeddings(vocab) 25 | embeds = torch.cat([embeds1, embeds1], dim = 1) 26 | print(' Combined embedding shape is ', embeds.shape) 27 | elif args.emb_type == 'gl+w2v': 28 | embeds1 = load_glove_embeddings(vocab) 29 | embeds2 = load_word2vec_embeddings(vocab) 30 | embeds = torch.cat([embeds1, embeds2], dim = 1) 31 | print(' Combined embedding shape is ', embeds.shape) 32 | elif args.emb_type == 'ft+w2v+gl': 33 | embeds1 = load_fasttext_embeddings(vocab) 34 | embeds2 = load_word2vec_embeddings(vocab) 35 | embeds3 = load_glove_embeddings(vocab) 36 | embeds = torch.cat([embeds1, embeds2, embeds3], dim = 1) 37 | print(' Combined embedding shape is ', embeds.shape) 38 | else: 39 | raise ValueError(' Invalid embedding. You have to choose an existing embedding type. Exit.') 40 | args.emb_dim = embeds.shape[1] 41 | return embeds 42 | 43 | def load_fasttext_embeddings(vocab): 44 | custom_map = { 45 | 'Faux.Fur': 'fake fur', 46 | 'Faux.Leather': 'fake leather', 47 | 'Full.grain.leather': 'thick leather', 48 | 'Hair.Calf': 'hairy leather', 49 | 'Patent.Leather': 'shiny leather', 50 | 'Boots.Ankle': 'ankle boots', 51 | 'Boots.Knee.High': 'kneehigh boots', 52 | 'Boots.Mid-Calf': 'midcalf boots', 53 | 'Shoes.Boat.Shoes': 'boatshoes', 54 | 'Shoes.Clogs.and.Mules': 'clogs shoes', 55 | 'Shoes.Flats': 'flats shoes', 56 | 'Shoes.Heels': 'heels', 57 | 'Shoes.Loafers': 'loafers', 58 | 'Shoes.Oxfords': 'oxford shoes', 59 | 'Shoes.Sneakers.and.Athletic.Shoes': 'sneakers', 60 | 'traffic_light': 'traficlight', 61 | 'trash_can': 'trashcan', 62 | 'dry-erase_board' : 'dry_erase_board', 63 | 'black_and_white' : 'black_white', 64 | 'eiffel_tower' : 'tower' 65 | } 66 | vocab_lower = [v.lower() for v in vocab] 67 | vocab = [] 68 | for current in vocab_lower: 69 | if current in custom_map: 70 | vocab.append(custom_map[current]) 71 | else: 72 | vocab.append(current) 73 | 74 | import fasttext.util 75 | 76 | ft = fasttext.load_model(DATA_FOLDER+'fasttext/cc.en.300.bin') 77 | embeds = [] 78 | for k in vocab: 79 | if '_' in k: 80 | ks = k.split('_') 81 | emb = np.stack([ft.get_word_vector(it) for it in ks]).mean(axis=0) 82 | else: 83 | emb = ft.get_word_vector(k) 84 | embeds.append(emb) 85 | 86 | embeds = torch.Tensor(np.stack(embeds)) 87 | print(' Fasttext Embeddings loaded, total embeddings: {}'.format(embeds.size())) 88 | return embeds 89 | 90 | def load_word2vec_embeddings(vocab): 91 | # vocab = [v.lower() for v in vocab] 92 | 93 | from gensim import models 94 | model = models.KeyedVectors.load_word2vec_format( 95 | DATA_FOLDER+'/word2vec/GoogleNews-vectors-negative300.bin', binary=True) 96 | 97 | custom_map = { 98 | 'Faux.Fur': 'fake_fur', 99 | 'Faux.Leather': 'fake_leather', 100 | 'Full.grain.leather': 'thick_leather', 101 | 'Hair.Calf': 'hair_leather', 102 | 'Patent.Leather': 'shiny_leather', 103 | 'Boots.Ankle': 'ankle_boots', 104 | 'Boots.Knee.High': 'knee_high_boots', 105 | 'Boots.Mid-Calf': 'midcalf_boots', 106 | 'Shoes.Boat.Shoes': 'boat_shoes', 107 | 'Shoes.Clogs.and.Mules': 'clogs_shoes', 108 | 'Shoes.Flats': 'flats_shoes', 109 | 'Shoes.Heels': 'heels', 110 | 'Shoes.Loafers': 'loafers', 111 | 'Shoes.Oxfords': 'oxford_shoes', 112 | 'Shoes.Sneakers.and.Athletic.Shoes': 'sneakers', 113 | 'traffic_light': 'traffic_light', 114 | 'trash_can': 'trashcan', 115 | 'dry-erase_board' : 'dry_erase_board', 116 | 'black_and_white' : 'black_white', 117 | 'eiffel_tower' : 'tower' 118 | } 119 | 120 | embeds = [] 121 | for k in vocab: 122 | if k in custom_map: 123 | k = custom_map[k] 124 | if '_' in k and k not in model: 125 | ks = k.split('_') 126 | emb = np.stack([model[it] for it in ks]).mean(axis=0) 127 | else: 128 | emb = model[k] 129 | embeds.append(emb) 130 | embeds = torch.Tensor(np.stack(embeds)) 131 | print(' Word2Vec Embeddings loaded, total embeddings: {}'.format(embeds.size())) 132 | return embeds 133 | 134 | def load_glove_embeddings(vocab): 135 | ''' 136 | Inputs 137 | emb_file: Text file with word embedding pairs e.g. Glove, Processed in lower case. 138 | vocab: List of words 139 | Returns 140 | Embedding Matrix 141 | ''' 142 | vocab = [v.lower() for v in vocab] 143 | emb_file = DATA_FOLDER+'/glove/glove.6B.300d.txt' 144 | model = {} # populating a dictionary of word and embeddings 145 | for line in open(emb_file, 'r'): 146 | line = line.strip().split(' ') # Word-embedding 147 | wvec = torch.FloatTensor(list(map(float, line[1:]))) 148 | model[line[0]] = wvec 149 | 150 | # Adding some vectors for UT Zappos 151 | custom_map = { 152 | 'faux.fur': 'fake_fur', 153 | 'faux.leather': 'fake_leather', 154 | 'full.grain.leather': 'thick_leather', 155 | 'hair.calf': 'hair_leather', 156 | 'patent.leather': 'shiny_leather', 157 | 'boots.ankle': 'ankle_boots', 158 | 'boots.knee.high': 'knee_high_boots', 159 | 'boots.mid-calf': 'midcalf_boots', 160 | 'shoes.boat.shoes': 'boat_shoes', 161 | 'shoes.clogs.and.mules': 'clogs_shoes', 162 | 'shoes.flats': 'flats_shoes', 163 | 'shoes.heels': 'heels', 164 | 'shoes.loafers': 'loafers', 165 | 'shoes.oxfords': 'oxford_shoes', 166 | 'shoes.sneakers.and.athletic.shoes': 'sneakers', 167 | 'traffic_light': 'traffic_light', 168 | 'trash_can': 'trashcan', 169 | 'dry-erase_board' : 'dry_erase_board', 170 | 'black_and_white' : 'black_white', 171 | 'eiffel_tower' : 'tower', 172 | 'nubuck' : 'grainy_leather', 173 | } 174 | 175 | embeds = [] 176 | for k in vocab: 177 | if k in custom_map: 178 | k = custom_map[k] 179 | if '_' in k: 180 | ks = k.split('_') 181 | emb = torch.stack([model[it] for it in ks]).mean(dim=0) 182 | else: 183 | emb = model[k] 184 | embeds.append(emb) 185 | embeds = torch.stack(embeds) 186 | print(' Glove Embeddings loaded, total embeddings: {}'.format(embeds.size())) 187 | return embeds -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | # Torch imports 2 | import torch 3 | from torch.utils.tensorboard import SummaryWriter 4 | from tensorboard import program 5 | from torch.utils.data import DataLoader 6 | # Python imports 7 | from tqdm import tqdm 8 | import os 9 | from os.path import join as ospj 10 | import numpy as np 11 | import random 12 | from flags import parser 13 | import csv 14 | #Local imports 15 | from model.common import Evaluator 16 | from config_model import configure_model 17 | from data import dataset as dset 18 | from utils.utils import load_args, set_torch 19 | 20 | best_attr = 0.0 21 | best_obj = 0.0 22 | best_seen = 0.0 23 | best_unseen = 0.0 24 | best_auc = 0.0 25 | best_hm = 0.0 26 | best_epoch = 0.0 27 | 28 | os.environ["CUDA_VISIBLE_DEVICES"] = '0, 1' 29 | 30 | def main(): 31 | # Get arguments and start logging 32 | print('> Initialize parameters') 33 | args = parser.parse_args() 34 | args.dataset = 'mit-states' # Choose from ut-zap50k | mit-states | cgqa 35 | args.main_root = os.path.dirname(__file__) 36 | args.data_root = '/root/datasets/' 37 | device = 0 # Your GPU order. If you use CPU, ignore this. 38 | args.test_set = 'val' 39 | set_torch(0) 40 | 41 | config_path = ospj(args.main_root, 'configs', args.dataset, 'CANet.yml') 42 | if os.path.exists(config_path): 43 | load_args(config_path, args) 44 | print(' Load parameter values from file {}'.format(config_path)) 45 | else: 46 | print(' No yml file found. Keep default parameter values in flags.py') 47 | 48 | # Choose device 49 | if torch.cuda.is_available(): 50 | args.device = 'cuda:{}'.format(device) 51 | else: 52 | args.device = 'cpu' 53 | print('> Choose device: {}'.format(args.device)) 54 | 55 | # Tensorboard 56 | print('> Initialize tensorboard') 57 | logpath = ospj(args.main_root, 'logs', args.dataset) 58 | writer = SummaryWriter(log_dir=logpath, flush_secs=30) 59 | os.makedirs(logpath, exist_ok=True) 60 | tb = program.TensorBoard() 61 | tb.configure(argv=[None, '--logdir', './logs']) 62 | tb.launch() 63 | 64 | # Get dataset 65 | print('> Load dataset {}'.format(args.dataset)) 66 | trainset = dset.CompositionDataset( 67 | args=args, 68 | root=ospj(args.data_root, args.dataset), 69 | phase='train', 70 | split=args.splitname, 71 | model =args.image_extractor, 72 | update_image_features = args.update_image_features, 73 | train_only= args.train_only, 74 | ) 75 | testset = dset.CompositionDataset( 76 | args=args, 77 | root=ospj(args.data_root, args.dataset), 78 | phase=args.test_set, 79 | split=args.splitname, 80 | model =args.image_extractor, 81 | update_image_features = args.update_image_features, 82 | ) 83 | 84 | # Get model and optimizer 85 | args.train = True 86 | image_extractor, model, optimizer = configure_model(args, trainset) 87 | print(model) 88 | 89 | # Dataloaders 90 | print('> Initialize trainset and {}set dataloaders'.format(args.test_set)) 91 | trainloader = DataLoader( 92 | trainset, 93 | batch_size=args.batch_size, 94 | shuffle=True, 95 | num_workers=args.num_workers) 96 | testloader = DataLoader( 97 | testset, 98 | batch_size=args.test_batch_size, 99 | shuffle=False, 100 | num_workers=args.num_workers) 101 | 102 | # Train an epoch 103 | train = train_normal 104 | 105 | # Evaluate an epoch 106 | print('> Initialize evaluator') 107 | evaluator = Evaluator(testset, args) 108 | 109 | for epoch in range(args.max_epochs): 110 | print('Epoch {} | Best Attr: {:.2f}% | Best Obj: {:.2f}% | Best Seen: {:.2f}% | Best Unseen: {:.2f}% | Best HM: {:.2f}% | Best AUC: {:.2f} | Best Epoch: {:.0f}'.\ 111 | format(epoch+1, best_attr*100, best_obj*100, best_seen*100, best_unseen*100, best_hm*100, best_auc*100, best_epoch)) 112 | train(args, epoch, image_extractor, model, trainloader, optimizer, writer) 113 | with torch.no_grad(): 114 | test(args, epoch, image_extractor, model, testloader, evaluator, logpath) 115 | 116 | def train_normal(args, epoch, image_extractor, model, trainloader, optimizer, writer): 117 | ''' 118 | Runs training for an epoch 119 | ''' 120 | if args.update_image_features: 121 | image_extractor.train() 122 | model = model.train() # Let's switch to training 123 | 124 | train_loss = 0.0 125 | trainloader = tqdm(trainloader, desc='|--Training') 126 | for idx, data in enumerate(trainloader): 127 | data = [d.to(args.device) for d in data] 128 | if args.update_image_features: 129 | data[0] = image_extractor(data[0]) 130 | loss = model(data)[0] 131 | 132 | trainloader.set_description(desc='|--Training | Batch Loss: {:.4f}'.format(loss.item())) 133 | if loss == None: 134 | trainloader.close() 135 | return 136 | 137 | optimizer.zero_grad() 138 | loss.backward() 139 | optimizer.step() 140 | 141 | train_loss += loss.item() 142 | 143 | trainloader.close() 144 | train_loss = train_loss/len(trainloader) 145 | print('|----Train Loss: {:.4f}'.format(train_loss)) 146 | writer.add_scalar('Loss/train_total', train_loss, epoch) 147 | 148 | def test(args, epoch, image_extractor, model, testloader, evaluator, logpath): 149 | ''' 150 | Runs testing for an epoch 151 | ''' 152 | def save_checkpoint(filename): 153 | state = { 154 | 'epoch': epoch+1, 155 | 'AUC': stats['AUC'] 156 | } 157 | state['net'] = model.state_dict() 158 | if image_extractor: 159 | state['image_extractor'] = image_extractor.state_dict() 160 | torch.save(state, ospj(args.main_root, 'logs', args.dataset, 'ckpt_{}_{}.t7'.format(filename, args.dataset))) 161 | 162 | if args.update_image_features: image_extractor.eval() 163 | model = model.eval() 164 | 165 | all_attr_gt, all_obj_gt, all_pair_gt, all_pred = [], [], [], [] 166 | 167 | testloader = tqdm(testloader, desc='|--Testing') 168 | for idx, data in enumerate(testloader): 169 | data = [d.to(args.device) for d in data] 170 | if args.update_image_features: 171 | data[0] = image_extractor(data[0]) 172 | predictions = model(data)[1] 173 | 174 | attr_truth, obj_truth, pair_truth = data[1], data[2], data[3] 175 | all_pred.append(predictions) 176 | all_attr_gt.append(attr_truth) 177 | all_obj_gt.append(obj_truth) 178 | all_pair_gt.append(pair_truth) 179 | 180 | del predictions, attr_truth, obj_truth, pair_truth 181 | testloader.close() 182 | all_attr_gt, all_obj_gt, all_pair_gt = torch.cat(all_attr_gt).to('cpu'), torch.cat(all_obj_gt).to( 183 | 'cpu'), torch.cat(all_pair_gt).to('cpu') 184 | 185 | global best_attr, best_obj, best_seen, best_unseen, best_auc, best_hm, best_epoch 186 | # Gather values as dict of (attr, obj) as key and list of predictions as values 187 | all_pred_dict = {} 188 | for k in all_pred[0].keys(): 189 | all_pred_dict[k] = torch.cat([all_pred[i][k].cpu() for i in range(len(all_pred))]) 190 | del all_pred 191 | 192 | # Calculate best unseen accuracy 193 | results = evaluator.score_model(all_pred_dict, all_obj_gt, bias=args.bias, topk=args.topk) 194 | stats = evaluator.evaluate_predictions(results, all_attr_gt, all_obj_gt, all_pair_gt, all_pred_dict, topk=args.topk) 195 | 196 | stats['a_epoch'] = epoch 197 | 198 | # print(result) 199 | attr_acc = stats['closed_attr_match'] 200 | obj_acc = stats['closed_obj_match'] 201 | seen_acc = stats['best_seen'] 202 | unseen_acc = stats['best_unseen'] 203 | HM = stats['best_hm'] 204 | AUC = stats['AUC'] 205 | print('|----Test Finished: Attr Acc: {:.2f}% | Obj Acc: {:.2f}% | Seen Acc: {:.2f}% | Unseen Acc: {:.2f}% | HM: {:.2f}% | AUC: {:.2f}'.\ 206 | format(attr_acc*100, obj_acc*100, seen_acc*100, unseen_acc*100, HM*100, AUC*100)) 207 | 208 | if epoch > 0 and epoch % args.save_every == 0: 209 | save_checkpoint(epoch) 210 | if AUC > best_auc: 211 | best_auc = AUC 212 | best_attr = attr_acc 213 | best_obj = obj_acc 214 | best_seen = seen_acc 215 | best_unseen = unseen_acc 216 | best_hm = HM 217 | best_epoch = epoch 218 | print('|----New Best AUC {:.2f}. SAVE to local disk!'.format(best_auc*100)) 219 | save_checkpoint('best_auc') 220 | 221 | # Logs 222 | with open(ospj(logpath, 'logs.csv'), 'a') as f: 223 | w = csv.DictWriter(f, stats.keys()) 224 | if epoch == 0: 225 | w.writeheader() 226 | w.writerow(stats) 227 | 228 | if __name__ == '__main__': 229 | print('======== Welcome! ========') 230 | print('> Program start') 231 | main() 232 | print('> Program terminated') 233 | -------------------------------------------------------------------------------- /data/dataset.py: -------------------------------------------------------------------------------- 1 | # external libs 2 | from tqdm import tqdm 3 | from PIL import Image 4 | import os 5 | from os.path import join as ospj 6 | from glob import glob 7 | # torch libs 8 | from torch.utils.data import Dataset 9 | import torch 10 | import torchvision.transforms as transforms 11 | # local libs 12 | from utils.utils import get_norm_values, chunks 13 | from model.image_extractor import get_image_extractor 14 | from itertools import product 15 | 16 | class ImageLoader: 17 | def __init__(self, root): 18 | self.root_dir = root 19 | 20 | def __call__(self, img): 21 | img = Image.open(ospj(self.root_dir, img)).convert('RGB') # We don't want alpha 22 | return img 23 | 24 | 25 | def dataset_transform(phase, norm_family='imagenet'): 26 | ''' 27 | Inputs 28 | phase: String controlling which set of transforms to use 29 | norm_family: String controlling which normaliztion values to use 30 | 31 | Returns 32 | transform: A list of pytorch transforms 33 | ''' 34 | mean, std = get_norm_values(norm_family=norm_family) 35 | 36 | if phase == 'train': 37 | transform = transforms.Compose([ 38 | transforms.RandomResizedCrop(224), 39 | transforms.RandomHorizontalFlip(), 40 | transforms.ToTensor(), 41 | transforms.Normalize(mean, std) 42 | ]) 43 | 44 | elif phase == 'val' or phase == 'test': 45 | transform = transforms.Compose([ 46 | transforms.Resize(256), 47 | transforms.CenterCrop(224), 48 | transforms.ToTensor(), 49 | transforms.Normalize(mean, std) 50 | ]) 51 | elif phase == 'all': 52 | transform = transforms.Compose([ 53 | transforms.Resize(256), 54 | transforms.CenterCrop(224), 55 | transforms.ToTensor(), 56 | transforms.Normalize(mean, std) 57 | ]) 58 | else: 59 | raise ValueError('Invalid transform') 60 | 61 | return transform 62 | 63 | # Dataset class now 64 | class CompositionDataset(Dataset): 65 | ''' 66 | Inputs 67 | root: String of base dir of dataset 68 | phase: String train, val, test 69 | split: String dataset split 70 | subset: Boolean if true uses a subset of train at each epoch 71 | num_negs: Int, numbers of negative pairs per batch 72 | pair_dropout: Percentage of pairs to leave in current epoch 73 | ''' 74 | 75 | def __init__( 76 | self, 77 | args, 78 | root, 79 | phase, 80 | split='compositional-split', 81 | model='resnet18', 82 | norm_family='imagenet', 83 | update_image_features=False, 84 | train_only=False, 85 | ): 86 | self.args = args 87 | self.root = root 88 | self.phase = phase 89 | self.split = split 90 | self.norm_family = norm_family 91 | self.update_image_features = update_image_features 92 | self.feat_dim = 512 if 'resnet18' in model else 2048 # todo, unify this with models 93 | self.device = args.device 94 | 95 | # attrs [115], objs [245], pairs [1962], train_pairs [1262], val_pairs [600], test_pairs [800] 96 | self.attrs, self.objs, self.pairs, self.train_pairs, \ 97 | self.val_pairs, self.test_pairs = self.parse_split() 98 | self.train_data, self.val_data, self.test_data = self.get_split_info() 99 | self.full_pairs = list(product(self.attrs, self.objs)) 100 | 101 | # Clean only was here 102 | self.obj2idx = {obj: idx for idx, obj in enumerate(self.objs)} 103 | self.attr2idx = {attr: idx for idx, attr in enumerate(self.attrs)} 104 | self.all_pair2idx = {pair: idx for idx, pair in enumerate(self.pairs)} # all pairs [1962], for val in training 105 | 106 | if train_only and self.phase == 'train': 107 | print(' Using only train pairs during training') 108 | self.pair2idx = {pair: idx for idx, pair in enumerate(self.train_pairs)} # train pairs [1262] 109 | else: 110 | print(' Using all pairs as classification classes during {} process'.format(self.phase)) 111 | self.pair2idx = {pair: idx for idx, pair in enumerate(self.pairs)} # all pairs [1962] 112 | 113 | if self.phase == 'train': 114 | self.data = self.train_data 115 | elif self.phase == 'val': 116 | self.data = self.val_data 117 | elif self.phase == 'test': 118 | self.data = self.test_data 119 | elif self.phase == 'all': 120 | self.data = self.train_data + self.val_data + self.test_data 121 | else: 122 | raise ValueError(' Invalid training phase') 123 | print(' Use data from {} set'.format(self.phase)) 124 | 125 | self.all_data = self.train_data + self.val_data + self.test_data 126 | 127 | # Keeping a list of all pairs that occur with each object 128 | self.obj_affordance = {} 129 | self.train_obj_affordance = {} 130 | for _obj in self.objs: 131 | candidates = [attr for (_, attr, obj) in self.train_data + self.test_data if obj == _obj] 132 | self.obj_affordance[_obj] = list(set(candidates)) 133 | 134 | candidates = [attr for (_, attr, obj) in self.train_data if obj == _obj] 135 | self.train_obj_affordance[_obj] = list(set(candidates)) 136 | 137 | self.sample_indices = list(range(len(self.data))) 138 | self.sample_pairs = self.train_pairs 139 | 140 | # Load based on what to output 141 | self.transform = dataset_transform(self.phase, self.norm_family) 142 | self.loader = ImageLoader(ospj(self.root, 'images')) 143 | 144 | if not self.update_image_features: 145 | feat_file = ospj(root, model + '_feature_vectors.t7') 146 | if not os.path.exists(feat_file): 147 | print(' Feature file not found. Now get one!') 148 | with torch.no_grad(): 149 | self.generate_features(feat_file, model) 150 | self.phase = phase 151 | print(f' Using {model} and feature file {feat_file}') 152 | activation_data = torch.load(feat_file) 153 | self.activations = dict( 154 | zip(activation_data['files'], activation_data['features'])) 155 | self.feat_dim = activation_data['features'].size(1) 156 | 157 | def parse_split(self): 158 | ''' 159 | Helper function to read splits of object attribute pair 160 | Returns 161 | all_attrs: List of all attributes 162 | all_objs: List of all objects 163 | all_pairs: List of all combination of attrs and objs 164 | tr_pairs: List of train pairs of attrs and objs 165 | vl_pairs: List of validation pairs of attrs and objs 166 | ts_pairs: List of test pairs of attrs and objs 167 | ''' 168 | 169 | def parse_pairs(pair_list): 170 | ''' 171 | Helper function to parse each phase to object attribute vectors 172 | Inputs 173 | pair_list: path to textfile 174 | ''' 175 | with open(pair_list, 'r') as f: 176 | pairs = f.read().strip().split('\n') 177 | pairs = [line.split() for line in pairs] 178 | pairs = list(map(tuple, pairs)) 179 | 180 | attrs, objs = zip(*pairs) 181 | return attrs, objs, pairs 182 | 183 | tr_attrs, tr_objs, tr_pairs = parse_pairs( 184 | ospj(self.root, self.split, 'train_pairs.txt') 185 | ) 186 | vl_attrs, vl_objs, vl_pairs = parse_pairs( 187 | ospj(self.root, self.split, 'val_pairs.txt') 188 | ) 189 | ts_attrs, ts_objs, ts_pairs = parse_pairs( 190 | ospj(self.root, self.split, 'test_pairs.txt') 191 | ) 192 | 193 | # now we compose all objs, attrs and pairs 194 | all_attrs, all_objs = sorted( 195 | list(set(tr_attrs + vl_attrs + ts_attrs))), sorted( 196 | list(set(tr_objs + vl_objs + ts_objs))) 197 | all_pairs = sorted(list(set(tr_pairs + vl_pairs + ts_pairs))) 198 | 199 | return all_attrs, all_objs, all_pairs, tr_pairs, vl_pairs, ts_pairs 200 | 201 | def get_split_info(self): 202 | ''' 203 | Helper method to read image, attrs, objs samples 204 | 205 | Returns 206 | train_data, val_data, test_data: List of tuple of image, attrs, obj 207 | ''' 208 | data = torch.load(ospj(self.root, 'metadata_{}.t7'.format(self.split))) 209 | 210 | train_data, val_data, test_data = [], [], [] 211 | 212 | for instance in data: 213 | image, attr, obj, settype = instance['image'], instance['attr'], \ 214 | instance['obj'], instance['set'] 215 | curr_data = [image, attr, obj] 216 | 217 | if attr == 'NA' or (attr, obj) not in self.pairs or settype == 'NA': 218 | # Skip incomplete pairs, unknown pairs and unknown set 219 | continue 220 | 221 | if settype == 'train': 222 | train_data.append(curr_data) 223 | elif settype == 'val': 224 | val_data.append(curr_data) 225 | else: 226 | test_data.append(curr_data) 227 | 228 | return train_data, val_data, test_data 229 | 230 | def generate_features(self, out_file, model): 231 | ''' 232 | Inputs 233 | out_file: Path to save features 234 | model: String of extraction model 235 | ''' 236 | # data = self.all_data 237 | data = ospj(self.root, 'images') 238 | files_before = glob(ospj(data, '**', '*.jpg'), recursive=True) 239 | files_all = [] 240 | for current in files_before: 241 | parts = current.split('/') 242 | if "cgqa" in self.root: 243 | files_all.append(parts[-1]) 244 | else: 245 | files_all.append(os.path.join(parts[-2], parts[-1])) 246 | transform = dataset_transform('test', self.norm_family) # Do not use any image augmentation, because we have a trained image backbone 247 | feat_extractor = get_image_extractor(arch=model).eval() 248 | feat_extractor = feat_extractor.to(self.device) 249 | 250 | image_feats = [] 251 | image_files = [] 252 | for chunk in tqdm(chunks(files_all, 1024), total=len(files_all) // 1024, desc=f'Extracting features {model}'): 253 | files = chunk 254 | imgs = list(map(self.loader, files)) 255 | imgs = list(map(transform, imgs)) 256 | feats = feat_extractor(torch.stack(imgs, 0).to(self.device)) 257 | image_feats.append(feats.data.cpu()) 258 | image_files += files 259 | image_feats = torch.cat(image_feats, dim=0) 260 | print('features for %d images generated' % (len(image_files))) 261 | 262 | torch.save({'features': image_feats, 'files': image_files}, out_file) 263 | 264 | def __getitem__(self, index): 265 | ''' 266 | Call for getting samples 267 | ''' 268 | index = self.sample_indices[index] 269 | 270 | image, attr, obj = self.data[index] 271 | 272 | # Decide what to output 273 | if not self.update_image_features: 274 | if self.args.dataset == 'mit-states': 275 | pair, img = image.split('/') 276 | pair = pair.replace('_', ' ') 277 | image = pair + '/' + img 278 | img = self.activations[image] 279 | else: 280 | img = self.loader(image) 281 | img = self.transform(img) 282 | 283 | data = [img, self.attr2idx[attr], self.obj2idx[obj], self.pair2idx[(attr, obj)]] 284 | 285 | return data 286 | 287 | def __len__(self): 288 | ''' 289 | Call for length 290 | ''' 291 | return len(self.sample_indices) 292 | -------------------------------------------------------------------------------- /model/CANet.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import torch 4 | import torch.nn as nn 5 | import torch.nn.functional as F 6 | 7 | from model.common import MLP 8 | from model.word_embedding import load_word_embeddings 9 | 10 | 11 | class HyperNet(nn.Module): 12 | def __init__(self, struct): 13 | super(HyperNet, self).__init__() 14 | self.struct = struct # channel config of the primary network 15 | for key, value in struct.items(): 16 | setattr(self, key, nn.Sequential( 17 | nn.Linear(value[0], value[1]), 18 | )) 19 | 20 | def forward(self, control_signal): 21 | weights = {} 22 | for key, _ in self.struct.items(): 23 | weight = getattr(self, key)(control_signal) 24 | weights[key] = weight 25 | return weights 26 | 27 | class HyperNetStructure(): 28 | ''' 29 | This class only defines the structure of Attribute Hyper Learner. 30 | ''' 31 | def __init__(self, input_dim, num_hiddenLayer, hidden_dim, output_dim): 32 | self.structure = {} 33 | if num_hiddenLayer == 0: 34 | self.structure['InGenerator'] = [input_dim, hidden_dim] 35 | self.structure['OutGenerator'] = [input_dim, output_dim] 36 | else: 37 | self.structure['InGenerator'] = [input_dim, hidden_dim] 38 | for i in range(num_hiddenLayer): 39 | self.structure['HiddenGenerator_{}'.format(i+1)] = [input_dim, hidden_dim] 40 | self.structure['OutGenerator'] = [input_dim, output_dim] 41 | 42 | def get_structure(self): 43 | return self.structure 44 | 45 | class AttrAdapter(nn.Module): 46 | def __init__(self, input_dim, hypernet_struct, relu=True): 47 | super().__init__() 48 | self.hypernet_struct = hypernet_struct 49 | self.hyper_net = HyperNet(struct=hypernet_struct) 50 | self.num_generator = len(hypernet_struct) 51 | self.relu = relu 52 | i = 0 53 | incoming = input_dim 54 | for _, value in hypernet_struct.items(): 55 | setattr(self, 'AdapterLayer_{}'.format(i), nn.Linear(incoming, value[1])) 56 | if i < self.num_generator - 1: 57 | setattr(self, 'AdapterLayer_{}_extend'.format(i), nn.Sequential( 58 | nn.LayerNorm(value[1]), 59 | nn.ReLU(True), 60 | nn.Dropout() 61 | )) 62 | incoming = value[1] 63 | i += 1 64 | if relu: 65 | setattr(self, 'AdapterLastReLU', nn.ReLU(True)) 66 | 67 | def forward(self, control_signal, attr_emb): 68 | batch_size = control_signal.shape[0] # 256 69 | num_attr = attr_emb.shape[0] # 115 70 | attr_emb = attr_emb.unsqueeze(dim=0).repeat(batch_size, 1, 1) # 256x115x300 71 | weights = self.hyper_net(control_signal) 72 | i = 0 73 | for key, _ in self.hypernet_struct.items(): 74 | attr_emb = getattr(self, 'AdapterLayer_{}'.format(i))(attr_emb) 75 | weights_extend = weights[key].unsqueeze(dim=1).repeat(1, num_attr, 1) 76 | attr_emb *= weights_extend 77 | if i < self.num_generator - 1: 78 | attr_emb = getattr(self, 'AdapterLayer_{}_extend'.format(i))(attr_emb) 79 | i += 1 80 | if self.relu: 81 | attr_emb = getattr(self, 'AdapterLastReLU')(attr_emb) 82 | return attr_emb 83 | 84 | class CANet(nn.Module): 85 | def __init__(self, dset, args): 86 | super(CANet, self).__init__() 87 | self.dset = dset 88 | 89 | def get_all_ids(relevant_pairs): 90 | # Precompute validation pairs 91 | attrs, objs = zip(*relevant_pairs) 92 | attrs = [dset.attr2idx[attr] for attr in attrs] 93 | objs = [dset.obj2idx[obj] for obj in objs] 94 | pairs = [a for a in range(len(relevant_pairs))] 95 | attrs = torch.LongTensor(attrs).to(args.device) 96 | objs = torch.LongTensor(objs).to(args.device) 97 | pairs = torch.LongTensor(pairs).to(args.device) 98 | return attrs, objs, pairs 99 | 100 | # Validation - Use all pairs to validate 101 | self.val_attrs, self.val_objs, self.val_pairs = get_all_ids(self.dset.pairs) 102 | # All attrs and objs without repetition 103 | self.uniq_attrs, self.uniq_objs = torch.arange(len(self.dset.attrs)).long().to(args.device), \ 104 | torch.arange(len(self.dset.objs)).long().to(args.device) 105 | if args.train_only: 106 | self.train_attrs, self.train_objs, self.train_pairs = get_all_ids(self.dset.train_pairs) 107 | else: 108 | self.train_attrs, self.train_objs, self.train_pairs = self.val_attrs, self.val_objs, self.val_pairs 109 | 110 | '''========== Word embedder for attrs and objs ==========''' 111 | attr_word_emb_file = '{}_{}_attr.save'.format(args.dataset, args.emb_type) 112 | attr_word_emb_file = os.path.join(args.main_root, 'word embedding', attr_word_emb_file) 113 | obj_word_emb_file = '{}_{}_obj.save'.format(args.dataset, args.emb_type) 114 | obj_word_emb_file = os.path.join(args.main_root, 'word embedding', obj_word_emb_file) 115 | 116 | print(' Load attribute word embeddings--') 117 | if os.path.exists(attr_word_emb_file): 118 | pretrained_weight_attr = torch.load(attr_word_emb_file, map_location=args.device) 119 | else: 120 | pretrained_weight_attr = load_word_embeddings(dset.attrs, args) 121 | print(' Save attr word embeddings using {}'.format(args.emb_type)) 122 | torch.save(pretrained_weight_attr, attr_word_emb_file) 123 | emb_dim = pretrained_weight_attr.shape[1] 124 | self.attr_embedder = nn.Embedding(len(dset.attrs), emb_dim).to(args.device) 125 | self.attr_embedder.weight.data.copy_(pretrained_weight_attr) 126 | 127 | print(' Load object word embeddings--') 128 | if os.path.exists(obj_word_emb_file): 129 | pretrained_weight_obj = torch.load(obj_word_emb_file, map_location=args.device) 130 | else: 131 | pretrained_weight_obj = load_word_embeddings(dset.objs, args) 132 | print(' Save obj word embeddings using {}'.format(args.emb_type)) 133 | torch.save(pretrained_weight_obj, obj_word_emb_file) 134 | self.obj_embedder = nn.Embedding(len(dset.objs), emb_dim).to(args.device) 135 | self.obj_embedder.weight.data.copy_(pretrained_weight_obj) 136 | '''======================================================''' 137 | 138 | '''====================== HyperNet ======================''' 139 | AttrHyperNet_struct = HyperNetStructure(input_dim=emb_dim, num_hiddenLayer=args.nhiddenlayers, 140 | hidden_dim=emb_dim*2, output_dim=emb_dim) 141 | self.AttrHyperNet_struct = AttrHyperNet_struct.get_structure() 142 | '''======================================================''' 143 | 144 | '''=================== Attr adapter =====================''' 145 | self.attr_adapter = AttrAdapter(input_dim=emb_dim, hypernet_struct=self.AttrHyperNet_struct, relu=False) 146 | '''======================================================''' 147 | 148 | '''======================= Mapper =======================''' 149 | self.image_embedder_attr = MLP(dset.feat_dim, emb_dim, num_layers=args.nlayers, relu=False, bias=True, 150 | dropout=True, norm=True, layers=[]) 151 | self.image_embedder_obj = MLP(dset.feat_dim, emb_dim, num_layers=args.nlayers, relu=False, bias=True, 152 | dropout=True, norm=True, layers=[]) 153 | self.image_embedder_both = MLP(dset.feat_dim, emb_dim, num_layers=args.nlayers, relu=False, bias=True, 154 | dropout=True, norm=True, layers=[]) 155 | '''======================================================''' 156 | 157 | # static inputs 158 | if not args.update_word_features: 159 | for param in self.attr_embedder.parameters(): 160 | param.requires_grad = False 161 | for param in self.obj_embedder.parameters(): 162 | param.requires_grad = False 163 | 164 | self.projection = MLP(emb_dim*2, emb_dim, relu=True, bias=True, dropout=True, norm=True, 165 | num_layers=2, layers=[]) 166 | 167 | self.img_obj_compose = MLP(emb_dim+dset.feat_dim, emb_dim, relu=True, bias=True, dropout=True, norm=True, 168 | num_layers=2, layers=[emb_dim]) 169 | 170 | self.alpha = args.alpha # weight factor 171 | self.τ = args.cosine_scale # temperature factor 172 | self._initialize_weights() 173 | 174 | def _initialize_weights(self): 175 | for n, m in self.named_modules(): 176 | if isinstance(m, nn.Linear) and 'hyper_net' not in n: 177 | nn.init.normal_(m.weight, 0, 0.001) 178 | if m.bias is not None: 179 | nn.init.constant_(m.bias, 0) 180 | if isinstance(m, nn.Linear) and 'hyper_net' in n: 181 | nn.init.kaiming_normal_(m.weight, nonlinearity='leaky_relu') 182 | if m.bias is not None: 183 | nn.init.constant_(m.bias, 0) 184 | elif isinstance(m, nn.Embedding): 185 | nn.init.normal_(m.weight, 0, 0.01) 186 | 187 | def compose(self, attrs, objs): 188 | attrs, objs = self.attr_embedder(attrs), self.obj_embedder(objs) 189 | inputs = torch.cat([attrs, objs], -1) 190 | output = self.projection(inputs) 191 | return output 192 | 193 | def val_forward(self, input_batch): 194 | x = input_batch[0] 195 | del input_batch 196 | # Map the input image embedding 197 | ω_a_x = self.image_embedder_attr(x) 198 | ω_c_x = self.image_embedder_both(x) 199 | ω_o_x = self.image_embedder_obj(x) 200 | 201 | # Acquire word embeddings of all attrs and objs 202 | v_a = self.attr_embedder(self.uniq_attrs) 203 | v_o = self.obj_embedder(self.uniq_objs) 204 | 205 | # Pred obj 206 | ω_o_x_norm = F.normalize(ω_o_x, dim=-1) 207 | v_o_norm = F.normalize(v_o, dim=-1) 208 | d_cos_oi = ω_o_x_norm @ v_o_norm.t() 209 | P_oi = (d_cos_oi + 1) / 2 210 | o_star = torch.argmax(d_cos_oi, dim=-1) 211 | v_o_star = self.obj_embedder(o_star) 212 | 213 | # Pred attr 214 | β = self.img_obj_compose(torch.cat((v_o_star, x), dim=-1)) 215 | e_a = self.attr_adapter(β, v_a) 216 | ω_a_x_norm = F.normalize(ω_a_x, dim=-1) 217 | e_a = F.normalize(e_a, dim=-1) 218 | d_cos_ei = torch.einsum('bd,bad->ba', ω_a_x_norm, e_a) 219 | P_ei = (d_cos_ei + 1) / 2 220 | 221 | # Pred composition 222 | v_ao = self.compose(self.val_attrs, self.val_objs) 223 | ω_c_x = F.normalize(ω_c_x, dim=-1) 224 | v_ao = F.normalize(v_ao, dim=-1) 225 | d_cos_ci = ω_c_x @ v_ao.t() 226 | P_ci = (d_cos_ci + 1) / 2 227 | 228 | scores = {} 229 | for itr, pair in enumerate(self.dset.pairs): 230 | scores[pair] = (1 - self.alpha) * P_ci[:, self.dset.all_pair2idx[pair]] 231 | scores[pair] += self.alpha * (P_ei[:, self.dset.attr2idx[pair[0]]] * P_oi[:, self.dset.obj2idx[pair[1]]]) 232 | 233 | return None, scores 234 | 235 | def train_forward(self, input_batch): 236 | x, a, o, c = input_batch[0], input_batch[1], input_batch[2], input_batch[3] 237 | del input_batch 238 | 239 | # Map the input image embedding 240 | ω_a_x = self.image_embedder_attr(x) 241 | ω_c_x = self.image_embedder_both(x) 242 | ω_o_x = self.image_embedder_obj(x) 243 | 244 | # Acquire word embeddings of all attrs and objs 245 | v_a = self.attr_embedder(self.uniq_attrs) 246 | v_o = self.obj_embedder(self.uniq_objs) 247 | 248 | # Pred obj 249 | ω_o_x_norm = F.normalize(ω_o_x, dim=-1) 250 | v_o_norm = F.normalize(v_o, dim=-1) 251 | d_cos_oi = ω_o_x_norm @ v_o_norm.t() # Eq.2 252 | o_star = torch.argmax(d_cos_oi, dim=-1) 253 | d_cos_oi = d_cos_oi / self.τ 254 | v_o_star = self.obj_embedder(o_star) 255 | 256 | # Pred attr 257 | β = self.img_obj_compose(torch.cat((v_o_star, x), dim=-1)) # Eq.3 258 | e_a = self.attr_adapter(β, v_a) # Eq.5 259 | ω_a_x_norm = F.normalize(ω_a_x, dim=-1) 260 | e_a_norm = F.normalize(e_a, dim=-1) 261 | d_cos_ei = torch.einsum('bd,bad->ba', ω_a_x_norm, e_a_norm) # Eq.7 262 | d_cos_ei = d_cos_ei / self.τ 263 | 264 | # Pred composition 265 | v_ao = self.compose(self.train_attrs, self.train_objs) 266 | ω_c_x_norm = F.normalize(ω_c_x, dim=-1) 267 | v_ao_norm = F.normalize(v_ao, dim=-1) 268 | d_cos_ci = ω_c_x_norm @ v_ao_norm.t() # Eq.8 269 | d_cos_ci = d_cos_ci / self.τ 270 | 271 | L_o = F.cross_entropy(d_cos_oi, o) # Eq.10 272 | L_a = F.cross_entropy(d_cos_ei, a) # Eq.9 273 | L_ao = F.cross_entropy(d_cos_ci, c) # Eq.11 274 | 275 | return (L_a + L_o) / 2 + L_ao, None # Eq.12 276 | 277 | def forward(self, x): 278 | if self.training: 279 | loss, pred = self.train_forward(x) 280 | return loss, pred 281 | else: 282 | with torch.no_grad(): 283 | loss, pred = self.val_forward(x) 284 | return loss, pred 285 | -------------------------------------------------------------------------------- /model/common.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import numpy as np 4 | from scipy.stats import hmean 5 | 6 | class MLP(nn.Module): 7 | ''' 8 | Baseclass to create a simple MLP 9 | Inputs 10 | inp_dim: Int, Input dimension 11 | out-dim: Int, Output dimension 12 | num_layer: Number of hidden layers 13 | relu: Bool, Use non linear function at output 14 | bias: Bool, Use bias 15 | ''' 16 | def __init__(self, inp_dim, out_dim, num_layers = 1, relu = True, bias = True, dropout = False, norm = False, layers=[4096]): 17 | super(MLP, self).__init__() 18 | mod = [] 19 | incoming = inp_dim 20 | for layer in range(num_layers - 1): 21 | if len(layers) == 0: 22 | outgoing = incoming 23 | else: 24 | outgoing = layers.pop(0) 25 | mod.append(nn.Linear(incoming, outgoing, bias = bias)) 26 | 27 | incoming = outgoing 28 | if norm: 29 | mod.append(nn.LayerNorm(outgoing)) 30 | # mod.append(nn.BatchNorm1d(outgoing)) 31 | mod.append(nn.ReLU(inplace = True)) 32 | # mod.append(nn.LeakyReLU(inplace=True, negative_slope=0.2)) 33 | if dropout: 34 | mod.append(nn.Dropout(p = 0.5)) 35 | 36 | mod.append(nn.Linear(incoming, out_dim, bias = bias)) 37 | 38 | if relu: 39 | mod.append(nn.ReLU(inplace = True)) 40 | # mod.append(nn.LeakyReLU(inplace=True, negative_slope=0.2)) 41 | self.mod = nn.Sequential(*mod) 42 | 43 | def forward(self, x): 44 | return self.mod(x) 45 | 46 | class Evaluator: 47 | 48 | def __init__(self, dset, args): 49 | 50 | self.dset = dset 51 | self.args = args 52 | self.device = args.device 53 | 54 | # Convert text pairs to idx tensors: [('sliced', 'apple'), ('ripe', 'apple'), ...] --> torch.LongTensor([[0,1],[1,1], ...]) 55 | pairs = [(dset.attr2idx[attr], dset.obj2idx[obj]) for attr, obj in dset.pairs] 56 | self.train_pairs = [(dset.attr2idx[attr], dset.obj2idx[obj]) for attr, obj in dset.train_pairs] 57 | self.pairs = torch.LongTensor(pairs) 58 | 59 | # Mask over pairs that occur in closed world 60 | # Select set based on phase 61 | if dset.phase == 'train': 62 | print(' Evaluating with train pairs') 63 | test_pair_set = set(dset.train_pairs) 64 | test_pair_gt = set(dset.train_pairs) 65 | elif dset.phase == 'val': 66 | print(' Evaluating with validation pairs') 67 | test_pair_set = set(dset.val_pairs + dset.train_pairs) 68 | test_pair_gt = set(dset.val_pairs) 69 | else: 70 | print(' Evaluating with test pairs') 71 | test_pair_set = set(dset.test_pairs + dset.train_pairs) 72 | test_pair_gt = set(dset.test_pairs) 73 | 74 | self.test_pair_dict = [(dset.attr2idx[attr], dset.obj2idx[obj]) for attr, obj in test_pair_gt] 75 | self.test_pair_dict = dict.fromkeys(self.test_pair_dict, 0) 76 | 77 | # dict values are pair val, score, total 78 | for attr, obj in test_pair_gt: 79 | pair_val = dset.pair2idx[(attr,obj)] 80 | key = (dset.attr2idx[attr], dset.obj2idx[obj]) 81 | self.test_pair_dict[key] = [pair_val, 0, 0] 82 | 83 | masks = [1 if pair in test_pair_set else 0 for pair in dset.pairs] 84 | 85 | self.closed_mask = torch.BoolTensor(masks) 86 | # Mask of seen concepts 87 | seen_pair_set = set(dset.train_pairs) 88 | mask = [1 if pair in seen_pair_set else 0 for pair in dset.pairs] 89 | self.seen_mask = torch.BoolTensor(mask) 90 | 91 | # Object specific mask over which pairs occur in the object oracle setting 92 | oracle_obj_mask = [] 93 | for _obj in dset.objs: 94 | mask = [1 if _obj == obj else 0 for attr, obj in dset.pairs] 95 | oracle_obj_mask.append(torch.BoolTensor(mask)) 96 | self.oracle_obj_mask = torch.stack(oracle_obj_mask, 0) 97 | 98 | # Decide if the model under evaluation is a manifold model or not 99 | self.score_model = self.score_manifold_model 100 | 101 | # Generate mask for each settings, mask scores, and get prediction labels 102 | def generate_predictions(self, scores, obj_truth, bias = 0.0, topk = 5): # (Batch, #pairs) 103 | ''' 104 | Inputs 105 | scores: Output scores 106 | obj_truth: Ground truth object 107 | Returns 108 | results: dict of results in 3 settings 109 | ''' 110 | def get_pred_from_scores(_scores, topk): 111 | ''' 112 | Given list of scores, returns top 10 attr and obj predictions 113 | Check later 114 | ''' 115 | _, pair_pred = _scores.topk(topk, dim = 1) #sort returns indices of k largest values 116 | pair_pred = pair_pred.contiguous().view(-1) 117 | attr_pred, obj_pred = self.pairs[pair_pred][:, 0].view(-1, topk), \ 118 | self.pairs[pair_pred][:, 1].view(-1, topk) 119 | return (attr_pred, obj_pred) 120 | 121 | results = {} 122 | orig_scores = scores.clone() 123 | mask = self.seen_mask.repeat(scores.shape[0],1) # Repeat mask along pairs dimension 124 | scores[~mask] += bias # Add bias to test pairs 125 | 126 | # Unbiased setting 127 | 128 | # Open world setting --no mask, all pairs of the dataset 129 | results.update({'open': get_pred_from_scores(scores, topk)}) 130 | results.update({'unbiased_open': get_pred_from_scores(orig_scores, topk)}) 131 | # Closed world setting - set the score for all Non test pairs to -1e10, 132 | # this excludes the pairs from set not in evaluation 133 | mask = self.closed_mask.repeat(scores.shape[0], 1) 134 | closed_scores = scores.clone() 135 | closed_scores[~mask] = -1e10 136 | closed_orig_scores = orig_scores.clone() 137 | closed_orig_scores[~mask] = -1e10 138 | results.update({'closed_logits': closed_scores}) 139 | results.update({'closed': get_pred_from_scores(closed_scores, topk)}) 140 | results.update({'unbiased_closed': get_pred_from_scores(closed_orig_scores, topk)}) 141 | 142 | # Object_oracle setting - set the score to -1e10 for all pairs where the true object does Not participate, can also use the closed score 143 | mask = self.oracle_obj_mask[obj_truth] 144 | oracle_obj_scores = scores.clone() 145 | oracle_obj_scores[~mask] = -1e10 146 | oracle_obj_scores_unbiased = orig_scores.clone() 147 | oracle_obj_scores_unbiased[~mask] = -1e10 148 | results.update({'object_oracle': get_pred_from_scores(oracle_obj_scores, 1)}) 149 | results.update({'object_oracle_unbiased': get_pred_from_scores(oracle_obj_scores_unbiased, 1)}) 150 | 151 | return results 152 | 153 | def score_clf_model(self, scores, obj_truth, topk = 5): 154 | ''' 155 | Wrapper function to call generate_predictions for CLF models 156 | ''' 157 | attr_pred, obj_pred = scores 158 | 159 | # Go to CPU 160 | attr_pred, obj_pred, obj_truth = attr_pred.to('cpu'), obj_pred.to('cpu'), obj_truth.to('cpu') 161 | 162 | # Gather scores (P(a), P(o)) for all relevant (a,o) pairs 163 | # Multiply P(a) * P(o) to get P(pair) 164 | attr_subset = attr_pred.index_select(1, self.pairs[:,0]) # Return only attributes that are in our pairs 165 | obj_subset = obj_pred.index_select(1, self.pairs[:, 1]) 166 | scores = (attr_subset * obj_subset) # (Batch, #pairs) 167 | 168 | results = self.generate_predictions(scores, obj_truth) 169 | results['biased_scores'] = scores 170 | 171 | return results 172 | 173 | def score_manifold_model(self, scores, obj_truth, bias = 0.0, topk = 5): 174 | ''' 175 | Wrapper function to call generate_predictions for manifold models 176 | ''' 177 | # Gather scores for all relevant (a,o) pairs 178 | scores = torch.stack( 179 | [scores[(attr,obj)] for attr, obj in self.dset.pairs], 1 180 | ) # (Batch, #pairs) 181 | orig_scores = scores.clone() 182 | results = self.generate_predictions(scores, obj_truth, bias, topk) 183 | results['scores'] = orig_scores 184 | return results 185 | 186 | def score_fast_model(self, scores, obj_truth, bias = 0.0, topk = 5): 187 | ''' 188 | Wrapper function to call generate_predictions for manifold models 189 | ''' 190 | 191 | results = {} 192 | mask = self.seen_mask.repeat(scores.shape[0],1) # Repeat mask along pairs dimension 193 | scores[~mask] += bias # Add bias to test pairs 194 | 195 | mask = self.closed_mask.repeat(scores.shape[0], 1) 196 | closed_scores = scores.clone() 197 | closed_scores[~mask] = -1e10 198 | 199 | _, pair_pred = closed_scores.topk(topk, dim = 1) #sort returns indices of k largest values 200 | pair_pred = pair_pred.contiguous().view(-1) 201 | attr_pred, obj_pred = self.pairs[pair_pred][:, 0].view(-1, topk), \ 202 | self.pairs[pair_pred][:, 1].view(-1, topk) 203 | 204 | results.update({'closed': (attr_pred, obj_pred)}) 205 | return results 206 | 207 | def add_bias_to_score(self, scores, bias = 0.0): 208 | mask = self.seen_mask.repeat(scores.shape[0],1) # Repeat mask along pairs dimension 209 | scores[~mask] += bias # Add bias to test pairs 210 | 211 | return scores 212 | 213 | def evaluate_predictions(self, predictions, attr_truth, obj_truth, pair_truth, allpred, topk = 1): 214 | # Go to CPU 215 | attr_truth, obj_truth, pair_truth = attr_truth.to('cpu'), obj_truth.to('cpu'), pair_truth.to('cpu') 216 | 217 | pairs = list( 218 | zip(list(attr_truth.numpy()), list(obj_truth.numpy()))) 219 | 220 | seen_ind, unseen_ind = [], [] 221 | for i in range(len(attr_truth)): 222 | if pairs[i] in self.train_pairs: 223 | seen_ind.append(i) 224 | else: 225 | unseen_ind.append(i) 226 | 227 | seen_ind, unseen_ind = torch.LongTensor(seen_ind), torch.LongTensor(unseen_ind) 228 | def _process(_scores): 229 | # Top k pair accuracy 230 | # Attribute, object and pair 231 | attr_match = (attr_truth.unsqueeze(1).repeat(1, topk) == _scores[0][:, :topk]) 232 | obj_match = (obj_truth.unsqueeze(1).repeat(1, topk) == _scores[1][:, :topk]) 233 | 234 | # Match of object pair 235 | match = (attr_match * obj_match).any(1).float() 236 | attr_match = attr_match.any(1).float() 237 | obj_match = obj_match.any(1).float() 238 | # Match of seen and unseen pairs 239 | seen_match = match[seen_ind] 240 | unseen_match = match[unseen_ind] 241 | ### Calculating class average accuracy 242 | 243 | # local_score_dict = copy.deepcopy(self.test_pair_dict) 244 | # for pair_gt, pair_pred in zip(pairs, match): 245 | # # print(pair_gt) 246 | # local_score_dict[pair_gt][2] += 1.0 #increase counter 247 | # if int(pair_pred) == 1: 248 | # local_score_dict[pair_gt][1] += 1.0 249 | 250 | # # Now we have hits and totals for classes in evaluation set 251 | # seen_score, unseen_score = [], [] 252 | # for key, (idx, hits, total) in local_score_dict.items(): 253 | # score = hits/total 254 | # if bool(self.seen_mask[idx]) == True: 255 | # seen_score.append(score) 256 | # else: 257 | # unseen_score.append(score) 258 | 259 | seen_score, unseen_score = torch.ones(512,5), torch.ones(512,5) 260 | 261 | return attr_match, obj_match, match, seen_match, unseen_match, \ 262 | torch.Tensor(seen_score+unseen_score), torch.Tensor(seen_score), torch.Tensor(unseen_score) 263 | 264 | def _add_to_dict(_scores, type_name, stats): 265 | base = ['_attr_match', '_obj_match', '_match', '_seen_match', '_unseen_match', '_ca', '_seen_ca', '_unseen_ca'] 266 | for val, name in zip(_scores, base): 267 | stats[type_name + name] = val 268 | 269 | ##################### Match in places where corrent object 270 | obj_oracle_match = (attr_truth == predictions['object_oracle'][0][:, 0]).float() #object is already conditioned 271 | obj_oracle_match_unbiased = (attr_truth == predictions['object_oracle_unbiased'][0][:, 0]).float() 272 | 273 | stats = dict(obj_oracle_match = obj_oracle_match, obj_oracle_match_unbiased = obj_oracle_match_unbiased) 274 | 275 | #################### Closed world 276 | closed_scores = _process(predictions['closed']) 277 | unbiased_closed = _process(predictions['unbiased_closed']) 278 | _add_to_dict(closed_scores, 'closed', stats) 279 | _add_to_dict(unbiased_closed, 'closed_ub', stats) 280 | 281 | #################### Calculating AUC 282 | scores = predictions['scores'] 283 | # getting score for each ground truth class 284 | correct_scores = scores[torch.arange(scores.shape[0]), pair_truth][unseen_ind] 285 | 286 | # Getting top predicted score for these unseen classes 287 | max_seen_scores = predictions['scores'][unseen_ind][:, self.seen_mask].topk(topk, dim=1)[0][:, topk - 1] 288 | 289 | # Getting difference between these scores 290 | unseen_score_diff = max_seen_scores - correct_scores 291 | 292 | # Getting matched classes at max bias for diff 293 | unseen_matches = stats['closed_unseen_match'].bool() 294 | correct_unseen_score_diff = unseen_score_diff[unseen_matches] - 1e-4 295 | 296 | # sorting these diffs 297 | correct_unseen_score_diff = torch.sort(correct_unseen_score_diff)[0] 298 | magic_binsize = 20 299 | # getting step size for these bias values 300 | bias_skip = max(len(correct_unseen_score_diff) // magic_binsize, 1) 301 | # Getting list 302 | biaslist = correct_unseen_score_diff[::bias_skip] 303 | 304 | seen_match_max = float(stats['closed_seen_match'].mean()) 305 | unseen_match_max = float(stats['closed_unseen_match'].mean()) 306 | closed_unseen_match = stats['closed_unseen_match'] 307 | seen_accuracy, unseen_accuracy = [], [] 308 | 309 | # Go to CPU 310 | base_scores = {k: v.to('cpu') for k, v in allpred.items()} 311 | obj_truth = obj_truth.to('cpu') 312 | 313 | # Gather scores for all relevant (a,o) pairs 314 | base_scores = torch.stack( 315 | [allpred[(attr,obj)] for attr, obj in self.dset.pairs], 1 316 | ) # (Batch, #pairs) 317 | 318 | for bias in biaslist: 319 | scores = base_scores.clone() 320 | results = self.score_fast_model(scores, obj_truth, bias = bias, topk = topk) 321 | del scores 322 | results = results['closed'] # we only need biased 323 | results = _process(results) 324 | seen_match = float(results[3].mean()) 325 | unseen_match = float(results[4].mean()) 326 | seen_accuracy.append(seen_match) 327 | unseen_accuracy.append(unseen_match) 328 | 329 | seen_accuracy.append(seen_match_max) 330 | unseen_accuracy.append(unseen_match_max) 331 | seen_accuracy, unseen_accuracy = np.array(seen_accuracy), np.array(unseen_accuracy) 332 | area = np.trapz(seen_accuracy, unseen_accuracy) 333 | 334 | for key in stats: 335 | stats[key] = float(stats[key].mean()) 336 | 337 | stats['closed_unseen_match_orig'] = closed_unseen_match 338 | 339 | harmonic_mean = hmean([seen_accuracy, unseen_accuracy], axis = 0) 340 | max_hm = np.max(harmonic_mean) 341 | idx = np.argmax(harmonic_mean) 342 | if idx == len(biaslist): 343 | bias_term = 1e3 344 | else: 345 | bias_term = biaslist[idx] 346 | stats['biasterm'] = float(bias_term) 347 | stats['best_unseen'] = np.max(unseen_accuracy) 348 | stats['best_seen'] = np.max(seen_accuracy) 349 | stats['AUC'] = area 350 | stats['hm_unseen'] = unseen_accuracy[idx] 351 | stats['hm_seen'] = seen_accuracy[idx] 352 | stats['best_hm'] = max_hm 353 | stats['unseen_ind'] = unseen_ind 354 | stats['closed_logits'] = predictions['closed_logits'] 355 | return stats -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------