roi_heads.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. from typing import Dict, List, Optional, Tuple
  2. import torch
  3. import torch.nn.functional as F
  4. import torchvision
  5. from torch import nn, Tensor
  6. from torchvision.ops import boxes as box_ops, roi_align
  7. from . import _utils as det_utils
  8. def fastrcnn_loss(class_logits, box_regression, labels, regression_targets):
  9. # type: (Tensor, Tensor, List[Tensor], List[Tensor]) -> Tuple[Tensor, Tensor]
  10. """
  11. Computes the loss for Faster R-CNN.
  12. Args:
  13. class_logits (Tensor)
  14. box_regression (Tensor)
  15. labels (list[BoxList])
  16. regression_targets (Tensor)
  17. Returns:
  18. classification_loss (Tensor)
  19. box_loss (Tensor)
  20. """
  21. print(f'compute fastrcnn_loss:{labels}')
  22. labels = torch.cat(labels, dim=0)
  23. regression_targets = torch.cat(regression_targets, dim=0)
  24. classification_loss = F.cross_entropy(class_logits, labels)
  25. # get indices that correspond to the regression targets for
  26. # the corresponding ground truth labels, to be used with
  27. # advanced indexing
  28. sampled_pos_inds_subset = torch.where(labels > 0)[0]
  29. labels_pos = labels[sampled_pos_inds_subset]
  30. N, num_classes = class_logits.shape
  31. box_regression = box_regression.reshape(N, box_regression.size(-1) // 4, 4)
  32. box_loss = F.smooth_l1_loss(
  33. box_regression[sampled_pos_inds_subset, labels_pos],
  34. regression_targets[sampled_pos_inds_subset],
  35. beta=1 / 9,
  36. reduction="sum",
  37. )
  38. box_loss = box_loss / labels.numel()
  39. return classification_loss, box_loss
  40. def maskrcnn_inference(x, labels):
  41. # type: (Tensor, List[Tensor]) -> List[Tensor]
  42. """
  43. From the results of the CNN, post process the masks
  44. by taking the ins corresponding to the class with max
  45. probability (which are of fixed size and directly output
  46. by the CNN) and return the masks in the ins field of the BoxList.
  47. Args:
  48. x (Tensor): the ins logits
  49. labels (list[BoxList]): bounding boxes that are used as
  50. reference, one for ech image
  51. Returns:
  52. results (list[BoxList]): one BoxList for each image, containing
  53. the extra field ins
  54. """
  55. mask_prob = x.sigmoid()
  56. # select masks corresponding to the predicted classes
  57. num_masks = x.shape[0]
  58. boxes_per_image = [label.shape[0] for label in labels]
  59. labels = torch.cat(labels)
  60. index = torch.arange(num_masks, device=labels.device)
  61. mask_prob = mask_prob[index, labels][:, None]
  62. mask_prob = mask_prob.split(boxes_per_image, dim=0)
  63. return mask_prob
  64. def project_masks_on_boxes(gt_masks, boxes, matched_idxs, M):
  65. # type: (Tensor, Tensor, Tensor, int) -> Tensor
  66. """
  67. Given segmentation masks and the bounding boxes corresponding
  68. to the location of the masks in the image, this function
  69. crops and resizes the masks in the position defined by the
  70. boxes. This prepares the masks for them to be fed to the
  71. loss computation as the targets.
  72. """
  73. matched_idxs = matched_idxs.to(boxes)
  74. rois = torch.cat([matched_idxs[:, None], boxes], dim=1)
  75. gt_masks = gt_masks[:, None].to(rois)
  76. return roi_align(gt_masks, rois, (M, M), 1.0)[:, 0]
  77. def maskrcnn_loss(mask_logits, proposals, gt_masks, gt_labels, mask_matched_idxs):
  78. # type: (Tensor, List[Tensor], List[Tensor], List[Tensor], List[Tensor]) -> Tensor
  79. """
  80. Args:
  81. proposals (list[BoxList])
  82. mask_logits (Tensor)
  83. targets (list[BoxList])
  84. Return:
  85. mask_loss (Tensor): scalar tensor containing the loss
  86. """
  87. discretization_size = mask_logits.shape[-1]
  88. labels = [gt_label[idxs] for gt_label, idxs in zip(gt_labels, mask_matched_idxs)]
  89. mask_targets = [
  90. project_masks_on_boxes(m, p, i, discretization_size) for m, p, i in zip(gt_masks, proposals, mask_matched_idxs)
  91. ]
  92. labels = torch.cat(labels, dim=0)
  93. mask_targets = torch.cat(mask_targets, dim=0)
  94. # torch.mean (in binary_cross_entropy_with_logits) doesn't
  95. # accept empty tensors, so handle it separately
  96. if mask_targets.numel() == 0:
  97. return mask_logits.sum() * 0
  98. mask_loss = F.binary_cross_entropy_with_logits(
  99. mask_logits[torch.arange(labels.shape[0], device=labels.device), labels], mask_targets
  100. )
  101. return mask_loss
  102. def keypoints_to_heatmap(keypoints, rois, heatmap_size):
  103. # type: (Tensor, Tensor, int) -> Tuple[Tensor, Tensor]
  104. offset_x = rois[:, 0]
  105. offset_y = rois[:, 1]
  106. scale_x = heatmap_size / (rois[:, 2] - rois[:, 0])
  107. scale_y = heatmap_size / (rois[:, 3] - rois[:, 1])
  108. offset_x = offset_x[:, None]
  109. offset_y = offset_y[:, None]
  110. scale_x = scale_x[:, None]
  111. scale_y = scale_y[:, None]
  112. x = keypoints[..., 0]
  113. y = keypoints[..., 1]
  114. x_boundary_inds = x == rois[:, 2][:, None]
  115. y_boundary_inds = y == rois[:, 3][:, None]
  116. x = (x - offset_x) * scale_x
  117. x = x.floor().long()
  118. y = (y - offset_y) * scale_y
  119. y = y.floor().long()
  120. x[x_boundary_inds] = heatmap_size - 1
  121. y[y_boundary_inds] = heatmap_size - 1
  122. valid_loc = (x >= 0) & (y >= 0) & (x < heatmap_size) & (y < heatmap_size)
  123. vis = keypoints[..., 2] > 0
  124. valid = (valid_loc & vis).long()
  125. lin_ind = y * heatmap_size + x
  126. heatmaps = lin_ind * valid
  127. return heatmaps, valid
  128. def _onnx_heatmaps_to_keypoints(
  129. maps, maps_i, roi_map_width, roi_map_height, widths_i, heights_i, offset_x_i, offset_y_i
  130. ):
  131. num_keypoints = torch.scalar_tensor(maps.size(1), dtype=torch.int64)
  132. width_correction = widths_i / roi_map_width
  133. height_correction = heights_i / roi_map_height
  134. roi_map = F.interpolate(
  135. maps_i[:, None], size=(int(roi_map_height), int(roi_map_width)), mode="bicubic", align_corners=False
  136. )[:, 0]
  137. w = torch.scalar_tensor(roi_map.size(2), dtype=torch.int64)
  138. pos = roi_map.reshape(num_keypoints, -1).argmax(dim=1)
  139. x_int = pos % w
  140. y_int = (pos - x_int) // w
  141. x = (torch.tensor(0.5, dtype=torch.float32) + x_int.to(dtype=torch.float32)) * width_correction.to(
  142. dtype=torch.float32
  143. )
  144. y = (torch.tensor(0.5, dtype=torch.float32) + y_int.to(dtype=torch.float32)) * height_correction.to(
  145. dtype=torch.float32
  146. )
  147. xy_preds_i_0 = x + offset_x_i.to(dtype=torch.float32)
  148. xy_preds_i_1 = y + offset_y_i.to(dtype=torch.float32)
  149. xy_preds_i_2 = torch.ones(xy_preds_i_1.shape, dtype=torch.float32)
  150. xy_preds_i = torch.stack(
  151. [
  152. xy_preds_i_0.to(dtype=torch.float32),
  153. xy_preds_i_1.to(dtype=torch.float32),
  154. xy_preds_i_2.to(dtype=torch.float32),
  155. ],
  156. 0,
  157. )
  158. # TODO: simplify when indexing without rank will be supported by ONNX
  159. base = num_keypoints * num_keypoints + num_keypoints + 1
  160. ind = torch.arange(num_keypoints)
  161. ind = ind.to(dtype=torch.int64) * base
  162. end_scores_i = (
  163. roi_map.index_select(1, y_int.to(dtype=torch.int64))
  164. .index_select(2, x_int.to(dtype=torch.int64))
  165. .view(-1)
  166. .index_select(0, ind.to(dtype=torch.int64))
  167. )
  168. return xy_preds_i, end_scores_i
  169. @torch.jit._script_if_tracing
  170. def _onnx_heatmaps_to_keypoints_loop(
  171. maps, rois, widths_ceil, heights_ceil, widths, heights, offset_x, offset_y, num_keypoints
  172. ):
  173. xy_preds = torch.zeros((0, 3, int(num_keypoints)), dtype=torch.float32, device=maps.device)
  174. end_scores = torch.zeros((0, int(num_keypoints)), dtype=torch.float32, device=maps.device)
  175. for i in range(int(rois.size(0))):
  176. xy_preds_i, end_scores_i = _onnx_heatmaps_to_keypoints(
  177. maps, maps[i], widths_ceil[i], heights_ceil[i], widths[i], heights[i], offset_x[i], offset_y[i]
  178. )
  179. xy_preds = torch.cat((xy_preds.to(dtype=torch.float32), xy_preds_i.unsqueeze(0).to(dtype=torch.float32)), 0)
  180. end_scores = torch.cat(
  181. (end_scores.to(dtype=torch.float32), end_scores_i.to(dtype=torch.float32).unsqueeze(0)), 0
  182. )
  183. return xy_preds, end_scores
  184. def heatmaps_to_keypoints(maps, rois):
  185. """Extract predicted keypoint locations from heatmaps. Output has shape
  186. (#rois, 4, #keypoints) with the 4 rows corresponding to (x, y, logit, prob)
  187. for each keypoint.
  188. """
  189. # This function converts a discrete image coordinate in a HEATMAP_SIZE x
  190. # HEATMAP_SIZE image to a continuous keypoint coordinate. We maintain
  191. # consistency with keypoints_to_heatmap_labels by using the conversion from
  192. # Heckbert 1990: c = d + 0.5, where d is a discrete coordinate and c is a
  193. # continuous coordinate.
  194. offset_x = rois[:, 0]
  195. offset_y = rois[:, 1]
  196. widths = rois[:, 2] - rois[:, 0]
  197. heights = rois[:, 3] - rois[:, 1]
  198. widths = widths.clamp(min=1)
  199. heights = heights.clamp(min=1)
  200. widths_ceil = widths.ceil()
  201. heights_ceil = heights.ceil()
  202. num_keypoints = maps.shape[1]
  203. if torchvision._is_tracing():
  204. xy_preds, end_scores = _onnx_heatmaps_to_keypoints_loop(
  205. maps,
  206. rois,
  207. widths_ceil,
  208. heights_ceil,
  209. widths,
  210. heights,
  211. offset_x,
  212. offset_y,
  213. torch.scalar_tensor(num_keypoints, dtype=torch.int64),
  214. )
  215. return xy_preds.permute(0, 2, 1), end_scores
  216. xy_preds = torch.zeros((len(rois), 3, num_keypoints), dtype=torch.float32, device=maps.device)
  217. end_scores = torch.zeros((len(rois), num_keypoints), dtype=torch.float32, device=maps.device)
  218. for i in range(len(rois)):
  219. roi_map_width = int(widths_ceil[i].item())
  220. roi_map_height = int(heights_ceil[i].item())
  221. width_correction = widths[i] / roi_map_width
  222. height_correction = heights[i] / roi_map_height
  223. roi_map = F.interpolate(
  224. maps[i][:, None], size=(roi_map_height, roi_map_width), mode="bicubic", align_corners=False
  225. )[:, 0]
  226. # roi_map_probs = scores_to_probs(roi_map.copy())
  227. w = roi_map.shape[2]
  228. pos = roi_map.reshape(num_keypoints, -1).argmax(dim=1)
  229. x_int = pos % w
  230. y_int = torch.div(pos - x_int, w, rounding_mode="floor")
  231. # assert (roi_map_probs[k, y_int, x_int] ==
  232. # roi_map_probs[k, :, :].max())
  233. x = (x_int.float() + 0.5) * width_correction
  234. y = (y_int.float() + 0.5) * height_correction
  235. xy_preds[i, 0, :] = x + offset_x[i]
  236. xy_preds[i, 1, :] = y + offset_y[i]
  237. xy_preds[i, 2, :] = 1
  238. end_scores[i, :] = roi_map[torch.arange(num_keypoints, device=roi_map.device), y_int, x_int]
  239. return xy_preds.permute(0, 2, 1), end_scores
  240. def keypointrcnn_loss(keypoint_logits, proposals, gt_keypoints, keypoint_matched_idxs):
  241. # type: (Tensor, List[Tensor], List[Tensor], List[Tensor]) -> Tensor
  242. N, K, H, W = keypoint_logits.shape
  243. if H != W:
  244. raise ValueError(
  245. f"keypoint_logits height and width (last two elements of shape) should be equal. Instead got H = {H} and W = {W}"
  246. )
  247. discretization_size = H
  248. heatmaps = []
  249. valid = []
  250. for proposals_per_image, gt_kp_in_image, midx in zip(proposals, gt_keypoints, keypoint_matched_idxs):
  251. kp = gt_kp_in_image[midx]
  252. heatmaps_per_image, valid_per_image = keypoints_to_heatmap(kp, proposals_per_image, discretization_size)
  253. heatmaps.append(heatmaps_per_image.view(-1))
  254. valid.append(valid_per_image.view(-1))
  255. keypoint_targets = torch.cat(heatmaps, dim=0)
  256. valid = torch.cat(valid, dim=0).to(dtype=torch.uint8)
  257. valid = torch.where(valid)[0]
  258. # torch.mean (in binary_cross_entropy_with_logits) doesn't
  259. # accept empty tensors, so handle it sepaartely
  260. if keypoint_targets.numel() == 0 or len(valid) == 0:
  261. return keypoint_logits.sum() * 0
  262. keypoint_logits = keypoint_logits.view(N * K, H * W)
  263. keypoint_loss = F.cross_entropy(keypoint_logits[valid], keypoint_targets[valid])
  264. return keypoint_loss
  265. def keypointrcnn_inference(x, boxes):
  266. # type: (Tensor, List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]
  267. kp_probs = []
  268. kp_scores = []
  269. boxes_per_image = [box.size(0) for box in boxes]
  270. x2 = x.split(boxes_per_image, dim=0)
  271. for xx, bb in zip(x2, boxes):
  272. kp_prob, scores = heatmaps_to_keypoints(xx, bb)
  273. kp_probs.append(kp_prob)
  274. kp_scores.append(scores)
  275. return kp_probs, kp_scores
  276. def _onnx_expand_boxes(boxes, scale):
  277. # type: (Tensor, float) -> Tensor
  278. w_half = (boxes[:, 2] - boxes[:, 0]) * 0.5
  279. h_half = (boxes[:, 3] - boxes[:, 1]) * 0.5
  280. x_c = (boxes[:, 2] + boxes[:, 0]) * 0.5
  281. y_c = (boxes[:, 3] + boxes[:, 1]) * 0.5
  282. w_half = w_half.to(dtype=torch.float32) * scale
  283. h_half = h_half.to(dtype=torch.float32) * scale
  284. boxes_exp0 = x_c - w_half
  285. boxes_exp1 = y_c - h_half
  286. boxes_exp2 = x_c + w_half
  287. boxes_exp3 = y_c + h_half
  288. boxes_exp = torch.stack((boxes_exp0, boxes_exp1, boxes_exp2, boxes_exp3), 1)
  289. return boxes_exp
  290. # the next two functions should be merged inside Masker
  291. # but are kept here for the moment while we need them
  292. # temporarily for paste_mask_in_image
  293. def expand_boxes(boxes, scale):
  294. # type: (Tensor, float) -> Tensor
  295. if torchvision._is_tracing():
  296. return _onnx_expand_boxes(boxes, scale)
  297. w_half = (boxes[:, 2] - boxes[:, 0]) * 0.5
  298. h_half = (boxes[:, 3] - boxes[:, 1]) * 0.5
  299. x_c = (boxes[:, 2] + boxes[:, 0]) * 0.5
  300. y_c = (boxes[:, 3] + boxes[:, 1]) * 0.5
  301. w_half *= scale
  302. h_half *= scale
  303. boxes_exp = torch.zeros_like(boxes)
  304. boxes_exp[:, 0] = x_c - w_half
  305. boxes_exp[:, 2] = x_c + w_half
  306. boxes_exp[:, 1] = y_c - h_half
  307. boxes_exp[:, 3] = y_c + h_half
  308. return boxes_exp
  309. @torch.jit.unused
  310. def expand_masks_tracing_scale(M, padding):
  311. # type: (int, int) -> float
  312. return torch.tensor(M + 2 * padding).to(torch.float32) / torch.tensor(M).to(torch.float32)
  313. def expand_masks(mask, padding):
  314. # type: (Tensor, int) -> Tuple[Tensor, float]
  315. M = mask.shape[-1]
  316. if torch._C._get_tracing_state(): # could not import is_tracing(), not sure why
  317. scale = expand_masks_tracing_scale(M, padding)
  318. else:
  319. scale = float(M + 2 * padding) / M
  320. padded_mask = F.pad(mask, (padding,) * 4)
  321. return padded_mask, scale
  322. def paste_mask_in_image(mask, box, im_h, im_w):
  323. # type: (Tensor, Tensor, int, int) -> Tensor
  324. TO_REMOVE = 1
  325. w = int(box[2] - box[0] + TO_REMOVE)
  326. h = int(box[3] - box[1] + TO_REMOVE)
  327. w = max(w, 1)
  328. h = max(h, 1)
  329. # Set shape to [batchxCxHxW]
  330. mask = mask.expand((1, 1, -1, -1))
  331. # Resize ins
  332. mask = F.interpolate(mask, size=(h, w), mode="bilinear", align_corners=False)
  333. mask = mask[0][0]
  334. im_mask = torch.zeros((im_h, im_w), dtype=mask.dtype, device=mask.device)
  335. x_0 = max(box[0], 0)
  336. x_1 = min(box[2] + 1, im_w)
  337. y_0 = max(box[1], 0)
  338. y_1 = min(box[3] + 1, im_h)
  339. im_mask[y_0:y_1, x_0:x_1] = mask[(y_0 - box[1]) : (y_1 - box[1]), (x_0 - box[0]) : (x_1 - box[0])]
  340. return im_mask
  341. def _onnx_paste_mask_in_image(mask, box, im_h, im_w):
  342. one = torch.ones(1, dtype=torch.int64)
  343. zero = torch.zeros(1, dtype=torch.int64)
  344. w = box[2] - box[0] + one
  345. h = box[3] - box[1] + one
  346. w = torch.max(torch.cat((w, one)))
  347. h = torch.max(torch.cat((h, one)))
  348. # Set shape to [batchxCxHxW]
  349. mask = mask.expand((1, 1, mask.size(0), mask.size(1)))
  350. # Resize ins
  351. mask = F.interpolate(mask, size=(int(h), int(w)), mode="bilinear", align_corners=False)
  352. mask = mask[0][0]
  353. x_0 = torch.max(torch.cat((box[0].unsqueeze(0), zero)))
  354. x_1 = torch.min(torch.cat((box[2].unsqueeze(0) + one, im_w.unsqueeze(0))))
  355. y_0 = torch.max(torch.cat((box[1].unsqueeze(0), zero)))
  356. y_1 = torch.min(torch.cat((box[3].unsqueeze(0) + one, im_h.unsqueeze(0))))
  357. unpaded_im_mask = mask[(y_0 - box[1]) : (y_1 - box[1]), (x_0 - box[0]) : (x_1 - box[0])]
  358. # TODO : replace below with a dynamic padding when support is added in ONNX
  359. # pad y
  360. zeros_y0 = torch.zeros(y_0, unpaded_im_mask.size(1))
  361. zeros_y1 = torch.zeros(im_h - y_1, unpaded_im_mask.size(1))
  362. concat_0 = torch.cat((zeros_y0, unpaded_im_mask.to(dtype=torch.float32), zeros_y1), 0)[0:im_h, :]
  363. # pad x
  364. zeros_x0 = torch.zeros(concat_0.size(0), x_0)
  365. zeros_x1 = torch.zeros(concat_0.size(0), im_w - x_1)
  366. im_mask = torch.cat((zeros_x0, concat_0, zeros_x1), 1)[:, :im_w]
  367. return im_mask
  368. @torch.jit._script_if_tracing
  369. def _onnx_paste_masks_in_image_loop(masks, boxes, im_h, im_w):
  370. res_append = torch.zeros(0, im_h, im_w)
  371. for i in range(masks.size(0)):
  372. mask_res = _onnx_paste_mask_in_image(masks[i][0], boxes[i], im_h, im_w)
  373. mask_res = mask_res.unsqueeze(0)
  374. res_append = torch.cat((res_append, mask_res))
  375. return res_append
  376. def paste_masks_in_image(masks, boxes, img_shape, padding=1):
  377. # type: (Tensor, Tensor, Tuple[int, int], int) -> Tensor
  378. masks, scale = expand_masks(masks, padding=padding)
  379. boxes = expand_boxes(boxes, scale).to(dtype=torch.int64)
  380. im_h, im_w = img_shape
  381. if torchvision._is_tracing():
  382. return _onnx_paste_masks_in_image_loop(
  383. masks, boxes, torch.scalar_tensor(im_h, dtype=torch.int64), torch.scalar_tensor(im_w, dtype=torch.int64)
  384. )[:, None]
  385. res = [paste_mask_in_image(m[0], b, im_h, im_w) for m, b in zip(masks, boxes)]
  386. if len(res) > 0:
  387. ret = torch.stack(res, dim=0)[:, None]
  388. else:
  389. ret = masks.new_empty((0, 1, im_h, im_w))
  390. return ret
  391. class RoIHeads(nn.Module):
  392. __annotations__ = {
  393. "box_coder": det_utils.BoxCoder,
  394. "proposal_matcher": det_utils.Matcher,
  395. "fg_bg_sampler": det_utils.BalancedPositiveNegativeSampler,
  396. }
  397. def __init__(
  398. self,
  399. box_roi_pool,
  400. box_head,
  401. box_predictor,
  402. # Faster R-CNN training
  403. fg_iou_thresh,
  404. bg_iou_thresh,
  405. batch_size_per_image,
  406. positive_fraction,
  407. bbox_reg_weights,
  408. # Faster R-CNN inference
  409. score_thresh,
  410. nms_thresh,
  411. detections_per_img,
  412. # Mask
  413. mask_roi_pool=None,
  414. mask_head=None,
  415. mask_predictor=None,
  416. keypoint_roi_pool=None,
  417. keypoint_head=None,
  418. keypoint_predictor=None,
  419. ):
  420. super().__init__()
  421. self.box_similarity = box_ops.box_iou
  422. # assign ground-truth boxes for each proposal
  423. self.proposal_matcher = det_utils.Matcher(fg_iou_thresh, bg_iou_thresh, allow_low_quality_matches=False)
  424. self.fg_bg_sampler = det_utils.BalancedPositiveNegativeSampler(batch_size_per_image, positive_fraction)
  425. if bbox_reg_weights is None:
  426. bbox_reg_weights = (10.0, 10.0, 5.0, 5.0)
  427. self.box_coder = det_utils.BoxCoder(bbox_reg_weights)
  428. self.box_roi_pool = box_roi_pool
  429. self.box_head = box_head
  430. self.box_predictor = box_predictor
  431. self.score_thresh = score_thresh
  432. self.nms_thresh = nms_thresh
  433. self.detections_per_img = detections_per_img
  434. self.mask_roi_pool = mask_roi_pool
  435. self.mask_head = mask_head
  436. self.mask_predictor = mask_predictor
  437. self.keypoint_roi_pool = keypoint_roi_pool
  438. self.keypoint_head = keypoint_head
  439. self.keypoint_predictor = keypoint_predictor
  440. def has_mask(self):
  441. if self.mask_roi_pool is None:
  442. return False
  443. if self.mask_head is None:
  444. return False
  445. if self.mask_predictor is None:
  446. return False
  447. return True
  448. def has_keypoint(self):
  449. if self.keypoint_roi_pool is None:
  450. return False
  451. if self.keypoint_head is None:
  452. return False
  453. if self.keypoint_predictor is None:
  454. return False
  455. return True
  456. def assign_targets_to_proposals(self, proposals, gt_boxes, gt_labels):
  457. # type: (List[Tensor], List[Tensor], List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]
  458. matched_idxs = []
  459. labels = []
  460. for proposals_in_image, gt_boxes_in_image, gt_labels_in_image in zip(proposals, gt_boxes, gt_labels):
  461. if gt_boxes_in_image.numel() == 0:
  462. # Background image
  463. device = proposals_in_image.device
  464. clamped_matched_idxs_in_image = torch.zeros(
  465. (proposals_in_image.shape[0],), dtype=torch.int64, device=device
  466. )
  467. labels_in_image = torch.zeros((proposals_in_image.shape[0],), dtype=torch.int64, device=device)
  468. else:
  469. # set to self.box_similarity when https://github.com/pytorch/pytorch/issues/27495 lands
  470. match_quality_matrix = box_ops.box_iou(gt_boxes_in_image, proposals_in_image)
  471. matched_idxs_in_image = self.proposal_matcher(match_quality_matrix)
  472. clamped_matched_idxs_in_image = matched_idxs_in_image.clamp(min=0)
  473. labels_in_image = gt_labels_in_image[clamped_matched_idxs_in_image]
  474. labels_in_image = labels_in_image.to(dtype=torch.int64)
  475. # Label background (below the low threshold)
  476. bg_inds = matched_idxs_in_image == self.proposal_matcher.BELOW_LOW_THRESHOLD
  477. labels_in_image[bg_inds] = 0
  478. # Label ignore proposals (between low and high thresholds)
  479. ignore_inds = matched_idxs_in_image == self.proposal_matcher.BETWEEN_THRESHOLDS
  480. labels_in_image[ignore_inds] = -1 # -1 is ignored by sampler
  481. matched_idxs.append(clamped_matched_idxs_in_image)
  482. labels.append(labels_in_image)
  483. return matched_idxs, labels
  484. def subsample(self, labels):
  485. # type: (List[Tensor]) -> List[Tensor]
  486. sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels)
  487. sampled_inds = []
  488. for img_idx, (pos_inds_img, neg_inds_img) in enumerate(zip(sampled_pos_inds, sampled_neg_inds)):
  489. img_sampled_inds = torch.where(pos_inds_img | neg_inds_img)[0]
  490. sampled_inds.append(img_sampled_inds)
  491. return sampled_inds
  492. def add_gt_proposals(self, proposals, gt_boxes):
  493. # type: (List[Tensor], List[Tensor]) -> List[Tensor]
  494. proposals = [torch.cat((proposal, gt_box)) for proposal, gt_box in zip(proposals, gt_boxes)]
  495. return proposals
  496. def check_targets(self, targets):
  497. # type: (Optional[List[Dict[str, Tensor]]]) -> None
  498. if targets is None:
  499. raise ValueError("targets should not be None")
  500. if not all(["boxes" in t for t in targets]):
  501. raise ValueError("Every element of targets should have a boxes key")
  502. if not all(["labels" in t for t in targets]):
  503. raise ValueError("Every element of targets should have a labels key")
  504. if self.has_mask():
  505. if not all(["masks" in t for t in targets]):
  506. raise ValueError("Every element of targets should have a masks key")
  507. def select_training_samples(
  508. self,
  509. proposals, # type: List[Tensor]
  510. targets, # type: Optional[List[Dict[str, Tensor]]]
  511. ):
  512. # type: (...) -> Tuple[List[Tensor], List[Tensor], List[Tensor], List[Tensor]]
  513. self.check_targets(targets)
  514. if targets is None:
  515. raise ValueError("targets should not be None")
  516. dtype = proposals[0].dtype
  517. device = proposals[0].device
  518. gt_boxes = [t["boxes"].to(dtype) for t in targets]
  519. gt_labels = [t["labels"] for t in targets]
  520. # append ground-truth bboxes to propos
  521. proposals = self.add_gt_proposals(proposals, gt_boxes)
  522. # get matching gt indices for each proposal
  523. matched_idxs, labels = self.assign_targets_to_proposals(proposals, gt_boxes, gt_labels)
  524. # sample a fixed proportion of positive-negative proposals
  525. sampled_inds = self.subsample(labels)
  526. matched_gt_boxes = []
  527. num_images = len(proposals)
  528. for img_id in range(num_images):
  529. img_sampled_inds = sampled_inds[img_id]
  530. proposals[img_id] = proposals[img_id][img_sampled_inds]
  531. labels[img_id] = labels[img_id][img_sampled_inds]
  532. matched_idxs[img_id] = matched_idxs[img_id][img_sampled_inds]
  533. gt_boxes_in_image = gt_boxes[img_id]
  534. if gt_boxes_in_image.numel() == 0:
  535. gt_boxes_in_image = torch.zeros((1, 4), dtype=dtype, device=device)
  536. matched_gt_boxes.append(gt_boxes_in_image[matched_idxs[img_id]])
  537. regression_targets = self.box_coder.encode(matched_gt_boxes, proposals)
  538. return proposals, matched_idxs, labels, regression_targets
  539. def postprocess_detections(
  540. self,
  541. class_logits, # type: Tensor
  542. box_regression, # type: Tensor
  543. proposals, # type: List[Tensor]
  544. image_shapes, # type: List[Tuple[int, int]]
  545. ):
  546. # type: (...) -> Tuple[List[Tensor], List[Tensor], List[Tensor]]
  547. device = class_logits.device
  548. num_classes = class_logits.shape[-1]
  549. boxes_per_image = [boxes_in_image.shape[0] for boxes_in_image in proposals]
  550. pred_boxes = self.box_coder.decode(box_regression, proposals)
  551. pred_scores = F.softmax(class_logits, -1)
  552. pred_boxes_list = pred_boxes.split(boxes_per_image, 0)
  553. pred_scores_list = pred_scores.split(boxes_per_image, 0)
  554. all_boxes = []
  555. all_scores = []
  556. all_labels = []
  557. for boxes, scores, image_shape in zip(pred_boxes_list, pred_scores_list, image_shapes):
  558. boxes = box_ops.clip_boxes_to_image(boxes, image_shape)
  559. # create labels for each prediction
  560. labels = torch.arange(num_classes, device=device)
  561. labels = labels.view(1, -1).expand_as(scores)
  562. # remove predictions with the background label
  563. boxes = boxes[:, 1:]
  564. scores = scores[:, 1:]
  565. labels = labels[:, 1:]
  566. # batch everything, by making every class prediction be a separate instance
  567. boxes = boxes.reshape(-1, 4)
  568. scores = scores.reshape(-1)
  569. labels = labels.reshape(-1)
  570. # remove low scoring boxes
  571. inds = torch.where(scores > self.score_thresh)[0]
  572. boxes, scores, labels = boxes[inds], scores[inds], labels[inds]
  573. # remove empty boxes
  574. keep = box_ops.remove_small_boxes(boxes, min_size=1e-2)
  575. boxes, scores, labels = boxes[keep], scores[keep], labels[keep]
  576. # non-maximum suppression, independently done per class
  577. keep = box_ops.batched_nms(boxes, scores, labels, self.nms_thresh)
  578. # keep only topk scoring predictions
  579. keep = keep[: self.detections_per_img]
  580. boxes, scores, labels = boxes[keep], scores[keep], labels[keep]
  581. all_boxes.append(boxes)
  582. all_scores.append(scores)
  583. all_labels.append(labels)
  584. return all_boxes, all_scores, all_labels
  585. def forward(
  586. self,
  587. features, # type: Dict[str, Tensor]
  588. proposals, # type: List[Tensor]
  589. image_shapes, # type: List[Tuple[int, int]]
  590. targets=None, # type: Optional[List[Dict[str, Tensor]]]
  591. ):
  592. # type: (...) -> Tuple[List[Dict[str, Tensor]], Dict[str, Tensor]]
  593. """
  594. Args:
  595. features (List[Tensor])
  596. proposals (List[Tensor[N, 4]])
  597. image_shapes (List[Tuple[H, W]])
  598. targets (List[Dict])
  599. """
  600. print(f'roihead forward!!!')
  601. if targets is not None:
  602. for t in targets:
  603. # TODO: https://github.com/pytorch/pytorch/issues/26731
  604. floating_point_types = (torch.float, torch.double, torch.half)
  605. if not t["boxes"].dtype in floating_point_types:
  606. raise TypeError(f"target boxes must of float type, instead got {t['boxes'].dtype}")
  607. if not t["labels"].dtype == torch.int64:
  608. raise TypeError(f"target labels must of int64 type, instead got {t['labels'].dtype}")
  609. if self.has_keypoint():
  610. if not t["keypoints"].dtype == torch.float32:
  611. raise TypeError(f"target keypoints must of float type, instead got {t['keypoints'].dtype}")
  612. if self.training:
  613. proposals, matched_idxs, labels, regression_targets = self.select_training_samples(proposals, targets)
  614. else:
  615. labels = None
  616. regression_targets = None
  617. matched_idxs = None
  618. box_features = self.box_roi_pool(features, proposals, image_shapes)
  619. box_features = self.box_head(box_features)
  620. class_logits, box_regression = self.box_predictor(box_features)
  621. result: List[Dict[str, torch.Tensor]] = []
  622. losses = {}
  623. if self.training:
  624. if labels is None:
  625. raise ValueError("labels cannot be None")
  626. if regression_targets is None:
  627. raise ValueError("regression_targets cannot be None")
  628. print(f'boxes compute losses')
  629. loss_classifier, loss_box_reg = fastrcnn_loss(class_logits, box_regression, labels, regression_targets)
  630. losses = {"loss_classifier": loss_classifier, "loss_box_reg": loss_box_reg}
  631. else:
  632. print(f'boxes postprocess')
  633. boxes, scores, labels = self.postprocess_detections(class_logits, box_regression, proposals, image_shapes)
  634. num_images = len(boxes)
  635. for i in range(num_images):
  636. result.append(
  637. {
  638. "boxes": boxes[i],
  639. "labels": labels[i],
  640. "scores": scores[i],
  641. }
  642. )
  643. if self.has_mask():
  644. mask_proposals = [p["boxes"] for p in result]
  645. if self.training:
  646. if matched_idxs is None:
  647. raise ValueError("if in training, matched_idxs should not be None")
  648. # during training, only focus on positive boxes
  649. num_images = len(proposals)
  650. mask_proposals = []
  651. pos_matched_idxs = []
  652. for img_id in range(num_images):
  653. pos = torch.where(labels[img_id] > 0)[0]
  654. mask_proposals.append(proposals[img_id][pos])
  655. pos_matched_idxs.append(matched_idxs[img_id][pos])
  656. else:
  657. pos_matched_idxs = None
  658. if self.mask_roi_pool is not None:
  659. mask_features = self.mask_roi_pool(features, mask_proposals, image_shapes)
  660. mask_features = self.mask_head(mask_features)
  661. mask_logits = self.mask_predictor(mask_features)
  662. else:
  663. raise Exception("Expected mask_roi_pool to be not None")
  664. loss_mask = {}
  665. if self.training:
  666. if targets is None or pos_matched_idxs is None or mask_logits is None:
  667. raise ValueError("targets, pos_matched_idxs, mask_logits cannot be None when training")
  668. gt_masks = [t["masks"] for t in targets]
  669. gt_labels = [t["labels"] for t in targets]
  670. rcnn_loss_mask = maskrcnn_loss(mask_logits, mask_proposals, gt_masks, gt_labels, pos_matched_idxs)
  671. loss_mask = {"loss_mask": rcnn_loss_mask}
  672. else:
  673. labels = [r["labels"] for r in result]
  674. masks_probs = maskrcnn_inference(mask_logits, labels)
  675. for mask_prob, r in zip(masks_probs, result):
  676. r["masks"] = mask_prob
  677. losses.update(loss_mask)
  678. # keep none checks in if conditional so torchscript will conditionally
  679. # compile each branch
  680. if (
  681. self.keypoint_roi_pool is not None
  682. and self.keypoint_head is not None
  683. and self.keypoint_predictor is not None
  684. ):
  685. keypoint_proposals = [p["boxes"] for p in result]
  686. if self.training:
  687. # during training, only focus on positive boxes
  688. num_images = len(proposals)
  689. keypoint_proposals = []
  690. pos_matched_idxs = []
  691. if matched_idxs is None:
  692. raise ValueError("if in trainning, matched_idxs should not be None")
  693. for img_id in range(num_images):
  694. pos = torch.where(labels[img_id] > 0)[0]
  695. keypoint_proposals.append(proposals[img_id][pos])
  696. pos_matched_idxs.append(matched_idxs[img_id][pos])
  697. else:
  698. pos_matched_idxs = None
  699. keypoint_features = self.line_roi_pool(features, keypoint_proposals, image_shapes)
  700. keypoint_features = self.line_head(keypoint_features)
  701. keypoint_logits = self.line_predictor(keypoint_features)
  702. loss_keypoint = {}
  703. if self.training:
  704. if targets is None or pos_matched_idxs is None:
  705. raise ValueError("both targets and pos_matched_idxs should not be None when in training mode")
  706. gt_keypoints = [t["keypoints"] for t in targets]
  707. rcnn_loss_keypoint = keypointrcnn_loss(
  708. keypoint_logits, keypoint_proposals, gt_keypoints, pos_matched_idxs
  709. )
  710. loss_keypoint = {"loss_keypoint": rcnn_loss_keypoint}
  711. else:
  712. if keypoint_logits is None or keypoint_proposals is None:
  713. raise ValueError(
  714. "both keypoint_logits and keypoint_proposals should not be None when not in training mode"
  715. )
  716. keypoints_probs, kp_scores = keypointrcnn_inference(keypoint_logits, keypoint_proposals)
  717. for keypoint_prob, kps, r in zip(keypoints_probs, kp_scores, result):
  718. r["keypoints"] = keypoint_prob
  719. r["keypoints_scores"] = kps
  720. losses.update(loss_keypoint)
  721. return result, losses