yolov8_head.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. import torch
  2. import torch.nn as nn
  3. try:
  4. from .yolov8_basic import Conv
  5. except:
  6. from yolov8_basic import Conv
  7. # Single-level Head
  8. class SingleLevelHead(nn.Module):
  9. def __init__(self, in_dim, cls_head_dim, reg_head_dim, num_cls_head, num_reg_head, act_type, norm_type, depthwise):
  10. super().__init__()
  11. # --------- Basic Parameters ----------
  12. self.in_dim = in_dim
  13. self.num_cls_head = num_cls_head
  14. self.num_reg_head = num_reg_head
  15. self.act_type = act_type
  16. self.norm_type = norm_type
  17. self.depthwise = depthwise
  18. # --------- Network Parameters ----------
  19. ## cls head
  20. cls_feats = []
  21. self.cls_head_dim = cls_head_dim
  22. for i in range(num_cls_head):
  23. if i == 0:
  24. cls_feats.append(
  25. Conv(in_dim, self.cls_head_dim, k=3, p=1, s=1,
  26. act_type=act_type,
  27. norm_type=norm_type,
  28. depthwise=depthwise)
  29. )
  30. else:
  31. cls_feats.append(
  32. Conv(self.cls_head_dim, self.cls_head_dim, k=3, p=1, s=1,
  33. act_type=act_type,
  34. norm_type=norm_type,
  35. depthwise=depthwise)
  36. )
  37. ## reg head
  38. reg_feats = []
  39. self.reg_head_dim = reg_head_dim
  40. for i in range(num_reg_head):
  41. if i == 0:
  42. reg_feats.append(
  43. Conv(in_dim, self.reg_head_dim, k=3, p=1, s=1,
  44. act_type=act_type,
  45. norm_type=norm_type,
  46. depthwise=depthwise)
  47. )
  48. else:
  49. reg_feats.append(
  50. Conv(self.reg_head_dim, self.reg_head_dim, k=3, p=1, s=1,
  51. act_type=act_type,
  52. norm_type=norm_type,
  53. depthwise=depthwise)
  54. )
  55. self.cls_feats = nn.Sequential(*cls_feats)
  56. self.reg_feats = nn.Sequential(*reg_feats)
  57. self.init_weights()
  58. def init_weights(self):
  59. """Initialize the parameters."""
  60. for m in self.modules():
  61. if isinstance(m, torch.nn.Conv2d):
  62. # In order to be consistent with the source code,
  63. # reset the Conv2d initialization parameters
  64. m.reset_parameters()
  65. def forward(self, x):
  66. """
  67. in_feats: (Tensor) [B, C, H, W]
  68. """
  69. cls_feats = self.cls_feats(x)
  70. reg_feats = self.reg_feats(x)
  71. return cls_feats, reg_feats
  72. # Multi-level Head
  73. class MultiLevelHead(nn.Module):
  74. def __init__(self, cfg, in_dims, num_levels=3, num_classes=80, reg_max=16):
  75. super().__init__()
  76. ## ----------- Network Parameters -----------
  77. self.multi_level_heads = nn.ModuleList(
  78. [SingleLevelHead(
  79. in_dims[level],
  80. max(in_dims[0], min(num_classes, 100)), # cls head out_dim
  81. max(in_dims[0]//4, 16, 4*reg_max), # reg head out_dim
  82. cfg['num_cls_head'],
  83. cfg['num_reg_head'],
  84. cfg['head_act'],
  85. cfg['head_norm'],
  86. cfg['head_depthwise'])
  87. for level in range(num_levels)
  88. ])
  89. # --------- Basic Parameters ----------
  90. self.in_dims = in_dims
  91. self.cls_head_dim = self.multi_level_heads[0].cls_head_dim
  92. self.reg_head_dim = self.multi_level_heads[0].reg_head_dim
  93. def forward(self, feats):
  94. """
  95. feats: List[(Tensor)] [[B, C, H, W], ...]
  96. """
  97. cls_feats = []
  98. reg_feats = []
  99. for feat, head in zip(feats, self.multi_level_heads):
  100. # ---------------- Pred ----------------
  101. cls_feat, reg_feat = head(feat)
  102. cls_feats.append(cls_feat)
  103. reg_feats.append(reg_feat)
  104. return cls_feats, reg_feats
  105. # build detection head
  106. def build_det_head(cfg, in_dims, num_levels=3, num_classes=80, reg_max=16):
  107. if cfg['head'] == 'decoupled_head':
  108. head = MultiLevelHead(cfg, in_dims, num_levels, num_classes, reg_max)
  109. return head
  110. if __name__ == '__main__':
  111. import time
  112. from thop import profile
  113. cfg = {
  114. 'head': 'decoupled_head',
  115. 'num_cls_head': 2,
  116. 'num_reg_head': 2,
  117. 'head_act': 'silu',
  118. 'head_norm': 'BN',
  119. 'head_depthwise': False,
  120. 'reg_max': 16,
  121. }
  122. fpn_dims = [256, 512, 512]
  123. cls_out_dim = 256
  124. reg_out_dim = 64
  125. # Head-1
  126. model = build_det_head(cfg, fpn_dims, num_levels=3, num_classes=80, reg_max=16)
  127. print(model)
  128. fpn_feats = [torch.randn(1, fpn_dims[0], 80, 80), torch.randn(1, fpn_dims[1], 40, 40), torch.randn(1, fpn_dims[2], 20, 20)]
  129. t0 = time.time()
  130. outputs = model(fpn_feats)
  131. t1 = time.time()
  132. print('Time: ', t1 - t0)
  133. # for out in outputs:
  134. # print(out.shape)
  135. print('==============================')
  136. flops, params = profile(model, inputs=(fpn_feats, ), verbose=False)
  137. print('==============================')
  138. print('Head-1: GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
  139. print('Head-1: Params : {:.2f} M'.format(params / 1e6))