adaptive_avgmax_pool.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. """ PyTorch selectable adaptive pooling
  2. Adaptive pooling with the ability to select the type of pooling from:
  3. * 'avg' - Average pooling
  4. * 'max' - Max pooling
  5. * 'avgmax' - Sum of average and max pooling re-scaled by 0.5
  6. * 'avgmaxc' - Concatenation of average and max pooling along feature dim, doubles feature dim
  7. Both a functional and a nn.Module version of the pooling is provided.
  8. Hacked together by / Copyright 2020 Ross Wightman
  9. """
  10. from typing import Optional, Tuple, Union
  11. import torch
  12. import torch.nn as nn
  13. import torch.nn.functional as F
  14. from .format import get_spatial_dim, get_channel_dim
  15. _int_tuple_2_t = Union[int, Tuple[int, int]]
  16. def adaptive_pool_feat_mult(pool_type='avg'):
  17. if pool_type.endswith('catavgmax'):
  18. return 2
  19. else:
  20. return 1
  21. def adaptive_avgmax_pool2d(x, output_size: _int_tuple_2_t = 1):
  22. x_avg = F.adaptive_avg_pool2d(x, output_size)
  23. x_max = F.adaptive_max_pool2d(x, output_size)
  24. return 0.5 * (x_avg + x_max)
  25. def adaptive_catavgmax_pool2d(x, output_size: _int_tuple_2_t = 1):
  26. x_avg = F.adaptive_avg_pool2d(x, output_size)
  27. x_max = F.adaptive_max_pool2d(x, output_size)
  28. return torch.cat((x_avg, x_max), 1)
  29. def select_adaptive_pool2d(x, pool_type='avg', output_size: _int_tuple_2_t = 1):
  30. """Selectable global pooling function with dynamic input kernel size
  31. """
  32. if pool_type == 'avg':
  33. x = F.adaptive_avg_pool2d(x, output_size)
  34. elif pool_type == 'avgmax':
  35. x = adaptive_avgmax_pool2d(x, output_size)
  36. elif pool_type == 'catavgmax':
  37. x = adaptive_catavgmax_pool2d(x, output_size)
  38. elif pool_type == 'max':
  39. x = F.adaptive_max_pool2d(x, output_size)
  40. else:
  41. assert False, 'Invalid pool type: %s' % pool_type
  42. return x
  43. class FastAdaptiveAvgPool(nn.Module):
  44. def __init__(self, flatten: bool = False, input_fmt: F = 'NCHW'):
  45. super().__init__()
  46. self.flatten = flatten
  47. self.dim = get_spatial_dim(input_fmt)
  48. def forward(self, x):
  49. return x.mean(self.dim, keepdim=not self.flatten)
  50. class FastAdaptiveMaxPool(nn.Module):
  51. def __init__(self, flatten: bool = False, input_fmt: str = 'NCHW'):
  52. super().__init__()
  53. self.flatten = flatten
  54. self.dim = get_spatial_dim(input_fmt)
  55. def forward(self, x):
  56. return x.amax(self.dim, keepdim=not self.flatten)
  57. class FastAdaptiveAvgMaxPool(nn.Module):
  58. def __init__(self, flatten: bool = False, input_fmt: str = 'NCHW'):
  59. super().__init__()
  60. self.flatten = flatten
  61. self.dim = get_spatial_dim(input_fmt)
  62. def forward(self, x):
  63. x_avg = x.mean(self.dim, keepdim=not self.flatten)
  64. x_max = x.amax(self.dim, keepdim=not self.flatten)
  65. return 0.5 * x_avg + 0.5 * x_max
  66. class FastAdaptiveCatAvgMaxPool(nn.Module):
  67. def __init__(self, flatten: bool = False, input_fmt: str = 'NCHW'):
  68. super().__init__()
  69. self.flatten = flatten
  70. self.dim_reduce = get_spatial_dim(input_fmt)
  71. if flatten:
  72. self.dim_cat = 1
  73. else:
  74. self.dim_cat = get_channel_dim(input_fmt)
  75. def forward(self, x):
  76. x_avg = x.mean(self.dim_reduce, keepdim=not self.flatten)
  77. x_max = x.amax(self.dim_reduce, keepdim=not self.flatten)
  78. return torch.cat((x_avg, x_max), self.dim_cat)
  79. class AdaptiveAvgMaxPool2d(nn.Module):
  80. def __init__(self, output_size: _int_tuple_2_t = 1):
  81. super().__init__()
  82. self.output_size = output_size
  83. def forward(self, x):
  84. return adaptive_avgmax_pool2d(x, self.output_size)
  85. class AdaptiveCatAvgMaxPool2d(nn.Module):
  86. def __init__(self, output_size: _int_tuple_2_t = 1):
  87. super().__init__()
  88. self.output_size = output_size
  89. def forward(self, x):
  90. return adaptive_catavgmax_pool2d(x, self.output_size)
  91. class SelectAdaptivePool2d(nn.Module):
  92. """Selectable global pooling layer with dynamic input kernel size
  93. """
  94. def __init__(
  95. self,
  96. output_size: _int_tuple_2_t = 1,
  97. pool_type: str = 'fast',
  98. flatten: bool = False,
  99. input_fmt: str = 'NCHW',
  100. ):
  101. super().__init__()
  102. assert input_fmt in ('NCHW', 'NHWC')
  103. self.pool_type = pool_type or '' # convert other falsy values to empty string for consistent TS typing
  104. pool_type = pool_type.lower()
  105. if not pool_type:
  106. self.pool = nn.Identity() # pass through
  107. self.flatten = nn.Flatten(1) if flatten else nn.Identity()
  108. elif pool_type.startswith('fast') or input_fmt != 'NCHW':
  109. assert output_size == 1, 'Fast pooling and non NCHW input formats require output_size == 1.'
  110. if pool_type.endswith('catavgmax'):
  111. self.pool = FastAdaptiveCatAvgMaxPool(flatten, input_fmt=input_fmt)
  112. elif pool_type.endswith('avgmax'):
  113. self.pool = FastAdaptiveAvgMaxPool(flatten, input_fmt=input_fmt)
  114. elif pool_type.endswith('max'):
  115. self.pool = FastAdaptiveMaxPool(flatten, input_fmt=input_fmt)
  116. elif pool_type == 'fast' or pool_type.endswith('avg'):
  117. self.pool = FastAdaptiveAvgPool(flatten, input_fmt=input_fmt)
  118. else:
  119. assert False, 'Invalid pool type: %s' % pool_type
  120. self.flatten = nn.Identity()
  121. else:
  122. assert input_fmt == 'NCHW'
  123. if pool_type == 'avgmax':
  124. self.pool = AdaptiveAvgMaxPool2d(output_size)
  125. elif pool_type == 'catavgmax':
  126. self.pool = AdaptiveCatAvgMaxPool2d(output_size)
  127. elif pool_type == 'max':
  128. self.pool = nn.AdaptiveMaxPool2d(output_size)
  129. elif pool_type == 'avg':
  130. self.pool = nn.AdaptiveAvgPool2d(output_size)
  131. else:
  132. assert False, 'Invalid pool type: %s' % pool_type
  133. self.flatten = nn.Flatten(1) if flatten else nn.Identity()
  134. def is_identity(self):
  135. return not self.pool_type
  136. def forward(self, x):
  137. x = self.pool(x)
  138. x = self.flatten(x)
  139. return x
  140. def feat_mult(self):
  141. return adaptive_pool_feat_mult(self.pool_type)
  142. def __repr__(self):
  143. return self.__class__.__name__ + '(' \
  144. + 'pool_type=' + self.pool_type \
  145. + ', flatten=' + str(self.flatten) + ')'