選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

64 行
1.6KB

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