-
Notifications
You must be signed in to change notification settings - Fork 3
/
emmental_utils.py
333 lines (256 loc) · 9.6 KB
/
emmental_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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
import json
import os
import pickle
from emmental.scorer import Scorer
from emmental.task import EmmentalTask
from emmental.data import EmmentalDataLoader
from emmental.utils.utils import pred_to_prob, move_to_device
from end_model.dataset import (
ObservationalDataset,
num_classes_dict,
)
from end_model.soft_cross_entropy import SoftCrossEntropyLoss
from transforms import get_data_transforms
from tqdm import tqdm
from functools import partial
import pdb
gaze_norm_stats = {
"cxr": (
torch.Tensor([0.3585, 0.5312, 1.2828]),
torch.Tensor([0.2142, 0.2206, 0.5644]),
)
}
helper_output_dim_dict = {"loc": 9, "time": 2, "diffusivity": 2}
def ce_loss(task_name, num_classes, immediate_output_dict, Y, active):
if num_classes > 2:
if len(Y.shape) < 2: # i.e. if Y not already in pred form
Y_ = torch.Tensor(pred_to_prob(Y, num_classes))
Y_ = move_to_device(Y_, 0)
else:
Y_ = Y
else:
Y_ = torch.stack((1 - Y, Y), axis=1)
# active = Y != -1
ce_loss = SoftCrossEntropyLoss().forward(
immediate_output_dict[f"classification_module_{task_name}"][0][active],
Y_[active],
)
loss = ce_loss
return loss
def ce_loss_reweight(task_name, num_classes, immediate_output_dict, Y, active):
if num_classes > 2:
Y_ = torch.Tensor(pred_to_prob(Y, num_classes))
Y_ = move_to_device(Y_, 0)
else:
Y_ = torch.stack((1 - Y, Y), axis=1)
loss_outputs = SoftCrossEntropyLoss(reduction="none").forward(
immediate_output_dict[f"classification_module_{task_name}"][0][active],
Y_[active],
)
confidence_weights = torch.Tensor(
immediate_output_dict["_input_"]["confidence"]
).cuda()
return confidence_weights.dot(loss_outputs) / confidence_weights.sum()
def output(task_name, immediate_output_dict):
return F.softmax(
immediate_output_dict[f"classification_module_{task_name}"][0], dim=1
)
# Two functions below for MSE gaze feature learning
def mse_loss(task_name, immediate_output_dict, Y, active):
prediction = immediate_output_dict[f"classification_module_{task_name}"][0]
return F.mse_loss(prediction[active], Y[active])
def mse_output(task_name, immediate_ouput_dict):
return immediate_ouput_dict[f"classification_module_{task_name}"][0]
# this squeeze module was necessary to connect resnet encoder in emmental
class SqueezeModule(nn.Module):
"""A default identity input module that simply passes the squeezed input through."""
def __init__(self):
super().__init__()
def reset_parameters(self):
pass
def forward(self, x):
return x.squeeze()
# helper
def save_dict_to_json(d, json_path):
"""Saves dict of floats in json file
Args:
d: (dict) of float-castable values (np.float, int, float, etc.)
json_path: (string) path to json file
"""
with open(json_path, "w") as f:
# We need to convert the values to float for json (it doesn't accept np.array, np.float, )
d = {k: float(v) for k, v in d.items()}
json.dump(d, f, indent=4)
def str2list(v, dim=","):
return [t.strip() for t in v.split(dim)]
def write_to_file(path, file_name, value):
if not isinstance(value, str):
value = str(value)
fout = open(os.path.join(path, file_name), "w")
fout.write(value + "\n")
fout.close()
def fetch_dataloaders(
task_type,
gaze_mtl_task,
source,
data_dir,
train_scale,
val_scale,
seed,
batch_size,
):
helper_tasks = gaze_mtl_task.split("_")
num_helper_tasks = len(helper_tasks)
datasets = {}
transforms = get_data_transforms(source, normalization_type="train_images")
for split in ["train", "val", "test"]:
datasets[split] = ObservationalDataset(
source=source,
task=task_type,
gaze_mtl_task=gaze_mtl_task,
data_dir=data_dir,
split_type=split,
transform=transforms[split],
train_scale=train_scale,
val_scale=val_scale,
seed=seed,
)
task_to_label_dict = {"target": "target"}
if task_type == "gaze_mtl":
for i in range(num_helper_tasks):
task_to_label_dict["helper_task_" + str(i)] = "helper_task_" + str(i)
elif task_type == "weak_gaze":
task_to_label_dict = {"target": "weak"}
dataloaders = []
for split in ["train", "val", "test"]:
dataloaders.append(
EmmentalDataLoader(
task_to_label_dict=task_to_label_dict,
dataset=datasets[split],
split=split,
shuffle=split == "train",
batch_size=batch_size,
num_workers=8,
)
)
return dataloaders
def create_tasks(
task_type,
gaze_mtl_task,
source,
pretrained,
task_weights,
load_path=None,
):
helper_tasks = gaze_mtl_task.split("_")
num_helper_tasks = len(helper_tasks)
helper_output_dims = [helper_output_dim_dict[task] for task in helper_tasks]
num_classes = num_classes_dict[source]
input_module = models.resnet50(pretrained=pretrained)
num_features = 2048
# remove last FC layer
modules = list(input_module.children())[:-1]
modules.append(SqueezeModule())
cnn_module = nn.Sequential(*modules)
if load_path is not None:
print(f"Loading from {load_path}...")
loaded = torch.load(load_path)
cnn_module.load_state_dict(loaded["model"]["module_pool"]["cnn"])
task_names = ["target"]
weights = [1]
num_classes_task = {"target": num_classes}
if task_type in ["gaze_mtl", "gaze_mtl_ws"]:
for i in range(num_helper_tasks):
task_names.append("helper_task_" + str(i))
num_classes_task["helper_task_" + str(i)] = helper_output_dims[i]
weights.append(task_weights[i])
loss_fnc = ce_loss
tasks = [
EmmentalTask(
name=task_name,
module_pool=nn.ModuleDict(
{
"cnn": cnn_module,
f"classification_module_{task_name}": nn.Linear(
num_features, num_classes_task[task_name]
),
}
),
task_flow=[
{"name": "cnn", "module": "cnn", "inputs": [("_input_", "image")]},
{
"name": f"classification_module_{task_name}",
"module": f"classification_module_{task_name}",
"inputs": [("cnn", 0)],
},
],
loss_func=partial(loss_fnc, task_name, num_classes_task[task_name]),
output_func=partial(output, task_name),
scorer=Scorer(metrics=["accuracy", "roc_auc", "precision", "recall", "f1"]),
weight=weights[t_ndx],
)
for t_ndx, task_name in enumerate(task_names)
]
return tasks
def save_features(save_pth, model, dataloader, task):
model.eval()
features_dict = {}
encoder = model.module_pool.cnn
for x_dict_b, y_dict_b in tqdm(dataloader, total=len(dataloader)):
if task in ["unsup_gaze", "gaze_lstm"]:
input_b = x_dict_b["gaze_seq"]
img_pth_b = x_dict_b["id"]
else:
input_b = x_dict_b["image"]
img_pth_b = x_dict_b["img_id"]
feature_b = encoder(input_b.cuda()).squeeze()
for i in range(feature_b.shape[0]):
features_dict[img_pth_b[i]] = feature_b[i, :].detach().cpu().numpy()
with open(os.path.join(save_pth, "train_features_dict.pkl"), "wb") as pkl_f:
pickle.dump(features_dict, pkl_f)
def save_predictions(save_pth, emm_model, dataloaders, task):
emm_model.eval()
encoder = emm_model.module_pool.cnn
target_head = emm_model.module_pool.classification_module_target
model = nn.Sequential(encoder, target_head)
if task == "gaze_mtl":
helper_head = emm_model.module_pool.classification_module_helper_task_0
helper_model = nn.Sequential(encoder, helper_head)
for ndx, dataloader in enumerate(dataloaders):
predictions_dict = {}
for x_dict_b, y_dict_b in tqdm(dataloader, total=len(dataloader)):
input_b = x_dict_b["image"]
img_pth_b = x_dict_b["img_id"]
true_labels_b = y_dict_b["target"]
logits = model(input_b)
predictions_b = F.softmax(logits, dim=1)[:, 1].detach().cpu().numpy()
if task == "gaze_mtl":
helper_true_labels_b = y_dict_b["helper_task_0"]
logits = helper_model(input_b)
helper_predictions_b = F.softmax(logits, dim=1).detach().cpu().numpy()
for i in range(predictions_b.shape[0]):
if task == "gaze_mtl":
predictions_dict[img_pth_b[i]] = (
predictions_b[i],
true_labels_b[i],
helper_predictions_b[i],
helper_true_labels_b[i],
)
else:
predictions_dict[img_pth_b[i]] = (
predictions_b[i],
true_labels_b[i],
)
if ndx == 0:
file_name = "train_predictions_dict.pkl"
elif ndx == 1:
file_name = "val_predictions_dict.pkl"
elif ndx == 2:
file_name = "test_predictions_dict.pkl"
with open(os.path.join(save_pth, file_name), "wb") as pkl_f:
pickle.dump(predictions_dict, pkl_f)