Created
April 7, 2020 20:21
-
-
Save rohit-gupta/20dd994332b35c71be6b497f4f4a1dc7 to your computer and use it in GitHub Desktop.
Reverse Gradients in PyTorch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from torch.autograd import Function | |
class GradientReversal(Function): | |
@staticmethod | |
def forward(ctx, x): | |
ctx.save_for_backward(x) | |
output = x | |
return output | |
@staticmethod | |
def backward(ctx, grad_output): | |
grad_input = None | |
if ctx.needs_input_grad[0]: | |
grad_input = grad_output.neg() | |
return grad_input | |
reverse_gradients = GradientReversal.apply |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment