yolox_plus.py 8.5 KB

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