forked from oleg-yaroshevskiy/quest_qa_labeling
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loops.py
121 lines (95 loc) · 3.51 KB
/
loops.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
import numpy as np
import torch
import gc
from scipy.stats import spearmanr
from tqdm import tqdm
def train_loop(model, train_loader, optimizer, criterion, scheduler, args, iteration):
model.train()
avg_loss = 0.0
optimizer.zero_grad()
for idx, batch in enumerate(tqdm(train_loader, desc="Train", ncols=80)):
input_ids, input_masks, input_segments, labels = (
batch["input_ids"],
batch["input_masks"],
batch["input_segments"],
batch["labels"]
)
input_ids, input_masks, input_segments, labels = (
input_ids.cuda(),
input_masks.cuda(),
input_segments.cuda(),
labels.cuda(),
)
logits = model(
input_ids=input_ids.long(),
attention_mask=input_masks,
token_type_ids=input_segments,
)
loss = criterion(logits, labels)
loss.backward()
if (iteration + 1) % args.batch_accumulation == 0:
optimizer.step()
scheduler.step()
optimizer.zero_grad()
iteration += 1
avg_loss += loss.item() / (len(train_loader) * args.batch_accumulation)
torch.cuda.empty_cache()
gc.collect()
return (
avg_loss,
iteration
)
def evaluate(args, model, val_loader, criterion, val_shape):
avg_val_loss = 0.0
model.eval()
valid_preds = []
original = []
ids = []
with torch.no_grad():
for idx, batch in enumerate(tqdm(val_loader, desc="Valid", ncols=80)):
id, input_ids, input_masks, input_segments, labels = (
batch["idx"],
batch["input_ids"],
batch["input_masks"],
batch["input_segments"],
batch["labels"]
)
ids.extend(id.cpu().numpy())
input_ids, input_masks, input_segments, labels = (
input_ids.cuda(),
input_masks.cuda(),
input_segments.cuda(),
labels.cuda(),
)
logits = model(
input_ids=input_ids.long(),
attention_mask=input_masks,
token_type_ids=input_segments,
)
avg_val_loss += criterion(logits, labels).item() / len(val_loader)
valid_preds.extend(logits.detach().cpu().numpy())
original.extend(labels.detach().cpu().numpy())
valid_preds = np.array(valid_preds)
original = np.array(original)
score = 0
preds = torch.sigmoid(torch.tensor(valid_preds)).numpy()
for i in range(len(args.target_columns)):
score += np.nan_to_num(spearmanr(original[:, i], preds[:, i]).correlation)
return avg_val_loss, score / len(args.target_columns), preds[np.argsort(ids)]
def infer(args, model, test_loader, test_shape):
test_preds = np.zeros((test_shape, args.num_classes))
model.eval()
ids = []
test_preds = []
for idx, batch in enumerate(tqdm(test_loader, desc="Test", ncols=80)):
with torch.no_grad():
ids.extend(batch["idx"].cpu().numpy())
predictions = model(
input_ids=batch["input_ids"].cuda(),
attention_mask=batch["input_masks"].cuda(),
token_type_ids=batch["input_segments"].cuda(),
)
test_preds.extend(predictions.detach().cpu().numpy())
test_preds = np.array(test_preds)
output = torch.sigmoid(torch.tensor(test_preds)).numpy()
return output[np.argsort(ids)]