"""Squared per-sample normalized inner products; original similarity/reconstruction retained.""" import json import torch import torch.nn.functional as F from torch import nn from typing import Optional def squared_orthogonality(z_tuple): (ca, cb, sa, sb) = [F.normalize(z, p=2, dim=1) for z in z_tuple] dots = torch.stack(((ca * sa).sum(1), (cb * sb).sum(1), (sa * sb).sum(1)), dim=1) return dots.square().sum(1).mean() class SquaredMDTLoss(nn.Module): def __init__(self, alpha_sim: float=1.0, alpha_diff: float=0.5, alpha_recon: float=1.0, class_loss_fn: Optional[nn.Module]=None): super().__init__() self.alpha_sim = alpha_sim self.alpha_diff = alpha_diff self.alpha_recon = alpha_recon self.class_loss_fn = class_loss_fn or nn.CrossEntropyLoss() def reset_epoch(self): self.diag_sum = None self.count = 0 def forward(self, logits, targets, h_tuple, z_tuple): (ha, hb, ra, rb) = h_tuple (ca, cb, sa, sb) = [F.normalize(z, p=2, dim=1) for z in z_tuple] sim = 1.0 - (ca * cb).sum(1).mean() diff = squared_orthogonality(z_tuple) recon = F.mse_loss(ra, ha) + F.mse_loss(rb, hb) classification = self.class_loss_fn(logits, targets) total = classification + self.alpha_sim * sim + self.alpha_diff * diff + self.alpha_recon * recon with torch.no_grad(): dots = torch.stack(((ca * sa).sum(1), (cb * sb).sum(1), (sa * sb).sum(1)), 1) n = len(targets) values = torch.cat((dots.mean(0), dots.abs().mean(0), dots.square().mean(0), torch.stack((ca.var(0, unbiased=False).mean(), cb.var(0, unbiased=False).mean())))).cpu() * n self.diag_sum = values if getattr(self, 'diag_sum', None) is None else self.diag_sum + values self.count = getattr(self, 'count', 0) + n return (total, classification, sim, diff, recon) def write_diagnostics(self, folder, epoch): pairs = ('sharedA_specificA', 'sharedH_specificH', 'specificA_specificH') keys = [p + '_' + m for m in ('signed_dot', 'absolute_dot', 'squared_dot') for p in pairs] + ['sharedA_within_batch_feature_variance', 'sharedH_within_batch_feature_variance'] row = {'epoch': epoch, 'alpha_diff': self.alpha_diff, **dict(zip(keys, (self.diag_sum / self.count).tolist()))} with (folder / 'disentanglement_diagnostics.jsonl').open('a') as f: f.write(json.dumps(row) + '\n')