line_predictor.py 15 KB

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