line_predictor.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. from typing import Any, Optional
  2. import torch
  3. from torch import nn
  4. from torchvision.ops import MultiScaleRoIAlign
  5. from libs.vision_libs.ops import misc as misc_nn_ops
  6. from libs.vision_libs.transforms._presets import ObjectDetection
  7. from .roi_heads import RoIHeads
  8. from libs.vision_libs.models._api import register_model, Weights, WeightsEnum
  9. from libs.vision_libs.models._meta import _COCO_PERSON_CATEGORIES, _COCO_PERSON_KEYPOINT_NAMES
  10. from libs.vision_libs.models._utils import _ovewrite_value_param, handle_legacy_interface
  11. from libs.vision_libs.models.resnet import resnet50, ResNet50_Weights
  12. from libs.vision_libs.models.detection._utils import overwrite_eps
  13. from libs.vision_libs.models.detection.backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers
  14. from libs.vision_libs.models.detection.faster_rcnn import FasterRCNN, TwoMLPHead, FastRCNNPredictor
  15. from models.config.config_tool import read_yaml
  16. import numpy as np
  17. import torch.nn.functional as F
  18. FEATURE_DIM = 8
  19. def non_maximum_suppression(a):
  20. ap = F.max_pool2d(a, 3, stride=1, padding=1)
  21. mask = (a == ap).float().clamp(min=0.0)
  22. return a * mask
  23. class LineRCNNPredictor(nn.Module):
  24. def __init__(self, cfg):
  25. super().__init__()
  26. # self.backbone = backbone
  27. # self.cfg = read_yaml(cfg)
  28. # self.cfg = read_yaml(r'./config/wireframe.yaml')
  29. self.cfg = cfg
  30. self.n_pts0 = self.cfg['n_pts0']
  31. self.n_pts1 = self.cfg['n_pts1']
  32. self.n_stc_posl = self.cfg['n_stc_posl']
  33. self.dim_loi = self.cfg['dim_loi']
  34. self.use_conv = self.cfg['use_conv']
  35. self.dim_fc = self.cfg['dim_fc']
  36. self.n_out_line = self.cfg['n_out_line']
  37. self.n_out_junc = self.cfg['n_out_junc']
  38. self.loss_weight = self.cfg['loss_weight']
  39. self.n_dyn_junc = self.cfg['n_dyn_junc']
  40. self.eval_junc_thres = self.cfg['eval_junc_thres']
  41. self.n_dyn_posl = self.cfg['n_dyn_posl']
  42. self.n_dyn_negl = self.cfg['n_dyn_negl']
  43. self.n_dyn_othr = self.cfg['n_dyn_othr']
  44. self.use_cood = self.cfg['use_cood']
  45. self.use_slop = self.cfg['use_slop']
  46. self.n_stc_negl = self.cfg['n_stc_negl']
  47. self.head_size = self.cfg['head_size']
  48. self.num_class = sum(sum(self.head_size, []))
  49. self.head_off = np.cumsum([sum(h) for h in self.head_size])
  50. lambda_ = torch.linspace(0, 1, self.n_pts0)[:, None]
  51. self.register_buffer("lambda_", lambda_)
  52. self.do_static_sampling = self.n_stc_posl + self.n_stc_negl > 0
  53. self.fc1 = nn.Conv2d(256, self.dim_loi, 1)
  54. scale_factor = self.n_pts0 // self.n_pts1
  55. if self.use_conv:
  56. self.pooling = nn.Sequential(
  57. nn.MaxPool1d(scale_factor, scale_factor),
  58. Bottleneck1D(self.dim_loi, self.dim_loi),
  59. )
  60. self.fc2 = nn.Sequential(
  61. nn.ReLU(inplace=True), nn.Linear(self.dim_loi * self.n_pts1 + FEATURE_DIM, 1)
  62. )
  63. else:
  64. self.pooling = nn.MaxPool1d(scale_factor, scale_factor)
  65. self.fc2 = nn.Sequential(
  66. nn.Linear(self.dim_loi * self.n_pts1 + FEATURE_DIM, self.dim_fc),
  67. nn.ReLU(inplace=True),
  68. nn.Linear(self.dim_fc, self.dim_fc),
  69. nn.ReLU(inplace=True),
  70. nn.Linear(self.dim_fc, 1),
  71. )
  72. self.loss = nn.BCEWithLogitsLoss(reduction="none")
  73. def forward(self, inputs, features, targets=None):
  74. # outputs, features = input
  75. # for out in outputs:
  76. # print(f'out:{out.shape}')
  77. # outputs=merge_features(outputs,100)
  78. batch, channel, row, col = inputs.shape
  79. # print(f'outputs:{inputs.shape}')
  80. # print(f'batch:{batch}, channel:{channel}, row:{row}, col:{col}')
  81. if targets is not None:
  82. self.training = True
  83. # print(f'target:{targets}')
  84. wires_targets = [t["wires"] for t in targets]
  85. # print(f'wires_target:{wires_targets}')
  86. # 提取所有 'junc_map', 'junc_offset', 'line_map' 的张量
  87. junc_maps = [d["junc_map"] for d in wires_targets]
  88. junc_offsets = [d["junc_offset"] for d in wires_targets]
  89. line_maps = [d["line_map"] for d in wires_targets]
  90. junc_map_tensor = torch.stack(junc_maps, dim=0)
  91. junc_offset_tensor = torch.stack(junc_offsets, dim=0)
  92. line_map_tensor = torch.stack(line_maps, dim=0)
  93. wires_meta = {
  94. "junc_map": junc_map_tensor,
  95. "junc_offset": junc_offset_tensor,
  96. # "line_map": line_map_tensor,
  97. }
  98. else:
  99. self.training = False
  100. t = {
  101. "junc_coords": torch.zeros(1, 2),
  102. "jtyp": torch.zeros(1, dtype=torch.uint8),
  103. "line_pos_idx": torch.zeros(2, 2, dtype=torch.uint8),
  104. "line_neg_idx": torch.zeros(2, 2, dtype=torch.uint8),
  105. "junc_map": torch.zeros([1, 1, 128, 128]),
  106. "junc_offset": torch.zeros([1, 1, 2, 128, 128]),
  107. }
  108. wires_targets = [t for b in range(inputs.size(0))]
  109. wires_meta = {
  110. "junc_map": torch.zeros([1, 1, 128, 128]),
  111. "junc_offset": torch.zeros([1, 1, 2, 128, 128]),
  112. }
  113. T = wires_meta.copy()
  114. n_jtyp = T["junc_map"].shape[1]
  115. offset = self.head_off
  116. result = {}
  117. for stack, output in enumerate([inputs]):
  118. output = output.transpose(0, 1).reshape([-1, batch, row, col]).contiguous()
  119. # print(f"Stack {stack} output shape: {output.shape}") # 打印每层的输出形状
  120. jmap = output[0: offset[0]].reshape(n_jtyp, 2, batch, row, col)
  121. lmap = output[offset[0]: offset[1]].squeeze(0)
  122. joff = output[offset[1]: offset[2]].reshape(n_jtyp, 2, batch, row, col)
  123. if stack == 0:
  124. result["preds"] = {
  125. "jmap": jmap.permute(2, 0, 1, 3, 4).softmax(2)[:, :, 1],
  126. "lmap": lmap.sigmoid(),
  127. "joff": joff.permute(2, 0, 1, 3, 4).sigmoid() - 0.5,
  128. }
  129. # visualize_feature_map(jmap[0, 0], title=f"jmap - Stack {stack}")
  130. # visualize_feature_map(lmap, title=f"lmap - Stack {stack}")
  131. # visualize_feature_map(joff[0, 0], title=f"joff - Stack {stack}")
  132. h = result["preds"]
  133. # print(f'features shape:{features.shape}')
  134. x = self.fc1(features)
  135. # print(f'x:{x.shape}')
  136. n_batch, n_channel, row, col = x.shape
  137. # print(f'n_batch:{n_batch}, n_channel:{n_channel}, row:{row}, col:{col}')
  138. xs, ys, fs, ps, idx, jcs = [], [], [], [], [0], []
  139. for i, meta in enumerate(wires_targets):
  140. p, label, feat, jc = self.sample_lines(
  141. meta, h["jmap"][i], h["joff"][i],
  142. )
  143. # print(f"p.shape:{p.shape},label:{label.shape},feat:{feat.shape},jc:{len(jc)}")
  144. ys.append(label)
  145. if self.training and self.do_static_sampling:
  146. p = torch.cat([p, meta["lpre"]])
  147. feat = torch.cat([feat, meta["lpre_feat"]])
  148. ys.append(meta["lpre_label"])
  149. del jc
  150. else:
  151. jcs.append(jc)
  152. ps.append(p)
  153. fs.append(feat)
  154. p = p[:, 0:1, :] * self.lambda_ + p[:, 1:2, :] * (1 - self.lambda_) - 0.5
  155. p = p.reshape(-1, 2) # [N_LINE x N_POINT, 2_XY]
  156. px, py = p[:, 0].contiguous(), p[:, 1].contiguous()
  157. px0 = px.floor().clamp(min=0, max=127)
  158. py0 = py.floor().clamp(min=0, max=127)
  159. px1 = (px0 + 1).clamp(min=0, max=127)
  160. py1 = (py0 + 1).clamp(min=0, max=127)
  161. px0l, py0l, px1l, py1l = px0.long(), py0.long(), px1.long(), py1.long()
  162. # xp: [N_LINE, N_CHANNEL, N_POINT]
  163. xp = (
  164. (
  165. x[i, :, px0l, py0l] * (px1 - px) * (py1 - py)
  166. + x[i, :, px1l, py0l] * (px - px0) * (py1 - py)
  167. + x[i, :, px0l, py1l] * (px1 - px) * (py - py0)
  168. + x[i, :, px1l, py1l] * (px - px0) * (py - py0)
  169. )
  170. .reshape(n_channel, -1, self.n_pts0)
  171. .permute(1, 0, 2)
  172. )
  173. xp = self.pooling(xp)
  174. # print(f'xp.shape:{xp.shape}')
  175. xs.append(xp)
  176. idx.append(idx[-1] + xp.shape[0])
  177. # print(f'idx__:{idx}')
  178. x, y = torch.cat(xs), torch.cat(ys)
  179. f = torch.cat(fs)
  180. x = x.reshape(-1, self.n_pts1 * self.dim_loi)
  181. # print("Weight dtype:", self.fc2.weight.dtype)
  182. x = torch.cat([x, f], 1)
  183. # print("Input dtype:", x.dtype)
  184. x = x.to(dtype=torch.float32)
  185. # print("Input dtype1:", x.dtype)
  186. x = self.fc2(x).flatten()
  187. # return x,idx,jcs,n_batch,ps,self.n_out_line,self.n_out_junc
  188. return x, y, idx, jcs, n_batch, ps, self.n_out_line, self.n_out_junc
  189. # if mode != "training":
  190. # self.inference(x, idx, jcs, n_batch, ps)
  191. # return result
  192. def sample_lines(self, meta, jmap, joff):
  193. device = jmap.device
  194. with torch.no_grad():
  195. junc = meta["junc_coords"].to(device) # [N, 2]
  196. jtyp = meta["jtyp"].to(device) # [N]
  197. Lpos = meta["line_pos_idx"].to(device)
  198. Lneg = meta["line_neg_idx"].to(device)
  199. n_type = jmap.shape[0]
  200. jmap = non_maximum_suppression(jmap).reshape(n_type, -1)
  201. joff = joff.reshape(n_type, 2, -1)
  202. max_K = self.n_dyn_junc // n_type
  203. N = len(junc)
  204. # if mode != "training":
  205. if not self.training:
  206. K = min(int((jmap > self.eval_junc_thres).float().sum().item()), max_K)
  207. else:
  208. K = min(int(N * 2 + 2), max_K)
  209. if K < 2:
  210. K = 2
  211. device = jmap.device
  212. # index: [N_TYPE, K]
  213. score, index = torch.topk(jmap, k=K)
  214. y = (index // 128).float() + torch.gather(joff[:, 0], 1, index) + 0.5
  215. x = (index % 128).float() + torch.gather(joff[:, 1], 1, index) + 0.5
  216. # xy: [N_TYPE, K, 2]
  217. xy = torch.cat([y[..., None], x[..., None]], dim=-1)
  218. xy_ = xy[..., None, :]
  219. del x, y, index
  220. # dist: [N_TYPE, K, N]
  221. dist = torch.sum((xy_ - junc) ** 2, -1)
  222. cost, match = torch.min(dist, -1)
  223. # xy: [N_TYPE * K, 2]
  224. # match: [N_TYPE, K]
  225. for t in range(n_type):
  226. match[t, jtyp[match[t]] != t] = N
  227. match[cost > 1.5 * 1.5] = N
  228. match = match.flatten()
  229. _ = torch.arange(n_type * K, device=device)
  230. u, v = torch.meshgrid(_, _)
  231. u, v = u.flatten(), v.flatten()
  232. up, vp = match[u], match[v]
  233. label = Lpos[up, vp]
  234. # if mode == "training":
  235. if self.training:
  236. c = torch.zeros_like(label, dtype=torch.bool)
  237. # sample positive lines
  238. cdx = label.nonzero().flatten()
  239. if len(cdx) > self.n_dyn_posl:
  240. # print("too many positive lines")
  241. perm = torch.randperm(len(cdx), device=device)[: self.n_dyn_posl]
  242. cdx = cdx[perm]
  243. c[cdx] = 1
  244. # sample negative lines
  245. cdx = Lneg[up, vp].nonzero().flatten()
  246. if len(cdx) > self.n_dyn_negl:
  247. # print("too many negative lines")
  248. perm = torch.randperm(len(cdx), device=device)[: self.n_dyn_negl]
  249. cdx = cdx[perm]
  250. c[cdx] = 1
  251. # sample other (unmatched) lines
  252. cdx = torch.randint(len(c), (self.n_dyn_othr,), device=device)
  253. c[cdx] = 1
  254. else:
  255. c = (u < v).flatten()
  256. # sample lines
  257. u, v, label = u[c], v[c], label[c]
  258. xy = xy.reshape(n_type * K, 2)
  259. xyu, xyv = xy[u], xy[v]
  260. u2v = xyu - xyv
  261. u2v /= torch.sqrt((u2v ** 2).sum(-1, keepdim=True)).clamp(min=1e-6)
  262. feat = torch.cat(
  263. [
  264. xyu / 128 * self.use_cood,
  265. xyv / 128 * self.use_cood,
  266. u2v * self.use_slop,
  267. (u[:, None] > K).float(),
  268. (v[:, None] > K).float(),
  269. ],
  270. 1,
  271. )
  272. line = torch.cat([xyu[:, None], xyv[:, None]], 1)
  273. xy = xy.reshape(n_type, K, 2)
  274. jcs = [xy[i, score[i] > 0.03] for i in range(n_type)]
  275. return line, label.float(), feat, jcs
  276. _COMMON_META = {
  277. "categories": _COCO_PERSON_CATEGORIES,
  278. "keypoint_names": _COCO_PERSON_KEYPOINT_NAMES,
  279. "min_size": (1, 1),
  280. }