yolov1_neck.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import torch
  2. import torch.nn as nn
  3. try:
  4. from .yolov1_basic import BasicConv
  5. except:
  6. from yolov1_basic import BasicConv
  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, cfg, in_dim, out_dim):
  13. super().__init__()
  14. ## ----------- Basic Parameters -----------
  15. inter_dim = round(in_dim * cfg.neck_expand_ratio)
  16. self.out_dim = out_dim
  17. ## ----------- Network Parameters -----------
  18. self.cv1 = BasicConv(in_dim, inter_dim,
  19. kernel_size=1, padding=0, stride=1,
  20. act_type=cfg.neck_act, norm_type=cfg.neck_norm)
  21. self.cv2 = BasicConv(inter_dim * 4, out_dim,
  22. kernel_size=1, padding=0, stride=1,
  23. act_type=cfg.neck_act, norm_type=cfg.neck_norm)
  24. self.m = nn.MaxPool2d(kernel_size=cfg.spp_pooling_size,
  25. stride=1,
  26. padding=cfg.spp_pooling_size // 2)
  27. # Initialize all layers
  28. self.init_weights()
  29. def init_weights(self):
  30. """Initialize the parameters."""
  31. for m in self.modules():
  32. if isinstance(m, torch.nn.Conv2d):
  33. # In order to be consistent with the source code,
  34. # reset the Conv2d initialization parameters
  35. m.reset_parameters()
  36. def forward(self, x):
  37. x = self.cv1(x)
  38. y1 = self.m(x)
  39. y2 = self.m(y1)
  40. return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))
  41. if __name__=='__main__':
  42. import time
  43. from thop import profile
  44. # Model config
  45. # YOLOv8-Base config
  46. class Yolov1BaseConfig(object):
  47. def __init__(self) -> None:
  48. # ---------------- Model config ----------------
  49. self.out_stride = 32
  50. self.max_stride = 32
  51. ## Neck
  52. self.neck_act = 'lrelu'
  53. self.neck_norm = 'BN'
  54. self.neck_depthwise = False
  55. self.neck_expand_ratio = 0.5
  56. self.spp_pooling_size = 5
  57. cfg = Yolov1BaseConfig()
  58. # Build a head
  59. in_dim = 512
  60. out_dim = 512
  61. neck = SPPF(cfg, 512, 512)
  62. # Inference
  63. x = torch.randn(1, in_dim, 20, 20)
  64. t0 = time.time()
  65. output = neck(x)
  66. t1 = time.time()
  67. print('Time: ', t1 - t0)
  68. print('Neck output: ', output.shape)
  69. flops, params = profile(neck, inputs=(x, ), verbose=False)
  70. print('==============================')
  71. print('GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  72. print('Params : {:.2f} M'.format(params / 1e6))