forked from FereshteShakeri/Histo-TransCLIP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
214 lines (161 loc) · 8.7 KB
/
utils.py
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
from tqdm import tqdm
from CONCH.conch.open_clip_custom import tokenize, get_tokenizer
import time
import torch
import torch.nn.functional as F
import clip
def cls_acc(output, target, topk=1):
pred = output.topk(topk, 1, True, True)[1].t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
acc = float(correct[: topk].reshape(-1).float().sum(0, keepdim=True).cpu().numpy())
acc = 100 * acc / target.shape[0]
return acc
def clip_classifier(classnames, template, clip_model, model_name, reduce='mean', gpt=False, wordnet_dict=None):
with torch.no_grad():
clip_weights = []
if wordnet_dict is not None:
indices = []
i = 0
for classname in classnames:
allnames = [classname] + wordnet_dict[classname]
for name in allnames:
# Tokenize the prompts
name = name.replace('_', ' ')
texts = [t.format(name) for t in template]
texts = clip.tokenize(texts).cuda()
class_embeddings = clip_model.encode_text(texts)
class_embeddings /= class_embeddings.norm(dim=-1, keepdim=True)
if reduce=='mean':
class_embedding = class_embeddings.mean(dim=0)
class_embedding /= class_embedding.norm()
clip_weights.append(class_embedding)
if reduce is None:
class_embeddings /= class_embeddings.norm(dim=1, keepdim=True)
clip_weights.append(class_embeddings)
i+=1
indices.append(i)
return clip_weights, indices
else:
for classname in classnames:
# Tokenize the prompts
classname = classname.replace('_', ' ')
if gpt:
texts = template[classname]
else:
texts = [t.format(classname) for t in template]
if model_name == 'Quilt' or model_name == 'CLIP':
texts = clip.tokenize(texts).cuda()
class_embeddings = clip_model.encode_text(texts)
# CONCH
elif model_name == 'CONCH':
tokenizer = get_tokenizer()
text_tokens = tokenize(texts=texts, tokenizer=tokenizer)
class_embeddings = clip_model.encode_text(text_tokens.cuda())
elif model_name == 'PLIP':
texts = clip.tokenize(texts).cuda()
class_embeddings = clip_model.get_text_features(texts)
class_embeddings /= class_embeddings.norm(dim=-1, keepdim=True)
if reduce=='mean':
class_embedding = class_embeddings.mean(dim=0)
class_embedding /= class_embedding.norm()
clip_weights.append(class_embedding)
if reduce is None:
class_embeddings /= class_embeddings.norm(dim=1, keepdim=True)
clip_weights.append(class_embeddings)
clip_weights = torch.stack(clip_weights, dim=-1).cuda()
return clip_weights
def get_all_features(cfg, train_loader, val_loader, test_loader, dataset, clip_model):
clip_prototypes = clip_classifier(dataset.classnames, dataset.template, clip_model, cfg['model'], reduce=None)
test_features, test_labels = pre_load_features(cfg, "test", clip_model, cfg['model'], test_loader)
shot_features = None
shot_labels = None
val_features = None
val_labels = None
if cfg['shots'] > 0:
shot_features, shot_labels = build_cache_model(cfg, clip_model, train_loader, n_views=0,
reduce=None)
val_features, val_labels = pre_load_features(cfg, "val", clip_model, val_loader)
return shot_features, shot_labels, val_features, val_labels, test_features, test_labels, clip_prototypes
def build_cache_model(cfg, clip_model, train_loader_cache, n_views=0, reduce=None):
print('... for shot samples from train split:')
if cfg['load_cache'] == False:
cache_keys = []
cache_values = []
if n_views == 0:
n_epochs =1
else:
n_epochs = n_views
with torch.no_grad():
# Data augmentation for the cache model
for augment_idx in range(n_epochs):
train_features = []
train_labels = []
for i, (images, target) in enumerate(tqdm(train_loader_cache)):
images = images.cuda()
image_features = clip_model.encode_image(images)
train_features.append(image_features)
if augment_idx == 0:
target = target.cuda()
cache_values.append(target)
cache_keys.append(torch.cat(train_features, dim=0).unsqueeze(0))
if n_views == 1:
cache_keys = torch.cat(cache_keys, dim=0).mean(dim=0)
cache_keys /= cache_keys.norm(dim=-1, keepdim=True)
#cache_keys = cache_keys.permute(1, 0)
else:
cache_keys = torch.cat(cache_keys, dim=0) # [n_views, n_classes, n_features]
if reduce == 'mean':
cache_keys = cache_keys.mean(0, keepdim=True)
cache_keys /= cache_keys.norm(dim=-1, keepdim=True)
cache_keys.permute(0, 2, 1)
cache_values = F.one_hot(torch.cat(cache_values, dim=0)).half()
torch.save(cache_keys, cfg['cache_dir'] + '/keys_' + str(cfg['shots']) + "shots.pt")
torch.save(cache_values, cfg['cache_dir'] + '/values_' + str(cfg['shots']) + "shots.pt")
else:
cache_keys = torch.load(cfg['cache_dir'] + '/keys_' + str(cfg['shots']) + "shots.pt")
cache_values = torch.load(cfg['cache_dir'] + '/values_' + str(cfg['shots']) + "shots.pt")
return cache_keys, cache_values
def pre_load_features(cfg, split, clip_model, model_name, loader, n_views=1):
print('... from {} split:'.format(split))
if cfg['load_pre_feat'] == False:
features, labels = [], []
feature_time = time.time()
with torch.no_grad():
for view in range(n_views):
length = 0
for i, (images, target) in enumerate(tqdm(loader)):
if n_views == 1:
images, target = images.cuda(), target.cuda()
if model_name == "PLIP":
image_features = clip_model.get_image_features(images)
else:
image_features = clip_model.encode_image(images)
image_features /= image_features.norm(dim=-1, keepdim=True)
features.append(image_features.cpu())
labels.append(target.cpu())
else:
images, target = images.cuda(), target.cuda()
image_features = clip_model.encode_image(images)
image_features /= image_features.norm(dim=-1, keepdim=True)
if view == 0:
labels.append(target.cpu())
if i ==0:
mean_features = image_features
else:
mean_features = torch.cat((mean_features, image_features))
else:
mean_features[length:length+image_features.size(0)] += image_features
length += image_features.size(0)
if n_views > 1:
mean_features = mean_features / n_views
features = mean_features / mean_features.norm(dim=-1, keepdim=True)
labels = torch.cat(labels)
elif n_views==1:
features, labels = torch.cat(features), torch.cat(labels)
print("real feature extraction time {}".format(str(time.time() - feature_time)))
torch.save(features, cfg['cache_dir'] + "/" + split + "_f.pt")
torch.save(labels, cfg['cache_dir'] + "/" + split + "_l.pt")
else:
features = torch.load(cfg['cache_dir'] + "/" + split + "_f.pt")
labels = torch.load(cfg['cache_dir'] + "/" + split + "_l.pt")
return features, labels