yolov5_plus.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. from .yolov5_plus_backbone import build_backbone
  5. from .yolov5_plus_neck import build_neck
  6. from .yolov5_plus_pafpn import build_fpn
  7. from .yolov5_plus_head import build_head
  8. from utils.misc import multiclass_nms
  9. # Stronger YOLOv5
  10. class YOLOv5_Plus(nn.Module):
  11. def __init__(self,
  12. cfg,
  13. device,
  14. num_classes = 20,
  15. conf_thresh = 0.05,
  16. nms_thresh = 0.6,
  17. trainable = False,
  18. topk = 1000):
  19. super(YOLOv5_Plus, self).__init__()
  20. # --------- Basic Parameters ----------
  21. self.cfg = cfg
  22. self.device = device
  23. self.stride = cfg['stride']
  24. self.num_classes = num_classes
  25. self.trainable = trainable
  26. self.conf_thresh = conf_thresh
  27. self.nms_thresh = nms_thresh
  28. self.topk = topk
  29. # ------------------- Anchor box -------------------
  30. self.num_levels = 3
  31. self.num_anchors = len(cfg['anchor_size']) // self.num_levels
  32. self.anchor_size = torch.as_tensor(
  33. cfg['anchor_size']
  34. ).view(self.num_levels, self.num_anchors, 2) # [S, A, 2]
  35. # ------------------- Network Structure -------------------
  36. ## backbone
  37. self.backbone, feats_dim = build_backbone(cfg, cfg['pretrained']*trainable)
  38. ## neck
  39. self.neck = build_neck(cfg=cfg, in_dim=feats_dim[-1], out_dim=feats_dim[-1])
  40. feats_dim[-1] = self.neck.out_dim
  41. ## fpn
  42. self.fpn = build_fpn(cfg=cfg, in_dims=feats_dim, out_dim=round(256*cfg['width']))
  43. self.head_dim = self.fpn.out_dim
  44. ## non-shared heads
  45. self.non_shared_heads = nn.ModuleList(
  46. [build_head(cfg, head_dim, head_dim, num_classes)
  47. for head_dim in self.head_dim
  48. ])
  49. ## pred
  50. self.cls_preds = nn.ModuleList(
  51. [nn.Conv2d(head.cls_out_dim, self.num_classes * self.num_anchors, kernel_size=1)
  52. for head in self.non_shared_heads
  53. ])
  54. self.reg_preds = nn.ModuleList(
  55. [nn.Conv2d(head.reg_out_dim, 4 * self.num_anchors, kernel_size=1)
  56. for head in self.non_shared_heads
  57. ])
  58. # ---------------------- Basic Functions ----------------------
  59. ## generate anchor points
  60. def generate_anchors(self, level, fmp_size):
  61. fmp_h, fmp_w = fmp_size
  62. # [KA, 2]
  63. anchor_size = self.anchor_size[level]
  64. # generate grid cells
  65. anchor_y, anchor_x = torch.meshgrid([torch.arange(fmp_h), torch.arange(fmp_w)])
  66. anchor_xy = torch.stack([anchor_x, anchor_y], dim=-1).float().view(-1, 2)
  67. # [HW, 2] -> [HW, KA, 2] -> [M, 2]
  68. anchor_xy = anchor_xy.unsqueeze(1).repeat(1, self.num_anchors, 1)
  69. anchor_xy = anchor_xy.view(-1, 2).to(self.device)
  70. anchor_xy += 0.5
  71. anchor_xy *= self.stride[level]
  72. # [KA, 2] -> [1, KA, 2] -> [HW, KA, 2] -> [M, 2]
  73. anchor_wh = anchor_size.unsqueeze(0).repeat(fmp_h*fmp_w, 1, 1)
  74. anchor_wh = anchor_wh.view(-1, 2).to(self.device)
  75. anchors = torch.cat([anchor_xy, anchor_wh], dim=-1)
  76. return anchors
  77. ## post-process
  78. def post_process(self, cls_preds, box_preds):
  79. """
  80. Input:
  81. cls_preds: List(Tensor) [[H x W, C], ...]
  82. box_preds: List(Tensor) [[H x W, 4], ...]
  83. """
  84. all_scores = []
  85. all_labels = []
  86. all_bboxes = []
  87. for cls_pred_i, box_pred_i in zip(cls_preds, box_preds):
  88. # (H x W x C,)
  89. scores_i = cls_pred_i.sigmoid().flatten()
  90. # Keep top k top scoring indices only.
  91. num_topk = min(self.topk, box_pred_i.size(0))
  92. # torch.sort is actually faster than .topk (at least on GPUs)
  93. predicted_prob, topk_idxs = scores_i.sort(descending=True)
  94. topk_scores = predicted_prob[:num_topk]
  95. topk_idxs = topk_idxs[:num_topk]
  96. # filter out the proposals with low confidence score
  97. keep_idxs = topk_scores > self.conf_thresh
  98. topk_scores = topk_scores[keep_idxs]
  99. topk_idxs = topk_idxs[keep_idxs]
  100. anchor_idxs = torch.div(topk_idxs, self.num_classes, rounding_mode='floor')
  101. topk_labels = topk_idxs % self.num_classes
  102. topk_bboxes = box_pred_i[anchor_idxs]
  103. all_scores.append(topk_scores)
  104. all_labels.append(topk_labels)
  105. all_bboxes.append(topk_bboxes)
  106. scores = torch.cat(all_scores)
  107. labels = torch.cat(all_labels)
  108. bboxes = torch.cat(all_bboxes)
  109. # to cpu & numpy
  110. scores = scores.cpu().numpy()
  111. labels = labels.cpu().numpy()
  112. bboxes = bboxes.cpu().numpy()
  113. # nms
  114. scores, labels, bboxes = multiclass_nms(
  115. scores, labels, bboxes, self.nms_thresh, self.num_classes, False)
  116. return bboxes, scores, labels
  117. # ---------------------- Main Process for Inference ----------------------
  118. @torch.no_grad()
  119. def inference_single_image(self, x):
  120. # backbone
  121. pyramid_feats = self.backbone(x)
  122. # neck
  123. pyramid_feats[-1] = self.neck(pyramid_feats[-1])
  124. # fpn
  125. pyramid_feats = self.fpn(pyramid_feats)
  126. # non-shared heads
  127. all_cls_preds = []
  128. all_box_preds = []
  129. all_anchors = []
  130. for level, (feat, head) in enumerate(zip(pyramid_feats, self.non_shared_heads)):
  131. cls_feat, reg_feat = head(feat)
  132. # pred
  133. cls_pred = self.cls_preds[level](cls_feat) # [B, C*A, H, W]
  134. reg_pred = self.reg_preds[level](reg_feat) # [B, 4*A, H, W]
  135. B, _, H, W = cls_pred.size()
  136. fmp_size = [H, W]
  137. # [M, 2]
  138. anchors = self.generate_anchors(level, fmp_size)
  139. # [B, C, H, W] -> [B, H, W, C] -> [B, M, C]
  140. cls_pred = cls_pred[0].permute(1, 2, 0).contiguous().view(-1, self.num_classes)
  141. reg_pred = reg_pred[0].permute(1, 2, 0).contiguous().view(-1, 4)
  142. # decode bbox
  143. ctr_pred = anchors[..., :2] + reg_pred[..., :2] * self.stride[level]
  144. wh_pred = torch.exp(reg_pred[..., 2:]) * anchors[..., 2:]
  145. pred_x1y1 = ctr_pred - wh_pred * 0.5
  146. pred_x2y2 = ctr_pred + wh_pred * 0.5
  147. box_pred = torch.cat([pred_x1y1, pred_x2y2], dim=-1)
  148. all_cls_preds.append(cls_pred)
  149. all_box_preds.append(box_pred)
  150. all_anchors.append(anchors)
  151. # post process
  152. bboxes, scores, labels = self.post_process(
  153. all_cls_preds, all_box_preds)
  154. return bboxes, scores, labels
  155. # ---------------------- Main Process for Training ----------------------
  156. def forward(self, x):
  157. if not self.trainable:
  158. return self.inference_single_image(x)
  159. else:
  160. # backbone
  161. pyramid_feats = self.backbone(x)
  162. # neck
  163. pyramid_feats[-1] = self.neck(pyramid_feats[-1])
  164. # fpn
  165. pyramid_feats = self.fpn(pyramid_feats)
  166. # non-shared heads
  167. all_fmp_sizes = []
  168. all_cls_preds = []
  169. all_box_preds = []
  170. all_anchors = []
  171. for level, (feat, head) in enumerate(zip(pyramid_feats, self.non_shared_heads)):
  172. cls_feat, reg_feat = head(feat)
  173. # pred
  174. cls_pred = self.cls_preds[level](cls_feat) # [B, C, H, W]
  175. reg_pred = self.reg_preds[level](reg_feat) # [B, 4*(reg_max), H, W]
  176. B, _, H, W = cls_pred.size()
  177. fmp_size = [H, W]
  178. # generate anchor boxes: [M, 2]
  179. anchors = self.generate_anchors(level, fmp_size)
  180. # [B, C, H, W] -> [B, H, W, C] -> [B, M, C]
  181. cls_pred = cls_pred.permute(0, 2, 3, 1).contiguous().view(B, -1, self.num_classes)
  182. reg_pred = reg_pred.permute(0, 2, 3, 1).contiguous().view(B, -1, 4)
  183. # decode bbox
  184. ctr_pred = anchors[..., :2] + reg_pred[..., :2] * self.stride[level]
  185. wh_pred = torch.exp(reg_pred[..., 2:]) * anchors[..., 2:]
  186. pred_x1y1 = ctr_pred - wh_pred * 0.5
  187. pred_x2y2 = ctr_pred + wh_pred * 0.5
  188. box_pred = torch.cat([pred_x1y1, pred_x2y2], dim=-1)
  189. all_fmp_sizes.append(fmp_size)
  190. all_cls_preds.append(cls_pred)
  191. all_box_preds.append(box_pred)
  192. all_anchors.append(anchors)
  193. # output dict
  194. outputs = {"pred_cls": all_cls_preds, # List(Tensor) [B, M, C]
  195. "pred_box": all_box_preds, # List(Tensor) [B, M, 4]
  196. "anchors": all_anchors, # List(Tensor) [B, M, 4]
  197. 'fmp_sizes': all_fmp_sizes, # List
  198. 'strides': self.stride, # List
  199. }
  200. return outputs