roi_heads.py 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  1. from typing import Dict, List, Optional, Tuple
  2. import matplotlib.pyplot as plt
  3. import torch
  4. import torch.nn.functional as F
  5. import torchvision
  6. from torch import nn, Tensor
  7. from libs.vision_libs.ops import boxes as box_ops, roi_align
  8. import libs.vision_libs.models.detection._utils as det_utils
  9. from collections import OrderedDict
  10. def fastrcnn_loss(class_logits, box_regression, labels, regression_targets):
  11. # type: (Tensor, Tensor, List[Tensor], List[Tensor]) -> Tuple[Tensor, Tensor]
  12. """
  13. Computes the loss for Faster R-CNN.
  14. Args:
  15. class_logits (Tensor)
  16. box_regression (Tensor)
  17. labels (list[BoxList])
  18. regression_targets (Tensor)
  19. Returns:
  20. classification_loss (Tensor)
  21. box_loss (Tensor)
  22. """
  23. # print(f'compute fastrcnn_loss:{labels}')
  24. labels = torch.cat(labels, dim=0)
  25. regression_targets = torch.cat(regression_targets, dim=0)
  26. classification_loss = F.cross_entropy(class_logits, labels)
  27. # get indices that correspond to the regression targets for
  28. # the corresponding ground truth labels, to be used with
  29. # advanced indexing
  30. sampled_pos_inds_subset = torch.where(labels > 0)[0]
  31. labels_pos = labels[sampled_pos_inds_subset]
  32. N, num_classes = class_logits.shape
  33. box_regression = box_regression.reshape(N, box_regression.size(-1) // 4, 4)
  34. box_loss = F.smooth_l1_loss(
  35. box_regression[sampled_pos_inds_subset, labels_pos],
  36. regression_targets[sampled_pos_inds_subset],
  37. beta=1 / 9,
  38. reduction="sum",
  39. )
  40. box_loss = box_loss / labels.numel()
  41. return classification_loss, box_loss
  42. def maskrcnn_inference(x, labels):
  43. # type: (Tensor, List[Tensor]) -> List[Tensor]
  44. """
  45. From the results of the CNN, post process the masks
  46. by taking the mask corresponding to the class with max
  47. probability (which are of fixed size and directly output
  48. by the CNN) and return the masks in the mask field of the BoxList.
  49. Args:
  50. x (Tensor): the mask logits
  51. labels (list[BoxList]): bounding boxes that are used as
  52. reference, one for ech image
  53. Returns:
  54. results (list[BoxList]): one BoxList for each image, containing
  55. the extra field mask
  56. """
  57. mask_prob = x.sigmoid()
  58. # select masks corresponding to the predicted classes
  59. num_masks = x.shape[0]
  60. boxes_per_image = [label.shape[0] for label in labels]
  61. labels = torch.cat(labels)
  62. index = torch.arange(num_masks, device=labels.device)
  63. mask_prob = mask_prob[index, labels][:, None]
  64. mask_prob = mask_prob.split(boxes_per_image, dim=0)
  65. return mask_prob
  66. def project_masks_on_boxes(gt_masks, boxes, matched_idxs, M):
  67. # type: (Tensor, Tensor, Tensor, int) -> Tensor
  68. """
  69. Given segmentation masks and the bounding boxes corresponding
  70. to the location of the masks in the image, this function
  71. crops and resizes the masks in the position defined by the
  72. boxes. This prepares the masks for them to be fed to the
  73. loss computation as the targets.
  74. """
  75. matched_idxs = matched_idxs.to(boxes)
  76. rois = torch.cat([matched_idxs[:, None], boxes], dim=1)
  77. gt_masks = gt_masks[:, None].to(rois)
  78. return roi_align(gt_masks, rois, (M, M), 1.0)[:, 0]
  79. def maskrcnn_loss(mask_logits, proposals, gt_masks, gt_labels, mask_matched_idxs):
  80. # type: (Tensor, List[Tensor], List[Tensor], List[Tensor], List[Tensor]) -> Tensor
  81. """
  82. Args:
  83. proposals (list[BoxList])
  84. mask_logits (Tensor)
  85. targets (list[BoxList])
  86. Return:
  87. mask_loss (Tensor): scalar tensor containing the loss
  88. """
  89. discretization_size = mask_logits.shape[-1]
  90. labels = [gt_label[idxs] for gt_label, idxs in zip(gt_labels, mask_matched_idxs)]
  91. mask_targets = [
  92. project_masks_on_boxes(m, p, i, discretization_size) for m, p, i in zip(gt_masks, proposals, mask_matched_idxs)
  93. ]
  94. labels = torch.cat(labels, dim=0)
  95. mask_targets = torch.cat(mask_targets, dim=0)
  96. # torch.mean (in binary_cross_entropy_with_logits) doesn't
  97. # accept empty tensors, so handle it separately
  98. if mask_targets.numel() == 0:
  99. return mask_logits.sum() * 0
  100. mask_loss = F.binary_cross_entropy_with_logits(
  101. mask_logits[torch.arange(labels.shape[0], device=labels.device), labels], mask_targets
  102. )
  103. return mask_loss
  104. def line_points_to_heatmap(keypoints, rois, heatmap_size):
  105. # type: (Tensor, Tensor, int) -> Tuple[Tensor, Tensor]
  106. print(f'rois:{rois.shape}')
  107. print(f'heatmap_size:{heatmap_size}')
  108. offset_x = rois[:, 0]
  109. offset_y = rois[:, 1]
  110. scale_x = heatmap_size / (rois[:, 2] - rois[:, 0])
  111. scale_y = heatmap_size / (rois[:, 3] - rois[:, 1])
  112. offset_x = offset_x[:, None]
  113. offset_y = offset_y[:, None]
  114. scale_x = scale_x[:, None]
  115. scale_y = scale_y[:, None]
  116. print(f'keypoints.shape:{keypoints.shape}')
  117. # batch_size, num_keypoints, _ = keypoints.shape
  118. x = keypoints[..., 0]
  119. y = keypoints[..., 1]
  120. # gs=generate_gaussian_heatmaps(x,y,512,1.0)
  121. # print(f'gs_heatmap shape:{gs.shape}')
  122. #
  123. # show_heatmap(gs,'target')
  124. x_boundary_inds = x == rois[:, 2][:, None]
  125. y_boundary_inds = y == rois[:, 3][:, None]
  126. x = (x - offset_x) * scale_x
  127. x = x.floor().long()
  128. y = (y - offset_y) * scale_y
  129. y = y.floor().long()
  130. x[x_boundary_inds] = heatmap_size - 1
  131. y[y_boundary_inds] = heatmap_size - 1
  132. # print(f'heatmaps x:{x}')
  133. # print(f'heatmaps y:{y}')
  134. valid_loc = (x >= 0) & (y >= 0) & (x < heatmap_size) & (y < heatmap_size)
  135. vis = keypoints[..., 2] > 0
  136. valid = (valid_loc & vis).long()
  137. gs_heatmap=generate_gaussian_heatmaps(x,y,heatmap_size,1.0)
  138. # show_heatmap(gs_heatmap[0],'feature')
  139. print(f'gs_heatmap:{gs_heatmap.shape}')
  140. #
  141. # lin_ind = y * heatmap_size + x
  142. # print(f'lin_ind:{lin_ind.shape}')
  143. # heatmaps = lin_ind * valid
  144. return gs_heatmap
  145. def generate_gaussian_heatmaps(xs, ys, heatmap_size, sigma=2.0, device='cuda'):
  146. """
  147. 为一组点生成并合并高斯热图。
  148. Args:
  149. xs (Tensor): 形状为 (N, 2) 的所有点的 x 坐标
  150. ys (Tensor): 形状为 (N, 2) 的所有点的 y 坐标
  151. heatmap_size (int): 热图大小 H=W
  152. sigma (float): 高斯核标准差
  153. device (str): 设备类型 ('cpu' or 'cuda')
  154. Returns:
  155. Tensor: 形状为 (H, W) 的合并后的热图
  156. """
  157. assert xs.shape == ys.shape, "x and y must have the same shape"
  158. N = xs.shape[0]
  159. print(f'N:{N}')
  160. # 创建网格
  161. grid_y, grid_x = torch.meshgrid(
  162. torch.arange(heatmap_size, device=device),
  163. torch.arange(heatmap_size, device=device),
  164. indexing='ij'
  165. )
  166. # print(f'heatmap_size:{heatmap_size}')
  167. # 初始化输出热图
  168. combined_heatmap = torch.zeros((N,heatmap_size, heatmap_size), device=device)
  169. for i in range(N):
  170. mu_x1 = xs[i, 0].clamp(0, heatmap_size - 1).item()
  171. mu_y1 = ys[i, 0].clamp(0, heatmap_size - 1).item()
  172. # 计算距离平方
  173. dist1 = (grid_x - mu_x1) ** 2 + (grid_y - mu_y1) ** 2
  174. # 计算高斯分布
  175. heatmap1 = torch.exp(-dist1 / (2 * sigma ** 2))
  176. mu_x2 = xs[i, 1].clamp(0, heatmap_size - 1).item()
  177. mu_y2 = ys[i, 1].clamp(0, heatmap_size - 1).item()
  178. # 计算距离平方
  179. dist2 = (grid_x - mu_x2) ** 2 + (grid_y - mu_y2) ** 2
  180. # 计算高斯分布
  181. heatmap2 = torch.exp(-dist2 / (2 * sigma ** 2))
  182. heatmap=heatmap1+heatmap2
  183. # 将当前热图累加到结果中
  184. combined_heatmap[i]= heatmap
  185. return combined_heatmap
  186. # 显示热图的函数
  187. def show_heatmap(heatmap, title="Heatmap"):
  188. """
  189. 使用 matplotlib 显示热图。
  190. Args:
  191. heatmap (Tensor): 要显示的热图张量
  192. title (str): 图表标题
  193. """
  194. # 如果在 GPU 上,首先将其移动到 CPU 并转换为 numpy 数组
  195. if heatmap.is_cuda:
  196. heatmap = heatmap.cpu().numpy()
  197. else:
  198. heatmap = heatmap.numpy()
  199. plt.imshow(heatmap, cmap='hot', interpolation='nearest')
  200. plt.colorbar()
  201. plt.title(title)
  202. plt.show()
  203. def keypoints_to_heatmap(keypoints, rois, heatmap_size):
  204. # type: (Tensor, Tensor, int) -> Tuple[Tensor, Tensor]
  205. offset_x = rois[:, 0]
  206. offset_y = rois[:, 1]
  207. scale_x = heatmap_size / (rois[:, 2] - rois[:, 0])
  208. scale_y = heatmap_size / (rois[:, 3] - rois[:, 1])
  209. offset_x = offset_x[:, None]
  210. offset_y = offset_y[:, None]
  211. scale_x = scale_x[:, None]
  212. scale_y = scale_y[:, None]
  213. x = keypoints[..., 0]
  214. y = keypoints[..., 1]
  215. x_boundary_inds = x == rois[:, 2][:, None]
  216. y_boundary_inds = y == rois[:, 3][:, None]
  217. x = (x - offset_x) * scale_x
  218. x = x.floor().long()
  219. y = (y - offset_y) * scale_y
  220. y = y.floor().long()
  221. x[x_boundary_inds] = heatmap_size - 1
  222. y[y_boundary_inds] = heatmap_size - 1
  223. valid_loc = (x >= 0) & (y >= 0) & (x < heatmap_size) & (y < heatmap_size)
  224. vis = keypoints[..., 2] > 0
  225. valid = (valid_loc & vis).long()
  226. lin_ind = y * heatmap_size + x
  227. heatmaps = lin_ind * valid
  228. return heatmaps, valid
  229. def _onnx_heatmaps_to_keypoints(
  230. maps, maps_i, roi_map_width, roi_map_height, widths_i, heights_i, offset_x_i, offset_y_i
  231. ):
  232. num_keypoints = torch.scalar_tensor(maps.size(1), dtype=torch.int64)
  233. width_correction = widths_i / roi_map_width
  234. height_correction = heights_i / roi_map_height
  235. roi_map = F.interpolate(
  236. maps_i[:, None], size=(int(roi_map_height), int(roi_map_width)), mode="bicubic", align_corners=False
  237. )[:, 0]
  238. w = torch.scalar_tensor(roi_map.size(2), dtype=torch.int64)
  239. pos = roi_map.reshape(num_keypoints, -1).argmax(dim=1)
  240. x_int = pos % w
  241. y_int = (pos - x_int) // w
  242. x = (torch.tensor(0.5, dtype=torch.float32) + x_int.to(dtype=torch.float32)) * width_correction.to(
  243. dtype=torch.float32
  244. )
  245. y = (torch.tensor(0.5, dtype=torch.float32) + y_int.to(dtype=torch.float32)) * height_correction.to(
  246. dtype=torch.float32
  247. )
  248. xy_preds_i_0 = x + offset_x_i.to(dtype=torch.float32)
  249. xy_preds_i_1 = y + offset_y_i.to(dtype=torch.float32)
  250. xy_preds_i_2 = torch.ones(xy_preds_i_1.shape, dtype=torch.float32)
  251. xy_preds_i = torch.stack(
  252. [
  253. xy_preds_i_0.to(dtype=torch.float32),
  254. xy_preds_i_1.to(dtype=torch.float32),
  255. xy_preds_i_2.to(dtype=torch.float32),
  256. ],
  257. 0,
  258. )
  259. # TODO: simplify when indexing without rank will be supported by ONNX
  260. base = num_keypoints * num_keypoints + num_keypoints + 1
  261. ind = torch.arange(num_keypoints)
  262. ind = ind.to(dtype=torch.int64) * base
  263. end_scores_i = (
  264. roi_map.index_select(1, y_int.to(dtype=torch.int64))
  265. .index_select(2, x_int.to(dtype=torch.int64))
  266. .view(-1)
  267. .index_select(0, ind.to(dtype=torch.int64))
  268. )
  269. return xy_preds_i, end_scores_i
  270. @torch.jit._script_if_tracing
  271. def _onnx_heatmaps_to_keypoints_loop(
  272. maps, rois, widths_ceil, heights_ceil, widths, heights, offset_x, offset_y, num_keypoints
  273. ):
  274. xy_preds = torch.zeros((0, 3, int(num_keypoints)), dtype=torch.float32, device=maps.device)
  275. end_scores = torch.zeros((0, int(num_keypoints)), dtype=torch.float32, device=maps.device)
  276. for i in range(int(rois.size(0))):
  277. xy_preds_i, end_scores_i = _onnx_heatmaps_to_keypoints(
  278. maps, maps[i], widths_ceil[i], heights_ceil[i], widths[i], heights[i], offset_x[i], offset_y[i]
  279. )
  280. xy_preds = torch.cat((xy_preds.to(dtype=torch.float32), xy_preds_i.unsqueeze(0).to(dtype=torch.float32)), 0)
  281. end_scores = torch.cat(
  282. (end_scores.to(dtype=torch.float32), end_scores_i.to(dtype=torch.float32).unsqueeze(0)), 0
  283. )
  284. return xy_preds, end_scores
  285. def heatmaps_to_keypoints(maps, rois):
  286. """Extract predicted keypoint locations from heatmaps. Output has shape
  287. (#rois, 4, #keypoints) with the 4 rows corresponding to (x, y, logit, prob)
  288. for each keypoint.
  289. """
  290. # This function converts a discrete image coordinate in a HEATMAP_SIZE x
  291. # HEATMAP_SIZE image to a continuous keypoint coordinate. We maintain
  292. # consistency with keypoints_to_heatmap_labels by using the conversion from
  293. # Heckbert 1990: c = d + 0.5, where d is a discrete coordinate and c is a
  294. # continuous coordinate.
  295. offset_x = rois[:, 0]
  296. offset_y = rois[:, 1]
  297. widths = rois[:, 2] - rois[:, 0]
  298. heights = rois[:, 3] - rois[:, 1]
  299. widths = widths.clamp(min=1)
  300. heights = heights.clamp(min=1)
  301. widths_ceil = widths.ceil()
  302. heights_ceil = heights.ceil()
  303. num_keypoints = maps.shape[1]
  304. if torchvision._is_tracing():
  305. xy_preds, end_scores = _onnx_heatmaps_to_keypoints_loop(
  306. maps,
  307. rois,
  308. widths_ceil,
  309. heights_ceil,
  310. widths,
  311. heights,
  312. offset_x,
  313. offset_y,
  314. torch.scalar_tensor(num_keypoints, dtype=torch.int64),
  315. )
  316. return xy_preds.permute(0, 2, 1), end_scores
  317. xy_preds = torch.zeros((len(rois), 3, num_keypoints), dtype=torch.float32, device=maps.device)
  318. end_scores = torch.zeros((len(rois), num_keypoints), dtype=torch.float32, device=maps.device)
  319. for i in range(len(rois)):
  320. roi_map_width = int(widths_ceil[i].item())
  321. roi_map_height = int(heights_ceil[i].item())
  322. width_correction = widths[i] / roi_map_width
  323. height_correction = heights[i] / roi_map_height
  324. roi_map = F.interpolate(
  325. maps[i][:, None], size=(roi_map_height, roi_map_width), mode="bicubic", align_corners=False
  326. )[:, 0]
  327. # roi_map_probs = scores_to_probs(roi_map.copy())
  328. w = roi_map.shape[2]
  329. pos = roi_map.reshape(num_keypoints, -1).argmax(dim=1)
  330. x_int = pos % w
  331. y_int = torch.div(pos - x_int, w, rounding_mode="floor")
  332. # assert (roi_map_probs[k, y_int, x_int] ==
  333. # roi_map_probs[k, :, :].max())
  334. x = (x_int.float() + 0.5) * width_correction
  335. y = (y_int.float() + 0.5) * height_correction
  336. xy_preds[i, 0, :] = x + offset_x[i]
  337. xy_preds[i, 1, :] = y + offset_y[i]
  338. xy_preds[i, 2, :] = 1
  339. end_scores[i, :] = roi_map[torch.arange(num_keypoints, device=roi_map.device), y_int, x_int]
  340. return xy_preds.permute(0, 2, 1), end_scores
  341. def lines_point_pair_loss(line_logits, proposals, gt_lines, line_matched_idxs):
  342. # type: (Tensor, List[Tensor], List[Tensor], List[Tensor]) -> Tensor
  343. N, K, H, W = line_logits.shape
  344. batch_size=len(proposals)
  345. print(f'lines_point_pair_loss line_logits.shape:{line_logits.shape}')
  346. if H != W:
  347. raise ValueError(
  348. f"line_logits height and width (last two elements of shape) should be equal. Instead got H = {H} and W = {W}"
  349. )
  350. discretization_size = H
  351. heatmaps = []
  352. gs_heatmaps=[]
  353. valid = []
  354. for proposals_per_image, gt_kp_in_image, midx in zip(proposals, gt_lines, line_matched_idxs):
  355. print(f'proposals_per_image:{proposals_per_image.shape}')
  356. kp = gt_kp_in_image[midx]
  357. gs_heatmaps_per_img = line_points_to_heatmap(kp, proposals_per_image, discretization_size)
  358. gs_heatmaps.append(gs_heatmaps_per_img)
  359. # print(f'heatmaps_per_image:{heatmaps_per_image.shape}')
  360. # heatmaps.append(heatmaps_per_image.view(-1))
  361. # valid.append(valid_per_image.view(-1))
  362. # line_targets = torch.cat(heatmaps, dim=0)
  363. gs_heatmaps=torch.cat(gs_heatmaps,dim=0)
  364. print(f'gs_heatmaps:{gs_heatmaps.shape}, line_logits.shape:{line_logits.squeeze(1).shape}')
  365. # print(f'line_targets:{line_targets.shape},{line_targets}')
  366. # valid = torch.cat(valid, dim=0).to(dtype=torch.uint8)
  367. # valid = torch.where(valid)[0]
  368. # print(f' line_targets[valid]:{line_targets[valid]}')
  369. # torch.mean (in binary_cross_entropy_with_logits) doesn't
  370. # accept empty tensors, so handle it sepaartely
  371. # if line_targets.numel() == 0 or len(valid) == 0:
  372. # return line_logits.sum() * 0
  373. # line_logits = line_logits.view(N * K, H * W)
  374. # print(f'line_logits[valid]:{line_logits[valid].shape}')
  375. line_logits=line_logits.squeeze(1)
  376. # line_loss = F.cross_entropy(line_logits[valid], line_targets[valid])
  377. line_loss=F.cross_entropy(line_logits,gs_heatmaps)
  378. return line_loss
  379. def line_inference(x, boxes):
  380. # type: (Tensor, List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]
  381. kp_probs = []
  382. kp_scores = []
  383. boxes_per_image = [box.size(0) for box in boxes]
  384. x2 = x.split(boxes_per_image, dim=0)
  385. for xx, bb in zip(x2, boxes):
  386. kp_prob, scores = heatmaps_to_keypoints(xx, bb)
  387. kp_probs.append(kp_prob)
  388. kp_scores.append(scores)
  389. return kp_probs, kp_scores
  390. def keypointrcnn_loss(keypoint_logits, proposals, gt_keypoints, keypoint_matched_idxs):
  391. # type: (Tensor, List[Tensor], List[Tensor], List[Tensor]) -> Tensor
  392. N, K, H, W = keypoint_logits.shape
  393. if H != W:
  394. raise ValueError(
  395. f"keypoint_logits height and width (last two elements of shape) should be equal. Instead got H = {H} and W = {W}"
  396. )
  397. discretization_size = H
  398. heatmaps = []
  399. valid = []
  400. for proposals_per_image, gt_kp_in_image, midx in zip(proposals, gt_keypoints, keypoint_matched_idxs):
  401. kp = gt_kp_in_image[midx]
  402. heatmaps_per_image, valid_per_image = keypoints_to_heatmap(kp, proposals_per_image, discretization_size)
  403. heatmaps.append(heatmaps_per_image.view(-1))
  404. valid.append(valid_per_image.view(-1))
  405. keypoint_targets = torch.cat(heatmaps, dim=0)
  406. valid = torch.cat(valid, dim=0).to(dtype=torch.uint8)
  407. valid = torch.where(valid)[0]
  408. # torch.mean (in binary_cross_entropy_with_logits) doesn't
  409. # accept empty tensors, so handle it sepaartely
  410. if keypoint_targets.numel() == 0 or len(valid) == 0:
  411. return keypoint_logits.sum() * 0
  412. keypoint_logits = keypoint_logits.view(N * K, H * W)
  413. keypoint_loss = F.cross_entropy(keypoint_logits[valid], keypoint_targets[valid])
  414. return keypoint_loss
  415. def keypointrcnn_inference(x, boxes):
  416. # type: (Tensor, List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]
  417. kp_probs = []
  418. kp_scores = []
  419. boxes_per_image = [box.size(0) for box in boxes]
  420. x2 = x.split(boxes_per_image, dim=0)
  421. for xx, bb in zip(x2, boxes):
  422. kp_prob, scores = heatmaps_to_keypoints(xx, bb)
  423. kp_probs.append(kp_prob)
  424. kp_scores.append(scores)
  425. return kp_probs, kp_scores
  426. def _onnx_expand_boxes(boxes, scale):
  427. # type: (Tensor, float) -> Tensor
  428. w_half = (boxes[:, 2] - boxes[:, 0]) * 0.5
  429. h_half = (boxes[:, 3] - boxes[:, 1]) * 0.5
  430. x_c = (boxes[:, 2] + boxes[:, 0]) * 0.5
  431. y_c = (boxes[:, 3] + boxes[:, 1]) * 0.5
  432. w_half = w_half.to(dtype=torch.float32) * scale
  433. h_half = h_half.to(dtype=torch.float32) * scale
  434. boxes_exp0 = x_c - w_half
  435. boxes_exp1 = y_c - h_half
  436. boxes_exp2 = x_c + w_half
  437. boxes_exp3 = y_c + h_half
  438. boxes_exp = torch.stack((boxes_exp0, boxes_exp1, boxes_exp2, boxes_exp3), 1)
  439. return boxes_exp
  440. # the next two functions should be merged inside Masker
  441. # but are kept here for the moment while we need them
  442. # temporarily for paste_mask_in_image
  443. def expand_boxes(boxes, scale):
  444. # type: (Tensor, float) -> Tensor
  445. if torchvision._is_tracing():
  446. return _onnx_expand_boxes(boxes, scale)
  447. w_half = (boxes[:, 2] - boxes[:, 0]) * 0.5
  448. h_half = (boxes[:, 3] - boxes[:, 1]) * 0.5
  449. x_c = (boxes[:, 2] + boxes[:, 0]) * 0.5
  450. y_c = (boxes[:, 3] + boxes[:, 1]) * 0.5
  451. w_half *= scale
  452. h_half *= scale
  453. boxes_exp = torch.zeros_like(boxes)
  454. boxes_exp[:, 0] = x_c - w_half
  455. boxes_exp[:, 2] = x_c + w_half
  456. boxes_exp[:, 1] = y_c - h_half
  457. boxes_exp[:, 3] = y_c + h_half
  458. return boxes_exp
  459. @torch.jit.unused
  460. def expand_masks_tracing_scale(M, padding):
  461. # type: (int, int) -> float
  462. return torch.tensor(M + 2 * padding).to(torch.float32) / torch.tensor(M).to(torch.float32)
  463. def expand_masks(mask, padding):
  464. # type: (Tensor, int) -> Tuple[Tensor, float]
  465. M = mask.shape[-1]
  466. if torch._C._get_tracing_state(): # could not import is_tracing(), not sure why
  467. scale = expand_masks_tracing_scale(M, padding)
  468. else:
  469. scale = float(M + 2 * padding) / M
  470. padded_mask = F.pad(mask, (padding,) * 4)
  471. return padded_mask, scale
  472. def paste_mask_in_image(mask, box, im_h, im_w):
  473. # type: (Tensor, Tensor, int, int) -> Tensor
  474. TO_REMOVE = 1
  475. w = int(box[2] - box[0] + TO_REMOVE)
  476. h = int(box[3] - box[1] + TO_REMOVE)
  477. w = max(w, 1)
  478. h = max(h, 1)
  479. # Set shape to [batchxCxHxW]
  480. mask = mask.expand((1, 1, -1, -1))
  481. # Resize mask
  482. mask = F.interpolate(mask, size=(h, w), mode="bilinear", align_corners=False)
  483. mask = mask[0][0]
  484. im_mask = torch.zeros((im_h, im_w), dtype=mask.dtype, device=mask.device)
  485. x_0 = max(box[0], 0)
  486. x_1 = min(box[2] + 1, im_w)
  487. y_0 = max(box[1], 0)
  488. y_1 = min(box[3] + 1, im_h)
  489. 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])]
  490. return im_mask
  491. def _onnx_paste_mask_in_image(mask, box, im_h, im_w):
  492. one = torch.ones(1, dtype=torch.int64)
  493. zero = torch.zeros(1, dtype=torch.int64)
  494. w = box[2] - box[0] + one
  495. h = box[3] - box[1] + one
  496. w = torch.max(torch.cat((w, one)))
  497. h = torch.max(torch.cat((h, one)))
  498. # Set shape to [batchxCxHxW]
  499. mask = mask.expand((1, 1, mask.size(0), mask.size(1)))
  500. # Resize mask
  501. mask = F.interpolate(mask, size=(int(h), int(w)), mode="bilinear", align_corners=False)
  502. mask = mask[0][0]
  503. x_0 = torch.max(torch.cat((box[0].unsqueeze(0), zero)))
  504. x_1 = torch.min(torch.cat((box[2].unsqueeze(0) + one, im_w.unsqueeze(0))))
  505. y_0 = torch.max(torch.cat((box[1].unsqueeze(0), zero)))
  506. y_1 = torch.min(torch.cat((box[3].unsqueeze(0) + one, im_h.unsqueeze(0))))
  507. unpaded_im_mask = mask[(y_0 - box[1]) : (y_1 - box[1]), (x_0 - box[0]) : (x_1 - box[0])]
  508. # TODO : replace below with a dynamic padding when support is added in ONNX
  509. # pad y
  510. zeros_y0 = torch.zeros(y_0, unpaded_im_mask.size(1))
  511. zeros_y1 = torch.zeros(im_h - y_1, unpaded_im_mask.size(1))
  512. concat_0 = torch.cat((zeros_y0, unpaded_im_mask.to(dtype=torch.float32), zeros_y1), 0)[0:im_h, :]
  513. # pad x
  514. zeros_x0 = torch.zeros(concat_0.size(0), x_0)
  515. zeros_x1 = torch.zeros(concat_0.size(0), im_w - x_1)
  516. im_mask = torch.cat((zeros_x0, concat_0, zeros_x1), 1)[:, :im_w]
  517. return im_mask
  518. @torch.jit._script_if_tracing
  519. def _onnx_paste_masks_in_image_loop(masks, boxes, im_h, im_w):
  520. res_append = torch.zeros(0, im_h, im_w)
  521. for i in range(masks.size(0)):
  522. mask_res = _onnx_paste_mask_in_image(masks[i][0], boxes[i], im_h, im_w)
  523. mask_res = mask_res.unsqueeze(0)
  524. res_append = torch.cat((res_append, mask_res))
  525. return res_append
  526. def paste_masks_in_image(masks, boxes, img_shape, padding=1):
  527. # type: (Tensor, Tensor, Tuple[int, int], int) -> Tensor
  528. masks, scale = expand_masks(masks, padding=padding)
  529. boxes = expand_boxes(boxes, scale).to(dtype=torch.int64)
  530. im_h, im_w = img_shape
  531. if torchvision._is_tracing():
  532. return _onnx_paste_masks_in_image_loop(
  533. masks, boxes, torch.scalar_tensor(im_h, dtype=torch.int64), torch.scalar_tensor(im_w, dtype=torch.int64)
  534. )[:, None]
  535. res = [paste_mask_in_image(m[0], b, im_h, im_w) for m, b in zip(masks, boxes)]
  536. if len(res) > 0:
  537. ret = torch.stack(res, dim=0)[:, None]
  538. else:
  539. ret = masks.new_empty((0, 1, im_h, im_w))
  540. return ret
  541. class RoIHeads(nn.Module):
  542. __annotations__ = {
  543. "box_coder": det_utils.BoxCoder,
  544. "proposal_matcher": det_utils.Matcher,
  545. "fg_bg_sampler": det_utils.BalancedPositiveNegativeSampler,
  546. }
  547. def __init__(
  548. self,
  549. box_roi_pool,
  550. box_head,
  551. box_predictor,
  552. # Faster R-CNN training
  553. fg_iou_thresh,
  554. bg_iou_thresh,
  555. batch_size_per_image,
  556. positive_fraction,
  557. bbox_reg_weights,
  558. # Faster R-CNN inference
  559. score_thresh,
  560. nms_thresh,
  561. detections_per_img,
  562. # Line
  563. line_roi_pool=None,
  564. line_head=None,
  565. line_predictor=None,
  566. # Mask
  567. mask_roi_pool=None,
  568. mask_head=None,
  569. mask_predictor=None,
  570. keypoint_roi_pool=None,
  571. keypoint_head=None,
  572. keypoint_predictor=None,
  573. ):
  574. super().__init__()
  575. self.box_similarity = box_ops.box_iou
  576. # assign ground-truth boxes for each proposal
  577. self.proposal_matcher = det_utils.Matcher(fg_iou_thresh, bg_iou_thresh, allow_low_quality_matches=False)
  578. self.fg_bg_sampler = det_utils.BalancedPositiveNegativeSampler(batch_size_per_image, positive_fraction)
  579. if bbox_reg_weights is None:
  580. bbox_reg_weights = (10.0, 10.0, 5.0, 5.0)
  581. self.box_coder = det_utils.BoxCoder(bbox_reg_weights)
  582. self.box_roi_pool = box_roi_pool
  583. self.box_head = box_head
  584. self.box_predictor = box_predictor
  585. self.score_thresh = score_thresh
  586. self.nms_thresh = nms_thresh
  587. self.detections_per_img = detections_per_img
  588. self.line_roi_pool = line_roi_pool
  589. self.line_head = line_head
  590. self.line_predictor = line_predictor
  591. self.mask_roi_pool = mask_roi_pool
  592. self.mask_head = mask_head
  593. self.mask_predictor = mask_predictor
  594. self.keypoint_roi_pool = keypoint_roi_pool
  595. self.keypoint_head = keypoint_head
  596. self.keypoint_predictor = keypoint_predictor
  597. def has_mask(self):
  598. if self.mask_roi_pool is None:
  599. return False
  600. if self.mask_head is None:
  601. return False
  602. if self.mask_predictor is None:
  603. return False
  604. return True
  605. def has_keypoint(self):
  606. if self.keypoint_roi_pool is None:
  607. return False
  608. if self.keypoint_head is None:
  609. return False
  610. if self.keypoint_predictor is None:
  611. return False
  612. return True
  613. def has_line(self):
  614. if self.line_roi_pool is None:
  615. return False
  616. if self.line_head is None:
  617. return False
  618. if self.line_predictor is None:
  619. return False
  620. return True
  621. def assign_targets_to_proposals(self, proposals, gt_boxes, gt_labels):
  622. # type: (List[Tensor], List[Tensor], List[Tensor]) -> Tuple[List[Tensor], List[Tensor]]
  623. matched_idxs = []
  624. labels = []
  625. for proposals_in_image, gt_boxes_in_image, gt_labels_in_image in zip(proposals, gt_boxes, gt_labels):
  626. if gt_boxes_in_image.numel() == 0:
  627. # Background image
  628. device = proposals_in_image.device
  629. clamped_matched_idxs_in_image = torch.zeros(
  630. (proposals_in_image.shape[0],), dtype=torch.int64, device=device
  631. )
  632. labels_in_image = torch.zeros((proposals_in_image.shape[0],), dtype=torch.int64, device=device)
  633. else:
  634. # set to self.box_similarity when https://github.com/pytorch/pytorch/issues/27495 lands
  635. match_quality_matrix = box_ops.box_iou(gt_boxes_in_image, proposals_in_image)
  636. matched_idxs_in_image = self.proposal_matcher(match_quality_matrix)
  637. clamped_matched_idxs_in_image = matched_idxs_in_image.clamp(min=0)
  638. labels_in_image = gt_labels_in_image[clamped_matched_idxs_in_image]
  639. labels_in_image = labels_in_image.to(dtype=torch.int64)
  640. # Label background (below the low threshold)
  641. bg_inds = matched_idxs_in_image == self.proposal_matcher.BELOW_LOW_THRESHOLD
  642. labels_in_image[bg_inds] = 0
  643. # Label ignore proposals (between low and high thresholds)
  644. ignore_inds = matched_idxs_in_image == self.proposal_matcher.BETWEEN_THRESHOLDS
  645. labels_in_image[ignore_inds] = -1 # -1 is ignored by sampler
  646. matched_idxs.append(clamped_matched_idxs_in_image)
  647. labels.append(labels_in_image)
  648. return matched_idxs, labels
  649. def subsample(self, labels):
  650. # type: (List[Tensor]) -> List[Tensor]
  651. sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels)
  652. sampled_inds = []
  653. for img_idx, (pos_inds_img, neg_inds_img) in enumerate(zip(sampled_pos_inds, sampled_neg_inds)):
  654. img_sampled_inds = torch.where(pos_inds_img | neg_inds_img)[0]
  655. sampled_inds.append(img_sampled_inds)
  656. return sampled_inds
  657. def add_gt_proposals(self, proposals, gt_boxes):
  658. # type: (List[Tensor], List[Tensor]) -> List[Tensor]
  659. proposals = [torch.cat((proposal, gt_box)) for proposal, gt_box in zip(proposals, gt_boxes)]
  660. return proposals
  661. def check_targets(self, targets):
  662. # type: (Optional[List[Dict[str, Tensor]]]) -> None
  663. if targets is None:
  664. raise ValueError("targets should not be None")
  665. if not all(["boxes" in t for t in targets]):
  666. raise ValueError("Every element of targets should have a boxes key")
  667. if not all(["labels" in t for t in targets]):
  668. raise ValueError("Every element of targets should have a labels key")
  669. if self.has_mask():
  670. if not all(["masks" in t for t in targets]):
  671. raise ValueError("Every element of targets should have a masks key")
  672. def select_training_samples(
  673. self,
  674. proposals, # type: List[Tensor]
  675. targets, # type: Optional[List[Dict[str, Tensor]]]
  676. ):
  677. # type: (...) -> Tuple[List[Tensor], List[Tensor], List[Tensor], List[Tensor]]
  678. self.check_targets(targets)
  679. if targets is None:
  680. raise ValueError("targets should not be None")
  681. dtype = proposals[0].dtype
  682. device = proposals[0].device
  683. gt_boxes = [t["boxes"].to(dtype) for t in targets]
  684. gt_labels = [t["labels"] for t in targets]
  685. # append ground-truth bboxes to propos
  686. proposals = self.add_gt_proposals(proposals, gt_boxes)
  687. # get matching gt indices for each proposal
  688. matched_idxs, labels = self.assign_targets_to_proposals(proposals, gt_boxes, gt_labels)
  689. # sample a fixed proportion of positive-negative proposals
  690. sampled_inds = self.subsample(labels)
  691. matched_gt_boxes = []
  692. num_images = len(proposals)
  693. for img_id in range(num_images):
  694. img_sampled_inds = sampled_inds[img_id]
  695. proposals[img_id] = proposals[img_id][img_sampled_inds]
  696. labels[img_id] = labels[img_id][img_sampled_inds]
  697. matched_idxs[img_id] = matched_idxs[img_id][img_sampled_inds]
  698. gt_boxes_in_image = gt_boxes[img_id]
  699. if gt_boxes_in_image.numel() == 0:
  700. gt_boxes_in_image = torch.zeros((1, 4), dtype=dtype, device=device)
  701. matched_gt_boxes.append(gt_boxes_in_image[matched_idxs[img_id]])
  702. regression_targets = self.box_coder.encode(matched_gt_boxes, proposals)
  703. return proposals, matched_idxs, labels, regression_targets
  704. def postprocess_detections(
  705. self,
  706. class_logits, # type: Tensor
  707. box_regression, # type: Tensor
  708. proposals, # type: List[Tensor]
  709. image_shapes, # type: List[Tuple[int, int]]
  710. ):
  711. # type: (...) -> Tuple[List[Tensor], List[Tensor], List[Tensor]]
  712. device = class_logits.device
  713. num_classes = class_logits.shape[-1]
  714. boxes_per_image = [boxes_in_image.shape[0] for boxes_in_image in proposals]
  715. pred_boxes = self.box_coder.decode(box_regression, proposals)
  716. pred_scores = F.softmax(class_logits, -1)
  717. pred_boxes_list = pred_boxes.split(boxes_per_image, 0)
  718. pred_scores_list = pred_scores.split(boxes_per_image, 0)
  719. all_boxes = []
  720. all_scores = []
  721. all_labels = []
  722. for boxes, scores, image_shape in zip(pred_boxes_list, pred_scores_list, image_shapes):
  723. boxes = box_ops.clip_boxes_to_image(boxes, image_shape)
  724. # create labels for each prediction
  725. labels = torch.arange(num_classes, device=device)
  726. labels = labels.view(1, -1).expand_as(scores)
  727. # remove predictions with the background label
  728. boxes = boxes[:, 1:]
  729. scores = scores[:, 1:]
  730. labels = labels[:, 1:]
  731. # batch everything, by making every class prediction be a separate instance
  732. boxes = boxes.reshape(-1, 4)
  733. scores = scores.reshape(-1)
  734. labels = labels.reshape(-1)
  735. # remove low scoring boxes
  736. inds = torch.where(scores > self.score_thresh)[0]
  737. boxes, scores, labels = boxes[inds], scores[inds], labels[inds]
  738. # remove empty boxes
  739. keep = box_ops.remove_small_boxes(boxes, min_size=1e-2)
  740. boxes, scores, labels = boxes[keep], scores[keep], labels[keep]
  741. # non-maximum suppression, independently done per class
  742. keep = box_ops.batched_nms(boxes, scores, labels, self.nms_thresh)
  743. # keep only topk scoring predictions
  744. keep = keep[: self.detections_per_img]
  745. boxes, scores, labels = boxes[keep], scores[keep], labels[keep]
  746. all_boxes.append(boxes)
  747. all_scores.append(scores)
  748. all_labels.append(labels)
  749. return all_boxes, all_scores, all_labels
  750. def forward(
  751. self,
  752. features, # type: Dict[str, Tensor]
  753. proposals, # type: List[Tensor]
  754. image_shapes, # type: List[Tuple[int, int]]
  755. targets=None, # type: Optional[List[Dict[str, Tensor]]]
  756. ):
  757. # type: (...) -> Tuple[List[Dict[str, Tensor]], Dict[str, Tensor]]
  758. """
  759. Args:
  760. features (List[Tensor])
  761. proposals (List[Tensor[N, 4]])
  762. image_shapes (List[Tuple[H, W]])
  763. targets (List[Dict])
  764. """
  765. print(f'roihead forward!!!')
  766. if targets is not None:
  767. for t in targets:
  768. # TODO: https://github.com/pytorch/pytorch/issues/26731
  769. floating_point_types = (torch.float, torch.double, torch.half)
  770. if not t["boxes"].dtype in floating_point_types:
  771. raise TypeError(f"target boxes must of float type, instead got {t['boxes'].dtype}")
  772. if not t["labels"].dtype == torch.int64:
  773. raise TypeError(f"target labels must of int64 type, instead got {t['labels'].dtype}")
  774. if self.has_keypoint():
  775. if not t["keypoints"].dtype == torch.float32:
  776. raise TypeError(f"target keypoints must of float type, instead got {t['keypoints'].dtype}")
  777. if self.training:
  778. proposals, matched_idxs, labels, regression_targets = self.select_training_samples(proposals, targets)
  779. else:
  780. if targets is not None:
  781. proposals, matched_idxs, labels, regression_targets = self.select_training_samples(proposals, targets)
  782. else:
  783. labels = None
  784. regression_targets = None
  785. matched_idxs = None
  786. box_features = self.box_roi_pool(features, proposals, image_shapes)
  787. box_features = self.box_head(box_features)
  788. class_logits, box_regression = self.box_predictor(box_features)
  789. result: List[Dict[str, torch.Tensor]] = []
  790. losses = {}
  791. # _, C, H, W = features['0'].shape # 忽略 batch_size,因为我们只关心 C, H, W
  792. if self.training:
  793. if labels is None:
  794. raise ValueError("labels cannot be None")
  795. if regression_targets is None:
  796. raise ValueError("regression_targets cannot be None")
  797. print(f'boxes compute losses')
  798. loss_classifier, loss_box_reg = fastrcnn_loss(class_logits, box_regression, labels, regression_targets)
  799. losses = {"loss_classifier": loss_classifier, "loss_box_reg": loss_box_reg}
  800. else:
  801. if targets is not None:
  802. loss_classifier, loss_box_reg = fastrcnn_loss(class_logits, box_regression, labels, regression_targets)
  803. losses = {"loss_classifier": loss_classifier, "loss_box_reg": loss_box_reg}
  804. boxes, scores, labels = self.postprocess_detections(class_logits, box_regression, proposals,
  805. image_shapes)
  806. num_images = len(boxes)
  807. for i in range(num_images):
  808. result.append(
  809. {
  810. "boxes": boxes[i],
  811. "labels": labels[i],
  812. "scores": scores[i],
  813. }
  814. )
  815. if self.has_line():
  816. print(f'roi_heads forward has_line()!!!!')
  817. line_proposals = [p["boxes"] for p in result]
  818. print(f'boxes_proposals:{len(line_proposals)}')
  819. # if line_proposals is None or len(line_proposals) == 0:
  820. # # 返回空特征或者跳过该部分计算
  821. # return torch.empty(0, C, H, W).to(features['0'].device)
  822. if self.training:
  823. # during training, only focus on positive boxes
  824. num_images = len(proposals)
  825. line_proposals = []
  826. pos_matched_idxs = []
  827. if matched_idxs is None:
  828. raise ValueError("if in trainning, matched_idxs should not be None")
  829. for img_id in range(num_images):
  830. pos = torch.where(labels[img_id] > 0)[0]
  831. line_proposals.append(proposals[img_id][pos])
  832. pos_matched_idxs.append(matched_idxs[img_id][pos])
  833. else:
  834. if targets is not None:
  835. pos_matched_idxs = []
  836. num_images = len(proposals)
  837. if matched_idxs is None:
  838. raise ValueError("if in trainning, matched_idxs should not be None")
  839. for img_id in range(num_images):
  840. pos = torch.where(labels[img_id] > 0)[0]
  841. line_proposals.append(proposals[img_id][pos])
  842. pos_matched_idxs.append(matched_idxs[img_id][pos])
  843. else:
  844. pos_matched_idxs = None
  845. print(f'line_proposals:{len(line_proposals)}')
  846. line_features = self.line_roi_pool(features, line_proposals, image_shapes)
  847. print(f'line_features from line_roi_pool:{line_features.shape}')
  848. line_features = self.line_head(line_features)
  849. print(f'line_features from line_head:{line_features.shape}')
  850. line_logits = self.line_predictor(line_features)
  851. print(f'line_logits:{line_logits.shape}')
  852. loss_line = {}
  853. if self.training:
  854. if targets is None or pos_matched_idxs is None:
  855. raise ValueError("both targets and pos_matched_idxs should not be None when in training mode")
  856. gt_lines = [t["lines"] for t in targets]
  857. rcnn_loss_line = lines_point_pair_loss(
  858. line_logits, line_proposals, gt_lines, pos_matched_idxs
  859. )
  860. loss_line = {"loss_line": rcnn_loss_line}
  861. else:
  862. if targets is not None:
  863. gt_lines = [t["lines"] for t in targets]
  864. rcnn_loss_lines = lines_point_pair_loss(
  865. line_logits, line_proposals, gt_lines, pos_matched_idxs
  866. )
  867. loss_line = {"loss_line": rcnn_loss_lines}
  868. else:
  869. if line_logits is None or line_proposals is None:
  870. raise ValueError(
  871. "both keypoint_logits and keypoint_proposals should not be None when not in training mode"
  872. )
  873. lines_probs, kp_scores = line_inference(line_logits, line_proposals)
  874. for keypoint_prob, kps, r in zip(lines_probs, kp_scores, result):
  875. r["lines"] = keypoint_prob
  876. r["liness_scores"] = kps
  877. losses.update(loss_line)
  878. if self.has_mask():
  879. mask_proposals = [p["boxes"] for p in result]
  880. if self.training:
  881. if matched_idxs is None:
  882. raise ValueError("if in training, matched_idxs should not be None")
  883. # during training, only focus on positive boxes
  884. num_images = len(proposals)
  885. mask_proposals = []
  886. pos_matched_idxs = []
  887. for img_id in range(num_images):
  888. pos = torch.where(labels[img_id] > 0)[0]
  889. mask_proposals.append(proposals[img_id][pos])
  890. pos_matched_idxs.append(matched_idxs[img_id][pos])
  891. else:
  892. pos_matched_idxs = None
  893. if self.mask_roi_pool is not None:
  894. mask_features = self.mask_roi_pool(features, mask_proposals, image_shapes)
  895. mask_features = self.mask_head(mask_features)
  896. mask_logits = self.mask_predictor(mask_features)
  897. else:
  898. raise Exception("Expected mask_roi_pool to be not None")
  899. loss_mask = {}
  900. if self.training:
  901. if targets is None or pos_matched_idxs is None or mask_logits is None:
  902. raise ValueError("targets, pos_matched_idxs, mask_logits cannot be None when training")
  903. gt_masks = [t["masks"] for t in targets]
  904. gt_labels = [t["labels"] for t in targets]
  905. rcnn_loss_mask = maskrcnn_loss(mask_logits, mask_proposals, gt_masks, gt_labels, pos_matched_idxs)
  906. loss_mask = {"loss_mask": rcnn_loss_mask}
  907. else:
  908. labels = [r["labels"] for r in result]
  909. masks_probs = maskrcnn_inference(mask_logits, labels)
  910. for mask_prob, r in zip(masks_probs, result):
  911. r["masks"] = mask_prob
  912. losses.update(loss_mask)
  913. # keep none checks in if conditional so torchscript will conditionally
  914. # compile each branch
  915. if self.has_keypoint():
  916. keypoint_proposals = [p["boxes"] for p in result]
  917. if self.training:
  918. # during training, only focus on positive boxes
  919. num_images = len(proposals)
  920. keypoint_proposals = []
  921. pos_matched_idxs = []
  922. if matched_idxs is None:
  923. raise ValueError("if in trainning, matched_idxs should not be None")
  924. for img_id in range(num_images):
  925. pos = torch.where(labels[img_id] > 0)[0]
  926. keypoint_proposals.append(proposals[img_id][pos])
  927. pos_matched_idxs.append(matched_idxs[img_id][pos])
  928. else:
  929. pos_matched_idxs = None
  930. keypoint_features = self.line_roi_pool(features, keypoint_proposals, image_shapes)
  931. keypoint_features = self.line_head(keypoint_features)
  932. keypoint_logits = self.line_predictor(keypoint_features)
  933. loss_keypoint = {}
  934. if self.training:
  935. if targets is None or pos_matched_idxs is None:
  936. raise ValueError("both targets and pos_matched_idxs should not be None when in training mode")
  937. gt_keypoints = [t["keypoints"] for t in targets]
  938. rcnn_loss_keypoint = keypointrcnn_loss(
  939. keypoint_logits, keypoint_proposals, gt_keypoints, pos_matched_idxs
  940. )
  941. loss_keypoint = {"loss_keypoint": rcnn_loss_keypoint}
  942. else:
  943. if keypoint_logits is None or keypoint_proposals is None:
  944. raise ValueError(
  945. "both keypoint_logits and keypoint_proposals should not be None when not in training mode"
  946. )
  947. keypoints_probs, kp_scores = keypointrcnn_inference(keypoint_logits, keypoint_proposals)
  948. for keypoint_prob, kps, r in zip(keypoints_probs, kp_scores, result):
  949. r["keypoints"] = keypoint_prob
  950. r["keypoints_scores"] = kps
  951. losses.update(loss_keypoint)
  952. return result, losses