head.py 48 KB

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