yolov2_neck.py 2.2 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. # 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 = 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. # Model config
  37. # YOLOv2-Base config
  38. class Yolov2BaseConfig(object):
  39. def __init__(self) -> None:
  40. # ---------------- Model config ----------------
  41. self.out_stride = 32
  42. self.max_stride = 32
  43. ## Neck
  44. self.neck_act = 'lrelu'
  45. self.neck_norm = 'BN'
  46. self.neck_depthwise = False
  47. self.neck_expand_ratio = 0.5
  48. self.spp_pooling_size = 5
  49. cfg = Yolov2BaseConfig()
  50. # Build a head
  51. in_dim = 512
  52. out_dim = 512
  53. neck = SPPF(cfg, in_dim, out_dim)
  54. # Inference
  55. x = torch.randn(1, in_dim, 20, 20)
  56. t0 = time.time()
  57. output = neck(x)
  58. t1 = time.time()
  59. print('Time: ', t1 - t0)
  60. print('Neck output: ', output.shape)
  61. flops, params = profile(neck, inputs=(x, ), verbose=False)
  62. print('==============================')
  63. print('GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  64. print('Params : {:.2f} M'.format(params / 1e6))