line_predictor.py 14 KB

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