File size: 1,502 Bytes
dadf189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
46
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_)