yolov8_neck.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import torch
  2. import torch.nn as nn
  3. try:
  4. from .modules import ConvModule
  5. except:
  6. from modules import ConvModule
  7. # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
  8. class SPPF(nn.Module):
  9. """
  10. This code referenced to https://github.com/ultralytics/yolov5
  11. """
  12. def __init__(self, in_dim, out_dim):
  13. super().__init__()
  14. ## ----------- Basic Parameters -----------
  15. inter_dim = in_dim // 2
  16. self.out_dim = out_dim
  17. ## ----------- Network Parameters -----------
  18. self.cv1 = ConvModule(in_dim, inter_dim, kernel_size=1, padding=0, stride=1)
  19. self.cv2 = ConvModule(inter_dim * 4, out_dim, kernel_size=1, padding=0, stride=1)
  20. self.m = nn.MaxPool2d(kernel_size=5, stride=1, padding=2)
  21. # Initialize all layers
  22. self.init_weights()
  23. def init_weights(self):
  24. """Initialize the parameters."""
  25. for m in self.modules():
  26. if isinstance(m, torch.nn.Conv2d):
  27. m.reset_parameters()
  28. def forward(self, x):
  29. x = self.cv1(x)
  30. y1 = self.m(x)
  31. y2 = self.m(y1)
  32. return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))
  33. if __name__=='__main__':
  34. import time
  35. from thop import profile
  36. # Build a head
  37. in_dim = 256
  38. out_dim = 256
  39. neck = SPPF(in_dim, out_dim)
  40. # Inference
  41. x = torch.randn(1, in_dim, 20, 20)
  42. t0 = time.time()
  43. output = neck(x)
  44. t1 = time.time()
  45. print('Time: ', t1 - t0)
  46. print('Neck output: ', output.shape)
  47. flops, params = profile(neck, inputs=(x, ), verbose=False)
  48. print('==============================')
  49. print('GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  50. print('Params : {:.2f} M'.format(params / 1e6))