README.md
1: 
2: # QuRe: Query-Relevant Retrieval through Hard Negative Sampling in Composed Image Retrieval [ICML 2025]
3: 
4: Official implementation of **QuRe: Query-Relevant Retrieval through Hard Negative Sampling in Composed Image Retrieval** (*ICML 2025*).  
5: [[Paper Link]](https://arxiv.org/abs/2507.12416)
6: 
7: 
8: ## Python Environment
9: 
10: 
11: The following commands set up a local Anaconda environment and install the required packages:
12: 
13:     conda env create -f environment.yml -n qure
14: 
15: 
16: 
17: ## Prepare Datasets 
18: Before running the code, please download the following datasets:
19: 
20: - [FashionIQ](https://drive.google.com/drive/folders/17WgyAkiTb21y8BdTNJptyfEm4wjk4FPx?usp=drive_link)
21: - [CIRR](https://drive.google.com/drive/folders/17WgyAkiTb21y8BdTNJptyfEm4wjk4FPx?usp=drive_link)
22: - [CIRCO](https://github.com/miccunifi/CIRCO)
23: - [HP-FashionIQ](https://github.com/jackwaky/QuRe/tree/main/HP_FashionIQ)
24: 
25: Once downloaded, update the `base_path` variable in each corresponding file with the local path to the dataset:
26: 
27: - `./data/fashionIQ.py`
28: - `./data/cirr.py`
29: - `./data/circo.py`
30: 
31: For example:
32: ```bash
33: base_path = '/path/to/dataset'
34: ```
35:     
36: 
37: 
38: ## Training
39: 
40: To train the model on FashionIQ and CIRR datasets, use the following commands:
41: 
42: **For FashionIQ:**
43: ```bash
44: python train_qure.py --config_path=configs/fashionIQ/train.json
45: ```
46: 
47: **For CIRR:**
48: ```bash
49: python train_qure.py --config_path=configs/cirr/train.json
50: ```
51: 
52: ## Evaluation
53: 
54: To test the model on FashionIQ, CIRR, and CIRCO datasets, use the following commands:
55: 
56: **For FashionIQ:**
57: ```bash
58: python evaluate_qure/evaluate_fiq.py --config_path=configs/fashionIQ/eval.json
59: ```
60: 
61: **For CIRR:**
62: ```bash
63: python evaluate_qure/evaluate_cirr.py --config_path=configs/cirr/eval.json
64: ```
65: 
66: **For CIRCO:**
67: ```bash
68: python evaluate_qure/evaluate_circo.py --config_path=configs/circo/eval.json
69: ```
70: 
71: ## Checkpoints
72: 
73: We provide pre-trained checkpoints for both the FashionIQ and CIRR datasets.  
74: You can download them from the [link](https://drive.google.com/drive/folders/1tEMZ4wcriZOQZNsXdo5R5IiLOud3ecph?usp=drive_link).
75: 
76: 
77: ## Acknowledgment
78: This code is built on top of the [CoSMo](https://github.com/postBG/CosMo.pytorch) and utilizes [LAVIS](https://github.com/salesforce/LAVIS).
79: We thank the authors for their valuable contribution.
80: 
81: ## Citation
82: 
83: ```bibtex
84: @inproceedings{kwakqure,
85:   title={QuRe: Query-Relevant Retrieval through Hard Negative Sampling in Composed Image Retrieval},
86:   author={Kwak, Jaehyun and Inhar, Ramahdani Muhammad Izaaz and Yun, Se-Young and Lee, Sung-Ju},
87:   booktitle={Forty-second International Conference on Machine Learning}
88: }
89: ```

train_qure.py
1: from options import get_experiment_config
2: from set_up import setup_experiment
3: from transforms import image_transform_factory
4: from data import create_dataloaders
5: from models import create_qure_models
6: import wandb
7: 
8: 
9: import math
10: from tqdm import tqdm
11: import torch
12: import torch.nn.functional as F
13: import os
14: 
15: from evaluate_qure.eval_utils import eval_fiq, eval_cirr
16: 
17: 
18: def main():
19:     configs = get_experiment_config()
20:     export_root, configs = setup_experiment(configs)
21:     device = torch.device(f"cuda:{configs['device_idx']}") if torch.cuda.is_available() else "cpu"
22: 
23:     model, txt_processors = create_qure_models(configs, device)
24: 
25:     image_transform = image_transform_factory(config=configs)
26:     train_dataloader, test_dataloaders = create_dataloaders(image_transform, None, configs)
27: 
28:     optimizer = torch.optim.AdamW(filter(lambda p: p.requires_grad, model.parameters()), lr=configs['init_lr'],
29:                                   weight_decay=configs['weight_decay'])
30: 
31:     max_epochs = configs['epoch']
32: 
33:     model.train()
34:     scaler =  torch.cuda.amp.GradScaler()
35:     for epoch in range(max_epochs):
36:         model.train()
37:         if configs["use_rerank"]:
38:             if (epoch % (max_epochs // configs["negative_definition_epoch_num"])) == 0:
39:                 if not configs['rerank_warmup'] or (epoch != 0 and configs['rerank_warmup']):
40:                     train_dataloader.dataset.rerank_score(model, device, txt_processors, configs, epoch)
41: 
42: 
43:         epoch_running_loss = 0.0
44:         cosine_lr_schedule(optimizer, epoch, max_epochs, configs["init_lr"], configs["init_lr"]/100)
45:         train_dataloader_tqdm = tqdm(train_dataloader, desc="Epoch {}".format(epoch+1))
46:         for batch_idx, (ref_images, tar_images, negative_images, sentences) in enumerate(train_dataloader_tqdm):
47:             optimizer.zero_grad()
48: 
49:             with torch.autocast(device_type='cuda', dtype=torch.float16):
50:                 ref_images, tar_images, negative_images = ref_images.to(device), tar_images.to(
51:                     device), negative_images.to(device)
52: 
53:                 sentences = [txt_processors["eval"](caption) for caption in sentences]
54:                 scores = model(ref_images, tar_images, sentences, negative_images, configs['use_temp'])
55: 
56:                 log_softmax_scores = F.log_softmax(scores, dim=1)  
57: 
58:                 target_probs = torch.zeros_like(log_softmax_scores)
59:                 target_probs[:, 0] = 1.0  # p0 = 1 for each data point
60: 
61:                 loss = F.kl_div(log_softmax_scores, target_probs, reduction='batchmean')
62: 
63:             scaler.scale(loss).backward()
64:             scaler.step(optimizer)
65:             scaler.update()
66: 
67:             epoch_running_loss += loss.item()
68:             cur_loss = epoch_running_loss / (batch_idx + 1)
69:             train_dataloader_tqdm.set_postfix({'loss': cur_loss})
70: 
71:         train_results = {'loss' : cur_loss, 'lr' : get_current_lr(optimizer)}
72:         print(f"[EPOCH {epoch+1}/{max_epochs}] Loss : {train_results['loss']} lr : {train_results['lr']}")
73:         if configs["experiment_description"] != 'debug':
74:             wandb.log({"loss" : cur_loss, "epoch" : epoch})
75:             wandb.log({'lr' : get_current_lr(optimizer), "epoch": epoch})
76:             wandb.log({'k': topk, "epoch": epoch})
77:             if hasattr(model, 'temp'):
78:                 wandb.log({'temp': model.temp.item(), "epoch": epoch})
79: 
80:             if hasattr(model, 'logit_scale'):
81:                 wandb.log({'temp': model.logit_scale.item(), "epoch": epoch})
82: 
83: 
84:         # Save the model for every 10 epochs
85:         # todo: adding evaluation
86:         if (epoch + 1) % 1 == 0:
87:             #Save the model
88:             saving_path = f""
89:             os.makedirs(saving_path, exist_ok=True)
90:             torch.save(model.state_dict(), f'{saving_path}/model.pth')
91:             append_log(f'{saving_path}/log.txt', f"Epoch : {epoch + 1}\n")
92: 
93:         eval_frequency = 1
94:         if (epoch + 1) % eval_frequency == 0:
95:             if configs['dataset'] == 'fashionIQ':
96:                 eval_fiq(model, txt_processors, test_dataloaders, epoch, configs)
97: 
98:             elif configs['dataset'] == 'cirr':
99:                 eval_cirr(model, txt_processors, test_dataloaders, epoch, configs)
100: 
101: def cosine_lr_schedule(optimizer, epoch, max_epoch, init_lr, min_lr):
102:     """Decay the learning rate"""
103:     lr = (init_lr - min_lr) * 0.5 * (1. + math.cos(math.pi * epoch / max_epoch)) + min_lr
104:     for param_group in optimizer.param_groups:
105:         param_group['lr'] = lr
106: 
107: def get_current_lr(optimizer):
108:     for param_group in optimizer.param_groups:
109:         return param_group['lr']
110: 
111: def append_log(file_path, log_message):
112:     with open(file_path, 'a') as file:
113:         file.write(log_message + '\n')
114: 
115: if __name__ == '__main__':
116:     main()

HP_FashionIQ/README.md
1: # Human-Prefernce FashionIQ (HP-FashionIQ) dataset
2: 
3: The commonly used evaluation metric, **Recall@k**, fails to fully capture user satisfaction. While user satisfaction generally increases as more relevant items are retrieved, Recall@k only verifies whether a specific target image appears—ignoring the relevance of other retrieved results.
4: 
5: Evaluating image relevance in **Composed Image Retrieval (CIR)** is especially challenging, as it requires assessing how well each image aligns with both textual and visual inputs. This often involves subtle and complex attribute matching. Human evaluation remains the most reliable method for this task, as humans can accurately judge how well an image satisfies a multi-modal query.
6: 
7: To support this evaluation, we introduce the **Human-Preference FashionIQ (HP-FashionIQ)** dataset, built from the validation set of the [FashionIQ dataset](https://drive.google.com/drive/folders/17WgyAkiTb21y8BdTNJptyfEm4wjk4FPx?usp=drive_link), with human annotations from 61 participants. FashionIQ was selected for its detailed attribute supervision and alignment with real-world e-commerce search behaviors.
8: 
9: For more information, see **Section 4** and **Appendix C** of our paper.
10: 
11: ## Preparation
12: 
13: 1. Download and set up the [FashionIQ dataset](https://drive.google.com/drive/folders/17WgyAkiTb21y8BdTNJptyfEm4wjk4FPx?usp=drive_link).
14: 2. Replace all instances of `"-"` in the `hpfiq.json` file with the absolute path to your FashionIQ dataset directory.
15: 3. Modify the `load_model` and `get_score_of_image` functions in `evaluate.py` to use your own model and scoring method.
16: 
17: ## Preference Ratio
18: 
19: To evaluate how well a CIR model aligns with human preferences, we define the following metric:
20: 
21: $$\mathbb{P}(A \succ B \mid s_{\text{rel}}(A) > s_{\text{rel}}(B))$$
22: 
23: This represents the probability that set **A** is preferred over set **B** by humans, given that the model assigns a higher relevance score to **A** than to **B**.
24: 
25: 
26: ## Run
27: 
28: To compute the preference ratio for a CIR model:
29: 
30: ```bash
31: python -m evaluate --config_path=../configs/fashionIQ/eval.json
32: ```
33: 
34: This will evaluate how closely your model’s relevance scores align with human preferences in the HP-FashionIQ dataset.

HP_FashionIQ/evaluate.py
1: import os
2: import sys
3: import json
4: import torch
5: import PIL
6: import PIL.Image
7: from torch.utils.data import DataLoader
8: 
9: parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))
10: sys.path.append(parent_dir)
11: 
12: from options import get_experiment_config
13: from set_up import setup_experiment
14: from transforms import image_transform_factory
15: from models import create_qure_models
16: from data.utils import targetpad_transform
17: 
18: def load_model():
19:     # Load configuration
20:     configs = get_experiment_config()
21:     export_root, configs = setup_experiment(configs)
22:     device = torch.device(f"cuda:{configs['device_idx']}") if torch.cuda.is_available() else "cpu"
23:     
24:     # Create model
25:     model, txt_processors = create_qure_models(configs, device)
26:     
27:     # Load pretrained weights
28:     MS_pretrained_path = configs["pretrained_path"]
29:     msg = model.load_state_dict(torch.load(f'{MS_pretrained_path}/model.pth', map_location=device), strict=False)
30:     model.to(device)
31:     model.eval()
32:     
33:     print(f"Loaded Finetuned QuRe models : {msg}")
34:     return model, txt_processors, device, configs
35: 
36: 
37: 
38: def get_score_of_image(model, txt_processors, sentence, query_image_path, retrieved_image_paths, config, device):
39:     target_ratio = 1.25
40:     preprocess = targetpad_transform(target_ratio, config['img_size'])
41: 
42:     score = []
43:     query_image = preprocess(PIL.Image.open(query_image_path))
44: 
45:     # query_image = query_image.to(device)
46:     query_dataloader = DataLoader([(query_image, sentence, 'None')], batch_size=1, shuffle=False)
47: 
48:     # Query Feature
49:     predicted_features, target_names = model.extract_query_features_fiq(
50:         query_dataloader, config['use_temp'], txt_processors, device)
51: 
52:     retrieved_image_list = []
53:     for retrieve_image_path in retrieved_image_paths:
54:         retrieve_image = preprocess(PIL.Image.open(retrieve_image_path))
55:         # retrieve_image = retrieve_image.to(device)
56:         retrieved_image_list.append((retrieve_image, 'None'))
57:     #todo: get scores with batch size 5 and average it
58:     image_dataloader = DataLoader(retrieved_image_list, batch_size=5, shuffle=False)
59:     # Target Feature
60:     index_features, index_names = model.extract_target_features(image_dataloader,
61:                                                                 config['use_temp'], device)
62: 
63: 
64:     cur_score = model.score(predicted_features, index_features)
65:     # score.append(cur_score.item())
66: 
67:     averaged_score = torch.mean(cur_score).item()
68: 
69:     return averaged_score
70: 
71: def evaluate_preference_ratio(model_list_1, model_list_2, preferred_set):
72:     assert len(model_list_1) == len(model_list_2) == len(preferred_set)
73: 
74:     conditioned_total = 0
75:     preferred_count = 0
76:     
77:     for m1, m2, p in zip(model_list_1, model_list_2, preferred_set):
78:         if m1 > m2:
79:             conditioned_total += 1
80:             if p == '1':
81:                 preferred_count += 1
82:                 
83:     if conditioned_total == 0:
84:         return 0.0  # or np.nan
85:     
86:     return preferred_count / conditioned_total
87:             
88: 
89: def main():
90:     # Load configuration
91:     
92:     # Load model
93:     model, txt_processors, device, configs = load_model()
94:     
95:     # Load hpfiq.json
96:     with open('hpfiq.json', 'r') as f:
97:         hpfiq_data = json.load(f)
98:     
99:     # Extract model scores and user scores
100:     model_list_1, model_list_2, preferred_list = [], [], []
101:     for user_id, cur_user_data in hpfiq_data.items():
102:         for question_id, cur_question_data in cur_user_data.items():
103:             ref_img_paths = cur_question_data['ref_img_paths']
104:             sentences = cur_question_data['sentences']
105:             retrieved_set1 = cur_question_data['retrieved_set1']
106:             retrieved_set2 = cur_question_data['retrieved_set2']
107:             preferred_set = cur_question_data['preferred set']
108:             for cur_ref_img_path, cur_ref_text, cur_retrieved_set1, cur_retrieved_set2, cur_preferred_set in zip(ref_img_paths, sentences, retrieved_set1, retrieved_set2, preferred_set):
109: 
110:                 _cur_retrieved_set1 = cur_retrieved_set1['img_path']
111:                 _cur_retrieved_set2 = cur_retrieved_set2['img_path']
112: 
113:                 set1_model_score = get_score_of_image(model, txt_processors, cur_ref_text, cur_ref_img_path, _cur_retrieved_set1, configs, device)
114:                 set2_model_score = get_score_of_image(model, txt_processors, cur_ref_text, cur_ref_img_path, _cur_retrieved_set2, configs, device)
115:     
116: 
117:                 model_list_1.append(set1_model_score)
118:                 model_list_2.append(set2_model_score)
119:                 preferred_list.append(cur_preferred_set)
120: 
121:                 
122:     # todo: you can save the scores for efficiency
123: 
124:     # Evaluation
125:     # Extract Preference Ratio
126:     preference_ratio = evaluate_preference_ratio(model_list_1, model_list_2, preferred_list)
127:     print(f"Preference Ratio : {preference_ratio}")
128: 
129: if __name__ == "__main__":
130:     main()

data/fashionIQ.py
1: import copy
2: import json
3: import numpy as np
4: import os
5: import random
6: from tqdm import tqdm
7: from typing import List
8: from pathlib import Path
9: import wandb
10: import math
11: 
12: from torch.utils.data import Dataset, DataLoader
13: from data.utils import targetpad_transform, _get_img_from_path
14: from data.abc import AbstractBaseDataset
15: from data.collate_fns import BLIPPaddingCollateFunctionTest4FIQ
16: import torch
17: from torch.nn import functional as F
18: 
19: import PIL
20: import PIL.Image
21: 
22: 
23: base_path = '-'
24: target_ratio = 1.25
25: 
26: class FashionIQDataset(Dataset):
27:     """
28:     FashionIQ dataset class which manage FashionIQ data.
29:     The dataset can be used in 'relative' or 'classic' mode:
30:         - In 'classic' mode the dataset yield tuples made of (image_name, image)
31:         - In 'relative' mode the dataset yield tuples made of:
32:             - (reference_image, target_image, image_captions) when split == train
33:             - (reference_name, target_name, image_captions) when split == val
34:             - (reference_name, reference_image, image_captions) when split == test
35:     The dataset manage an arbitrary numbers of FashionIQ category, e.g. only dress, dress+toptee+shirt, dress+shirt...
36:     """
37: 
38:     def __init__(self, split, dress_types, mode, preprocess: callable, config):
39:         """
40:         :param split: dataset split, should be in ['test', 'train', 'val']
41:         :param dress_types: list of fashionIQ category
42:         :param mode: dataset mode, should be in ['relative', 'classic']:
43:             - In 'classic' mode the dataset yield tuples made of (image_name, image)
44:             - In 'relative' mode the dataset yield tuples made of:
45:                 - (reference_image, target_image, image_captions) when split == train
46:                 - (reference_name, target_name, image_captions) when split == val
47:                 - (reference_name, reference_image, image_captions) when split == test
48:         :param preprocess: function which preprocesses the image
49:         """
50:         self.preprocess = targetpad_transform(target_ratio, config['img_size'])
51:         # self.preprocess = image_transform(config, split)
52:         self.mode = mode
53:         self.split = split
54:         self.config = config
55:         self.dress_types = dress_types
56:         self.negative = 'random'
57: 
58:         if mode not in ['relative', 'classic']:
59:             raise ValueError("mode should be in ['relative', 'classic']")
60:         if split not in ['test', 'train', 'val']:
61:             raise ValueError("split should be in ['test', 'train', 'val']")
62:         for dress_type in dress_types:
63:             if dress_type not in ['dress', 'shirt', 'toptee']:
64:                 raise ValueError("dress_type should be in ['dress', 'shirt', 'toptee']")
65: 
66:         # get triplets made by (reference_image, target_image, a pair of relative captions)
67:         self.triplets: List[dict] = []
68:         self.domain_triplets = dict()
69:         self.dress_type_indices_relative = dict()
70:         for dress_type in dress_types:
71:             with open(base_path /  'captions' / f'cap.{dress_type}.{split}.json') as f:
72:                 triplets = json.load(f)
73: 
74:                 start_idx = len(self.triplets)
75:                 for triplet in triplets:
76:                     triplet['dress_type'] = dress_type
77:                 self.triplets.extend(triplets)
78:                 end_idx = len(self.triplets)
79:                 self.dress_type_indices_relative[dress_type] = list(range(start_idx, end_idx))
80: 
81:                 self.domain_triplets[dress_type] = triplets
82: 
83:         # get the image names
84:         self.domain_image_names = dict()
85:         self.image_names: list = []
86:         self.dress_type_indices_classic = dict()
87:         for dress_type in dress_types:
88:             with open(base_path / 'image_splits' / f'split.{dress_type}.{split}.json') as f:
89:                 images = json.load(f)
90:                 start_idx = len(self.image_names)
91:                 self.image_names.extend(images)
92:                 end_idx = len(self.image_names)
93:                 self.dress_type_indices_classic[dress_type] = list(range(start_idx, end_idx))
94:                 self.domain_image_names[dress_type] = images
95: 
96:         self.hard_images = []
97: 
98:         print(f"FashionIQ {split} - {dress_types} dataset in {mode} mode initialized")
99: 
100:     def __getitem__(self, index):
101:         try:
102:             if self.mode == 'relative':
103:                 image_captions = self.triplets[index]['captions']
104:                 reference_name = self.triplets[index]['candidate']
105:                 rel_caption = image_captions[0].strip('.?, ').capitalize() + " and " + image_captions[1].strip('.?, ')
106:                 # rel_caption = caption_post_process(rel_caption)
107: 
108:                 if self.split == 'train':
109:                     reference_image_path = base_path / 'images' / f"{reference_name}.png"
110:                     reference_image = self.preprocess(PIL.Image.open(reference_image_path))
111:                     # reference_image = _get_img_from_path(reference_image_path, self.preprocess)
112:                     target_name = self.triplets[index]['target']
113:                     target_image_path = base_path / 'images' / f"{target_name}.png"
114:                     target_image = self.preprocess(PIL.Image.open(target_image_path))
115:                     # target_image = _get_img_from_path(target_image_path, self.preprocess)
116: 
117:                     cur_dress_type = self.triplets[index]['dress_type']
118:                     # self.non_target_pool = self.domain_image_names[cur_dress_type]
119:                     self.non_target_pool = [triplet['target'] for triplet in self.domain_triplets[cur_dress_type]]
120: 
121:                     if self.negative == 'random': # random negative sampling
122:                         cur_non_target_pool = [name for name in self.non_target_pool if name != target_name]
123:                         negative_name = random.choice(cur_non_target_pool) # Sample from Target pool (!= target)
124:                         negative_targ_img_path = base_path / 'images' / f"{negative_name}.png"
125:                         negative_target_img = self.preprocess(PIL.Image.open(negative_targ_img_path))
126:                         # negative_target_img = _get_img_from_path(negative_targ_img_path, self.preprocess)
127:                     elif self.negative == 'random_rerank': # hard negative sampling after reranking
128:                         if index not in self.negative_selection_history:
129:                             self.negative_selection_history[index] = []
130: 
131:                         if len(self.hard_images[index]) == len(self.negative_selection_history[index]):
132:                             self.negative_selection_history[index] = []
133: 
134:                         while True:
135:                             negative_name = random.choice(self.hard_images[index])
136:                             if negative_name not in self.negative_selection_history[index]:
137:                                 break  # Stop resampling once a unique negative is found
138:                         # negative_name = random.choice(self.hard_images[index])
139:                         negative_targ_img_path = base_path / 'images' / f"{negative_name}.png"
140:                         negative_target_img = self.preprocess(PIL.Image.open(negative_targ_img_path))
141: 
142:                         self.negative_selection_history[index].append(negative_name)
143: 
144:                     # elif self.negative == 'rerank':
145:                     #     negative_target_img = []
146:                     #     for negative_name in self.hard_images[index]:
147:                     #         negative_targ_img_path = base_path / 'images' / f"{negative_name}.png"
148:                     #         negative_target_img_ = self.preprocess(PIL.Image.open(negative_targ_img_path))
149:                     #         negative_target_img.append(negative_target_img_)
150:                     #     # negative_target_img = torch.stack(negative_target_img, dim=0)
151:                     else:
152:                         raise ValueError("Undefined Negative Sampling Method")
153: 
154:                     return reference_image, target_image, negative_target_img, target_name, rel_caption
155: 
156:                 elif self.split == 'val':
157:                     reference_image_path = base_path / 'images' / f"{reference_name}.png"
158:                     reference_image = self.preprocess(PIL.Image.open(reference_image_path))
159:                     # reference_image = _get_img_from_path(reference_image_path, self.preprocess)
160:                     target_name = self.triplets[index]['target']
161:                     return reference_image, rel_caption, target_name
162: 
163:                 elif self.split == 'test':
164:                     reference_image_path = base_path / 'images' / f"{reference_name}.png"
165:                     reference_image = self.preprocess(PIL.Image.open(reference_image_path))
166:                     return reference_name, reference_image, rel_caption
167: 
168:             elif self.mode == 'classic':
169:                 image_name = self.image_names[index]
170:                 image_path = base_path / 'images' / f"{image_name}.png"
171:                 image = self.preprocess(PIL.Image.open(image_path))
172:                 # image = _get_img_from_path(image_path, self.preprocess)
173:                 return image, image_name
174: 
175:             else:
176:                 raise ValueError("mode should be in ['relative', 'classic']")
177:         except Exception as e:
178:             print(f"Exception: {e}")
179: 
180:     def __len__(self):
181:         if self.mode == 'relative':
182:             return len(self.triplets)
183:         elif self.mode == 'classic':
184:             return len(self.image_names)
185:         else:
186:             raise ValueError("mode should be in ['relative', 'classic']")
187: 
188:     @torch.no_grad()
189:     def rerank_score(self, model, device, txt_processors, configs, epoch):
190:         self.negative_selection_history = dict()
191:         self.negative = configs['negative']
192:         self.hard_images = []
193:         model.eval()
194: 
195:         sample_dataloader = self.get_sample_loader()
196:         query_dataloader = self.get_query_loader()
197: 
198:         predicted_features, _ = model.extract_query_features_fiq(query_dataloader, configs['use_temp'], txt_processors, device)
199:         index_features, index_names = model.extract_target_features(sample_dataloader, configs['use_temp'], device)
200: 
201:         scores = model.score(predicted_features, index_features)
202: 
203:         for index in tqdm(range(len(self.triplets)), desc=f"Reranking with score and image similarity"):
204:             image_captions = self.triplets[index]['captions']
205:             reference_name = self.triplets[index]['candidate']
206:             target_name = self.triplets[index]['target']
207:             cur_dress_type = self.triplets[index]['dress_type']
208: 
209:             cur_query_scores = scores[index]
210:             cur_query_cur_dress_type_scores = cur_query_scores[self.dress_type_indices_relative[cur_dress_type]]
211:             cur_query_score_sorted_indices = torch.argsort(cur_query_cur_dress_type_scores, dim=-1,
212:                                                            descending=True).cpu()
213:             
214:             cur_dress_type_target_images = [triplet['target'] for triplet in self.domain_triplets[cur_dress_type]]
215:             # cur_dress_type_target_images = [image for image in self.domain_image_names[cur_dress_type]]
216:             target_index = cur_dress_type_target_images.index(target_name)
217:             sorted_indices = [i for i in cur_query_score_sorted_indices.tolist()]
218:             target_sorted_index = sorted_indices.index(target_index)
219: 
220:             score_list = cur_query_cur_dress_type_scores[cur_query_score_sorted_indices]
221:             y = np.array(score_list)
222: 
223:             start_index = target_sorted_index + 1
224:             scores_after_target = y[start_index:]
225: 
226:             # Step 1: Compute differences
227:             differences = np.diff(scores_after_target)  # Differences between consecutive elements
228:             # Sort indices by difference values (ascending order)
229:             diff_sorted_indices = np.argsort(differences)
230: 
231:             idx = 0
232:             while idx < len(diff_sorted_indices) - 1:
233:                 idx1 = diff_sorted_indices[idx]
234:                 idx2 = diff_sorted_indices[idx + 1]
235: 
236:                 if idx1 > idx2:
237:                     idx1, idx2 = idx2, idx1
238:                 if idx2 - idx1 > configs["consecutive_threshold"]:
239:                     # Get the largest and second-largest drop indices
240:                     start_of_hard_negatives = idx1 + start_index
241:                     end_of_hard_negatives = idx2 + start_index
242:                     break
243:                 else:
244:                     idx += 1
245:                     # diff_sorted_indices = [idx_ for idx_ in diff_sorted_indices if idx_ > idx2]
246: 
247:             # Negative set : start_of_false_negatives + 1 ~ end_of_false_negatives
248:             top_k_score_indices = [i for i in cur_query_score_sorted_indices.tolist()][start_of_hard_negatives + 1:end_of_hard_negatives + 1]
249: 
250:             if len(top_k_score_indices) == 0:
251:                 assert 0, "Empty negative set is defined"
252: 
253: 
254:             if len(top_k_score_indices) != 0:
255:                 cur_dress_type_target_images = [triplet['target'] for triplet in self.domain_triplets[cur_dress_type]]
256:                 # cur_dress_type_target_images = [image for image in self.domain_image_names[cur_dress_type]]
257:                 topk_image_names = list(set([cur_dress_type_target_images[i] for i in top_k_score_indices if cur_dress_type_target_images[i] != target_name]))
258:             else:
259:                 assert 0, "Empty negative set is defined"
260:             self.hard_images.append(topk_image_names)
261: 
262:         if configs["experiment_description"] != 'debug':
263:             sizes = [len(sublist) for sublist in self.hard_images]
264:             average_size_negative_set = sum(sizes) / len(sizes)
265:             variance = sum((size - average_size_negative_set) ** 2 for size in sizes) / len(sizes)
266:             std_dev = math.sqrt(variance)
267: 
268:             wandb.log({'average size of negative set': average_size_negative_set, "epoch": epoch})
269:             wandb.log({'std of negative set size': std_dev, "epoch": epoch})
270: 
271:         model.train()
272:         print("Done\n")
273: 
274:     def get_sample_loader(self):
275:         image_corpus = [triplet['target'] for triplet in self.triplets]
276:         # image_corpus = [image for image in self.image_names]
277:         sample_dataset = FashionIQSampleDataset(base_path, image_corpus, self.preprocess)
278:         collate_fn = BLIPPaddingCollateFunctionTest4FIQ()
279:         sample_dataloader = DataLoader(sample_dataset, batch_size=64, shuffle=False, num_workers=16, pin_memory=True, collate_fn=collate_fn)
280: 
281:         return sample_dataloader
282:     def get_query_loader(self):
283:         query_dataset = FashionIQQueryDataset(base_path, self.triplets, self.preprocess)
284:         collate_fn = BLIPPaddingCollateFunctionTest4FIQ()
285:         query_dataloader = DataLoader(query_dataset, batch_size=64, shuffle=False, num_workers=16, pin_memory=True, collate_fn=collate_fn)
286: 
287:         return query_dataloader
288: 
289:     @classmethod
290:     def code(cls):
291:         return 'fashionIQ'
292: 
293:     @classmethod
294:     def all_codes(cls):
295:         return ['fashionIQ']
296:     
297:     @classmethod
298:     def all_subset_codes(cls):
299:         return ['dress', 'shirt', 'toptee']
300: 
301:     @classmethod
302:     def vocab_path(cls):
303:         return None
304:         
305: class FashionIQSampleDataset(Dataset):
306:     def __init__(self, base_path, image_names, preprocess):
307:         self.base_path = base_path
308:         self._image_names = image_names
309:         self.preprocess = preprocess
310: 
311:     def __len__(self):
312:         return len(self._image_names)
313: 
314:     def __getitem__(self, idx):
315:         image_name = self._image_names[idx]
316:         image_path = base_path / 'images' / f"{image_name}.png"
317:         im = PIL.Image.open(image_path)
318:         image = self.preprocess(im)
319: 
320:         return image, image_name
321: 
322: 
323: class FashionIQQueryDataset(Dataset):
324:     def __init__(self, base_path, triplets, preprocess):
325:         self.base_path = base_path
326:         self._triplets = triplets
327:         self.preprocess = preprocess
328: 
329:     def __len__(self):
330:         return len(self._triplets)
331: 
332:     def __getitem__(self, index):
333:         reference_name = self._triplets[index]['candidate']
334:         target_name = self._triplets[index]['target']
335:         image_captions = self._triplets[index]['captions']
336: 
337:         reference_image_path = base_path / 'images' / f"{reference_name}.png"
338:         reference_image = self.preprocess(PIL.Image.open(reference_image_path))
339:         # rel_caption = image_captions[0] + " and " + image_captions[1]
340:         rel_caption = f"{image_captions[0].strip('.?, ').capitalize()} and {image_captions[1].strip('.?, ')}"
341: 
342:         return target_name, reference_image, rel_caption
343: 
344: 
345: 
346: 
347: 
348: ##############################################################
349: ############## For User Suvery Generation ####################
350: ##############################################################
351: 
352: def _get_img_caption_json(dataset_root, clothing_type, split):
353:     with open(os.path.join(dataset_root, 'captions', 'cap.{}.{}.json'.format(clothing_type, split))) as json_file:
354:         img_caption_data = json.load(json_file)
355:     return img_caption_data
356: 
357: def _get_img_caption_txt(dataset_root, clothing_type, split, config):
358:     with open(os.path.join(dataset_root, 'captions_pairs', 'fashion_iq-{}-cap-{}.txt'.format(split, clothing_type))) as f:
359:         file_content = f.readlines()
360:     return file_content
361: 
362: def _get_img_split_json_as_list(dataset_root, clothing_type, split):
363:     with open(os.path.join(dataset_root, 'image_splits', 'split.{}.{}.json'.format(clothing_type, split))) as json_file:
364:         img_split_list = json.load(json_file)
365:     return img_split_list
366: 
367: def _create_img_path_from_id(root, id):
368:     return os.path.join(root, '{}.jpg'.format(id))
369: 
370: def _get_img_path_using_idx(img_caption_data, img_root, idx, is_ref=True):
371:     img_caption_pair = img_caption_data[idx]
372:     key = 'candidate' if is_ref else 'target'
373: 
374:     img = _create_img_path_from_id(img_root, img_caption_pair[key])
375:     id = img_caption_pair[key]
376:     return img, id
377: 
378: def _get_modifier(img_caption_data, idx, reverse=False):
379:     img_caption_pair = img_caption_data[idx]
380:     cap1, cap2 = img_caption_pair['captions']
381:     return _create_modifier_from_attributes(cap1, cap2) if not reverse else _create_modifier_from_attributes(cap2, cap1)
382: 
383: def _cat_captions(caps):
384:     I = []
385:     for i in range(len(caps)):
386:         if i % 2 == 0:
387:             I.append(_create_modifier_from_attributes(caps[i], caps[i+1]))
388:         else:
389:             I.append(_create_modifier_from_attributes(caps[i], caps[i-1]))
390:     return I
391: 
392: def _create_modifier_from_attributes(ref_attribute, targ_attribute):
393:     return ref_attribute + " and " + targ_attribute
394: 
395: def caption_post_process(s):
396:     return s.strip().replace('.', 'dotmark').replace('?', 'questionmark').replace('&', 'andmark').replace('*', 'starmark')
397: 
398: class AbstractBaseFashionIQDataset(AbstractBaseDataset):
399: 
400:     @classmethod
401:     def code(cls):
402:         return 'fashionIQ'
403: 
404:     @classmethod
405:     def all_codes(cls):
406:         return ['fashionIQ']
407:     
408:     @classmethod
409:     def all_subset_codes(cls):
410:         return ['dress', 'shirt', 'toptee']
411:     
412:     @classmethod
413:     def vocab_path(cls):
414:         return _DEFAULT_FASHION_IQ_VOCAB_PATH
415:     
416: 
417: class FashionIQUserSurveyDataset(AbstractBaseFashionIQDataset):
418:     """
419:     Fashion200K dataset.
420:     Image pairs in {root_path}/image_pairs/{split}_pairs.pkl
421: 
422:     """
423: 
424:     def __init__(self, root_path=base_path, clothing_type='dress', split='train',
425:                  img_transform=None, id_transform=None, config=None):
426:         super().__init__(root_path, split, img_transform)
427:         self.root_path = root_path
428:         self.img_root_path = os.path.join(self.root_path, 'image_data')
429:         self.clothing_type = clothing_type
430:         self.split = split
431:         self.img_transform = img_transform
432:         self.id_transform = id_transform
433:         self.img_caption_data = _get_img_caption_txt(root_path, clothing_type, split, config)
434:         self.ref_img_path = np.array([ff.strip().split(';')[0] for ff in self.img_caption_data])
435:         self.targ_img_path = np.array([ff.strip().split(';')[1] for ff in self.img_caption_data])
436:         self.caps = [ff.strip('\n').split(';')[-1] for ff in self.img_caption_data]
437:         self.caps_cat = _cat_captions(self.caps)
438:         self.config = config
439: 
440: 
441:     def __getitem__(self, idx):
442: 
443:         ref_img_path = os.path.join(self.img_root_path, self.ref_img_path[idx])
444:         targ_img_path = os.path.join(self.img_root_path, self.targ_img_path[idx])
445:         reference_img = _get_img_from_path(ref_img_path, self.img_transform)
446:         target_img = _get_img_from_path(targ_img_path, self.img_transform)
447: 
448: 
449:         sentences = self.caps_cat[idx]
450:         sentences = caption_post_process(sentences)
451:         # modifier = self.text_transform(sentences) if self.text_transform else sentences
452: 
453:         ref_id = self.ref_img_path[idx].split('/')[-1].split('.')[0]
454:         targ_id = self.targ_img_path[idx].split('/')[-1].split('.')[0]
455: 
456:         if self.id_transform:
457:             ref_id = self.id_transform(ref_id)
458:             targ_id = self.id_transform(targ_id)
459: 
460: 
461:         return reference_img, ref_img_path, target_img, targ_img_path, targ_id, sentences
462: 
463:     def __len__(self):
464:         return len(self.img_caption_data)# * 2
465: 
466: 
467: class FashionIQUserSurveyTestSampleDataset(AbstractBaseFashionIQDataset):
468:     """
469:     FashionIQ Test (Samples) dataset.
470:     indexing returns target samples and their unique ID
471:     """
472: 
473:     def __init__(self, root_path=base_path, clothing_type='dress', split='val',
474:                  img_transform=None, config=None):
475:         super().__init__(root_path, split, img_transform)
476:         self.root_path = root_path
477:         self.img_root_path = os.path.join(self.root_path, 'image_data')
478:         self.clothing_type = clothing_type
479:         self.img_transform = img_transform
480: 
481:         #self.img_list = _get_img_split_json_as_list(root_path, clothing_type, split)
482: 
483:         ''' Uncomment below for VAL Evaluation method '''
484:         self.img_caption_data = _get_img_caption_txt(root_path, clothing_type, split, config)
485:         self.img_list = []
486:         for d in self.img_caption_data:
487:             ref = d.split(';')[0].split('/')[-1].split('.')[0] #dress/xxx.jpg --> xxx
488:             targ = d.split(';')[1].split('/')[-1].split('.')[0] #dress/xxx.jpg --> xxx
489:             self.img_list.append(ref)
490:             self.img_list.append(targ)
491:         self.img_list = list(set(self.img_list))
492: 
493:     def __getitem__(self, idx, use_transform=True):
494:         img_transform = self.img_transform if use_transform else None
495:         img_id = self.img_list[idx]
496:         img_path = _create_img_path_from_id(os.path.join(self.img_root_path,self.clothing_type), img_id)
497: 
498:         target_img = _get_img_from_path(img_path, img_transform)
499: 
500:         return target_img, img_path, img_id
501: 
502:     def __len__(self):
503:         return len(self.img_list)

data/cirr.py
121:                     pair_id = self.triplets[index]['pairid']
122:                     return reference_name, reference_image, rel_caption, pair_id, group_members
123: 
124:             elif self.mode == 'classic':
125:                 image_name = list(self.name_to_relpath.keys())[index]
126:                 image_path = os.path.join(base_path, self.name_to_relpath[image_name])
127:                 im = PIL.Image.open(image_path)
128:                 image = self.preprocess(im)
129: 
130:                 # # This is only used for User survey generation
131:                 # if self.split == 'val':
132:                 #     return image, image_path, image_name
133:                 return image, image_name
134: 
135:             else:
136:                 raise ValueError("mode should be in ['relative', 'classic']")
137: 
138:         except Exception as e:
139:             print(f"Exception: {e}")
140: 
141:     def __len__(self):
142:         if self.mode == 'relative':
143:             return len(self.triplets)
144:         elif self.mode == 'classic':
145:             return len(self.name_to_relpath)
146:         else:
147:             raise ValueError("mode should be in ['relative', 'classic']")
148:         
149:     @torch.no_grad()
150:     def rerank_score(self, model, device, txt_processors, configs, epoch):
151:         self.negative = configs["negative"]
152:         self.negative_selection_history = dict()
153:         self.hard_images = []
154:         model.eval()
155: 
156:         sample_dataloader = self.get_sample_loader()
157:         query_dataloader = self.get_query_loader()
158: 
159:         index_features, index_names = model.extract_target_features(sample_dataloader, configs['use_temp'], device)
160:         predicted_features, _, _, _ = model.extract_query_features_cirr(query_dataloader, configs['use_temp'], txt_processors, device)
161: 
162:         scores = model.score(predicted_features, index_features)
163:         score_sorted_indices = torch.argsort(scores, dim=-1, descending=True).cpu()
164: 
165:         for index in tqdm(range(len(self.triplets)), desc=f"Reranking with score and image similarity"):
166:             target_hard_name = self.triplets[index]['target_hard']
167:             # target_index = self.image_names.index(target_hard_name)
168: 
169:             # Compute Score (it consider not only the image, but also text)
170:             cur_query_score_sorted_indices = score_sorted_indices[index]
171:             cur_query_score = scores[index]
172:             
173:             target_index = self.image_names.index(target_hard_name)
174:             sorted_indices = [i for i in cur_query_score_sorted_indices.tolist()]
175:             target_sorted_index = sorted_indices.index(target_index)
176: 
177:             score_list = cur_query_score[cur_query_score_sorted_indices]
178:             y = np.array(score_list)
179: 
180:             start_index = target_sorted_index + 1
181:             scores_after_target = y[start_index:]
182: 
183:             # Step 1: Compute differences
184:             differences = np.diff(scores_after_target)  # Differences between consecutive elements
185:             # Sort indices by difference values (ascending order)
186:             diff_sorted_indices = np.argsort(differences)
187: 
188:             idx = 0
189:             while idx < len(diff_sorted_indices) - 1:
190:                 idx1 = diff_sorted_indices[idx]
191:                 idx2 = diff_sorted_indices[idx + 1]
192: 
193:                 if idx1 > idx2:
194:                     idx1, idx2 = idx2, idx1
195:                 if idx2 - idx1 > configs["consecutive_threshold"]:
196:                     # Get the largest and second-largest drop indices
197:                     start_of_hard_negatives = idx1 + start_index
198:                     end_of_hard_negatives = idx2 + start_index
199:                     break
200:                 else:
201:                     idx += 1
202: 
203: 
204:             top_k_score_indices = [i for i in cur_query_score_sorted_indices.tolist()][
205:                                     start_of_hard_negatives + 1:end_of_hard_negatives + 1]
206: 
207:             if len(top_k_score_indices) == 0:
208:                 assert 0, "Empty negative set is defined"
209: 
210:             # wandb.log({"query_idx" : index, "number_of_hard_images" : len(top_k_score_indices)})
211:             topk_image_names = list(set([self.image_names[i] for i in top_k_score_indices if self.image_names[i] != target_hard_name]))
212:             self.hard_images.append(topk_image_names)
213: 
214: 
215:         if configs["experiment_description"] != 'debug':
216:             average_size_negative_set = sum(len(sublist) for sublist in self.hard_images) / len(self.hard_images)
217:             wandb.log({'average size of negative set': average_size_negative_set, "epoch": epoch})
218: 
219:         model.train()
220:         print("Done\n")
221: 
222:     def get_sample_loader(self):
223:         sample_dataset = CIRRSampleDataset(base_path, self.image_names, self.name_to_relpath, self.preprocess)
224:         collate_fn = BLIPPaddingCollateFunctionTest4CIRR()
225:         sample_dataloader = DataLoader(sample_dataset, batch_size=64, shuffle=False, num_workers=16, pin_memory=True, collate_fn=collate_fn)
226: 
227:         return sample_dataloader
228:     def get_query_loader(self):
229:         query_dataset = CIRRQueryDataset(base_path, self.triplets, self.name_to_relpath, self.preprocess)
230:         collate_fn = BLIPPaddingCollateFunctionTest4CIRR()
231:         query_dataloader = DataLoader(query_dataset, batch_size=64, shuffle=False, num_workers=16, pin_memory=True, collate_fn=collate_fn)
232: 
233:         return query_dataloader
234:     @classmethod
235:     def code(cls):
236:         return 'cirr'
237: 
238:     @classmethod
239:     def all_codes(cls):
240:         return ['cirr']
241: 
242:     @classmethod
243:     def vocab_path(cls):
244:         return None
245: 
246: class CIRRSampleDataset(Dataset):
247:     def __init__(self, base_path, image_names, name_to_relpath, preprocess):
248:         self.base_path = base_path
249:         self._image_names = image_names
250:         self._name_to_relpath = name_to_relpath
251:         self.preprocess = preprocess
252: 
253:     def __len__(self):
254:         return len(self._image_names)
255: 
256:     def __getitem__(self, idx):
257:         image_name = self._image_names[idx]
258:         image_path = os.path.join(self.base_path, self._name_to_relpath[image_name])
259:         im = PIL.Image.open(image_path)
260:         image = self.preprocess(im)
261: 
262:         return image, image_name
263: 
264: 
265: class CIRRQueryDataset(Dataset):
266:     def __init__(self, base_path, triplets, name_to_relpath, preprocess):
267:         self.base_path = base_path
268:         self._triplets = triplets
269:         self._name_to_relpath = name_to_relpath
270:         self.preprocess = preprocess
271: 
272:     def __len__(self):
273:         return len(self._triplets)
274: 
275:     def __getitem__(self, index):
276:         group_members = self._triplets[index]['img_set']['members']
277:         reference_name = self._triplets[index]['reference']
278:         rel_caption = self._triplets[index]['caption']
279:         reference_image_path = os.path.join(base_path, self._name_to_relpath[reference_name])
280:         reference_image = self.preprocess(PIL.Image.open(reference_image_path))
281:         pair_id = self._triplets[index]['pairid']
282: 
283:         return reference_name, reference_image, rel_caption, pair_id, group_members
284: 
285: if __name__ == '__main__':
286: 
287:     # cirr_train_dataset = CIRRDataset('test1', 'classic', None, None)
288:     #
289:     # train_loader = DataLoader(dataset=cirr_train_dataset, batch_size=32,
290:     #                           pin_memory=False, collate_fn=collate_fn,
291:     #                           drop_last=True, shuffle=True)
292:     #
293:     # for idx, (reference_image, target_image, negative_target_img, rel_caption) in enumerate(train_loader):
294:     #     print('hello')
295:     #
296:     # cirr_val_dataset = CIRRDataset('val', 'relative', None)
297:     # cirr_test1_dataset = CIRRDataset('test1', 'relative', None)
298:     #
299:     # print(len(cirr_train_dataset), len(cirr_val_dataset), len(cirr_test1_dataset))
300:     pass

configs/fashionIQ/train.json
1: {
2:     "epoch": 30,
3:     "negative_definition_epoch_num" : 6,
4:     "model": "blip2",
5:     "backbone": "pretrain_vitL",
6:     "batch_size": 32,
7:     "num_workers": 16,
8:     "img_size": 224,
9:     "blip_size": "base",
10:     "text_encoder": "blip",
11:     "weight_decay": 5e-2,
12:     "random_seed": 1000,
13:     "experiment_dir": "experiments",
14:     "init_lr": 5e-6,
15:     "min_lr": 5e-8,
16:     "dataset": "fashionIQ",
17:     "wandb_project_name": "QuRe",
18:     "wandb_account_name": "-",
19:     "device_idx": "0",
20:     "experiment_description": "debug",
21:     "mode": "train",
22:     "negative": "random_rerank",
23:     "use_temp": true,
24:     "use_rerank": true,
25:     "consecutive_threshold" : 1,
26:     "percentage_threshold" : 5,
27:     "rerank_warmup": true,
28:     "init_topk": 100
29: }

lavis/models/blip2_models/blip2_qure.py
1: """
2:  Copyright (c) 2022, salesforce.com, inc.
3:  All rights reserved.
4:  SPDX-License-Identifier: BSD-3-Clause
5:  For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
6: """
7: import os
8: import numpy as np
9: import logging
10: from tqdm import tqdm
11: import PIL
12: import PIL.Image
13: import torch
14: import torch.distributed as dist
15: import torch.nn as nn
16: from torch.cuda.amp import autocast as autocast
17: from torch.nn import functional as F
18: from data.utils import targetpad_transform
19: 
20: preprocess = targetpad_transform(1.25, 224)
21: 
22: from lavis.common.registry import registry
23: from lavis.models.base_model import all_gather_with_grad, concat_all_gather
24: from lavis.models.blip2_models.blip2 import (
25:     Blip2Base,
26:     compute_sim_matrix,
27:     disabled_train,
28: )
29: from lavis.models.blip_models.blip_outputs import BlipOutput, BlipOutputFeatures
30: 
31: 
32: @registry.register_model("blip2_qure")
33: class Blip2QuRe(Blip2Base):
34:     """
35:     BLIP Image-Text Matching (ITM) model.
36:     Supported model types:
37:         - pretrained: pretrained model
38:         - coco: fintuned model on coco
39:     Usage:
40:         >>> from lavis.models import load_model
41:         >>> model = load_model("blip2_qure", "pretrain")
42:     """
43: 
44:     PRETRAINED_MODEL_CONFIG_DICT = {
45:         "pretrain": "configs/models/blip2/blip2_pretrain.yaml",
46:         "pretrain_vitL": "configs/models/blip2/blip2_pretrain_vitL.yaml",
47:         "coco": "configs/models/blip2/blip2_coco.yaml",
48:     }
49: 
50:     def __init__(
51:         self,
52:         vit_model="eva_clip_g",
53:         img_size=224,
54:         drop_path_rate=0,
55:         use_grad_checkpoint=False,
56:         vit_precision="fp16",
57:         freeze_vit=True,
58:         num_query_token=32,
59:         cross_attention_freq=2,
60:         embed_dim=256,
61:         max_txt_len=32,
62:     ):
63:         super().__init__()
64: 
65:         self.tokenizer = self.init_tokenizer()
66: 
67:         self.visual_encoder, self.ln_vision = self.init_vision_encoder(
68:             vit_model, img_size, drop_path_rate, use_grad_checkpoint, vit_precision
69:         )
70:         if freeze_vit:
71:             for name, param in self.visual_encoder.named_parameters():
72:                 param.requires_grad = False
73:             self.visual_encoder = self.visual_encoder.eval()
74:             self.visual_encoder.train = disabled_train
75:             print("freeze vision encoder")
76:         else:
77:             print("train vision encoder")
78:         self.Qformer, self.query_tokens = self.init_Qformer(
79:             num_query_token, self.visual_encoder.num_features, cross_attention_freq
80:         )
81:         self.Qformer.resize_token_embeddings(len(self.tokenizer))
82:         state_dict = self.Qformer.state_dict()
83:         for name, param in self.Qformer.named_parameters():
84:             if "_query" in name:
85:                 key_orig = name.replace("_query", "")
86:                 param.data.copy_(state_dict[key_orig])
87: 
88:         self.vision_proj = nn.Linear(self.Qformer.config.hidden_size, embed_dim)
89:         self.text_proj = nn.Linear(self.Qformer.config.hidden_size, embed_dim)
90: 
91:         self.itm_head = nn.Linear(self.Qformer.config.hidden_size, 2)
92: 
93:         self.temp = nn.Parameter(0.07 * torch.ones([]))
94: 
95:         self.max_txt_len = max_txt_len
96: 
97:     def forward(self, ref_images, tar_images, sentences, negative_images, use_temp):
98:         device = ref_images.device
99:         batch_size = ref_images.shape[0]
100: 
101:         text_tokens = self.tokenizer(
102:             sentences,
103:             padding="max_length",
104:             truncation=True,
105:             max_length=self.max_txt_len,
106:             return_tensors="pt",
107:         ).to(device)
108: 
109:         # Query Embeddings
110:         with self.maybe_autocast():
111:             ref_image_embedding = self.ln_vision(self.visual_encoder(ref_images))
112:         ref_image_embedding = ref_image_embedding.float()
113:         ref_image_embedding_atts = torch.ones(ref_image_embedding.size()[:-1], dtype=torch.long).to(device)
114: 
115:         query_tokens = self.query_tokens.expand(ref_image_embedding.shape[0], -1, -1)
116:         query_atts = torch.ones(query_tokens.size()[:-1], dtype=torch.long).to(device)
117:         attention_mask = torch.cat([query_atts, text_tokens.attention_mask], dim=1)
118: 
119:         query_output = self.Qformer.bert(
120:                 text_tokens.input_ids,
121:                 query_embeds=query_tokens,
122:                 attention_mask=attention_mask,
123:                 encoder_hidden_states=ref_image_embedding,
124:                 encoder_attention_mask=ref_image_embedding_atts,
125:                 return_dict=True,
126:             )
127: 
128:         query_embeds = query_output.last_hidden_state[:, : query_tokens.size(1), :]
129:         projected_query = self.text_proj(query_embeds).mean(dim=1)
130:         # projected_query = projected_query.mean(dim=1)
131: 
132:         # Target & Negative Embeddings
133:         with self.maybe_autocast():
134:             tar_image_embedding = self.ln_vision(self.visual_encoder(tar_images))
135:             neg_image_embedding = self.ln_vision(self.visual_encoder(negative_images))
136: 
137:         tar_image_embedding = tar_image_embedding.float()
138:         tar_image_atts = torch.ones(
139:             tar_image_embedding.size()[:-1], dtype=torch.long
140:         ).to(self.device)
141: 
142:         tar_query_output = self.Qformer.bert(
143:             query_embeds=query_tokens,
144:             encoder_hidden_states=tar_image_embedding,
145:             encoder_attention_mask=tar_image_atts,
146:             return_dict=True,
147:         )
148:         tar_image_embeds = tar_query_output.last_hidden_state
149: 
150:         neg_image_embedding = neg_image_embedding.float()
151:         neg_image_atts = torch.ones(
152:             neg_image_embedding.size()[:-1], dtype=torch.long
153:         ).to(self.device)
154:         # neg_query_tokens = self.query_tokens.expand(
155:         #     neg_image_embedding.shape[0], -1, -1
156:         # )
157: 
158:         neg_query_output = self.Qformer.bert(
159:             query_embeds=query_tokens,
160:             encoder_hidden_states=neg_image_embedding,
161:             encoder_attention_mask=neg_image_atts,
162:             return_dict=True,
163:         )
164:         neg_image_embeds = neg_query_output.last_hidden_state
165: 
166:         tar_projected_image = self.vision_proj(tar_image_embeds)
167:         neg_projected_image = self.vision_proj(neg_image_embeds)
168: 
169:         projected_query = F.normalize(projected_query, p=2, dim=-1)
170:         tar_projected_image = F.normalize(tar_projected_image, p=2, dim=-1)
171:         neg_projected_image = F.normalize(neg_projected_image, p=2, dim=-1)
172: 
173:         scores_1 = torch.bmm(tar_projected_image, projected_query.unsqueeze(-1))
174:         score_1, _ = torch.max(scores_1, dim=1)
175: 
176:         scores_2 = torch.bmm(neg_projected_image, projected_query.unsqueeze(-1))
177:         score_2, _ = torch.max(scores_2, dim=1)
178: 
179:         if use_temp:
180:             score_1 = score_1 / self.temp
181:             score_2 = score_2 / self.temp
182: 
183:         scores = torch.stack([score_1, score_2], dim=1).squeeze(-1)
184:         return scores
185: 
186:     @torch.no_grad()
187:     def extract_target_features(self, dataloader, use_temp, device):
188:         feature_dim = 256
189:         index_features = torch.empty((0, 32, feature_dim)).to(device, non_blocking=True)
190:         index_names = []
191: 
192:         for images, names in tqdm(dataloader, desc="Extract Sample Features"):
193:             images = images.to(device, non_blocking=True)
194: 
195:             with self.maybe_autocast():
196:                 img_embedding = self.ln_vision(self.visual_encoder(images))
197: 
198:             img_embedding = img_embedding.float()
199:             img_atts = torch.ones(img_embedding.size()[:-1], dtype=torch.long).to(device)
200:             query_tokens = self.query_tokens.expand(img_embedding.shape[0], -1, -1)
201:             query_output = self.Qformer.bert(
202:                 query_embeds=query_tokens,
203:                 encoder_hidden_states=img_embedding,
204:                 encoder_attention_mask=img_atts,
205:                 return_dict=True,
206:             )
207:             batch_features = self.vision_proj(query_output.last_hidden_state)
208:             batch_features = F.normalize(batch_features, dim=-1)
209:             index_features = torch.vstack((index_features, batch_features))
210:             index_names.extend(names)
211:         return index_features.cpu(), index_names
212: 
213: 
214:     @torch.no_grad()
215:     def extract_query_features_fiq(self, dataloader, use_temp, txt_processors, device):
216: 
217:         feature_dim = 256
218: 
219:         # Initialize predicted features, target_names, group_members and reference_names
220:         predicted_features = torch.empty((0, feature_dim)).to(device, non_blocking=True)