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.

73 lines
2.2KB

  1. # Activation functions
  2. import torch
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. # SiLU https://arxiv.org/pdf/1606.08415.pdf ----------------------------------------------------------------------------
  6. class SiLU(nn.Module): # export-friendly version of nn.SiLU()
  7. @staticmethod
  8. def forward(x):
  9. return x * torch.sigmoid(x)
  10. class Hardswish(nn.Module): # export-friendly version of nn.Hardswish()
  11. @staticmethod
  12. def forward(x):
  13. # return x * F.hardsigmoid(x) # for torchscript and CoreML
  14. return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX
  15. class MemoryEfficientSwish(nn.Module):
  16. class F(torch.autograd.Function):
  17. @staticmethod
  18. def forward(ctx, x):
  19. ctx.save_for_backward(x)
  20. return x * torch.sigmoid(x)
  21. @staticmethod
  22. def backward(ctx, grad_output):
  23. x = ctx.saved_tensors[0]
  24. sx = torch.sigmoid(x)
  25. return grad_output * (sx * (1 + x * (1 - sx)))
  26. def forward(self, x):
  27. return self.F.apply(x)
  28. # Mish https://github.com/digantamisra98/Mish --------------------------------------------------------------------------
  29. class Mish(nn.Module):
  30. @staticmethod
  31. def forward(x):
  32. return x * F.softplus(x).tanh()
  33. class MemoryEfficientMish(nn.Module):
  34. class F(torch.autograd.Function):
  35. @staticmethod
  36. def forward(ctx, x):
  37. ctx.save_for_backward(x)
  38. return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
  39. @staticmethod
  40. def backward(ctx, grad_output):
  41. x = ctx.saved_tensors[0]
  42. sx = torch.sigmoid(x)
  43. fx = F.softplus(x).tanh()
  44. return grad_output * (fx + x * sx * (1 - fx * fx))
  45. def forward(self, x):
  46. return self.F.apply(x)
  47. # FReLU https://arxiv.org/abs/2007.11824 -------------------------------------------------------------------------------
  48. class FReLU(nn.Module):
  49. def __init__(self, c1, k=3): # ch_in, kernel
  50. super().__init__()
  51. self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)
  52. self.bn = nn.BatchNorm2d(c1)
  53. def forward(self, x):
  54. return torch.max(x, self.bn(self.conv(x)))