Download src/binaryforecast/core/loss/ctl.py from SPARK-LAB/ST-DTKD: direct link, hf CLI and curl.
- Browser
- Download file 2.69 kB
-
https://huggingface.co/SPARK-LAB/ST-DTKD/resolve/main/src/binaryforecast/core/loss/ctl.py
- Command line
-
hf download hf://SPARK-LAB/ST-DTKD/src/binaryforecast/core/loss/ctl.py
-
curl -L -o ctl.py https://huggingface.co/SPARK-LAB/ST-DTKD/resolve/main/src/binaryforecast/core/loss/ctl.py
2.69 kB
| """Supervised contrastive teacher learning and batch diagnostics.""" | |
| import torch | |
| from torch import nn | |
| from torch.nn import functional as F | |
| class SupConLoss(nn.Module): | |
| """Supervised contrastive loss supporting (B,D) and (B,n_views,D).""" | |
| def __init__(self, temperature: float=0.1, base_temperature: float=0.1): | |
| super().__init__() | |
| self.temperature = temperature | |
| self.base_temperature = base_temperature | |
| def forward(self, features: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: | |
| if features.dim() < 2: | |
| raise ValueError('features must have shape (B,D) or (B,n_views,D)') | |
| if features.dim() == 2: | |
| features = features.unsqueeze(1) | |
| elif features.dim() > 3: | |
| features = features.view(features.shape[0], features.shape[1], -1) | |
| (batch_size, contrast_count) = features.shape[:2] | |
| labels = labels.contiguous().view(-1, 1) | |
| if labels.shape[0] != batch_size: | |
| raise ValueError('labels and features must have the same batch size') | |
| mask = torch.eq(labels, labels.T).float().to(features.device) | |
| contrast = F.normalize(torch.cat(torch.unbind(features, dim=1), dim=0), dim=1) | |
| logits = torch.matmul(contrast, contrast.T) / self.temperature | |
| logits = logits - logits.max(dim=1, keepdim=True).values.detach() | |
| mask = mask.repeat(contrast_count, contrast_count) | |
| logits_mask = torch.ones_like(mask) | |
| logits_mask.scatter_(1, torch.arange(batch_size * contrast_count, device=features.device).view(-1, 1), 0) | |
| mask *= logits_mask | |
| log_prob = logits - torch.log((torch.exp(logits) * logits_mask).sum(dim=1, keepdim=True) + 1e-12) | |
| positive_count = mask.sum(dim=1) | |
| valid = positive_count > 0 | |
| if not valid.any(): | |
| return features.sum() * 0.0 | |
| mean_log_prob = (mask[valid] * log_prob[valid]).sum(dim=1) / positive_count[valid] | |
| return (-(self.temperature / self.base_temperature) * mean_log_prob).mean() | |
| def valid_anchor_ratio(labels: torch.Tensor) -> float: | |
| counts = torch.bincount(labels.detach().cpu()) | |
| valid = sum((int(count) for count in counts if int(count) >= 2)) | |
| return float(valid / max(1, labels.numel())) | |
| def anchor_diagnostics(labels): | |
| counts = torch.bincount(labels.detach().cpu(), minlength=2) | |
| n = labels.numel() | |
| return {'valid_anchor_ratio': SupConLoss.valid_anchor_ratio(labels), 'positive_class_anchor_ratio': float(counts[1] / n) if counts[1] >= 2 else 0.0, 'negative_class_anchor_ratio': float(counts[0] / n) if counts[0] >= 2 else 0.0, 'single_class_batch': float((counts > 0).sum() == 1)} | |