You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

160 line
5.9KB

  1. # This file contains modules common to various models
  2. import torch.nn.functional as F
  3. from utils.utils import *
  4. def DWConv(c1, c2, k=1, s=1, act=True): # depthwise convolution
  5. return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
  6. class Conv(nn.Module): # standard convolution
  7. def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
  8. super(Conv, self).__init__()
  9. self.conv = nn.Conv2d(c1, c2, k, s, k // 2, groups=g, bias=False)
  10. self.bn = nn.BatchNorm2d(c2)
  11. self.act = nn.LeakyReLU(0.1, inplace=True) if act else nn.Identity()
  12. def forward(self, x):
  13. return self.act(self.bn(self.conv(x)))
  14. def fuseforward(self, x):
  15. return self.act(self.conv(x))
  16. class Bottleneck(nn.Module):
  17. def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
  18. super(Bottleneck, self).__init__()
  19. c_ = int(c2 * e) # hidden channels
  20. self.cv1 = Conv(c1, c_, 1, 1)
  21. self.cv2 = Conv(c_, c2, 3, 1, g=g)
  22. self.add = shortcut and c1 == c2
  23. def forward(self, x):
  24. return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
  25. class BottleneckLight(nn.Module):
  26. def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
  27. super(BottleneckLight, self).__init__()
  28. c_ = int(c2 * e) # hidden channels
  29. self.cv1 = Conv(c1, c_, 1, 1)
  30. self.cv2 = nn.Conv2d(c_, c2, 3, 1, 3 // 2, groups=g, bias=False)
  31. self.bn = nn.BatchNorm2d(c2)
  32. self.act = nn.LeakyReLU(0.1, inplace=True)
  33. self.add = shortcut and c1 == c2
  34. def forward(self, x):
  35. return self.act(self.bn(x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))))
  36. class BottleneckCSP(nn.Module):
  37. def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
  38. super(BottleneckCSP, self).__init__()
  39. c_ = int(c2 * e) # hidden channels
  40. self.cv1 = Conv(c1, c_, 1, 1)
  41. self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
  42. self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
  43. self.cv4 = Conv(c2, c2, 1, 1)
  44. self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
  45. self.act = nn.LeakyReLU(0.1, inplace=True)
  46. self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
  47. def forward(self, x):
  48. y1 = self.cv3(self.m(self.cv1(x)))
  49. y2 = self.cv2(x)
  50. return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
  51. class Narrow(nn.Module):
  52. def __init__(self, c1, c2, shortcut=True, g=1): # ch_in, ch_out, shortcut, groups
  53. super(Narrow, self).__init__()
  54. c_ = c2 // 2 # hidden channels
  55. self.cv1 = Conv(c1, c_, 1, 1)
  56. self.cv2 = Conv(c_, c2, 3, 1, g=g)
  57. self.add = shortcut and c1 == c2
  58. def forward(self, x):
  59. return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
  60. class Origami(nn.Module): # 5-side layering
  61. def forward(self, x):
  62. y = F.pad(x, [1, 1, 1, 1])
  63. return torch.cat([x, y[..., :-2, 1:-1], y[..., 1:-1, :-2], y[..., 2:, 1:-1], y[..., 1:-1, 2:]], 1)
  64. class ConvPlus(nn.Module): # standard convolution
  65. def __init__(self, c1, c2, k=3, s=1, g=1, bias=True): # ch_in, ch_out, kernel, stride, groups
  66. super(ConvPlus, self).__init__()
  67. self.cv1 = nn.Conv2d(c1, c2, (k, 1), s, (k // 2, 0), groups=g, bias=bias)
  68. self.cv2 = nn.Conv2d(c1, c2, (1, k), s, (0, k // 2), groups=g, bias=bias)
  69. def forward(self, x):
  70. return self.cv1(x) + self.cv2(x)
  71. class SPP(nn.Module): # Spatial pyramid pooling layer used in YOLOv3-SPP
  72. def __init__(self, c1, c2, k=(5, 9, 13)):
  73. super(SPP, self).__init__()
  74. c_ = c1 // 2 # hidden channels
  75. self.cv1 = Conv(c1, c_, 1, 1)
  76. self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
  77. self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
  78. def forward(self, x):
  79. x = self.cv1(x)
  80. return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
  81. class Flatten(nn.Module):
  82. # Use after nn.AdaptiveAvgPool2d(1) to remove last 2 dimensions
  83. def forward(self, x):
  84. return x.view(x.size(0), -1)
  85. class Focus(nn.Module):
  86. # Focus wh information into c-space
  87. def __init__(self, c1, c2, k=1):
  88. super(Focus, self).__init__()
  89. self.conv = Conv(c1 * 4, c2, k, 1)
  90. def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
  91. return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
  92. class Concat(nn.Module):
  93. # Concatenate a list of tensors along dimension
  94. def __init__(self, dimension=1):
  95. super(Concat, self).__init__()
  96. self.d = dimension
  97. def forward(self, x):
  98. return torch.cat(x, self.d)
  99. class MixConv2d(nn.Module):
  100. # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595
  101. def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
  102. super(MixConv2d, self).__init__()
  103. groups = len(k)
  104. if equal_ch: # equal c_ per group
  105. i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices
  106. c_ = [(i == g).sum() for g in range(groups)] # intermediate channels
  107. else: # equal weight.numel() per group
  108. b = [c2] + [0] * groups
  109. a = np.eye(groups + 1, groups, k=-1)
  110. a -= np.roll(a, 1, axis=1)
  111. a *= np.array(k) ** 2
  112. a[0] = 1
  113. c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
  114. self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)])
  115. self.bn = nn.BatchNorm2d(c2)
  116. self.act = nn.LeakyReLU(0.1, inplace=True)
  117. def forward(self, x):
  118. return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))