UFR-Fing / src /models /grad_reverse.py
anbinh39's picture
Add files using upload-large-folder tool
dadf189 verified
Raw
History Blame Contribute Delete
1.5 kB
from __future__ import annotations
import math
import torch
import torch.nn as nn
class _GradientReverseFn(torch.autograd.Function):
@staticmethod
def forward(ctx, x: torch.Tensor, lambda_: float):
ctx.lambda_ = lambda_
return x.view_as(x)
@staticmethod
def backward(ctx, grad_output: torch.Tensor):
return -ctx.lambda_ * grad_output, None
class GradientReversalLayer(nn.Module):
"""Identity at forward, sign-flipped gradient at backward.
Supports dynamic lambda via ``set_lambda()`` or the DANN warm-up
schedule via ``dann_lambda(progress)`` where progress \u2208 [0, 1].
DANN schedule: \u03bb(p) = 2 / (1 + exp(-10\u00b7p)) - 1 (grows 0 \u2192 1 smoothly)
capped at ``lambda_max`` to prevent over-suppression early in training.
"""
def __init__(self, lambda_: float = 0.3, lambda_max: float = 0.6):
super().__init__()
self.lambda_ = float(lambda_)
self.lambda_max = float(lambda_max)
def set_lambda(self, value: float) -> None:
"""Directly set lambda (used by training loop)."""
self.lambda_ = float(value)
@staticmethod
def dann_lambda(progress: float, lambda_max: float = 0.6) -> float:
"""DANN warm-up schedule: \u03bb(p) = min(lambda_max, 2/(1+exp(-10p))-1)."""
return min(lambda_max, 2.0 / (1.0 + math.exp(-10.0 * progress)) - 1.0)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return _GradientReverseFn.apply(x, self.lambda_)