File size: 2,172 Bytes
21419ae | 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 | """Shared logit/feature distillation and weighted dual-teacher composition."""
import torch
from torch import nn
from torch.nn import functional as F
def logits_kd(student, teacher, temperature=4.0, reduction='batchmean'):
return F.kl_div(F.log_softmax(student / temperature, dim=1), F.softmax(teacher.detach() / temperature, dim=1), reduction=reduction) * temperature ** 2
def feature_kd(student, teacher, projector):
return (1 - F.cosine_similarity(projector(student), teacher.detach(), dim=1, eps=1e-06)).mean()
class LogitsKDLoss(nn.Module):
def __init__(self, temperature: float=2.0, reduction: str='batchmean'):
super().__init__()
self.temperature = float(temperature)
self.reduction = reduction
def forward(self, student_logits: torch.Tensor, teacher_logits: torch.Tensor) -> torch.Tensor:
return logits_kd(student_logits, teacher_logits, self.temperature, self.reduction)
def kd_warmup_lambda(epoch: int, base_lambda: float=1.0, warmup_start: int=5, warmup_epochs: int=10) -> float:
if epoch <= warmup_start:
return 0.0
return min(base_lambda, base_lambda * (epoch - warmup_start) / max(1, warmup_epochs))
class DualTeacherKDLoss(nn.Module):
def __init__(self, class_loss_fn: nn.Module, temperature: float=2.0, weight_3d: float=0.5, weight_mdt: float=0.5):
super().__init__()
total = float(weight_3d + weight_mdt)
if total <= 0:
raise ValueError('weight_3d + weight_mdt must be positive')
self.class_loss_fn = class_loss_fn
self.kd_loss_fn = LogitsKDLoss(temperature)
self.weight_3d = float(weight_3d) / total
self.weight_mdt = float(weight_mdt) / total
def forward(self, student_logits, labels, teacher_3d_logits, teacher_mdt_logits, lambda_kd: float=1.0):
class_loss = self.class_loss_fn(student_logits, labels)
kd_3d = self.kd_loss_fn(student_logits, teacher_3d_logits)
kd_mdt = self.kd_loss_fn(student_logits, teacher_mdt_logits)
kd_total = self.weight_3d * kd_3d + self.weight_mdt * kd_mdt
return (class_loss + lambda_kd * kd_total, class_loss, kd_3d, kd_mdt, kd_total)
|