basic.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. import math
  2. import warnings
  3. import numpy as np
  4. import torch
  5. import torch.nn as nn
  6. def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
  7. """Copy from timm"""
  8. with torch.no_grad():
  9. """Copy from timm"""
  10. def norm_cdf(x):
  11. return (1. + math.erf(x / math.sqrt(2.))) / 2.
  12. if (mean < a - 2 * std) or (mean > b + 2 * std):
  13. warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
  14. "The distribution of values may be incorrect.",
  15. stacklevel=2)
  16. l = norm_cdf((a - mean) / std)
  17. u = norm_cdf((b - mean) / std)
  18. tensor.uniform_(2 * l - 1, 2 * u - 1)
  19. tensor.erfinv_()
  20. tensor.mul_(std * math.sqrt(2.))
  21. tensor.add_(mean)
  22. tensor.clamp_(min=a, max=b)
  23. return tensor
  24. def box_xyxy_to_cxcywh(x):
  25. x0, y0, x1, y1 = x.unbind(-1)
  26. b = [(x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0), (y1 - y0)]
  27. return torch.stack(b, dim=-1)
  28. def delta2bbox(proposals,
  29. deltas,
  30. max_shape=None,
  31. wh_ratio_clip=16 / 1000,
  32. clip_border=True,
  33. add_ctr_clamp=False,
  34. ctr_clamp=32):
  35. dxy = deltas[..., :2]
  36. dwh = deltas[..., 2:]
  37. # Compute width/height of each roi
  38. pxy = proposals[..., :2]
  39. pwh = proposals[..., 2:]
  40. dxy_wh = pwh * dxy
  41. wh_ratio_clip = torch.as_tensor(wh_ratio_clip)
  42. max_ratio = torch.abs(torch.log(wh_ratio_clip)).item()
  43. if add_ctr_clamp:
  44. dxy_wh = torch.clamp(dxy_wh, max=ctr_clamp, min=-ctr_clamp)
  45. dwh = torch.clamp(dwh, max=max_ratio)
  46. else:
  47. dwh = dwh.clamp(min=-max_ratio, max=max_ratio)
  48. gxy = pxy + dxy_wh
  49. gwh = pwh * dwh.exp()
  50. x1y1 = gxy - (gwh * 0.5)
  51. x2y2 = gxy + (gwh * 0.5)
  52. bboxes = torch.cat([x1y1, x2y2], dim=-1)
  53. if clip_border and max_shape is not None:
  54. bboxes[..., 0::2].clamp_(min=0).clamp_(max=max_shape[1])
  55. bboxes[..., 1::2].clamp_(min=0).clamp_(max=max_shape[0])
  56. return bboxes
  57. # ---------------------------- NMS ----------------------------
  58. ## basic NMS
  59. def nms(bboxes, scores, nms_thresh):
  60. """"Pure Python NMS."""
  61. x1 = bboxes[:, 0] #xmin
  62. y1 = bboxes[:, 1] #ymin
  63. x2 = bboxes[:, 2] #xmax
  64. y2 = bboxes[:, 3] #ymax
  65. areas = (x2 - x1) * (y2 - y1)
  66. order = scores.argsort()[::-1]
  67. keep = []
  68. while order.size > 0:
  69. i = order[0]
  70. keep.append(i)
  71. # compute iou
  72. xx1 = np.maximum(x1[i], x1[order[1:]])
  73. yy1 = np.maximum(y1[i], y1[order[1:]])
  74. xx2 = np.minimum(x2[i], x2[order[1:]])
  75. yy2 = np.minimum(y2[i], y2[order[1:]])
  76. w = np.maximum(1e-10, xx2 - xx1)
  77. h = np.maximum(1e-10, yy2 - yy1)
  78. inter = w * h
  79. iou = inter / (areas[i] + areas[order[1:]] - inter + 1e-14)
  80. #reserve all the boundingbox whose ovr less than thresh
  81. inds = np.where(iou <= nms_thresh)[0]
  82. order = order[inds + 1]
  83. return keep
  84. ## class-agnostic NMS
  85. def multiclass_nms_class_agnostic(scores, labels, bboxes, nms_thresh):
  86. # nms
  87. keep = nms(bboxes, scores, nms_thresh)
  88. scores = scores[keep]
  89. labels = labels[keep]
  90. bboxes = bboxes[keep]
  91. return scores, labels, bboxes
  92. ## class-aware NMS
  93. def multiclass_nms_class_aware(scores, labels, bboxes, nms_thresh, num_classes):
  94. # nms
  95. keep = np.zeros(len(bboxes), dtype=np.int32)
  96. for i in range(num_classes):
  97. inds = np.where(labels == i)[0]
  98. if len(inds) == 0:
  99. continue
  100. c_bboxes = bboxes[inds]
  101. c_scores = scores[inds]
  102. c_keep = nms(c_bboxes, c_scores, nms_thresh)
  103. keep[inds[c_keep]] = 1
  104. keep = np.where(keep > 0)
  105. scores = scores[keep]
  106. labels = labels[keep]
  107. bboxes = bboxes[keep]
  108. return scores, labels, bboxes
  109. ## multi-class NMS
  110. def multiclass_nms(scores, labels, bboxes, nms_thresh, num_classes, class_agnostic=False):
  111. if class_agnostic:
  112. return multiclass_nms_class_agnostic(scores, labels, bboxes, nms_thresh)
  113. else:
  114. return multiclass_nms_class_aware(scores, labels, bboxes, nms_thresh, num_classes)
  115. # ----------------- Customed NormLayer Ops -----------------
  116. class FrozenBatchNorm2d(torch.nn.Module):
  117. def __init__(self, n):
  118. super(FrozenBatchNorm2d, self).__init__()
  119. self.register_buffer("weight", torch.ones(n))
  120. self.register_buffer("bias", torch.zeros(n))
  121. self.register_buffer("running_mean", torch.zeros(n))
  122. self.register_buffer("running_var", torch.ones(n))
  123. def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
  124. missing_keys, unexpected_keys, error_msgs):
  125. num_batches_tracked_key = prefix + 'num_batches_tracked'
  126. if num_batches_tracked_key in state_dict:
  127. del state_dict[num_batches_tracked_key]
  128. super(FrozenBatchNorm2d, self)._load_from_state_dict(
  129. state_dict, prefix, local_metadata, strict,
  130. missing_keys, unexpected_keys, error_msgs)
  131. def forward(self, x):
  132. # move reshapes to the beginning
  133. # to make it fuser-friendly
  134. w = self.weight.reshape(1, -1, 1, 1)
  135. b = self.bias.reshape(1, -1, 1, 1)
  136. rv = self.running_var.reshape(1, -1, 1, 1)
  137. rm = self.running_mean.reshape(1, -1, 1, 1)
  138. eps = 1e-5
  139. scale = w * (rv + eps).rsqrt()
  140. bias = b - rm * scale
  141. return x * scale + bias
  142. class LayerNorm2D(nn.Module):
  143. def __init__(self, normalized_shape, norm_layer=nn.LayerNorm):
  144. super().__init__()
  145. self.ln = norm_layer(normalized_shape) if norm_layer is not None else nn.Identity()
  146. def forward(self, x):
  147. """
  148. x: N C H W
  149. """
  150. x = x.permute(0, 2, 3, 1)
  151. x = self.ln(x)
  152. x = x.permute(0, 3, 1, 2)
  153. return x
  154. # ----------------- Basic CNN Ops -----------------
  155. def get_conv2d(c1, c2, k, p, s, g, bias=False):
  156. conv = nn.Conv2d(c1, c2, k, stride=s, padding=p, groups=g, bias=bias)
  157. return conv
  158. def get_activation(act_type=None):
  159. if act_type == 'relu':
  160. return nn.ReLU(inplace=True)
  161. elif act_type == 'lrelu':
  162. return nn.LeakyReLU(0.1, inplace=True)
  163. elif act_type == 'mish':
  164. return nn.Mish(inplace=True)
  165. elif act_type == 'silu':
  166. return nn.SiLU(inplace=True)
  167. elif act_type == 'gelu':
  168. return nn.GELU()
  169. elif act_type is None:
  170. return nn.Identity()
  171. else:
  172. raise NotImplementedError
  173. def get_norm(norm_type, dim):
  174. if norm_type == 'BN':
  175. return nn.BatchNorm2d(dim)
  176. elif norm_type == 'GN':
  177. return nn.GroupNorm(num_groups=32, num_channels=dim)
  178. elif norm_type is None:
  179. return nn.Identity()
  180. else:
  181. raise NotImplementedError
  182. class BasicConv(nn.Module):
  183. def __init__(self,
  184. in_dim, # in channels
  185. out_dim, # out channels
  186. kernel_size=1, # kernel size
  187. padding=0, # padding
  188. stride=1, # padding
  189. act_type :str = 'lrelu', # activation
  190. norm_type :str = 'BN', # normalization
  191. ):
  192. super(BasicConv, self).__init__()
  193. add_bias = False if norm_type else True
  194. self.conv = get_conv2d(in_dim, out_dim, k=kernel_size, p=padding, s=stride, g=1, bias=add_bias)
  195. self.norm = get_norm(norm_type, out_dim)
  196. self.act = get_activation(act_type)
  197. def forward(self, x):
  198. return self.act(self.norm(self.conv(x)))
  199. class UpSampleWrapper(nn.Module):
  200. """Upsample last feat map to specific stride."""
  201. def __init__(self, in_dim, upsample_factor):
  202. super(UpSampleWrapper, self).__init__()
  203. # ---------- Basic parameters ----------
  204. self.upsample_factor = upsample_factor
  205. # ---------- Network parameters ----------
  206. if upsample_factor == 1:
  207. self.upsample = nn.Identity()
  208. else:
  209. scale = int(math.log2(upsample_factor))
  210. dim = in_dim
  211. layers = []
  212. for _ in range(scale-1):
  213. layers += [
  214. nn.ConvTranspose2d(dim, dim, kernel_size=2, stride=2),
  215. LayerNorm2D(dim),
  216. nn.GELU()
  217. ]
  218. layers += [nn.ConvTranspose2d(dim, dim, kernel_size=2, stride=2)]
  219. self.upsample = nn.Sequential(*layers)
  220. self.out_dim = dim
  221. def forward(self, x):
  222. x = self.upsample(x)
  223. return x
  224. # ----------------- MLP modules -----------------
  225. class MLP(nn.Module):
  226. def __init__(self, in_dim, hidden_dim, out_dim, num_layers):
  227. super().__init__()
  228. self.num_layers = num_layers
  229. h = [hidden_dim] * (num_layers - 1)
  230. self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([in_dim] + h, h + [out_dim]))
  231. def forward(self, x):
  232. for i, layer in enumerate(self.layers):
  233. x = nn.functional.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
  234. return x
  235. class FFN(nn.Module):
  236. def __init__(self, d_model=256, mlp_ratio=4.0, dropout=0., act_type='relu', pre_norm=False):
  237. super().__init__()
  238. # ----------- Basic parameters -----------
  239. self.pre_norm = pre_norm
  240. self.fpn_dim = round(d_model * mlp_ratio)
  241. # ----------- Network parameters -----------
  242. self.linear1 = nn.Linear(d_model, self.fpn_dim)
  243. self.activation = get_activation(act_type)
  244. self.dropout2 = nn.Dropout(dropout)
  245. self.linear2 = nn.Linear(self.fpn_dim, d_model)
  246. self.dropout3 = nn.Dropout(dropout)
  247. self.norm = nn.LayerNorm(d_model)
  248. def forward(self, src):
  249. if self.pre_norm:
  250. src = self.norm(src)
  251. src2 = self.linear2(self.dropout2(self.activation(self.linear1(src))))
  252. src = src + self.dropout3(src2)
  253. else:
  254. src2 = self.linear2(self.dropout2(self.activation(self.linear1(src))))
  255. src = src + self.dropout3(src2)
  256. src = self.norm(src)
  257. return src
  258. # ----------------- Attention Ops -----------------
  259. class GlobalCrossAttention(nn.Module):
  260. def __init__(
  261. self,
  262. dim :int = 256,
  263. num_heads :int = 8,
  264. qkv_bias :bool = True,
  265. qk_scale :float = None,
  266. attn_drop :float = 0.0,
  267. proj_drop :float = 0.0,
  268. rpe_hidden_dim :int = 512,
  269. feature_stride :int = 16,
  270. ):
  271. super().__init__()
  272. # --------- Basic parameters ---------
  273. self.dim = dim
  274. self.num_heads = num_heads
  275. head_dim = dim // num_heads
  276. self.scale = qk_scale or head_dim ** -0.5
  277. self.feature_stride = feature_stride
  278. # --------- Network parameters ---------
  279. self.cpb_mlp1 = self.build_cpb_mlp(2, rpe_hidden_dim, num_heads)
  280. self.cpb_mlp2 = self.build_cpb_mlp(2, rpe_hidden_dim, num_heads)
  281. self.q = nn.Linear(dim, dim, bias=qkv_bias)
  282. self.k = nn.Linear(dim, dim, bias=qkv_bias)
  283. self.v = nn.Linear(dim, dim, bias=qkv_bias)
  284. self.attn_drop = nn.Dropout(attn_drop)
  285. self.proj = nn.Linear(dim, dim)
  286. self.proj_drop = nn.Dropout(proj_drop)
  287. self.softmax = nn.Softmax(dim=-1)
  288. def build_cpb_mlp(self, in_dim, hidden_dim, out_dim):
  289. cpb_mlp = nn.Sequential(nn.Linear(in_dim, hidden_dim, bias=True),
  290. nn.ReLU(inplace=True),
  291. nn.Linear(hidden_dim, out_dim, bias=False))
  292. return cpb_mlp
  293. def forward(
  294. self,
  295. query,
  296. reference_points,
  297. k_input_flatten,
  298. v_input_flatten,
  299. input_spatial_shapes,
  300. input_padding_mask=None,
  301. ):
  302. assert input_spatial_shapes.size(0) == 1, 'This is designed for single-scale decoder.'
  303. h, w = input_spatial_shapes[0]
  304. stride = self.feature_stride
  305. ref_pts = torch.cat([
  306. reference_points[:, :, :, :2] - reference_points[:, :, :, 2:] / 2,
  307. reference_points[:, :, :, :2] + reference_points[:, :, :, 2:] / 2,
  308. ], dim=-1) # B, nQ, 1, 4
  309. pos_x = torch.linspace(0.5, w - 0.5, w, dtype=torch.float32, device=w.device)[None, None, :, None] * stride # 1, 1, w, 1
  310. pos_y = torch.linspace(0.5, h - 0.5, h, dtype=torch.float32, device=h.device)[None, None, :, None] * stride # 1, 1, h, 1
  311. delta_x = ref_pts[..., 0::2] - pos_x # B, nQ, w, 2
  312. delta_y = ref_pts[..., 1::2] - pos_y # B, nQ, h, 2
  313. rpe_x, rpe_y = self.cpb_mlp1(delta_x), self.cpb_mlp2(delta_y) # B, nQ, w/h, nheads
  314. rpe = (rpe_x[:, :, None] + rpe_y[:, :, :, None]).flatten(2, 3) # B, nQ, h, w, nheads -> B, nQ, h*w, nheads
  315. rpe = rpe.permute(0, 3, 1, 2)
  316. B_, N, C = k_input_flatten.shape
  317. k = self.k(k_input_flatten).reshape(B_, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
  318. v = self.v(v_input_flatten).reshape(B_, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
  319. B_, N, C = query.shape
  320. q = self.q(query).reshape(B_, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
  321. q = q * self.scale
  322. attn = q @ k.transpose(-2, -1)
  323. attn += rpe
  324. if input_padding_mask is not None:
  325. attn += input_padding_mask[:, None, None] * -100
  326. fmin, fmax = torch.finfo(attn.dtype).min, torch.finfo(attn.dtype).max
  327. torch.clip_(attn, min=fmin, max=fmax)
  328. attn = self.softmax(attn)
  329. attn = self.attn_drop(attn)
  330. x = attn @ v
  331. x = x.transpose(1, 2).reshape(B_, N, C)
  332. x = self.proj(x)
  333. x = self.proj_drop(x)
  334. return x