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.

71 lines
2.1KB

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