You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 line
4.0KB

  1. # YOLOv5 experimental modules
  2. import numpy as np
  3. import torch
  4. import torch.nn as nn
  5. from models.common import Conv, DWConv
  6. from utils.downloads import attempt_download
  7. class CrossConv(nn.Module):
  8. # Cross Convolution Downsample
  9. def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
  10. # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
  11. super().__init__()
  12. c_ = int(c2 * e) # hidden channels
  13. self.cv1 = Conv(c1, c_, (1, k), (1, s))
  14. self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
  15. self.add = shortcut and c1 == c2
  16. def forward(self, x):
  17. return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
  18. class Sum(nn.Module):
  19. # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
  20. def __init__(self, n, weight=False): # n: number of inputs
  21. super().__init__()
  22. self.weight = weight # apply weights boolean
  23. self.iter = range(n - 1) # iter object
  24. if weight:
  25. self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights
  26. def forward(self, x):
  27. y = x[0] # no weight
  28. if self.weight:
  29. w = torch.sigmoid(self.w) * 2
  30. for i in self.iter:
  31. y = y + x[i + 1] * w[i]
  32. else:
  33. for i in self.iter:
  34. y = y + x[i + 1]
  35. return y
  36. class MixConv2d(nn.Module):
  37. # Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
  38. def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
  39. super().__init__()
  40. groups = len(k)
  41. if equal_ch: # equal c_ per group
  42. i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices
  43. c_ = [(i == g).sum() for g in range(groups)] # intermediate channels
  44. else: # equal weight.numel() per group
  45. b = [c2] + [0] * groups
  46. a = np.eye(groups + 1, groups, k=-1)
  47. a -= np.roll(a, 1, axis=1)
  48. a *= np.array(k) ** 2
  49. a[0] = 1
  50. c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
  51. self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)])
  52. self.bn = nn.BatchNorm2d(c2)
  53. self.act = nn.LeakyReLU(0.1, inplace=True)
  54. def forward(self, x):
  55. return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
  56. class Ensemble(nn.ModuleList):
  57. # Ensemble of models
  58. def __init__(self):
  59. super().__init__()
  60. def forward(self, x, augment=False, profile=False, visualize=False):
  61. y = []
  62. for module in self:
  63. y.append(module(x, augment, profile, visualize)[0])
  64. # y = torch.stack(y).max(0)[0] # max ensemble
  65. # y = torch.stack(y).mean(0) # mean ensemble
  66. y = torch.cat(y, 1) # nms ensemble
  67. return y, None # inference, train output
  68. def attempt_load(weights, map_location=None, inplace=True):
  69. from models.yolo import Detect, Model
  70. # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
  71. model = Ensemble()
  72. for w in weights if isinstance(weights, list) else [weights]:
  73. ckpt = torch.load(attempt_download(w), map_location=map_location) # load
  74. model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model
  75. # Compatibility updates
  76. for m in model.modules():
  77. if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model]:
  78. m.inplace = inplace # pytorch 1.7.0 compatibility
  79. elif type(m) is Conv:
  80. m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
  81. if len(model) == 1:
  82. return model[-1] # return model
  83. else:
  84. print(f'Ensemble created with {weights}\n')
  85. for k in ['names']:
  86. setattr(model, k, getattr(model[-1], k))
  87. model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
  88. return model # return ensemble