Skip to content

Commit dc2330e

Browse files
glenn-jochertdhooghe
authored andcommitted
Refactor modules (ultralytics#7823)
1 parent b45a1ba commit dc2330e

File tree

3 files changed

+17
-23
lines changed

3 files changed

+17
-23
lines changed

models/experimental.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -78,9 +78,7 @@ def __init__(self):
7878
super().__init__()
7979

8080
def forward(self, x, augment=False, profile=False, visualize=False):
81-
y = []
82-
for module in self:
83-
y.append(module(x, augment, profile, visualize)[0])
81+
y = [module(x, augment, profile, visualize)[0] for module in self]
8482
# y = torch.stack(y).max(0)[0] # max ensemble
8583
# y = torch.stack(y).mean(0) # mean ensemble
8684
y = torch.cat(y, 1) # nms ensemble
@@ -102,21 +100,19 @@ def attempt_load(weights, map_location=None, inplace=True, fuse=True):
102100
t = type(m)
103101
if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model):
104102
m.inplace = inplace # torch 1.7.0 compatibility
105-
if t is Detect:
106-
if not isinstance(m.anchor_grid, list): # new Detect Layer compatibility
107-
delattr(m, 'anchor_grid')
108-
setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)
103+
if t is Detect and not isinstance(m.anchor_grid, list):
104+
delattr(m, 'anchor_grid')
105+
setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)
109106
elif t is Conv:
110107
m._non_persistent_buffers_set = set() # torch 1.6.0 compatibility
111108
elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):
112109
m.recompute_scale_factor = None # torch 1.11.0 compatibility
113110

114111
if len(model) == 1:
115112
return model[-1] # return model
116-
else:
117-
print(f'Ensemble created with {weights}\n')
118-
for k in 'names', 'nc', 'yaml':
119-
setattr(model, k, getattr(model[0], k))
120-
model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
121-
assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}'
122-
return model # return ensemble
113+
print(f'Ensemble created with {weights}\n')
114+
for k in 'names', 'nc', 'yaml':
115+
setattr(model, k, getattr(model[0], k))
116+
model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
117+
assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}'
118+
return model # return ensemble

models/tf.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -362,7 +362,7 @@ def predict(self,
362362
conf_thres=0.25):
363363
y = [] # outputs
364364
x = inputs
365-
for i, m in enumerate(self.model.layers):
365+
for m in self.model.layers:
366366
if m.f != -1: # if not from previous layer
367367
x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
368368

@@ -377,7 +377,6 @@ def predict(self,
377377
scores = probs * classes
378378
if agnostic_nms:
379379
nms = AgnosticNMS()((boxes, classes, scores), topk_all, iou_thres, conf_thres)
380-
return nms, x[1]
381380
else:
382381
boxes = tf.expand_dims(boxes, 2)
383382
nms = tf.image.combined_non_max_suppression(boxes,
@@ -387,8 +386,7 @@ def predict(self,
387386
iou_thres,
388387
conf_thres,
389388
clip_boxes=False)
390-
return nms, x[1]
391-
389+
return nms, x[1]
392390
return x[0] # output only first tensor [1,6300,85] = [xywh, conf, class0, class1, ...]
393391
# x = x[0][0] # [x(1,6300,85), ...] to x(6300,85)
394392
# xywh = x[..., :4] # x(6300,4) boxes
@@ -444,10 +442,10 @@ def _nms(x, topk_all=100, iou_thres=0.45, conf_thres=0.25): # agnostic NMS
444442
def representative_dataset_gen(dataset, ncalib=100):
445443
# Representative dataset generator for use with converter.representative_dataset, returns a generator of np arrays
446444
for n, (path, img, im0s, vid_cap, string) in enumerate(dataset):
447-
input = np.transpose(img, [1, 2, 0])
448-
input = np.expand_dims(input, axis=0).astype(np.float32)
449-
input /= 255
450-
yield [input]
445+
im = np.transpose(img, [1, 2, 0])
446+
im = np.expand_dims(im, axis=0).astype(np.float32)
447+
im /= 255
448+
yield [im]
451449
if n >= ncalib:
452450
break
453451

models/yolo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ def _profile_one_layer(self, m, x, dt):
197197
m(x.copy() if c else x)
198198
dt.append((time_sync() - t) * 100)
199199
if m == self.model[0]:
200-
LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} {'module'}")
200+
LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} module")
201201
LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')
202202
if c:
203203
LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")

0 commit comments

Comments
 (0)