training_utils.py
5.17 KB
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
import typing
import torch
import numpy as np
from numpy import ndarray
from .constants import (
MASK_VALUE,
ADJACENCY_MATRIX,
GRAPH_DEPRELS,
GRAPH_ADJACENCY_MATRIX,
)
def _loss(logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
num_labels = logits.shape[-1]
# logits: batch x seq_len x num_labels -> batch*seq_len x num_labels
# labels: batch x seq_len -> batch*seq_len
logits_reshaped = logits.view(-1, num_labels)
labels_reshaped = labels.view(-1)
if (labels_reshaped != -100).any():
# cross_entropy will deal with all -100 labels (both all-row and token-masking)
return torch.nn.functional.cross_entropy(logits_reshaped, labels_reshaped)
else:
# the whole batch was masked
return torch.tensor(0.0, device=logits.device, requires_grad=True)
def _matrix_loss(logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
num_labels = logits.shape[-1]
logits_reshaped = logits.view(-1, num_labels)
labels_reshaped = labels.view(-1, num_labels)
# we need to apply the mask here as CrossEntropyLoss from ground truth
# probabilities doesn’t handle -100 mask
row_mask = ~(labels_reshaped == MASK_VALUE).all(dim=1)
if row_mask.any():
logits_masked = logits_reshaped[row_mask]
labels_masked = labels_reshaped[row_mask]
# add -MASK_VALUE where labels == MASK_VALUE to replace it with zero
# this will not affect the loss since its only non-zero component is for the true label
labels_masked = (labels_masked + (labels_masked == MASK_VALUE) * -MASK_VALUE).float()
return torch.nn.functional.cross_entropy(logits_masked, labels_masked)
else:
# the whole batch was masked
return torch.tensor(0.0, device=logits.device, requires_grad=True)
def _graph_loss(logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
# each value is an individual edge’s probability, so reshape them into vectors
# to easily deal with all -100’s at once (both all-row and token-masking)
logits_reshaped = logits.view(-1)
labels_reshaped = labels.view(-1)
# we need to apply the mask here as BCEWithLogitsLoss doesn’t handle -100 mask
mask = ~(labels_reshaped == MASK_VALUE)
logits_masked = logits_reshaped[mask]
labels_masked = labels_reshaped[mask].float()
return torch.nn.functional.binary_cross_entropy_with_logits(logits_masked, labels_masked)
def _graph_deprels_loss(logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
# the same loss logic, just one more dimension will be flattened by view()!
return _loss(logits, labels)
def get_loss(category: str) -> typing.Callable[[torch.Tensor, torch.Tensor], torch.Tensor]:
if category == ADJACENCY_MATRIX:
return _matrix_loss
if category == GRAPH_ADJACENCY_MATRIX:
return _graph_loss
if category == GRAPH_DEPRELS:
return _graph_deprels_loss
return _loss
def preprocess_logits(category: str, logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
#print(category, logits.shape, labels.shape)
if category in (ADJACENCY_MATRIX, GRAPH_ADJACENCY_MATRIX):
return logits.detach()
else:
return logits.detach().argmax(dim=-1)
def _accuracy(preds: ndarray, labels: ndarray) -> float:
# pred: batch x seq_len -> batch*seq_len
# labels: batch x seq_len -> batch*seq_len
preds_reshaped = preds.reshape(-1)
labels_reshaped = labels.reshape(-1)
mask = labels_reshaped != MASK_VALUE
preds_masked = preds_reshaped[mask]
labels_masked = labels_reshaped[mask]
return float(np.mean(preds_masked == labels_masked))
def _matrix_accuracy(logits: ndarray, labels: ndarray) -> float:
num_labels = logits.shape[-1]
logits_reshaped = logits.reshape(-1, num_labels)
labels_reshaped = labels.reshape(-1, num_labels)
row_mask = np.any(labels_reshaped != MASK_VALUE, axis=1)
logits_masked = logits_reshaped[row_mask]
labels_masked = labels_reshaped[row_mask]
logits_argmax = np.argmax(logits_masked, axis=1)
labels_argmax = np.argmax(labels_masked, axis=1)
return float(np.mean(logits_argmax == labels_argmax))
def _graph_accuracy(logits: ndarray, labels: ndarray) -> float:
# each value is an individual edge’s probability, so reshape them into vectors
# to easily deal with all -100’s at once (both all-row and token-masking)
logits_reshaped = logits.reshape(-1)
labels_reshaped = labels.reshape(-1)
mask = labels_reshaped != MASK_VALUE
logits_masked = logits_reshaped[mask]
labels_masked = labels_reshaped[mask].astype(np.float32)
# sigmoid >= 0.5 <=> logit >= 0
preds_binarised = logits_masked >= 0
return float(np.mean(preds_binarised == labels_masked))
def _graph_deprels_accuracy(preds: ndarray, labels: ndarray) -> float:
# the same accuracy logic, just one more dimension will be flattened by view()!
return _accuracy(preds, labels)
def get_metric(category: str) -> typing.Callable[[ndarray, ndarray], float]:
if category == ADJACENCY_MATRIX:
return _matrix_accuracy
if category == GRAPH_ADJACENCY_MATRIX:
return _graph_accuracy
if category == GRAPH_DEPRELS:
return _graph_deprels_accuracy
return _accuracy