roi_heads.py 44 KB

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