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.

64 lines
1.9KB

  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 MemoryEfficientSwish(nn.Module):
  10. class F(torch.autograd.Function):
  11. @staticmethod
  12. def forward(ctx, x):
  13. ctx.save_for_backward(x)
  14. return x * torch.sigmoid(x)
  15. @staticmethod
  16. def backward(ctx, grad_output):
  17. x = ctx.saved_tensors[0]
  18. sx = torch.sigmoid(x)
  19. return grad_output * (sx * (1 + x * (1 - sx)))
  20. def forward(self, x):
  21. return self.F.apply(x)
  22. # Mish https://github.com/digantamisra98/Mish --------------------------------------------------------------------------
  23. class Mish(nn.Module):
  24. @staticmethod
  25. def forward(x):
  26. return x * F.softplus(x).tanh()
  27. class MemoryEfficientMish(nn.Module):
  28. class F(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. def forward(self, x):
  40. return self.F.apply(x)
  41. # FReLU https://arxiv.org/abs/2007.11824 -------------------------------------------------------------------------------
  42. class FReLU(nn.Module):
  43. def __init__(self, c1, k=3): # ch_in, kernel
  44. super().__init__()
  45. self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1)
  46. self.bn = nn.BatchNorm2d(c1)
  47. def forward(self, x):
  48. return torch.max(x, self.bn(self.conv(x)))