line_predictor.py 14 KB

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