basic.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. # ---------------------------- NMS ----------------------------
  25. ## basic NMS
  26. def nms(bboxes, scores, nms_thresh):
  27. """"Pure Python NMS."""
  28. x1 = bboxes[:, 0] #xmin
  29. y1 = bboxes[:, 1] #ymin
  30. x2 = bboxes[:, 2] #xmax
  31. y2 = bboxes[:, 3] #ymax
  32. areas = (x2 - x1) * (y2 - y1)
  33. order = scores.argsort()[::-1]
  34. keep = []
  35. while order.size > 0:
  36. i = order[0]
  37. keep.append(i)
  38. # compute iou
  39. xx1 = np.maximum(x1[i], x1[order[1:]])
  40. yy1 = np.maximum(y1[i], y1[order[1:]])
  41. xx2 = np.minimum(x2[i], x2[order[1:]])
  42. yy2 = np.minimum(y2[i], y2[order[1:]])
  43. w = np.maximum(1e-10, xx2 - xx1)
  44. h = np.maximum(1e-10, yy2 - yy1)
  45. inter = w * h
  46. iou = inter / (areas[i] + areas[order[1:]] - inter + 1e-14)
  47. #reserve all the boundingbox whose ovr less than thresh
  48. inds = np.where(iou <= nms_thresh)[0]
  49. order = order[inds + 1]
  50. return keep
  51. ## class-agnostic NMS
  52. def multiclass_nms_class_agnostic(scores, labels, bboxes, nms_thresh):
  53. # nms
  54. keep = nms(bboxes, scores, nms_thresh)
  55. scores = scores[keep]
  56. labels = labels[keep]
  57. bboxes = bboxes[keep]
  58. return scores, labels, bboxes
  59. ## class-aware NMS
  60. def multiclass_nms_class_aware(scores, labels, bboxes, nms_thresh, num_classes):
  61. # nms
  62. keep = np.zeros(len(bboxes), dtype=np.int32)
  63. for i in range(num_classes):
  64. inds = np.where(labels == i)[0]
  65. if len(inds) == 0:
  66. continue
  67. c_bboxes = bboxes[inds]
  68. c_scores = scores[inds]
  69. c_keep = nms(c_bboxes, c_scores, nms_thresh)
  70. keep[inds[c_keep]] = 1
  71. keep = np.where(keep > 0)
  72. scores = scores[keep]
  73. labels = labels[keep]
  74. bboxes = bboxes[keep]
  75. return scores, labels, bboxes
  76. ## multi-class NMS
  77. def multiclass_nms(scores, labels, bboxes, nms_thresh, num_classes, class_agnostic=False):
  78. if class_agnostic:
  79. return multiclass_nms_class_agnostic(scores, labels, bboxes, nms_thresh)
  80. else:
  81. return multiclass_nms_class_aware(scores, labels, bboxes, nms_thresh, num_classes)
  82. # ----------------- Customed NormLayer Ops -----------------
  83. class LayerNorm2D(nn.Module):
  84. def __init__(self, normalized_shape, norm_layer=nn.LayerNorm):
  85. super().__init__()
  86. self.ln = norm_layer(normalized_shape) if norm_layer is not None else nn.Identity()
  87. def forward(self, x):
  88. """
  89. x: N C H W
  90. """
  91. x = x.permute(0, 2, 3, 1)
  92. x = self.ln(x)
  93. x = x.permute(0, 3, 1, 2)
  94. return x
  95. # ----------------- Basic CNN Ops -----------------
  96. def get_conv2d(c1, c2, k, p, s, g, bias=False):
  97. conv = nn.Conv2d(c1, c2, k, stride=s, padding=p, groups=g, bias=bias)
  98. return conv
  99. def get_activation(act_type=None):
  100. if act_type == 'relu':
  101. return nn.ReLU(inplace=True)
  102. elif act_type == 'lrelu':
  103. return nn.LeakyReLU(0.1, inplace=True)
  104. elif act_type == 'mish':
  105. return nn.Mish(inplace=True)
  106. elif act_type == 'silu':
  107. return nn.SiLU(inplace=True)
  108. elif act_type == 'gelu':
  109. return nn.GELU()
  110. elif act_type is None:
  111. return nn.Identity()
  112. else:
  113. raise NotImplementedError
  114. def get_norm(norm_type, dim):
  115. if norm_type == 'BN':
  116. return nn.BatchNorm2d(dim)
  117. elif norm_type == 'GN':
  118. return nn.GroupNorm(num_groups=32, num_channels=dim)
  119. elif norm_type is None:
  120. return nn.Identity()
  121. else:
  122. raise NotImplementedError
  123. class BasicConv(nn.Module):
  124. def __init__(self,
  125. in_dim, # in channels
  126. out_dim, # out channels
  127. kernel_size=1, # kernel size
  128. padding=0, # padding
  129. stride=1, # padding
  130. act_type :str = 'lrelu', # activation
  131. norm_type :str = 'BN', # normalization
  132. ):
  133. super(BasicConv, self).__init__()
  134. add_bias = False if norm_type else True
  135. self.conv = get_conv2d(in_dim, out_dim, k=kernel_size, p=padding, s=stride, g=1, bias=add_bias)
  136. self.norm = get_norm(norm_type, out_dim)
  137. self.act = get_activation(act_type)
  138. def forward(self, x):
  139. return self.act(self.norm(self.conv(x)))
  140. class UpSampleWrapper(nn.Module):
  141. """Upsample last feat map to specific stride."""
  142. def __init__(self, in_dim, upsample_factor):
  143. super(UpSampleWrapper, self).__init__()
  144. # ---------- Basic parameters ----------
  145. self.upsample_factor = upsample_factor
  146. # ---------- Network parameters ----------
  147. if upsample_factor == 1:
  148. self.upsample = nn.Identity()
  149. else:
  150. scale = int(math.log2(upsample_factor))
  151. dim = in_dim
  152. layers = []
  153. for _ in range(scale-1):
  154. layers += [
  155. nn.ConvTranspose2d(dim, dim, kernel_size=2, stride=2),
  156. LayerNorm2D(dim),
  157. nn.GELU()
  158. ]
  159. layers += [nn.ConvTranspose2d(dim, dim, kernel_size=2, stride=2)]
  160. self.upsample = nn.Sequential(*layers)
  161. self.out_dim = dim
  162. def forward(self, x):
  163. x = self.upsample(x)
  164. return x
  165. # ----------------- MLP modules -----------------
  166. class MLP(nn.Module):
  167. def __init__(self, in_dim, hidden_dim, out_dim, num_layers):
  168. super().__init__()
  169. self.num_layers = num_layers
  170. h = [hidden_dim] * (num_layers - 1)
  171. self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([in_dim] + h, h + [out_dim]))
  172. def forward(self, x):
  173. for i, layer in enumerate(self.layers):
  174. x = nn.functional.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
  175. return x
  176. class FFN(nn.Module):
  177. def __init__(self, d_model=256, mlp_ratio=4.0, dropout=0., act_type='relu', pre_norm=False):
  178. super().__init__()
  179. # ----------- Basic parameters -----------
  180. self.pre_norm = pre_norm
  181. self.fpn_dim = round(d_model * mlp_ratio)
  182. # ----------- Network parameters -----------
  183. self.linear1 = nn.Linear(d_model, self.fpn_dim)
  184. self.activation = get_activation(act_type)
  185. self.dropout2 = nn.Dropout(dropout)
  186. self.linear2 = nn.Linear(self.fpn_dim, d_model)
  187. self.dropout3 = nn.Dropout(dropout)
  188. self.norm = nn.LayerNorm(d_model)
  189. def forward(self, src):
  190. if self.pre_norm:
  191. src = self.norm(src)
  192. src2 = self.linear2(self.dropout2(self.activation(self.linear1(src))))
  193. src = src + self.dropout3(src2)
  194. else:
  195. src2 = self.linear2(self.dropout2(self.activation(self.linear1(src))))
  196. src = src + self.dropout3(src2)
  197. src = self.norm(src)
  198. return src