modules.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import numpy as np
  2. import torch
  3. import torch.nn as nn
  4. # --------------------- Basic modules ---------------------
  5. def get_activation(act_type=None):
  6. if act_type == 'relu':
  7. return nn.ReLU(inplace=True)
  8. elif act_type == 'lrelu':
  9. return nn.LeakyReLU(0.1, inplace=True)
  10. elif act_type == 'mish':
  11. return nn.Mish(inplace=True)
  12. elif act_type == 'silu':
  13. return nn.SiLU(inplace=True)
  14. elif act_type is None:
  15. return nn.Identity()
  16. else:
  17. raise NotImplementedError
  18. class ConvModule(nn.Module):
  19. def __init__(self,
  20. in_dim, # in channels
  21. out_dim, # out channels
  22. kernel_size=1, # kernel size
  23. padding=0, # padding
  24. stride=1, # padding
  25. act_type :str = 'lrelu', # activation
  26. ):
  27. super(ConvModule, self).__init__()
  28. self.conv = nn.Conv2d(in_dim, out_dim, kernel_size=kernel_size, padding=padding, stride=stride, bias=False)
  29. self.norm = nn.BatchNorm2d(out_dim)
  30. self.act = get_activation(act_type)
  31. def forward(self, x):
  32. return self.act(self.norm(self.conv(x)))
  33. class RepVGGBlock(nn.Module):
  34. def __init__(self,
  35. in_channels,
  36. out_channels,
  37. kernel_size=3,
  38. stride=1,
  39. padding=1,
  40. dilation=1,
  41. groups=1,
  42. deploy=False,
  43. ):
  44. super(RepVGGBlock, self).__init__()
  45. assert kernel_size == 3
  46. assert padding == 1
  47. # --------- Basic parameters ---------
  48. self.deploy = deploy
  49. self.groups = groups
  50. self.in_channels = in_channels
  51. self.out_channels = out_channels
  52. padding_11 = padding - kernel_size // 2
  53. # --------- Model parameters ---------
  54. if deploy:
  55. self.rbr_reparam = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride,
  56. padding=padding, dilation=dilation, groups=groups, bias=True)
  57. else:
  58. self.rbr_identity = nn.BatchNorm2d(num_features=in_channels) if out_channels == in_channels and stride == 1 else None
  59. self.rbr_dense = ConvModule(in_channels, out_channels, kernel_size=kernel_size, padding=padding, stride=stride, act_type=None)
  60. self.rbr_1x1 = ConvModule(in_channels, out_channels, kernel_size=1, padding=padding_11, stride=stride, act_type=None)
  61. self.nonlinearity = nn.ReLU()
  62. def forward(self, inputs):
  63. '''Forward process'''
  64. if hasattr(self, 'rbr_reparam'):
  65. return self.nonlinearity(self.rbr_reparam(inputs))
  66. if self.rbr_identity is None:
  67. id_out = 0
  68. else:
  69. id_out = self.rbr_identity(inputs)
  70. return self.nonlinearity(self.rbr_dense(inputs) + self.rbr_1x1(inputs) + id_out)
  71. def get_equivalent_kernel_bias(self):
  72. kernel3x3, bias3x3 = self._fuse_bn_tensor(self.rbr_dense)
  73. kernel1x1, bias1x1 = self._fuse_bn_tensor(self.rbr_1x1)
  74. kernelid, biasid = self._fuse_bn_tensor(self.rbr_identity)
  75. return kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid, bias3x3 + bias1x1 + biasid
  76. def _avg_to_3x3_tensor(self, avgp):
  77. channels = self.in_channels
  78. groups = self.groups
  79. kernel_size = avgp.kernel_size
  80. input_dim = channels // groups
  81. k = torch.zeros((channels, input_dim, kernel_size, kernel_size))
  82. k[np.arange(channels), np.tile(np.arange(input_dim), groups), :, :] = 1.0 / kernel_size ** 2
  83. return k
  84. def _pad_1x1_to_3x3_tensor(self, kernel1x1):
  85. if kernel1x1 is None:
  86. return 0
  87. else:
  88. return torch.nn.functional.pad(kernel1x1, [1, 1, 1, 1])
  89. def _fuse_bn_tensor(self, branch):
  90. if branch is None:
  91. return 0, 0
  92. if isinstance(branch, ConvModule):
  93. kernel = branch.conv.weight
  94. bias = branch.conv.bias
  95. return kernel, bias
  96. elif isinstance(branch, nn.BatchNorm2d):
  97. if not hasattr(self, 'id_tensor'):
  98. input_dim = self.in_channels // self.groups
  99. kernel_value = np.zeros((self.in_channels, input_dim, 3, 3), dtype=np.float32)
  100. for i in range(self.in_channels):
  101. kernel_value[i, i % input_dim, 1, 1] = 1
  102. self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
  103. kernel = self.id_tensor
  104. running_mean = branch.running_mean
  105. running_var = branch.running_var
  106. gamma = branch.weight
  107. beta = branch.bias
  108. eps = branch.eps
  109. std = (running_var + eps).sqrt()
  110. t = (gamma / std).reshape(-1, 1, 1, 1)
  111. return kernel * t, beta - running_mean * gamma / std
  112. def switch_to_deploy(self):
  113. if hasattr(self, 'rbr_reparam'):
  114. return
  115. kernel, bias = self.get_equivalent_kernel_bias()
  116. self.rbr_reparam = nn.Conv2d(in_channels=self.rbr_dense.conv.in_channels, out_channels=self.rbr_dense.conv.out_channels,
  117. kernel_size=self.rbr_dense.conv.kernel_size, stride=self.rbr_dense.conv.stride,
  118. padding=self.rbr_dense.conv.padding, dilation=self.rbr_dense.conv.dilation, groups=self.rbr_dense.conv.groups, bias=True)
  119. self.rbr_reparam.weight.data = kernel
  120. self.rbr_reparam.bias.data = bias
  121. for para in self.parameters():
  122. para.detach_()
  123. self.__delattr__('rbr_dense')
  124. self.__delattr__('rbr_1x1')
  125. if hasattr(self, 'rbr_identity'):
  126. self.__delattr__('rbr_identity')
  127. if hasattr(self, 'id_tensor'):
  128. self.__delattr__('id_tensor')
  129. self.deploy = True
  130. # ---------------------------- Basic Modules ----------------------------
  131. class RepBlock(nn.Module):
  132. def __init__(self, in_channels, out_channels, num_blocks=1, block=RepVGGBlock):
  133. super().__init__()
  134. self.conv1 = block(in_channels, out_channels)
  135. self.block = nn.Sequential(*(block(out_channels, out_channels)
  136. for _ in range(num_blocks - 1))) if num_blocks > 1 else nn.Identity()
  137. if block == BottleRep:
  138. self.conv1 = BottleRep(in_channels, out_channels, weight=True)
  139. num_blocks = num_blocks // 2
  140. self.block = nn.Sequential(*(BottleRep(out_channels, out_channels, weight=True)
  141. for _ in range(num_blocks - 1))) if num_blocks > 1 else None
  142. def forward(self, x):
  143. x = self.conv1(x)
  144. if self.block is not None:
  145. x = self.block(x)
  146. return x
  147. class BottleRep(nn.Module):
  148. def __init__(self, in_channels, out_channels, weight=False):
  149. super().__init__()
  150. self.conv1 = RepVGGBlock(in_channels, out_channels, kernel_size=3, padding=1, stride=1)
  151. self.conv2 = RepVGGBlock(out_channels, out_channels, kernel_size=3, padding=1, stride=1)
  152. if in_channels != out_channels:
  153. self.shortcut = False
  154. else:
  155. self.shortcut = True
  156. if weight:
  157. self.alpha = nn.Parameter(torch.ones(1))
  158. else:
  159. self.alpha = 1.0
  160. def forward(self, x):
  161. outputs = self.conv1(x)
  162. outputs = self.conv2(outputs)
  163. return outputs + self.alpha * x if self.shortcut else outputs
  164. class RepCSPBlock(nn.Module):
  165. def __init__(self, in_channels, out_channels, num_blocks=1, expansion=0.5):
  166. super().__init__()
  167. inter_dim = round(out_channels * expansion) # hidden channels
  168. self.cv1 = ConvModule(in_channels, inter_dim, kernel_size=1, act_type='relu')
  169. self.cv2 = ConvModule(in_channels, inter_dim, kernel_size=1, act_type='relu')
  170. self.cv3 = ConvModule(2 * inter_dim, out_channels, kernel_size=1, act_type='relu')
  171. self.module = RepBlock(inter_dim, inter_dim, num_blocks, block=BottleRep)
  172. def forward(self, x):
  173. x1 = self.cv1(x)
  174. x2 = self.module(self.cv2(x))
  175. out = self.cv3(torch.cat((x1, x2), dim=1))
  176. return out