yolox_plus.py 10 KB

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