yolov7_neck.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import torch
  2. import torch.nn as nn
  3. try:
  4. from .modules import ConvModule
  5. except:
  6. from modules import ConvModule
  7. class SPPF(nn.Module):
  8. """
  9. This code referenced to https://github.com/ultralytics/yolov5
  10. """
  11. def __init__(self, in_dim, out_dim, expand_ratio=0.5):
  12. super().__init__()
  13. inter_dim = int(in_dim * expand_ratio)
  14. self.out_dim = out_dim
  15. self.cv1 = ConvModule(in_dim, inter_dim, kernel_size=1)
  16. self.cv2 = ConvModule(inter_dim * 4, out_dim, kernel_size=1)
  17. self.m = nn.MaxPool2d(kernel_size=5, stride=1, padding=2)
  18. def forward(self, x):
  19. x = self.cv1(x)
  20. y1 = self.m(x)
  21. y2 = self.m(y1)
  22. return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))
  23. class SPPFBlockCSP(nn.Module):
  24. def __init__(self,
  25. in_dim: int,
  26. out_dim: int,
  27. expand_ratio: float = 0.5,
  28. ):
  29. super(SPPFBlockCSP, self).__init__()
  30. inter_dim = int(in_dim * expand_ratio)
  31. self.out_dim = out_dim
  32. self.cv1 = ConvModule(in_dim, inter_dim, kernel_size=1)
  33. self.cv2 = ConvModule(in_dim, inter_dim, kernel_size=1)
  34. self.m = nn.Sequential(
  35. ConvModule(inter_dim, inter_dim, kernel_size=3),
  36. SPPF(inter_dim, inter_dim, expand_ratio=1.0),
  37. ConvModule(inter_dim, inter_dim, kernel_size=3)
  38. )
  39. self.cv3 = ConvModule(inter_dim * 2, self.out_dim, kernel_size=1)
  40. def forward(self, x):
  41. x1 = self.cv1(x)
  42. x2 = self.cv2(x)
  43. x3 = self.m(x2)
  44. y = self.cv3(torch.cat([x1, x3], dim=1))
  45. return y
  46. if __name__=='__main__':
  47. from thop import profile
  48. # Build a neck
  49. in_dim = 512
  50. out_dim = 512
  51. model = SPPFBlockCSP(512, 512, expand_ratio=0.5)
  52. # Randomly generate a input data
  53. x = torch.randn(2, in_dim, 20, 20)
  54. # Inference
  55. output = model(x)
  56. print(' - the shape of input : ', x.shape)
  57. print(' - the shape of output : ', output.shape)
  58. x = torch.randn(1, in_dim, 20, 20)
  59. flops, params = profile(model, inputs=(x, ), verbose=False)
  60. print('============== FLOPs & Params ================')
  61. print(' - FLOPs : {:.2f} G'.format(flops / 1e9 * 2))
  62. print(' - Params : {:.2f} M'.format(params / 1e6))