File size: 469 Bytes
0161e74 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import torch
from torch.autograd import Function
class GradReverse(Function):
@staticmethod
def forward(ctx, x: torch.Tensor, lambd: float) -> torch.Tensor:
ctx.lambd = lambd
return x.view_as(x)
@staticmethod
def backward(ctx, grad_output: torch.Tensor) -> torch.Tensor:
return grad_output.neg() * ctx.lambd, None
def grad_reverse(x: torch.Tensor, lambd: float = 1.0) -> torch.Tensor:
return GradReverse.apply(x, lambd)
|