yolov7_neck.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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, expansion=0.5):
  12. super().__init__()
  13. inter_dim = int(in_dim * expansion)
  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. expansion: float = 0.5,
  28. ):
  29. super(SPPFBlockCSP, self).__init__()
  30. inter_dim = int(in_dim * expansion)
  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, expansion=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.m(self.cv2(x))
  43. y = self.cv3(torch.cat([x1, x2], dim=1))
  44. return y
  45. if __name__=='__main__':
  46. from thop import profile
  47. # Build a neck
  48. in_dim = 512
  49. out_dim = 512
  50. model = SPPFBlockCSP(512, 512, expansion=0.5)
  51. # Randomly generate a input data
  52. x = torch.randn(2, in_dim, 20, 20)
  53. # Inference
  54. output = model(x)
  55. print(' - the shape of input : ', x.shape)
  56. print(' - the shape of output : ', output.shape)
  57. x = torch.randn(1, in_dim, 20, 20)
  58. flops, params = profile(model, inputs=(x, ), verbose=False)
  59. print('============== FLOPs & Params ================')
  60. print(' - FLOPs : {:.2f} G'.format(flops / 1e9 * 2))
  61. print(' - Params : {:.2f} M'.format(params / 1e6))