rednet.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. # copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # Code was based on https://github.com/d-li14/involution
  15. import paddle
  16. import paddle.nn as nn
  17. from paddle.vision.models import resnet
  18. from paddlex.ppcls.utils.save_load import load_dygraph_pretrain, load_dygraph_pretrain_from_url
  19. MODEL_URLS = {
  20. "RedNet26":
  21. "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/RedNet26_pretrained.pdparams",
  22. "RedNet38":
  23. "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/RedNet38_pretrained.pdparams",
  24. "RedNet50":
  25. "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/RedNet50_pretrained.pdparams",
  26. "RedNet101":
  27. "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/RedNet101_pretrained.pdparams",
  28. "RedNet152":
  29. "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/RedNet152_pretrained.pdparams"
  30. }
  31. __all__ = MODEL_URLS.keys()
  32. class Involution(nn.Layer):
  33. def __init__(self, channels, kernel_size, stride):
  34. super(Involution, self).__init__()
  35. self.kernel_size = kernel_size
  36. self.stride = stride
  37. self.channels = channels
  38. reduction_ratio = 4
  39. self.group_channels = 16
  40. self.groups = self.channels // self.group_channels
  41. self.conv1 = nn.Sequential(
  42. ('conv', nn.Conv2D(
  43. in_channels=channels,
  44. out_channels=channels // reduction_ratio,
  45. kernel_size=1,
  46. bias_attr=False)),
  47. ('bn', nn.BatchNorm2D(channels // reduction_ratio)),
  48. ('activate', nn.ReLU()))
  49. self.conv2 = nn.Sequential(('conv', nn.Conv2D(
  50. in_channels=channels // reduction_ratio,
  51. out_channels=kernel_size**2 * self.groups,
  52. kernel_size=1,
  53. stride=1)))
  54. if stride > 1:
  55. self.avgpool = nn.AvgPool2D(stride, stride)
  56. def forward(self, x):
  57. weight = self.conv2(
  58. self.conv1(x if self.stride == 1 else self.avgpool(x)))
  59. b, c, h, w = weight.shape
  60. weight = weight.reshape(
  61. (b, self.groups, self.kernel_size**2, h, w)).unsqueeze(2)
  62. out = nn.functional.unfold(x, self.kernel_size, self.stride,
  63. (self.kernel_size - 1) // 2, 1)
  64. out = out.reshape(
  65. (b, self.groups, self.group_channels, self.kernel_size**2, h, w))
  66. out = (weight * out).sum(axis=3).reshape((b, self.channels, h, w))
  67. return out
  68. class BottleneckBlock(resnet.BottleneckBlock):
  69. def __init__(self,
  70. inplanes,
  71. planes,
  72. stride=1,
  73. downsample=None,
  74. groups=1,
  75. base_width=64,
  76. dilation=1,
  77. norm_layer=None):
  78. super(BottleneckBlock, self).__init__(inplanes, planes, stride,
  79. downsample, groups, base_width,
  80. dilation, norm_layer)
  81. width = int(planes * (base_width / 64.)) * groups
  82. self.conv2 = Involution(width, 7, stride)
  83. class RedNet(resnet.ResNet):
  84. def __init__(self, block, depth, class_num=1000, with_pool=True):
  85. super(RedNet, self).__init__(
  86. block=block, depth=50, num_classes=class_num, with_pool=with_pool)
  87. layer_cfg = {
  88. 26: [1, 2, 4, 1],
  89. 38: [2, 3, 5, 2],
  90. 50: [3, 4, 6, 3],
  91. 101: [3, 4, 23, 3],
  92. 152: [3, 8, 36, 3]
  93. }
  94. layers = layer_cfg[depth]
  95. self.conv1 = None
  96. self.bn1 = None
  97. self.relu = None
  98. self.inplanes = 64
  99. self.class_num = class_num
  100. self.stem = nn.Sequential(
  101. nn.Sequential(
  102. ('conv', nn.Conv2D(
  103. in_channels=3,
  104. out_channels=self.inplanes // 2,
  105. kernel_size=3,
  106. stride=2,
  107. padding=1,
  108. bias_attr=False)),
  109. ('bn', nn.BatchNorm2D(self.inplanes // 2)),
  110. ('activate', nn.ReLU())),
  111. Involution(self.inplanes // 2, 3, 1),
  112. nn.BatchNorm2D(self.inplanes // 2),
  113. nn.ReLU(),
  114. nn.Sequential(
  115. ('conv', nn.Conv2D(
  116. in_channels=self.inplanes // 2,
  117. out_channels=self.inplanes,
  118. kernel_size=3,
  119. stride=1,
  120. padding=1,
  121. bias_attr=False)), ('bn', nn.BatchNorm2D(self.inplanes)),
  122. ('activate', nn.ReLU())))
  123. self.layer1 = self._make_layer(block, 64, layers[0])
  124. self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
  125. self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
  126. self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
  127. def forward(self, x):
  128. x = self.stem(x)
  129. x = self.maxpool(x)
  130. x = self.layer1(x)
  131. x = self.layer2(x)
  132. x = self.layer3(x)
  133. x = self.layer4(x)
  134. if self.with_pool:
  135. x = self.avgpool(x)
  136. if self.class_num > 0:
  137. x = paddle.flatten(x, 1)
  138. x = self.fc(x)
  139. return x
  140. def _load_pretrained(pretrained, model, model_url, use_ssld=False):
  141. if pretrained is False:
  142. pass
  143. elif pretrained is True:
  144. load_dygraph_pretrain_from_url(model, model_url, use_ssld=use_ssld)
  145. elif isinstance(pretrained, str):
  146. load_dygraph_pretrain(model, pretrained)
  147. else:
  148. raise RuntimeError(
  149. "pretrained type is not available. Please use `string` or `boolean` type."
  150. )
  151. def RedNet26(pretrained=False, **kwargs):
  152. model = RedNet(BottleneckBlock, 26, **kwargs)
  153. _load_pretrained(pretrained, model, MODEL_URLS["RedNet26"])
  154. return model
  155. def RedNet38(pretrained=False, **kwargs):
  156. model = RedNet(BottleneckBlock, 38, **kwargs)
  157. _load_pretrained(pretrained, model, MODEL_URLS["RedNet38"])
  158. return model
  159. def RedNet50(pretrained=False, **kwargs):
  160. model = RedNet(BottleneckBlock, 50, **kwargs)
  161. _load_pretrained(pretrained, model, MODEL_URLS["RedNet50"])
  162. return model
  163. def RedNet101(pretrained=False, **kwargs):
  164. model = RedNet(BottleneckBlock, 101, **kwargs)
  165. _load_pretrained(pretrained, model, MODEL_URLS["RedNet101"])
  166. return model
  167. def RedNet152(pretrained=False, **kwargs):
  168. model = RedNet(BottleneckBlock, 152, **kwargs)
  169. _load_pretrained(pretrained, model, MODEL_URLS["RedNet152"])
  170. return model