UFR-Fing / src /losses /total_loss.py
anbinh39's picture
Add files using upload-large-folder tool
dadf189 verified
Raw
History Blame Contribute Delete
1.85 kB
from __future__ import annotations
from typing import Any
import torch
import torch.nn as nn
class SIFQLoss(nn.Module):
"""Combine all objective terms with stage-dependent weights."""
def __init__(
self,
matcher_teacher: nn.Module | None,
sensor_invariance: nn.Module | None,
degradation_ranking: nn.Module | None,
orthogonality: nn.Module,
):
super().__init__()
self.matcher_teacher = matcher_teacher
self.sensor_invariance = sensor_invariance
self.degradation_ranking = degradation_ranking
self.orthogonality = orthogonality
def forward(
self,
outputs: dict[str, torch.Tensor],
batch: dict[str, Any],
alpha: float,
beta: float,
gamma_stage: float,
) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
device = outputs["score"].device
zero = torch.tensor(0.0, device=device)
l_mat = zero
if self.matcher_teacher is not None and batch.get("matcher") is not None:
args = batch["matcher"]
l_mat = self.matcher_teacher(pred_score=outputs["score"], **args)
l_sens = zero
if self.sensor_invariance is not None and batch.get("sensor") is not None:
args = batch["sensor"]
l_sens = self.sensor_invariance(**args)
l_deg = zero
if self.degradation_ranking is not None and batch.get("degradation") is not None:
args = batch["degradation"]
l_deg = self.degradation_ranking(**args)
l_orth = self.orthogonality(outputs["concepts"])
total = alpha * l_mat + beta * l_sens + gamma_stage * l_deg + l_orth
return total, {
"l_mat": l_mat,
"l_sens": l_sens,
"l_deg": l_deg,
"l_orth": l_orth,
}