PKaushik commited on
Commit
e259ff9
1 Parent(s): 0c6d4ba
Files changed (1) hide show
  1. yolov6/layers/common.py +501 -0
yolov6/layers/common.py CHANGED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding:utf-8 -*-
3
+
4
+ import warnings
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from yolov6.layers.dbb_transforms import *
12
+
13
+
14
+ class SiLU(nn.Module):
15
+ '''Activation of SiLU'''
16
+ @staticmethod
17
+ def forward(x):
18
+ return x * torch.sigmoid(x)
19
+
20
+
21
+ class Conv(nn.Module):
22
+ '''Normal Conv with SiLU activation'''
23
+ def __init__(self, in_channels, out_channels, kernel_size, stride, groups=1, bias=False):
24
+ super().__init__()
25
+ padding = kernel_size // 2
26
+ self.conv = nn.Conv2d(
27
+ in_channels,
28
+ out_channels,
29
+ kernel_size=kernel_size,
30
+ stride=stride,
31
+ padding=padding,
32
+ groups=groups,
33
+ bias=bias,
34
+ )
35
+ self.bn = nn.BatchNorm2d(out_channels)
36
+ self.act = nn.SiLU()
37
+
38
+ def forward(self, x):
39
+ return self.act(self.bn(self.conv(x)))
40
+
41
+ def forward_fuse(self, x):
42
+ return self.act(self.conv(x))
43
+
44
+
45
+ class SimConv(nn.Module):
46
+ '''Normal Conv with ReLU activation'''
47
+ def __init__(self, in_channels, out_channels, kernel_size, stride, groups=1, bias=False):
48
+ super().__init__()
49
+ padding = kernel_size // 2
50
+ self.conv = nn.Conv2d(
51
+ in_channels,
52
+ out_channels,
53
+ kernel_size=kernel_size,
54
+ stride=stride,
55
+ padding=padding,
56
+ groups=groups,
57
+ bias=bias,
58
+ )
59
+ self.bn = nn.BatchNorm2d(out_channels)
60
+ self.act = nn.ReLU()
61
+
62
+ def forward(self, x):
63
+ return self.act(self.bn(self.conv(x)))
64
+
65
+ def forward_fuse(self, x):
66
+ return self.act(self.conv(x))
67
+
68
+
69
+ class SimSPPF(nn.Module):
70
+ '''Simplified SPPF with ReLU activation'''
71
+ def __init__(self, in_channels, out_channels, kernel_size=5):
72
+ super().__init__()
73
+ c_ = in_channels // 2 # hidden channels
74
+ self.cv1 = SimConv(in_channels, c_, 1, 1)
75
+ self.cv2 = SimConv(c_ * 4, out_channels, 1, 1)
76
+ self.m = nn.MaxPool2d(kernel_size=kernel_size, stride=1, padding=kernel_size // 2)
77
+
78
+ def forward(self, x):
79
+ x = self.cv1(x)
80
+ with warnings.catch_warnings():
81
+ warnings.simplefilter('ignore')
82
+ y1 = self.m(x)
83
+ y2 = self.m(y1)
84
+ return self.cv2(torch.cat([x, y1, y2, self.m(y2)], 1))
85
+
86
+
87
+ class Transpose(nn.Module):
88
+ '''Normal Transpose, default for upsampling'''
89
+ def __init__(self, in_channels, out_channels, kernel_size=2, stride=2):
90
+ super().__init__()
91
+ self.upsample_transpose = torch.nn.ConvTranspose2d(
92
+ in_channels=in_channels,
93
+ out_channels=out_channels,
94
+ kernel_size=kernel_size,
95
+ stride=stride,
96
+ bias=True
97
+ )
98
+
99
+ def forward(self, x):
100
+ return self.upsample_transpose(x)
101
+
102
+
103
+ class Concat(nn.Module):
104
+ def __init__(self, dimension=1):
105
+ super().__init__()
106
+ self.d = dimension
107
+
108
+ def forward(self, x):
109
+ return torch.cat(x, self.d)
110
+
111
+
112
+ def conv_bn(in_channels, out_channels, kernel_size, stride, padding, groups=1):
113
+ '''Basic cell for rep-style block, including conv and bn'''
114
+ result = nn.Sequential()
115
+ result.add_module('conv', nn.Conv2d(in_channels=in_channels, out_channels=out_channels,
116
+ kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, bias=False))
117
+ result.add_module('bn', nn.BatchNorm2d(num_features=out_channels))
118
+ return result
119
+
120
+
121
+ class RepBlock(nn.Module):
122
+ '''
123
+ RepBlock is a stage block with rep-style basic block
124
+ '''
125
+ def __init__(self, in_channels, out_channels, n=1):
126
+ super().__init__()
127
+ self.conv1 = RepVGGBlock(in_channels, out_channels)
128
+ self.block = nn.Sequential(*(RepVGGBlock(out_channels, out_channels) for _ in range(n - 1))) if n > 1 else None
129
+
130
+ def forward(self, x):
131
+ x = self.conv1(x)
132
+ if self.block is not None:
133
+ x = self.block(x)
134
+ return x
135
+
136
+
137
+ class RepVGGBlock(nn.Module):
138
+ '''RepVGGBlock is a basic rep-style block, including training and deploy status
139
+ This code is based on https://github.com/DingXiaoH/RepVGG/blob/main/repvgg.py
140
+ '''
141
+ def __init__(self, in_channels, out_channels, kernel_size=3,
142
+ stride=1, padding=1, dilation=1, groups=1, padding_mode='zeros', deploy=False, use_se=False):
143
+ super(RepVGGBlock, self).__init__()
144
+ """ Initialization of the class.
145
+ Args:
146
+ in_channels (int): Number of channels in the input image
147
+ out_channels (int): Number of channels produced by the convolution
148
+ kernel_size (int or tuple): Size of the convolving kernel
149
+ stride (int or tuple, optional): Stride of the convolution. Default: 1
150
+ padding (int or tuple, optional): Zero-padding added to both sides of
151
+ the input. Default: 1
152
+ dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
153
+ groups (int, optional): Number of blocked connections from input
154
+ channels to output channels. Default: 1
155
+ padding_mode (string, optional): Default: 'zeros'
156
+ deploy: Whether to be deploy status or training status. Default: False
157
+ use_se: Whether to use se. Default: False
158
+ """
159
+ self.deploy = deploy
160
+ self.groups = groups
161
+ self.in_channels = in_channels
162
+ self.out_channels = out_channels
163
+
164
+ assert kernel_size == 3
165
+ assert padding == 1
166
+
167
+ padding_11 = padding - kernel_size // 2
168
+
169
+ self.nonlinearity = nn.ReLU()
170
+
171
+ if use_se:
172
+ raise NotImplementedError("se block not supported yet")
173
+ else:
174
+ self.se = nn.Identity()
175
+
176
+ if deploy:
177
+ self.rbr_reparam = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride,
178
+ padding=padding, dilation=dilation, groups=groups, bias=True, padding_mode=padding_mode)
179
+
180
+ else:
181
+ self.rbr_identity = nn.BatchNorm2d(num_features=in_channels) if out_channels == in_channels and stride == 1 else None
182
+ self.rbr_dense = conv_bn(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, groups=groups)
183
+ self.rbr_1x1 = conv_bn(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride, padding=padding_11, groups=groups)
184
+
185
+ def forward(self, inputs):
186
+ '''Forward process'''
187
+ if hasattr(self, 'rbr_reparam'):
188
+ return self.nonlinearity(self.se(self.rbr_reparam(inputs)))
189
+
190
+ if self.rbr_identity is None:
191
+ id_out = 0
192
+ else:
193
+ id_out = self.rbr_identity(inputs)
194
+
195
+ return self.nonlinearity(self.se(self.rbr_dense(inputs) + self.rbr_1x1(inputs) + id_out))
196
+
197
+ def get_equivalent_kernel_bias(self):
198
+ kernel3x3, bias3x3 = self._fuse_bn_tensor(self.rbr_dense)
199
+ kernel1x1, bias1x1 = self._fuse_bn_tensor(self.rbr_1x1)
200
+ kernelid, biasid = self._fuse_bn_tensor(self.rbr_identity)
201
+ return kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid, bias3x3 + bias1x1 + biasid
202
+
203
+ def _pad_1x1_to_3x3_tensor(self, kernel1x1):
204
+ if kernel1x1 is None:
205
+ return 0
206
+ else:
207
+ return torch.nn.functional.pad(kernel1x1, [1, 1, 1, 1])
208
+
209
+ def _fuse_bn_tensor(self, branch):
210
+ if branch is None:
211
+ return 0, 0
212
+ if isinstance(branch, nn.Sequential):
213
+ kernel = branch.conv.weight
214
+ running_mean = branch.bn.running_mean
215
+ running_var = branch.bn.running_var
216
+ gamma = branch.bn.weight
217
+ beta = branch.bn.bias
218
+ eps = branch.bn.eps
219
+ else:
220
+ assert isinstance(branch, nn.BatchNorm2d)
221
+ if not hasattr(self, 'id_tensor'):
222
+ input_dim = self.in_channels // self.groups
223
+ kernel_value = np.zeros((self.in_channels, input_dim, 3, 3), dtype=np.float32)
224
+ for i in range(self.in_channels):
225
+ kernel_value[i, i % input_dim, 1, 1] = 1
226
+ self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
227
+ kernel = self.id_tensor
228
+ running_mean = branch.running_mean
229
+ running_var = branch.running_var
230
+ gamma = branch.weight
231
+ beta = branch.bias
232
+ eps = branch.eps
233
+ std = (running_var + eps).sqrt()
234
+ t = (gamma / std).reshape(-1, 1, 1, 1)
235
+ return kernel * t, beta - running_mean * gamma / std
236
+
237
+ def switch_to_deploy(self):
238
+ if hasattr(self, 'rbr_reparam'):
239
+ return
240
+ kernel, bias = self.get_equivalent_kernel_bias()
241
+ self.rbr_reparam = nn.Conv2d(in_channels=self.rbr_dense.conv.in_channels, out_channels=self.rbr_dense.conv.out_channels,
242
+ kernel_size=self.rbr_dense.conv.kernel_size, stride=self.rbr_dense.conv.stride,
243
+ padding=self.rbr_dense.conv.padding, dilation=self.rbr_dense.conv.dilation, groups=self.rbr_dense.conv.groups, bias=True)
244
+ self.rbr_reparam.weight.data = kernel
245
+ self.rbr_reparam.bias.data = bias
246
+ for para in self.parameters():
247
+ para.detach_()
248
+ self.__delattr__('rbr_dense')
249
+ self.__delattr__('rbr_1x1')
250
+ if hasattr(self, 'rbr_identity'):
251
+ self.__delattr__('rbr_identity')
252
+ if hasattr(self, 'id_tensor'):
253
+ self.__delattr__('id_tensor')
254
+ self.deploy = True
255
+
256
+
257
+ def conv_bn_v2(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1,
258
+ padding_mode='zeros'):
259
+ conv_layer = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,
260
+ stride=stride, padding=padding, dilation=dilation, groups=groups,
261
+ bias=False, padding_mode=padding_mode)
262
+ bn_layer = nn.BatchNorm2d(num_features=out_channels, affine=True)
263
+ se = nn.Sequential()
264
+ se.add_module('conv', conv_layer)
265
+ se.add_module('bn', bn_layer)
266
+ return se
267
+
268
+
269
+ class IdentityBasedConv1x1(nn.Conv2d):
270
+
271
+ def __init__(self, channels, groups=1):
272
+ super(IdentityBasedConv1x1, self).__init__(in_channels=channels, out_channels=channels, kernel_size=1, stride=1, padding=0, groups=groups, bias=False)
273
+
274
+ assert channels % groups == 0
275
+ input_dim = channels // groups
276
+ id_value = np.zeros((channels, input_dim, 1, 1))
277
+ for i in range(channels):
278
+ id_value[i, i % input_dim, 0, 0] = 1
279
+ self.id_tensor = torch.from_numpy(id_value).type_as(self.weight)
280
+ nn.init.zeros_(self.weight)
281
+
282
+ def forward(self, input):
283
+ kernel = self.weight + self.id_tensor.to(self.weight.device)
284
+ result = F.conv2d(input, kernel, None, stride=1, padding=0, dilation=self.dilation, groups=self.groups)
285
+ return result
286
+
287
+ def get_actual_kernel(self):
288
+ return self.weight + self.id_tensor.to(self.weight.device)
289
+
290
+
291
+ class BNAndPadLayer(nn.Module):
292
+ def __init__(self,
293
+ pad_pixels,
294
+ num_features,
295
+ eps=1e-5,
296
+ momentum=0.1,
297
+ affine=True,
298
+ track_running_stats=True):
299
+ super(BNAndPadLayer, self).__init__()
300
+ self.bn = nn.BatchNorm2d(num_features, eps, momentum, affine, track_running_stats)
301
+ self.pad_pixels = pad_pixels
302
+
303
+ def forward(self, input):
304
+ output = self.bn(input)
305
+ if self.pad_pixels > 0:
306
+ if self.bn.affine:
307
+ pad_values = self.bn.bias.detach() - self.bn.running_mean * self.bn.weight.detach() / torch.sqrt(self.bn.running_var + self.bn.eps)
308
+ else:
309
+ pad_values = - self.bn.running_mean / torch.sqrt(self.bn.running_var + self.bn.eps)
310
+ output = F.pad(output, [self.pad_pixels] * 4)
311
+ pad_values = pad_values.view(1, -1, 1, 1)
312
+ output[:, :, 0:self.pad_pixels, :] = pad_values
313
+ output[:, :, -self.pad_pixels:, :] = pad_values
314
+ output[:, :, :, 0:self.pad_pixels] = pad_values
315
+ output[:, :, :, -self.pad_pixels:] = pad_values
316
+ return output
317
+
318
+ @property
319
+ def bn_weight(self):
320
+ return self.bn.weight
321
+
322
+ @property
323
+ def bn_bias(self):
324
+ return self.bn.bias
325
+
326
+ @property
327
+ def running_mean(self):
328
+ return self.bn.running_mean
329
+
330
+ @property
331
+ def running_var(self):
332
+ return self.bn.running_var
333
+
334
+ @property
335
+ def eps(self):
336
+ return self.bn.eps
337
+
338
+
339
+ class DBBBlock(nn.Module):
340
+ '''
341
+ RepBlock is a stage block with rep-style basic block
342
+ '''
343
+ def __init__(self, in_channels, out_channels, n=1):
344
+ super().__init__()
345
+ self.conv1 = DiverseBranchBlock(in_channels, out_channels)
346
+ self.block = nn.Sequential(*(DiverseBranchBlock(out_channels, out_channels) for _ in range(n - 1))) if n > 1 else None
347
+
348
+ def forward(self, x):
349
+ x = self.conv1(x)
350
+ if self.block is not None:
351
+ x = self.block(x)
352
+ return x
353
+
354
+
355
+ class DiverseBranchBlock(nn.Module):
356
+
357
+ def __init__(self, in_channels, out_channels, kernel_size=3,
358
+ stride=1, padding=1, dilation=1, groups=1,
359
+ internal_channels_1x1_3x3=None,
360
+ deploy=False, nonlinear=nn.ReLU(), single_init=False):
361
+ super(DiverseBranchBlock, self).__init__()
362
+ self.deploy = deploy
363
+
364
+ if nonlinear is None:
365
+ self.nonlinear = nn.Identity()
366
+ else:
367
+ self.nonlinear = nonlinear
368
+
369
+ self.kernel_size = kernel_size
370
+ self.out_channels = out_channels
371
+ self.groups = groups
372
+ assert padding == kernel_size // 2
373
+
374
+ if deploy:
375
+ self.dbb_reparam = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride,
376
+ padding=padding, dilation=dilation, groups=groups, bias=True)
377
+
378
+ else:
379
+
380
+ self.dbb_origin = conv_bn_v2(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups)
381
+
382
+ self.dbb_avg = nn.Sequential()
383
+ if groups < out_channels:
384
+ self.dbb_avg.add_module('conv',
385
+ nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1,
386
+ stride=1, padding=0, groups=groups, bias=False))
387
+ self.dbb_avg.add_module('bn', BNAndPadLayer(pad_pixels=padding, num_features=out_channels))
388
+ self.dbb_avg.add_module('avg', nn.AvgPool2d(kernel_size=kernel_size, stride=stride, padding=0))
389
+ self.dbb_1x1 = conv_bn_v2(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride,
390
+ padding=0, groups=groups)
391
+ else:
392
+ self.dbb_avg.add_module('avg', nn.AvgPool2d(kernel_size=kernel_size, stride=stride, padding=padding))
393
+
394
+ self.dbb_avg.add_module('avgbn', nn.BatchNorm2d(out_channels))
395
+
396
+ if internal_channels_1x1_3x3 is None:
397
+ internal_channels_1x1_3x3 = in_channels if groups < out_channels else 2 * in_channels # For mobilenet, it is better to have 2X internal channels
398
+
399
+ self.dbb_1x1_kxk = nn.Sequential()
400
+ if internal_channels_1x1_3x3 == in_channels:
401
+ self.dbb_1x1_kxk.add_module('idconv1', IdentityBasedConv1x1(channels=in_channels, groups=groups))
402
+ else:
403
+ self.dbb_1x1_kxk.add_module('conv1', nn.Conv2d(in_channels=in_channels, out_channels=internal_channels_1x1_3x3,
404
+ kernel_size=1, stride=1, padding=0, groups=groups, bias=False))
405
+ self.dbb_1x1_kxk.add_module('bn1', BNAndPadLayer(pad_pixels=padding, num_features=internal_channels_1x1_3x3, affine=True))
406
+ self.dbb_1x1_kxk.add_module('conv2', nn.Conv2d(in_channels=internal_channels_1x1_3x3, out_channels=out_channels,
407
+ kernel_size=kernel_size, stride=stride, padding=0, groups=groups, bias=False))
408
+ self.dbb_1x1_kxk.add_module('bn2', nn.BatchNorm2d(out_channels))
409
+
410
+ # The experiments reported in the paper used the default initialization of bn.weight (all as 1). But changing the initialization may be useful in some cases.
411
+ if single_init:
412
+ # Initialize the bn.weight of dbb_origin as 1 and others as 0. This is not the default setting.
413
+ self.single_init()
414
+
415
+ def get_equivalent_kernel_bias(self):
416
+ k_origin, b_origin = transI_fusebn(self.dbb_origin.conv.weight, self.dbb_origin.bn)
417
+
418
+ if hasattr(self, 'dbb_1x1'):
419
+ k_1x1, b_1x1 = transI_fusebn(self.dbb_1x1.conv.weight, self.dbb_1x1.bn)
420
+ k_1x1 = transVI_multiscale(k_1x1, self.kernel_size)
421
+ else:
422
+ k_1x1, b_1x1 = 0, 0
423
+
424
+ if hasattr(self.dbb_1x1_kxk, 'idconv1'):
425
+ k_1x1_kxk_first = self.dbb_1x1_kxk.idconv1.get_actual_kernel()
426
+ else:
427
+ k_1x1_kxk_first = self.dbb_1x1_kxk.conv1.weight
428
+ k_1x1_kxk_first, b_1x1_kxk_first = transI_fusebn(k_1x1_kxk_first, self.dbb_1x1_kxk.bn1)
429
+ k_1x1_kxk_second, b_1x1_kxk_second = transI_fusebn(self.dbb_1x1_kxk.conv2.weight, self.dbb_1x1_kxk.bn2)
430
+ k_1x1_kxk_merged, b_1x1_kxk_merged = transIII_1x1_kxk(k_1x1_kxk_first, b_1x1_kxk_first, k_1x1_kxk_second, b_1x1_kxk_second, groups=self.groups)
431
+
432
+ k_avg = transV_avg(self.out_channels, self.kernel_size, self.groups)
433
+ k_1x1_avg_second, b_1x1_avg_second = transI_fusebn(k_avg.to(self.dbb_avg.avgbn.weight.device), self.dbb_avg.avgbn)
434
+ if hasattr(self.dbb_avg, 'conv'):
435
+ k_1x1_avg_first, b_1x1_avg_first = transI_fusebn(self.dbb_avg.conv.weight, self.dbb_avg.bn)
436
+ k_1x1_avg_merged, b_1x1_avg_merged = transIII_1x1_kxk(k_1x1_avg_first, b_1x1_avg_first, k_1x1_avg_second, b_1x1_avg_second, groups=self.groups)
437
+ else:
438
+ k_1x1_avg_merged, b_1x1_avg_merged = k_1x1_avg_second, b_1x1_avg_second
439
+
440
+ return transII_addbranch((k_origin, k_1x1, k_1x1_kxk_merged, k_1x1_avg_merged), (b_origin, b_1x1, b_1x1_kxk_merged, b_1x1_avg_merged))
441
+
442
+ def switch_to_deploy(self):
443
+ if hasattr(self, 'dbb_reparam'):
444
+ return
445
+ kernel, bias = self.get_equivalent_kernel_bias()
446
+ self.dbb_reparam = nn.Conv2d(in_channels=self.dbb_origin.conv.in_channels, out_channels=self.dbb_origin.conv.out_channels,
447
+ kernel_size=self.dbb_origin.conv.kernel_size, stride=self.dbb_origin.conv.stride,
448
+ padding=self.dbb_origin.conv.padding, dilation=self.dbb_origin.conv.dilation, groups=self.dbb_origin.conv.groups, bias=True)
449
+ self.dbb_reparam.weight.data = kernel
450
+ self.dbb_reparam.bias.data = bias
451
+ for para in self.parameters():
452
+ para.detach_()
453
+ self.__delattr__('dbb_origin')
454
+ self.__delattr__('dbb_avg')
455
+ if hasattr(self, 'dbb_1x1'):
456
+ self.__delattr__('dbb_1x1')
457
+ self.__delattr__('dbb_1x1_kxk')
458
+
459
+ def forward(self, inputs):
460
+
461
+ if hasattr(self, 'dbb_reparam'):
462
+ return self.nonlinear(self.dbb_reparam(inputs))
463
+
464
+ out = self.dbb_origin(inputs)
465
+ if hasattr(self, 'dbb_1x1'):
466
+ out += self.dbb_1x1(inputs)
467
+ out += self.dbb_avg(inputs)
468
+ out += self.dbb_1x1_kxk(inputs)
469
+ return self.nonlinear(out)
470
+
471
+ def init_gamma(self, gamma_value):
472
+ if hasattr(self, "dbb_origin"):
473
+ torch.nn.init.constant_(self.dbb_origin.bn.weight, gamma_value)
474
+ if hasattr(self, "dbb_1x1"):
475
+ torch.nn.init.constant_(self.dbb_1x1.bn.weight, gamma_value)
476
+ if hasattr(self, "dbb_avg"):
477
+ torch.nn.init.constant_(self.dbb_avg.avgbn.weight, gamma_value)
478
+ if hasattr(self, "dbb_1x1_kxk"):
479
+ torch.nn.init.constant_(self.dbb_1x1_kxk.bn2.weight, gamma_value)
480
+
481
+ def single_init(self):
482
+ self.init_gamma(0.0)
483
+ if hasattr(self, "dbb_origin"):
484
+ torch.nn.init.constant_(self.dbb_origin.bn.weight, 1.0)
485
+
486
+
487
+ class DetectBackend(nn.Module):
488
+ def __init__(self, weights='yolov6s.pt', device=None, dnn=True):
489
+
490
+ super().__init__()
491
+ assert isinstance(weights, str) and Path(weights).suffix == '.pt', f'{Path(weights).suffix} format is not supported.'
492
+ from yolov6.utils.checkpoint import load_checkpoint
493
+ model = load_checkpoint(weights, map_location=device)
494
+ stride = int(model.stride.max())
495
+ self.__dict__.update(locals()) # assign all variables to self
496
+
497
+ def forward(self, im, val=False):
498
+ y = self.model(im)
499
+ if isinstance(y, np.ndarray):
500
+ y = torch.tensor(y, device=self.device)
501
+ return y