training_utils.py 5.17 KB
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