arcface_arch.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. import torch.nn as nn
  2. from basicsr.utils.registry import ARCH_REGISTRY
  3. def conv3x3(inplanes, outplanes, stride=1):
  4. """A simple wrapper for 3x3 convolution with padding.
  5. Args:
  6. inplanes (int): Channel number of inputs.
  7. outplanes (int): Channel number of outputs.
  8. stride (int): Stride in convolution. Default: 1.
  9. """
  10. return nn.Conv2d(inplanes, outplanes, kernel_size=3, stride=stride, padding=1, bias=False)
  11. class BasicBlock(nn.Module):
  12. """Basic residual block used in the ResNetArcFace architecture.
  13. Args:
  14. inplanes (int): Channel number of inputs.
  15. planes (int): Channel number of outputs.
  16. stride (int): Stride in convolution. Default: 1.
  17. downsample (nn.Module): The downsample module. Default: None.
  18. """
  19. expansion = 1 # output channel expansion ratio
  20. def __init__(self, inplanes, planes, stride=1, downsample=None):
  21. super(BasicBlock, self).__init__()
  22. self.conv1 = conv3x3(inplanes, planes, stride)
  23. self.bn1 = nn.BatchNorm2d(planes)
  24. self.relu = nn.ReLU(inplace=True)
  25. self.conv2 = conv3x3(planes, planes)
  26. self.bn2 = nn.BatchNorm2d(planes)
  27. self.downsample = downsample
  28. self.stride = stride
  29. def forward(self, x):
  30. residual = x
  31. out = self.conv1(x)
  32. out = self.bn1(out)
  33. out = self.relu(out)
  34. out = self.conv2(out)
  35. out = self.bn2(out)
  36. if self.downsample is not None:
  37. residual = self.downsample(x)
  38. out += residual
  39. out = self.relu(out)
  40. return out
  41. class IRBlock(nn.Module):
  42. """Improved residual block (IR Block) used in the ResNetArcFace architecture.
  43. Args:
  44. inplanes (int): Channel number of inputs.
  45. planes (int): Channel number of outputs.
  46. stride (int): Stride in convolution. Default: 1.
  47. downsample (nn.Module): The downsample module. Default: None.
  48. use_se (bool): Whether use the SEBlock (squeeze and excitation block). Default: True.
  49. """
  50. expansion = 1 # output channel expansion ratio
  51. def __init__(self, inplanes, planes, stride=1, downsample=None, use_se=True):
  52. super(IRBlock, self).__init__()
  53. self.bn0 = nn.BatchNorm2d(inplanes)
  54. self.conv1 = conv3x3(inplanes, inplanes)
  55. self.bn1 = nn.BatchNorm2d(inplanes)
  56. self.prelu = nn.PReLU()
  57. self.conv2 = conv3x3(inplanes, planes, stride)
  58. self.bn2 = nn.BatchNorm2d(planes)
  59. self.downsample = downsample
  60. self.stride = stride
  61. self.use_se = use_se
  62. if self.use_se:
  63. self.se = SEBlock(planes)
  64. def forward(self, x):
  65. residual = x
  66. out = self.bn0(x)
  67. out = self.conv1(out)
  68. out = self.bn1(out)
  69. out = self.prelu(out)
  70. out = self.conv2(out)
  71. out = self.bn2(out)
  72. if self.use_se:
  73. out = self.se(out)
  74. if self.downsample is not None:
  75. residual = self.downsample(x)
  76. out += residual
  77. out = self.prelu(out)
  78. return out
  79. class Bottleneck(nn.Module):
  80. """Bottleneck block used in the ResNetArcFace architecture.
  81. Args:
  82. inplanes (int): Channel number of inputs.
  83. planes (int): Channel number of outputs.
  84. stride (int): Stride in convolution. Default: 1.
  85. downsample (nn.Module): The downsample module. Default: None.
  86. """
  87. expansion = 4 # output channel expansion ratio
  88. def __init__(self, inplanes, planes, stride=1, downsample=None):
  89. super(Bottleneck, self).__init__()
  90. self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
  91. self.bn1 = nn.BatchNorm2d(planes)
  92. self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
  93. self.bn2 = nn.BatchNorm2d(planes)
  94. self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False)
  95. self.bn3 = nn.BatchNorm2d(planes * self.expansion)
  96. self.relu = nn.ReLU(inplace=True)
  97. self.downsample = downsample
  98. self.stride = stride
  99. def forward(self, x):
  100. residual = x
  101. out = self.conv1(x)
  102. out = self.bn1(out)
  103. out = self.relu(out)
  104. out = self.conv2(out)
  105. out = self.bn2(out)
  106. out = self.relu(out)
  107. out = self.conv3(out)
  108. out = self.bn3(out)
  109. if self.downsample is not None:
  110. residual = self.downsample(x)
  111. out += residual
  112. out = self.relu(out)
  113. return out
  114. class SEBlock(nn.Module):
  115. """The squeeze-and-excitation block (SEBlock) used in the IRBlock.
  116. Args:
  117. channel (int): Channel number of inputs.
  118. reduction (int): Channel reduction ration. Default: 16.
  119. """
  120. def __init__(self, channel, reduction=16):
  121. super(SEBlock, self).__init__()
  122. self.avg_pool = nn.AdaptiveAvgPool2d(1) # pool to 1x1 without spatial information
  123. self.fc = nn.Sequential(
  124. nn.Linear(channel, channel // reduction), nn.PReLU(), nn.Linear(channel // reduction, channel),
  125. nn.Sigmoid())
  126. def forward(self, x):
  127. b, c, _, _ = x.size()
  128. y = self.avg_pool(x).view(b, c)
  129. y = self.fc(y).view(b, c, 1, 1)
  130. return x * y
  131. @ARCH_REGISTRY.register()
  132. class ResNetArcFace(nn.Module):
  133. """ArcFace with ResNet architectures.
  134. Ref: ArcFace: Additive Angular Margin Loss for Deep Face Recognition.
  135. Args:
  136. block (str): Block used in the ArcFace architecture.
  137. layers (tuple(int)): Block numbers in each layer.
  138. use_se (bool): Whether use the SEBlock (squeeze and excitation block). Default: True.
  139. """
  140. def __init__(self, block, layers, use_se=True):
  141. if block == 'IRBlock':
  142. block = IRBlock
  143. self.inplanes = 64
  144. self.use_se = use_se
  145. super(ResNetArcFace, self).__init__()
  146. self.conv1 = nn.Conv2d(1, 64, kernel_size=3, padding=1, bias=False)
  147. self.bn1 = nn.BatchNorm2d(64)
  148. self.prelu = nn.PReLU()
  149. self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2)
  150. self.layer1 = self._make_layer(block, 64, layers[0])
  151. self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
  152. self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
  153. self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
  154. self.bn4 = nn.BatchNorm2d(512)
  155. self.dropout = nn.Dropout()
  156. self.fc5 = nn.Linear(512 * 8 * 8, 512)
  157. self.bn5 = nn.BatchNorm1d(512)
  158. # initialization
  159. for m in self.modules():
  160. if isinstance(m, nn.Conv2d):
  161. nn.init.xavier_normal_(m.weight)
  162. elif isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.BatchNorm1d):
  163. nn.init.constant_(m.weight, 1)
  164. nn.init.constant_(m.bias, 0)
  165. elif isinstance(m, nn.Linear):
  166. nn.init.xavier_normal_(m.weight)
  167. nn.init.constant_(m.bias, 0)
  168. def _make_layer(self, block, planes, num_blocks, stride=1):
  169. downsample = None
  170. if stride != 1 or self.inplanes != planes * block.expansion:
  171. downsample = nn.Sequential(
  172. nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False),
  173. nn.BatchNorm2d(planes * block.expansion),
  174. )
  175. layers = []
  176. layers.append(block(self.inplanes, planes, stride, downsample, use_se=self.use_se))
  177. self.inplanes = planes
  178. for _ in range(1, num_blocks):
  179. layers.append(block(self.inplanes, planes, use_se=self.use_se))
  180. return nn.Sequential(*layers)
  181. def forward(self, x):
  182. x = self.conv1(x)
  183. x = self.bn1(x)
  184. x = self.prelu(x)
  185. x = self.maxpool(x)
  186. x = self.layer1(x)
  187. x = self.layer2(x)
  188. x = self.layer3(x)
  189. x = self.layer4(x)
  190. x = self.bn4(x)
  191. x = self.dropout(x)
  192. x = x.view(x.size(0), -1)
  193. x = self.fc5(x)
  194. x = self.bn5(x)
  195. return x