Spaces:
Sleeping
Sleeping
File size: 6,416 Bytes
ed00004 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 |
import datetime
import time
from pathlib import Path
import einops
import torch
import torch.nn.functional as F
from src.test.webvid_covr import eval_recall
from src.tools.files import json_dump
class TestWebVidCoVRTextOnly:
def __init__(self, remove_self_similarity=True):
self.remove_self_similarity = remove_self_similarity
@torch.no_grad()
def __call__(self, model, data_loader, fabric):
model.eval()
fabric.print("Computing features for evaluation...")
start_time = time.time()
tar_img_feats = []
query_feats = []
captions = []
pair_ids = []
for _, tar_feat, caption, pair_id, *_ in data_loader:
pair_ids.extend(pair_id.cpu().numpy().tolist())
captions.extend(caption)
device = pair_id.device
text = model.tokenizer(
caption,
padding="longest",
truncation=True,
max_length=64,
return_tensors="pt",
).to(device)
# Shift encoder
query_embs = model.text_encoder(
text.input_ids,
attention_mask=text.attention_mask,
return_dict=True,
mode="text",
)
query_feat = query_embs.last_hidden_state[:, 0, :]
query_feat = F.normalize(model.text_proj(query_feat), dim=-1)
query_feats.append(query_feat.cpu())
# Encode the target image
tar_img_feats.append(tar_feat.cpu())
query_feats = torch.cat(query_feats, dim=0)
tar_img_feats = torch.cat(tar_img_feats, dim=0)
query_feats = F.normalize(query_feats, dim=-1)
tar_img_feats = F.normalize(tar_img_feats, dim=-1)
ref_img_ids = [data_loader.dataset.pairid2ref[pair_id] for pair_id in pair_ids]
tar_img_ids = [data_loader.dataset.pairid2tar[pair_id] for pair_id in pair_ids]
ref_img_ids = torch.tensor(ref_img_ids, dtype=torch.long)
tar_img_ids = torch.tensor(tar_img_ids, dtype=torch.long)
if fabric.world_size > 1:
# Gather tensors from every process
query_feats = fabric.all_gather(query_feats)
tar_img_feats = fabric.all_gather(tar_img_feats)
ref_img_ids = fabric.all_gather(ref_img_ids)
tar_img_ids = fabric.all_gather(tar_img_ids)
query_feats = einops.rearrange(query_feats, "d b e -> (d b) e")
tar_img_feats = einops.rearrange(tar_img_feats, "d b e -> (d b) e")
ref_img_ids = einops.rearrange(ref_img_ids, "d b -> (d b)")
tar_img_ids = einops.rearrange(tar_img_ids, "d b -> (d b)")
if fabric.global_rank == 0:
sim_q2t = (query_feats @ tar_img_feats.t()).cpu().numpy()
if self.remove_self_similarity:
for i in range(len(ref_img_ids)):
for j in range(len(tar_img_ids)):
if ref_img_ids[i] == tar_img_ids[j]:
sim_q2t[i][j] = -10
total_time = time.time() - start_time
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
print("Evaluation time {}".format(total_time_str))
recalls = eval_recall(sim_q2t)
recalls["annotation"] = Path(data_loader.dataset.annotation_pth).name
fabric.print(recalls)
# Save results
self_sim = "" if self.remove_self_similarity else "_ss"
json_dump(recalls, f"recalls_covr_txt{self_sim}.json")
print(f"Recalls saved in {Path.cwd()} as recalls_covr_txt{self_sim}.json")
fabric.barrier()
class TestWebVidCoVRVisualOnly:
def __init__(self):
pass
@staticmethod
@torch.no_grad()
def __call__(model, data_loader, fabric):
model.eval()
fabric.print("Computing features for evaluation...")
start_time = time.time()
tar_img_feats = []
query_feats = []
pair_ids = []
for ref_img, tar_feat, _, pair_id, *_ in data_loader:
pair_ids.extend(pair_id.cpu().numpy().tolist())
ref_img_embs = model.visual_encoder(ref_img)
query_feat = F.normalize(model.vision_proj(ref_img_embs[:, 0, :]), dim=-1)
query_feats.append(query_feat.cpu())
# Encode the target image
tar_img_feats.append(tar_feat.cpu())
query_feats = torch.cat(query_feats, dim=0)
tar_img_feats = torch.cat(tar_img_feats, dim=0)
query_feats = F.normalize(query_feats, dim=-1)
tar_img_feats = F.normalize(tar_img_feats, dim=-1)
ref_img_ids = [data_loader.dataset.pairid2ref[pair_id] for pair_id in pair_ids]
tar_img_ids = [data_loader.dataset.pairid2tar[pair_id] for pair_id in pair_ids]
ref_img_ids = torch.tensor(ref_img_ids, dtype=torch.long)
tar_img_ids = torch.tensor(tar_img_ids, dtype=torch.long)
if fabric.world_size > 1:
# Gather tensors from every process
query_feats = fabric.all_gather(query_feats)
tar_img_feats = fabric.all_gather(tar_img_feats)
ref_img_ids = fabric.all_gather(ref_img_ids)
tar_img_ids = fabric.all_gather(tar_img_ids)
query_feats = einops.rearrange(query_feats, "d b e -> (d b) e")
tar_img_feats = einops.rearrange(tar_img_feats, "d b e -> (d b) e")
ref_img_ids = einops.rearrange(ref_img_ids, "d b -> (d b)")
tar_img_ids = einops.rearrange(tar_img_ids, "d b -> (d b)")
if fabric.global_rank == 0:
sim_q2t = (query_feats @ tar_img_feats.t()).cpu().numpy()
# Add zeros where ref_img_id == tar_img_id
for i in range(len(ref_img_ids)):
for j in range(len(tar_img_ids)):
if ref_img_ids[i] == tar_img_ids[j]:
sim_q2t[i][j] = -10
total_time = time.time() - start_time
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
print("Evaluation time {}".format(total_time_str))
recalls = eval_recall(sim_q2t)
fabric.print(recalls)
# Save results
json_dump(recalls, "recalls_covr.json")
print(f"Recalls saved in {Path.cwd()} as recalls_covr.json")
fabric.barrier()
|