squeeze_excite.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. """ Squeeze-and-Excitation Channel Attention
  2. An SE implementation originally based on PyTorch SE-Net impl.
  3. Has since evolved with additional functionality / configuration.
  4. Paper: `Squeeze-and-Excitation Networks` - https://arxiv.org/abs/1709.01507
  5. Also included is Effective Squeeze-Excitation (ESE).
  6. Paper: `CenterMask : Real-Time Anchor-Free Instance Segmentation` - https://arxiv.org/abs/1911.06667
  7. Hacked together by / Copyright 2021 Ross Wightman
  8. """
  9. from typing import Optional, Tuple, Type, Union
  10. from torch import nn as nn
  11. from .create_act import create_act_layer
  12. from .helpers import make_divisible
  13. class SEModule(nn.Module):
  14. """ SE Module as defined in original SE-Nets with a few additions
  15. Additions include:
  16. * divisor can be specified to keep channels % div == 0 (default: 8)
  17. * reduction channels can be specified directly by arg (if rd_channels is set)
  18. * reduction channels can be specified by float rd_ratio (default: 1/16)
  19. * global max pooling can be added to the squeeze aggregation
  20. * customizable activation, normalization, and gate layer
  21. """
  22. def __init__(
  23. self,
  24. channels: int,
  25. rd_ratio: float = 1. / 16,
  26. rd_channels: Optional[int] = None,
  27. rd_divisor: int = 8,
  28. add_maxpool: bool = False,
  29. bias: bool = True,
  30. act_layer: Type[nn.Module] = nn.ReLU,
  31. norm_layer: Optional[Type[nn.Module]] = None,
  32. gate_layer: Union[str, Type[nn.Module]] = 'sigmoid',
  33. device=None,
  34. dtype=None,
  35. ):
  36. dd = {'device': device, 'dtype': dtype}
  37. super().__init__()
  38. self.add_maxpool = add_maxpool
  39. if not rd_channels:
  40. rd_channels = make_divisible(channels * rd_ratio, rd_divisor, round_limit=0.)
  41. self.fc1 = nn.Conv2d(channels, rd_channels, kernel_size=1, bias=bias, **dd)
  42. self.bn = norm_layer(rd_channels, **dd) if norm_layer else nn.Identity()
  43. self.act = create_act_layer(act_layer, inplace=True)
  44. self.fc2 = nn.Conv2d(rd_channels, channels, kernel_size=1, bias=bias, **dd)
  45. self.gate = create_act_layer(gate_layer)
  46. def forward(self, x):
  47. x_se = x.mean((2, 3), keepdim=True)
  48. if self.add_maxpool:
  49. # experimental codepath, may remove or change
  50. x_se = 0.5 * x_se + 0.5 * x.amax((2, 3), keepdim=True)
  51. x_se = self.fc1(x_se)
  52. x_se = self.act(self.bn(x_se))
  53. x_se = self.fc2(x_se)
  54. return x * self.gate(x_se)
  55. SqueezeExcite = SEModule # alias
  56. class EffectiveSEModule(nn.Module):
  57. """ 'Effective Squeeze-Excitation
  58. From `CenterMask : Real-Time Anchor-Free Instance Segmentation` - https://arxiv.org/abs/1911.06667
  59. """
  60. def __init__(
  61. self,
  62. channels: int,
  63. add_maxpool: bool = False,
  64. gate_layer: Union[str, Type[nn.Module]] = 'hard_sigmoid',
  65. device=None,
  66. dtype=None,
  67. **_,
  68. ):
  69. dd = {'device': device, 'dtype': dtype}
  70. super().__init__()
  71. self.add_maxpool = add_maxpool
  72. self.fc = nn.Conv2d(channels, channels, kernel_size=1, padding=0, device=device, dtype=dtype)
  73. self.gate = create_act_layer(gate_layer)
  74. def forward(self, x):
  75. x_se = x.mean((2, 3), keepdim=True)
  76. if self.add_maxpool:
  77. # experimental codepath, may remove or change
  78. x_se = 0.5 * x_se + 0.5 * x.amax((2, 3), keepdim=True)
  79. x_se = self.fc(x_se)
  80. return x * self.gate(x_se)
  81. EffectiveSqueezeExcite = EffectiveSEModule # alias
  82. class SqueezeExciteCl(nn.Module):
  83. """ SE Module as defined in original SE-Nets with a few additions
  84. Additions include:
  85. * divisor can be specified to keep channels % div == 0 (default: 8)
  86. * reduction channels can be specified directly by arg (if rd_channels is set)
  87. * reduction channels can be specified by float rd_ratio (default: 1/16)
  88. * global max pooling can be added to the squeeze aggregation
  89. * customizable activation, normalization, and gate layer
  90. """
  91. def __init__(
  92. self,
  93. channels: int,
  94. rd_ratio: float = 1. / 16,
  95. rd_channels: Optional[int] = None,
  96. rd_divisor: int = 8,
  97. bias: bool = True,
  98. act_layer: Type[nn.Module] = nn.ReLU,
  99. gate_layer: Union[str, Type[nn.Module]] = 'sigmoid',
  100. device=None,
  101. dtype=None,
  102. ):
  103. dd = {'device': device, 'dtype': dtype}
  104. super().__init__()
  105. if not rd_channels:
  106. rd_channels = make_divisible(channels * rd_ratio, rd_divisor, round_limit=0.)
  107. self.fc1 = nn.Linear(channels, rd_channels, bias=bias, **dd)
  108. self.act = create_act_layer(act_layer, inplace=True)
  109. self.fc2 = nn.Linear(rd_channels, channels, bias=bias, **dd)
  110. self.gate = create_act_layer(gate_layer)
  111. def forward(self, x):
  112. x_se = x.mean((1, 2), keepdims=True) # FIXME avg dim [1:n-1], don't assume 2D NHWC
  113. x_se = self.fc1(x_se)
  114. x_se = self.act(x_se)
  115. x_se = self.fc2(x_se)
  116. return x * self.gate(x_se)