UFR-Fing / src /losses /sensor_invariance.py
anbinh39's picture
Add files using upload-large-folder tool
dadf189 verified
Raw
History Blame Contribute Delete
1.86 kB
from __future__ import annotations
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class SensorInvarianceLoss(nn.Module):
"""Cross-sensor pair + adversarial sensor loss.
Returns a 3-tuple ``(total, l_pair_detached, l_adv_detached)`` so callers
can log sub-components without extra forward passes.
GRL anti-correlation fix: l_adv is clamped at the random-guess baseline
``log(num_sensors)`` before being weighted into the total. This prevents
the backbone from overshooting — i.e. learning to actively anti-encode
sensor identity — while still driving the discriminator toward confusion.
Once l_adv >= log(N) the adversarial pressure on the backbone drops to
zero and the GRL game reaches a stable equilibrium instead of cycling.
"""
def __init__(self, delta: float = 0.05, lambda_adv: float = 0.3):
super().__init__()
self.delta = float(delta)
self.lambda_adv = float(lambda_adv)
def forward(
self,
score_s1: torch.Tensor,
score_s2: torch.Tensor,
sensor_logits: torch.Tensor,
sensor_labels: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
l_pair = F.relu((score_s1 - score_s2).abs() - self.delta).mean()
l_adv = F.cross_entropy(sensor_logits, sensor_labels)
# Clamp adversarial contribution at the random-guess CE baseline.
# Above this ceiling the backbone is already fooling the discriminator
# sufficiently; continued gradient reversal only creates anti-correlation
# oscillation without improving sensor invariance.
rand_ce = math.log(sensor_logits.size(1))
l_adv_clamped = l_adv.clamp(max=rand_ce)
total = l_pair + self.lambda_adv * l_adv_clamped
return total, l_pair.detach(), l_adv.detach()