You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.6KB

  1. import torch
  2. import torch.functional as F
  3. import torch.nn as nn
  4. # Swish ------------------------------------------------------------------------
  5. class SwishImplementation(torch.autograd.Function):
  6. @staticmethod
  7. def forward(ctx, x):
  8. ctx.save_for_backward(x)
  9. return x * torch.sigmoid(x)
  10. @staticmethod
  11. def backward(ctx, grad_output):
  12. x = ctx.saved_tensors[0]
  13. sx = torch.sigmoid(x)
  14. return grad_output * (sx * (1 + x * (1 - sx)))
  15. class MemoryEfficientSwish(nn.Module):
  16. @staticmethod
  17. def forward(x):
  18. return SwishImplementation.apply(x)
  19. class HardSwish(nn.Module): # https://arxiv.org/pdf/1905.02244.pdf
  20. @staticmethod
  21. def forward(x):
  22. return x * F.hardtanh(x + 3, 0., 6., True) / 6.
  23. class Swish(nn.Module):
  24. @staticmethod
  25. def forward(x):
  26. return x * torch.sigmoid(x)
  27. # Mish ------------------------------------------------------------------------
  28. class MishImplementation(torch.autograd.Function):
  29. @staticmethod
  30. def forward(ctx, x):
  31. ctx.save_for_backward(x)
  32. return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
  33. @staticmethod
  34. def backward(ctx, grad_output):
  35. x = ctx.saved_tensors[0]
  36. sx = torch.sigmoid(x)
  37. fx = F.softplus(x).tanh()
  38. return grad_output * (fx + x * sx * (1 - fx * fx))
  39. class MemoryEfficientMish(nn.Module):
  40. @staticmethod
  41. def forward(x):
  42. return MishImplementation.apply(x)
  43. class Mish(nn.Module): # https://github.com/digantamisra98/Mish
  44. @staticmethod
  45. def forward(x):
  46. return x * F.softplus(x).tanh()