yolov2_neck.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. from thop import profile
  35. # YOLOv2 configuration
  36. class Yolov2BaseConfig(object):
  37. def __init__(self) -> None:
  38. # ---------------- Model config ----------------
  39. self.out_stride = 32
  40. self.max_stride = 32
  41. ## Neck
  42. self.neck_expand_ratio = 0.5
  43. self.spp_pooling_size = 5
  44. cfg = Yolov2BaseConfig()
  45. # Build a neck
  46. in_dim = 512
  47. out_dim = 512
  48. model = SPPF(cfg, 512, 512)
  49. # Randomly generate a input data
  50. x = torch.randn(2, in_dim, 20, 20)
  51. # Inference
  52. output = model(x)
  53. print(' - the shape of input : ', x.shape)
  54. print(' - the shape of output : ', output.shape)
  55. x = torch.randn(1, in_dim, 20, 20)
  56. flops, params = profile(model, inputs=(x, ), verbose=False)
  57. print('============== FLOPs & Params ================')
  58. print(' - FLOPs : {:.2f} G'.format(flops / 1e9 * 2))
  59. print(' - Params : {:.2f} M'.format(params / 1e6))