eca.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. """
  2. ECA module from ECAnet
  3. paper: ECA-Net: Efficient Channel Attention for Deep Convolutional Neural Networks
  4. https://arxiv.org/abs/1910.03151
  5. Original ECA model borrowed from https://github.com/BangguWu/ECANet
  6. Modified circular ECA implementation and adaption for use in timm package
  7. by Chris Ha https://github.com/VRandme
  8. Original License:
  9. MIT License
  10. Copyright (c) 2019 BangguWu, Qilong Wang
  11. Permission is hereby granted, free of charge, to any person obtaining a copy
  12. of this software and associated documentation files (the "Software"), to deal
  13. in the Software without restriction, including without limitation the rights
  14. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. copies of the Software, and to permit persons to whom the Software is
  16. furnished to do so, subject to the following conditions:
  17. The above copyright notice and this permission notice shall be included in all
  18. copies or substantial portions of the Software.
  19. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  25. SOFTWARE.
  26. """
  27. from typing import Optional, Tuple, Type, Union
  28. import math
  29. from torch import nn
  30. import torch.nn.functional as F
  31. from .create_act import create_act_layer
  32. from .helpers import make_divisible
  33. class EcaModule(nn.Module):
  34. """Constructs an ECA module.
  35. Args:
  36. channels: Number of channels of the input feature map for use in adaptive kernel sizes
  37. for actual calculations according to channel.
  38. gamma, beta: when channel is given parameters of mapping function
  39. refer to original paper https://arxiv.org/pdf/1910.03151.pdf
  40. (default=None. if channel size not given, use k_size given for kernel size.)
  41. kernel_size: Adaptive selection of kernel size (default=3)
  42. gamm: used in kernel_size calc, see above
  43. beta: used in kernel_size calc, see above
  44. act_layer: optional non-linearity after conv, enables conv bias, this is an experiment
  45. gate_layer: gating non-linearity to use
  46. """
  47. def __init__(
  48. self,
  49. channels: Optional[int] = None,
  50. kernel_size: int = 3,
  51. gamma: float = 2,
  52. beta: float = 1,
  53. act_layer: Optional[Type[nn.Module]] = None,
  54. gate_layer: Union[str, Type[nn.Module]] = 'sigmoid',
  55. rd_ratio: float = 1/8,
  56. rd_channels: Optional[int] = None,
  57. rd_divisor: int = 8,
  58. use_mlp: bool = False,
  59. device=None,
  60. dtype=None,
  61. ):
  62. dd = {'device': device, 'dtype': dtype}
  63. super().__init__()
  64. if channels is not None:
  65. t = int(abs(math.log(channels, 2) + beta) / gamma)
  66. kernel_size = max(t if t % 2 else t + 1, 3)
  67. assert kernel_size % 2 == 1
  68. padding = (kernel_size - 1) // 2
  69. if use_mlp:
  70. # NOTE 'mlp' mode is a timm experiment, not in paper
  71. assert channels is not None
  72. if rd_channels is None:
  73. rd_channels = make_divisible(channels * rd_ratio, divisor=rd_divisor)
  74. act_layer = act_layer or nn.ReLU
  75. self.conv = nn.Conv1d(1, rd_channels, kernel_size=1, padding=0, bias=True, **dd)
  76. self.act = create_act_layer(act_layer)
  77. self.conv2 = nn.Conv1d(rd_channels, 1, kernel_size=kernel_size, padding=padding, bias=True, **dd)
  78. else:
  79. self.conv = nn.Conv1d(1, 1, kernel_size=kernel_size, padding=padding, bias=False, **dd)
  80. self.act = None
  81. self.conv2 = None
  82. self.gate = create_act_layer(gate_layer)
  83. def forward(self, x):
  84. y = x.mean((2, 3)).view(x.shape[0], 1, -1) # view for 1d conv
  85. y = self.conv(y)
  86. if self.conv2 is not None:
  87. y = self.act(y)
  88. y = self.conv2(y)
  89. y = self.gate(y).view(x.shape[0], -1, 1, 1)
  90. return x * y.expand_as(x)
  91. EfficientChannelAttn = EcaModule # alias
  92. class CecaModule(nn.Module):
  93. """Constructs a circular ECA module.
  94. ECA module where the conv uses circular padding rather than zero padding.
  95. Unlike the spatial dimension, the channels do not have inherent ordering nor
  96. locality. Although this module in essence, applies such an assumption, it is unnecessary
  97. to limit the channels on either "edge" from being circularly adapted to each other.
  98. This will fundamentally increase connectivity and possibly increase performance metrics
  99. (accuracy, robustness), without significantly impacting resource metrics
  100. (parameter size, throughput,latency, etc)
  101. Args:
  102. channels: Number of channels of the input feature map for use in adaptive kernel sizes
  103. for actual calculations according to channel.
  104. gamma, beta: when channel is given parameters of mapping function
  105. refer to original paper https://arxiv.org/pdf/1910.03151.pdf
  106. (default=None. if channel size not given, use k_size given for kernel size.)
  107. kernel_size: Adaptive selection of kernel size (default=3)
  108. gamm: used in kernel_size calc, see above
  109. beta: used in kernel_size calc, see above
  110. act_layer: optional non-linearity after conv, enables conv bias, this is an experiment
  111. gate_layer: gating non-linearity to use
  112. """
  113. def __init__(
  114. self,
  115. channels: Optional[int] = None,
  116. kernel_size: int = 3,
  117. gamma: float = 2,
  118. beta: float = 1,
  119. act_layer: Optional[nn.Module] = None,
  120. gate_layer: Union[str, Type[nn.Module]] = 'sigmoid',
  121. device=None,
  122. dtype=None,
  123. ):
  124. dd = {'device': device, 'dtype': dtype}
  125. super().__init__()
  126. if channels is not None:
  127. t = int(abs(math.log(channels, 2) + beta) / gamma)
  128. kernel_size = max(t if t % 2 else t + 1, 3)
  129. has_act = act_layer is not None
  130. assert kernel_size % 2 == 1
  131. # PyTorch circular padding mode is buggy as of pytorch 1.4
  132. # see https://github.com/pytorch/pytorch/pull/17240
  133. # implement manual circular padding
  134. self.padding = (kernel_size - 1) // 2
  135. self.conv = nn.Conv1d(1, 1, kernel_size=kernel_size, padding=0, bias=has_act, **dd)
  136. self.gate = create_act_layer(gate_layer)
  137. def forward(self, x):
  138. y = x.mean((2, 3)).view(x.shape[0], 1, -1)
  139. # Manually implement circular padding, F.pad does not seemed to be bugged
  140. y = F.pad(y, (self.padding, self.padding), mode='circular')
  141. y = self.conv(y)
  142. y = self.gate(y).view(x.shape[0], -1, 1, 1)
  143. return x * y.expand_as(x)
  144. CircularEfficientChannelAttn = CecaModule