line_predictor.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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 = 1,
  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 * 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. print(f' wires_targets len:{len(wires_targets)}')
  172. for stack, output in enumerate([inputs]):
  173. output = output.transpose(0, 1).reshape([-1, batch, row, col]).contiguous()
  174. # print(f"Stack {stack} output shape: {output.shape}") # 打印每层的输出形状
  175. jmap = output[0: offset[0]].reshape(n_jtyp, 2, batch, row, col)
  176. # lmap = output[offset[0]: offset[1]].squeeze(0)
  177. lmap = output[offset[0]: offset[1]]
  178. joff = output[offset[1]: offset[2]].reshape(n_jtyp, 2, batch, row, col)
  179. if stack == 0:
  180. result["preds"] = {
  181. "jmap": jmap.permute(2, 0, 1, 3, 4).softmax(2)[:, :, 1],
  182. "lmap": lmap.sigmoid(),
  183. "joff": joff.permute(2, 0, 1, 3, 4).sigmoid() - 0.5,
  184. }
  185. # visualize_feature_map(jmap[0, 0], title=f"jmap - Stack {stack}")
  186. # visualize_feature_map(lmap, title=f"lmap - Stack {stack}")
  187. # visualize_feature_map(joff[0, 0], title=f"joff - Stack {stack}")
  188. h = result["preds"]
  189. print(f'features shape:{features.shape}')
  190. print(f'inputs shape :{inputs.shape}')
  191. # x = self.fc1(features)
  192. lmap = inputs[:,2:3,:,:].sigmoid()
  193. x=lmap
  194. print(f'x:{lmap.shape}')
  195. n_batch, n_channel, row, col = lmap.shape
  196. # n_batch, n_channel, row, col = x.shape
  197. # print(f'n_batch:{n_batch}, n_channel:{n_channel}, row:{row}, col:{col}')
  198. xs, ys, fs, ps, idx, jcs = [], [], [], [], [0], []
  199. for i, meta in enumerate(wires_targets):
  200. p, label, feat, jc = self.sample_lines(
  201. meta, h["jmap"][i], h["joff"][i],lmap[i]
  202. )
  203. print(f"p.shape:{p.shape},label:{label.shape},feat:{feat.shape},jc:{len(jc)}")
  204. ys.append(label)
  205. if self.training and self.do_static_sampling:
  206. p = torch.cat([p, meta["lpre"]])
  207. feat = torch.cat([feat, meta["lpre_feat"]])
  208. ys.append(meta["lpre_label"])
  209. del jc
  210. else:
  211. jcs.append(jc)
  212. ps.append(p)
  213. fs.append(feat)
  214. #
  215. # p = p[:, 0:1, :] * self.lambda_ + p[:, 1:2, :] * (1 - self.lambda_) - 0.5
  216. # p = p.reshape(-1, 2) # [N_LINE x N_POINT, 2_XY]
  217. # px, py = p[:, 0].contiguous(), p[:, 1].contiguous()
  218. # px0 = px.floor().clamp(min=0, max=127)
  219. # py0 = py.floor().clamp(min=0, max=127)
  220. # px1 = (px0 + 1).clamp(min=0, max=127)
  221. # py1 = (py0 + 1).clamp(min=0, max=127)
  222. # px0l, py0l, px1l, py1l = px0.long(), py0.long(), px1.long(), py1.long()
  223. #
  224. # # xp: [N_LINE, N_CHANNEL, N_POINT]
  225. # xp = (
  226. # (
  227. # x[i, :, px0l, py0l] * (px1 - px) * (py1 - py)
  228. # + x[i, :, px1l, py0l] * (px - px0) * (py1 - py)
  229. # + x[i, :, px0l, py1l] * (px1 - px) * (py - py0)
  230. # + x[i, :, px1l, py1l] * (px - px0) * (py - py0)
  231. # )
  232. # .reshape(n_channel, -1, self.n_pts0)
  233. # .permute(1, 0, 2)
  234. # )
  235. # xp = self.pooling(xp)
  236. # # print(f'xp.shape:{xp.shape}')
  237. # xs.append(xp)
  238. idx.append(idx[-1] + feat.shape[0])
  239. # print(f'idx__:{idx}')
  240. # x, y = torch.cat(xs), torch.cat(ys)
  241. y=torch.cat(ys)
  242. f = torch.cat(fs)
  243. print(f'f:{f.shape}')
  244. # x = x.reshape(-1, self.n_pts1 * self.dim_loi)
  245. # print("Weight dtype:", self.fc2.weight.dtype)
  246. # x = torch.cat([x, f], 1)
  247. # print(f'x3:{x.shape}')
  248. # print("Input dtype:", x.dtype)
  249. f= f.to(dtype=torch.float32)
  250. # x = x.to(dtype=torch.float32)
  251. # print("Input dtype1:", x.dtype)
  252. x = self.fc2(f).flatten()
  253. # return x,idx,jcs,n_batch,ps,self.n_out_line,self.n_out_junc
  254. return x, y, idx, jcs, n_batch, ps, self.n_out_line, self.n_out_junc
  255. # if mode != "training":
  256. # self.inference(x, idx, jcs, n_batch, ps)
  257. # return result
  258. def sample_lines(self, meta, jmap, joff,lmap):
  259. device = jmap.device
  260. with torch.no_grad():
  261. junc = meta["junc_coords"].to(device) # [N, 2]
  262. jtyp = meta["jtyp"].to(device) # [N]
  263. Lpos = meta["line_pos_idx"].to(device)
  264. Lneg = meta["line_neg_idx"].to(device)
  265. n_type = jmap.shape[0]
  266. jmap = non_maximum_suppression(jmap).reshape(n_type, -1)
  267. joff = joff.reshape(n_type, 2, -1)
  268. max_K = self.n_dyn_junc // n_type
  269. N = len(junc)
  270. # if mode != "training":
  271. if not self.training:
  272. K = min(int((jmap > self.eval_junc_thres).float().sum().item()), max_K)
  273. else:
  274. K = min(int(N * 2 + 2), max_K)
  275. if K < 2:
  276. K = 2
  277. device = jmap.device
  278. # index: [N_TYPE, K]
  279. score, index = torch.topk(jmap, k=K)
  280. y = (index // 128).float() + torch.gather(joff[:, 0], 1, index) + 0.5
  281. x = (index % 128).float() + torch.gather(joff[:, 1], 1, index) + 0.5
  282. # xy: [N_TYPE, K, 2]
  283. xy = torch.cat([y[..., None], x[..., None]], dim=-1)
  284. xy_ = xy[..., None, :]
  285. del x, y, index
  286. # dist: [N_TYPE, K, N]
  287. dist = torch.sum((xy_ - junc) ** 2, -1)
  288. cost, match = torch.min(dist, -1)
  289. # xy: [N_TYPE * K, 2]
  290. # match: [N_TYPE, K]
  291. for t in range(n_type):
  292. match[t, jtyp[match[t]] != t] = N
  293. match[cost > 1.5 * 1.5] = N
  294. match = match.flatten()
  295. _ = torch.arange(n_type * K, device=device)
  296. u, v = torch.meshgrid(_, _)
  297. u, v = u.flatten(), v.flatten()
  298. up, vp = match[u], match[v]
  299. label = Lpos[up, vp]
  300. # if mode == "training":
  301. if self.training:
  302. c = torch.zeros_like(label, dtype=torch.bool)
  303. # sample positive lines
  304. cdx = label.nonzero().flatten()
  305. if len(cdx) > self.n_dyn_posl:
  306. # print("too many positive lines")
  307. perm = torch.randperm(len(cdx), device=device)[: self.n_dyn_posl]
  308. cdx = cdx[perm]
  309. c[cdx] = 1
  310. # sample negative lines
  311. cdx = Lneg[up, vp].nonzero().flatten()
  312. if len(cdx) > self.n_dyn_negl:
  313. # print("too many negative lines")
  314. perm = torch.randperm(len(cdx), device=device)[: self.n_dyn_negl]
  315. cdx = cdx[perm]
  316. c[cdx] = 1
  317. # sample other (unmatched) lines
  318. cdx = torch.randint(len(c), (self.n_dyn_othr,), device=device)
  319. c[cdx] = 1
  320. else:
  321. c = (u < v).flatten()
  322. # sample lines
  323. u, v, label = u[c], v[c], label[c]
  324. xy = xy.reshape(n_type * K, 2)
  325. xyu, xyv = xy[u], xy[v]
  326. u2v = xyu - xyv
  327. u2v /= torch.sqrt((u2v ** 2).sum(-1, keepdim=True)).clamp(min=1e-6)
  328. # print(f'xp.shape:{xp.shape}')
  329. feat = torch.cat(
  330. [
  331. xyu / 128 * self.use_cood,
  332. xyv / 128 * self.use_cood,
  333. u2v * self.use_slop,
  334. (u[:, None] > K).float(),
  335. (v[:, None] > K).float(),
  336. ],
  337. 1,
  338. )
  339. print(f'feat shape:{feat.shape}')
  340. line = torch.cat([xyu[:, None], xyv[:, None]], 1)
  341. # print(f'line:{line.shape}')
  342. n_channel, row, col = lmap.shape
  343. p=line
  344. print(f'p.shape :{p.shape}')
  345. p = p[:, 0:1, :] * self.lambda_ + p[:, 1:2, :] * (1 - self.lambda_) - 0.5
  346. p = p.reshape(-1, 2) # [N_LINE x N_POINT, 2_XY]
  347. px, py = p[:, 0].contiguous(), p[:, 1].contiguous()
  348. px0 = px.floor().clamp(min=0, max=127)
  349. py0 = py.floor().clamp(min=0, max=127)
  350. px1 = (px0 + 1).clamp(min=0, max=127)
  351. py1 = (py0 + 1).clamp(min=0, max=127)
  352. px0l, py0l, px1l, py1l = px0.long(), py0.long(), px1.long(), py1.long()
  353. # xp: [N_LINE, N_CHANNEL, N_POINT]
  354. x=lmap
  355. xp = (
  356. (
  357. x[ :, px0l, py0l] * (px1 - px) * (py1 - py)
  358. + x[ :, px1l, py0l] * (px - px0) * (py1 - py)
  359. + x[ :, px0l, py1l] * (px1 - px) * (py - py0)
  360. + x[ :, px1l, py1l] * (px - px0) * (py - py0)
  361. )
  362. .reshape(n_channel, -1, self.n_pts0)
  363. .permute(1, 0, 2)
  364. )
  365. xp = self.pooling(xp).squeeze(1)
  366. print(f'xp shape:{xp.shape}')
  367. xy = xy.reshape(n_type, K, 2)
  368. jcs = [xy[i, score[i] > 0.03] for i in range(n_type)]
  369. return line, label.float(), xp, jcs
  370. _COMMON_META = {
  371. "categories": _COCO_PERSON_CATEGORIES,
  372. "keypoint_names": _COCO_PERSON_KEYPOINT_NAMES,
  373. "min_size": (1, 1),
  374. }