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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
|
| 7 |
+
from utils.downloads import attempt_download
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class Sum(nn.Module):
|
| 11 |
+
# Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
|
| 12 |
+
def __init__(self, n, weight=False): # n: number of inputs
|
| 13 |
+
super().__init__()
|
| 14 |
+
self.weight = weight # apply weights boolean
|
| 15 |
+
self.iter = range(n - 1) # iter object
|
| 16 |
+
if weight:
|
| 17 |
+
self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights
|
| 18 |
+
|
| 19 |
+
def forward(self, x):
|
| 20 |
+
y = x[0] # no weight
|
| 21 |
+
if self.weight:
|
| 22 |
+
w = torch.sigmoid(self.w) * 2
|
| 23 |
+
for i in self.iter:
|
| 24 |
+
y = y + x[i + 1] * w[i]
|
| 25 |
+
else:
|
| 26 |
+
for i in self.iter:
|
| 27 |
+
y = y + x[i + 1]
|
| 28 |
+
return y
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class MixConv2d(nn.Module):
|
| 32 |
+
# Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
|
| 33 |
+
def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): # ch_in, ch_out, kernel, stride, ch_strategy
|
| 34 |
+
super().__init__()
|
| 35 |
+
n = len(k) # number of convolutions
|
| 36 |
+
if equal_ch: # equal c_ per group
|
| 37 |
+
i = torch.linspace(0, n - 1E-6, c2).floor() # c2 indices
|
| 38 |
+
c_ = [(i == g).sum() for g in range(n)] # intermediate channels
|
| 39 |
+
else: # equal weight.numel() per group
|
| 40 |
+
b = [c2] + [0] * n
|
| 41 |
+
a = np.eye(n + 1, n, k=-1)
|
| 42 |
+
a -= np.roll(a, 1, axis=1)
|
| 43 |
+
a *= np.array(k) ** 2
|
| 44 |
+
a[0] = 1
|
| 45 |
+
c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
|
| 46 |
+
|
| 47 |
+
self.m = nn.ModuleList([
|
| 48 |
+
nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)])
|
| 49 |
+
self.bn = nn.BatchNorm2d(c2)
|
| 50 |
+
self.act = nn.SiLU()
|
| 51 |
+
|
| 52 |
+
def forward(self, x):
|
| 53 |
+
return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class Ensemble(nn.ModuleList):
|
| 57 |
+
# Ensemble of models
|
| 58 |
+
def __init__(self):
|
| 59 |
+
super().__init__()
|
| 60 |
+
|
| 61 |
+
def forward(self, x, augment=False, profile=False, visualize=False):
|
| 62 |
+
y = [module(x, augment, profile, visualize)[0] for module in self]
|
| 63 |
+
# y = torch.stack(y).max(0)[0] # max ensemble
|
| 64 |
+
# y = torch.stack(y).mean(0) # mean ensemble
|
| 65 |
+
y = torch.cat(y, 1) # nms ensemble
|
| 66 |
+
return y, None # inference, train output
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class ORT_NMS(torch.autograd.Function):
|
| 70 |
+
'''ONNX-Runtime NMS operation'''
|
| 71 |
+
@staticmethod
|
| 72 |
+
def forward(ctx,
|
| 73 |
+
boxes,
|
| 74 |
+
scores,
|
| 75 |
+
max_output_boxes_per_class=torch.tensor([100]),
|
| 76 |
+
iou_threshold=torch.tensor([0.45]),
|
| 77 |
+
score_threshold=torch.tensor([0.25])):
|
| 78 |
+
device = boxes.device
|
| 79 |
+
batch = scores.shape[0]
|
| 80 |
+
num_det = random.randint(0, 100)
|
| 81 |
+
batches = torch.randint(0, batch, (num_det,)).sort()[0].to(device)
|
| 82 |
+
idxs = torch.arange(100, 100 + num_det).to(device)
|
| 83 |
+
zeros = torch.zeros((num_det,), dtype=torch.int64).to(device)
|
| 84 |
+
selected_indices = torch.cat([batches[None], zeros[None], idxs[None]], 0).T.contiguous()
|
| 85 |
+
selected_indices = selected_indices.to(torch.int64)
|
| 86 |
+
return selected_indices
|
| 87 |
+
|
| 88 |
+
@staticmethod
|
| 89 |
+
def symbolic(g, boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold):
|
| 90 |
+
return g.op("NonMaxSuppression", boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class TRT_NMS(torch.autograd.Function):
|
| 94 |
+
'''TensorRT NMS operation'''
|
| 95 |
+
@staticmethod
|
| 96 |
+
def forward(
|
| 97 |
+
ctx,
|
| 98 |
+
boxes,
|
| 99 |
+
scores,
|
| 100 |
+
background_class=-1,
|
| 101 |
+
box_coding=1,
|
| 102 |
+
iou_threshold=0.45,
|
| 103 |
+
max_output_boxes=100,
|
| 104 |
+
plugin_version="1",
|
| 105 |
+
score_activation=0,
|
| 106 |
+
score_threshold=0.25,
|
| 107 |
+
):
|
| 108 |
+
|
| 109 |
+
batch_size, num_boxes, num_classes = scores.shape
|
| 110 |
+
num_det = torch.randint(0, max_output_boxes, (batch_size, 1), dtype=torch.int32)
|
| 111 |
+
det_boxes = torch.randn(batch_size, max_output_boxes, 4)
|
| 112 |
+
det_scores = torch.randn(batch_size, max_output_boxes)
|
| 113 |
+
det_classes = torch.randint(0, num_classes, (batch_size, max_output_boxes), dtype=torch.int32)
|
| 114 |
+
return num_det, det_boxes, det_scores, det_classes
|
| 115 |
+
|
| 116 |
+
@staticmethod
|
| 117 |
+
def symbolic(g,
|
| 118 |
+
boxes,
|
| 119 |
+
scores,
|
| 120 |
+
background_class=-1,
|
| 121 |
+
box_coding=1,
|
| 122 |
+
iou_threshold=0.45,
|
| 123 |
+
max_output_boxes=100,
|
| 124 |
+
plugin_version="1",
|
| 125 |
+
score_activation=0,
|
| 126 |
+
score_threshold=0.25):
|
| 127 |
+
out = g.op("TRT::EfficientNMS_TRT",
|
| 128 |
+
boxes,
|
| 129 |
+
scores,
|
| 130 |
+
background_class_i=background_class,
|
| 131 |
+
box_coding_i=box_coding,
|
| 132 |
+
iou_threshold_f=iou_threshold,
|
| 133 |
+
max_output_boxes_i=max_output_boxes,
|
| 134 |
+
plugin_version_s=plugin_version,
|
| 135 |
+
score_activation_i=score_activation,
|
| 136 |
+
score_threshold_f=score_threshold,
|
| 137 |
+
outputs=4)
|
| 138 |
+
nums, boxes, scores, classes = out
|
| 139 |
+
return nums, boxes, scores, classes
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class ONNX_ORT(nn.Module):
|
| 143 |
+
'''onnx module with ONNX-Runtime NMS operation.'''
|
| 144 |
+
def __init__(self, max_obj=100, iou_thres=0.45, score_thres=0.25, max_wh=640, device=None, n_classes=80):
|
| 145 |
+
super().__init__()
|
| 146 |
+
self.device = device if device else torch.device("cpu")
|
| 147 |
+
self.max_obj = torch.tensor([max_obj]).to(device)
|
| 148 |
+
self.iou_threshold = torch.tensor([iou_thres]).to(device)
|
| 149 |
+
self.score_threshold = torch.tensor([score_thres]).to(device)
|
| 150 |
+
self.max_wh = max_wh # if max_wh != 0 : non-agnostic else : agnostic
|
| 151 |
+
self.convert_matrix = torch.tensor([[1, 0, 1, 0], [0, 1, 0, 1], [-0.5, 0, 0.5, 0], [0, -0.5, 0, 0.5]],
|
| 152 |
+
dtype=torch.float32,
|
| 153 |
+
device=self.device)
|
| 154 |
+
self.n_classes=n_classes
|
| 155 |
+
|
| 156 |
+
def forward(self, x):
|
| 157 |
+
## https://github.com/thaitc-hust/yolov9-tensorrt/blob/main/torch2onnx.py
|
| 158 |
+
## thanks https://github.com/thaitc-hust
|
| 159 |
+
if isinstance(x, list): ## yolov9-c.pt and yolov9-e.pt return list
|
| 160 |
+
x = x[1]
|
| 161 |
+
x = x.permute(0, 2, 1)
|
| 162 |
+
bboxes_x = x[..., 0:1]
|
| 163 |
+
bboxes_y = x[..., 1:2]
|
| 164 |
+
bboxes_w = x[..., 2:3]
|
| 165 |
+
bboxes_h = x[..., 3:4]
|
| 166 |
+
bboxes = torch.cat([bboxes_x, bboxes_y, bboxes_w, bboxes_h], dim = -1)
|
| 167 |
+
bboxes = bboxes.unsqueeze(2) # [n_batch, n_bboxes, 4] -> [n_batch, n_bboxes, 1, 4]
|
| 168 |
+
obj_conf = x[..., 4:]
|
| 169 |
+
scores = obj_conf
|
| 170 |
+
bboxes @= self.convert_matrix
|
| 171 |
+
max_score, category_id = scores.max(2, keepdim=True)
|
| 172 |
+
dis = category_id.float() * self.max_wh
|
| 173 |
+
nmsbox = bboxes + dis
|
| 174 |
+
max_score_tp = max_score.transpose(1, 2).contiguous()
|
| 175 |
+
selected_indices = ORT_NMS.apply(nmsbox, max_score_tp, self.max_obj, self.iou_threshold, self.score_threshold)
|
| 176 |
+
X, Y = selected_indices[:, 0], selected_indices[:, 2]
|
| 177 |
+
selected_boxes = bboxes[X, Y, :]
|
| 178 |
+
selected_categories = category_id[X, Y, :].float()
|
| 179 |
+
selected_scores = max_score[X, Y, :]
|
| 180 |
+
X = X.unsqueeze(1).float()
|
| 181 |
+
return torch.cat([X, selected_boxes, selected_categories, selected_scores], 1)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class ONNX_TRT(nn.Module):
|
| 185 |
+
'''onnx module with TensorRT NMS operation.'''
|
| 186 |
+
def __init__(self, max_obj=100, iou_thres=0.45, score_thres=0.25, max_wh=None ,device=None, n_classes=80):
|
| 187 |
+
super().__init__()
|
| 188 |
+
assert max_wh is None
|
| 189 |
+
self.device = device if device else torch.device('cpu')
|
| 190 |
+
self.background_class = -1,
|
| 191 |
+
self.box_coding = 1,
|
| 192 |
+
self.iou_threshold = iou_thres
|
| 193 |
+
self.max_obj = max_obj
|
| 194 |
+
self.plugin_version = '1'
|
| 195 |
+
self.score_activation = 0
|
| 196 |
+
self.score_threshold = score_thres
|
| 197 |
+
self.n_classes=n_classes
|
| 198 |
+
|
| 199 |
+
def forward(self, x):
|
| 200 |
+
## https://github.com/thaitc-hust/yolov9-tensorrt/blob/main/torch2onnx.py
|
| 201 |
+
## thanks https://github.com/thaitc-hust
|
| 202 |
+
if isinstance(x, list): ## yolov9-c.pt and yolov9-e.pt return list
|
| 203 |
+
x = x[1]
|
| 204 |
+
x = x.permute(0, 2, 1)
|
| 205 |
+
bboxes_x = x[..., 0:1]
|
| 206 |
+
bboxes_y = x[..., 1:2]
|
| 207 |
+
bboxes_w = x[..., 2:3]
|
| 208 |
+
bboxes_h = x[..., 3:4]
|
| 209 |
+
bboxes = torch.cat([bboxes_x, bboxes_y, bboxes_w, bboxes_h], dim = -1)
|
| 210 |
+
bboxes = bboxes.unsqueeze(2) # [n_batch, n_bboxes, 4] -> [n_batch, n_bboxes, 1, 4]
|
| 211 |
+
obj_conf = x[..., 4:]
|
| 212 |
+
scores = obj_conf
|
| 213 |
+
num_det, det_boxes, det_scores, det_classes = TRT_NMS.apply(bboxes, scores, self.background_class, self.box_coding,
|
| 214 |
+
self.iou_threshold, self.max_obj,
|
| 215 |
+
self.plugin_version, self.score_activation,
|
| 216 |
+
self.score_threshold)
|
| 217 |
+
return num_det, det_boxes, det_scores, det_classes
|
| 218 |
+
|
| 219 |
+
class End2End(nn.Module):
|
| 220 |
+
'''export onnx or tensorrt model with NMS operation.'''
|
| 221 |
+
def __init__(self, model, max_obj=100, iou_thres=0.45, score_thres=0.25, max_wh=None, device=None, n_classes=80):
|
| 222 |
+
super().__init__()
|
| 223 |
+
device = device if device else torch.device('cpu')
|
| 224 |
+
assert isinstance(max_wh,(int)) or max_wh is None
|
| 225 |
+
self.model = model.to(device)
|
| 226 |
+
self.model.model[-1].end2end = True
|
| 227 |
+
self.patch_model = ONNX_TRT if max_wh is None else ONNX_ORT
|
| 228 |
+
self.end2end = self.patch_model(max_obj, iou_thres, score_thres, max_wh, device, n_classes)
|
| 229 |
+
self.end2end.eval()
|
| 230 |
+
|
| 231 |
+
def forward(self, x):
|
| 232 |
+
x = self.model(x)
|
| 233 |
+
x = self.end2end(x)
|
| 234 |
+
return x
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def attempt_load(weights, device=None, inplace=True, fuse=True):
|
| 238 |
+
# Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
|
| 239 |
+
from models.yolo import Detect, Model
|
| 240 |
+
|
| 241 |
+
model = Ensemble()
|
| 242 |
+
for w in weights if isinstance(weights, list) else [weights]:
|
| 243 |
+
ckpt = torch.load(attempt_download(w), map_location='cpu') # load
|
| 244 |
+
ckpt = (ckpt.get('ema') or ckpt['model']).to(device).float() # FP32 model
|
| 245 |
+
|
| 246 |
+
# Model compatibility updates
|
| 247 |
+
if not hasattr(ckpt, 'stride'):
|
| 248 |
+
ckpt.stride = torch.tensor([32.])
|
| 249 |
+
if hasattr(ckpt, 'names') and isinstance(ckpt.names, (list, tuple)):
|
| 250 |
+
ckpt.names = dict(enumerate(ckpt.names)) # convert to dict
|
| 251 |
+
|
| 252 |
+
model.append(ckpt.fuse().eval() if fuse and hasattr(ckpt, 'fuse') else ckpt.eval()) # model in eval mode
|
| 253 |
+
|
| 254 |
+
# Module compatibility updates
|
| 255 |
+
for m in model.modules():
|
| 256 |
+
t = type(m)
|
| 257 |
+
if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model):
|
| 258 |
+
m.inplace = inplace # torch 1.7.0 compatibility
|
| 259 |
+
# if t is Detect and not isinstance(m.anchor_grid, list):
|
| 260 |
+
# delattr(m, 'anchor_grid')
|
| 261 |
+
# setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)
|
| 262 |
+
elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):
|
| 263 |
+
m.recompute_scale_factor = None # torch 1.11.0 compatibility
|
| 264 |
+
|
| 265 |
+
# Return model
|
| 266 |
+
if len(model) == 1:
|
| 267 |
+
return model[-1]
|
| 268 |
+
|
| 269 |
+
# Return detection ensemble
|
| 270 |
+
print(f'Ensemble created with {weights}\n')
|
| 271 |
+
for k in 'names', 'nc', 'yaml':
|
| 272 |
+
setattr(model, k, getattr(model[0], k))
|
| 273 |
+
model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
|
| 274 |
+
assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}'
|
| 275 |
+
return model
|