"""Permutation-invariant matching with field-level masks.""" import math import torch from scipy.optimize import linear_sum_assignment from torch.nn import functional as F from .config import ATTRIBUTES from .temporal import TIME_TARGETS def match_predictions(output, targets, *, temporal_loss_weight=1.0, date_loss_weight=1.0): size = len(targets["attribute"]) if size == 0: empty = torch.empty(0, dtype=torch.long, device=output["attribute"].device) return empty, empty if size > output["attribute"].shape[0]: raise ValueError("More target facts than available query slots") cost = output["attribute"].new_zeros((output["attribute"].shape[0], size), dtype=torch.float32) fields = ("attribute", "polarity", "object_type", "source", "object", "value") # Copy-class zero does not identify a fact: several facts in one turn can # all share it. Their actual spans must participate in the assignment, or # gold order arbitrarily determines which query learns which object/value. pointers = ("object_start", "object_end", "value_start", "value_end", "source_start", "source_end", "date_from", "date_to") for name in fields + pointers + tuple(name for name in TIME_TARGETS if name in output): if name not in output or name not in targets: continue labels = targets[name] valid = labels >= 0 log_probabilities = output[name].detach().float().log_softmax(-1) weight = (0.25 * temporal_loss_weight if name in TIME_TARGETS else 0.25 * date_loss_weight if name in ("date_from", "date_to") else 0.5 if name in pointers else 1.0) cost[:, valid] -= weight * log_probabilities[:, labels[valid]] rows, columns = linear_sum_assignment(cost.detach().cpu().numpy()) device = cost.device return torch.as_tensor(rows, device=device), torch.as_tensor(columns, device=device) def fact_loss(output, targets, no_fact_weight=0.1, *, temporal_loss_weight=1.0, date_loss_weight=1.0): if not math.isfinite(no_fact_weight) or no_fact_weight <= 0: raise ValueError("no_fact_weight must be finite and positive") if any(not math.isfinite(weight) or weight < 0 for weight in (temporal_loss_weight, date_loss_weight)): raise ValueError("Temporal and date loss weights must be finite and nonnegative") rows, columns = match_predictions(output, targets, temporal_loss_weight=temporal_loss_weight, date_loss_weight=date_loss_weight) no_fact = len(ATTRIBUTES) labels = torch.full((output["attribute"].shape[0],), no_fact, device=output["attribute"].device, dtype=torch.long) labels[rows] = targets["attribute"][columns] weights = output["attribute"].new_ones(no_fact + 1) weights[-1] = no_fact_weight losses = {"attribute": F.cross_entropy(output["attribute"], labels, weight=weights)} for name, logits in output.items(): if name == "attribute": continue selected = targets[name][columns] valid = selected >= 0 if valid.any(): losses[name] = F.cross_entropy(logits[rows[valid]], selected[valid]) weighted = [] for name, loss in losses.items(): weight = (temporal_loss_weight if name in TIME_TARGETS else date_loss_weight if name in ("date_from", "date_to") else 1.0) weighted.append(weight * loss) # Keep unweighted field losses available for comparing supervision coverage. return torch.stack(weighted).sum(), losses