Skip to content

Commit 4a295b1

Browse files
Add @threaded decorator (#7813)
* Add `@threaded` decorator * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 9d8ed37 commit 4a295b1

File tree

5 files changed

+25
-17
lines changed

5 files changed

+25
-17
lines changed

train.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,8 @@
4848
from utils.downloads import attempt_download
4949
from utils.general import (LOGGER, check_dataset, check_file, check_git_status, check_img_size, check_requirements,
5050
check_suffix, check_version, check_yaml, colorstr, get_latest_run, increment_path,
51-
init_seeds, intersect_dicts, is_ascii, labels_to_class_weights, labels_to_image_weights,
52-
methods, one_cycle, print_args, print_mutation, strip_optimizer)
51+
init_seeds, intersect_dicts, labels_to_class_weights, labels_to_image_weights, methods,
52+
one_cycle, print_args, print_mutation, strip_optimizer)
5353
from utils.loggers import Loggers
5454
from utils.loggers.wandb.wandb_utils import check_wandb_resume
5555
from utils.loss import ComputeLoss

utils/general.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import re
1515
import shutil
1616
import signal
17+
import threading
1718
import time
1819
import urllib
1920
from datetime import datetime
@@ -167,6 +168,16 @@ def handler(*args, **kwargs):
167168
return handler
168169

169170

171+
def threaded(func):
172+
# Multi-threads a target function and returns thread. Usage: @threaded decorator
173+
def wrapper(*args, **kwargs):
174+
thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)
175+
thread.start()
176+
return thread
177+
178+
return wrapper
179+
180+
170181
def methods(instance):
171182
# Get class/instance methods
172183
return [f for f in dir(instance) if callable(getattr(instance, f)) and not f.startswith("__")]

utils/loggers/__init__.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55

66
import os
77
import warnings
8-
from threading import Thread
98

109
import pkg_resources as pkg
1110
import torch
@@ -109,7 +108,7 @@ def on_train_batch_end(self, ni, model, imgs, targets, paths, plots):
109108
self.tb.add_graph(torch.jit.trace(de_parallel(model), imgs[0:1], strict=False), [])
110109
if ni < 3:
111110
f = self.save_dir / f'train_batch{ni}.jpg' # filename
112-
Thread(target=plot_images, args=(imgs, targets, paths, f), daemon=True).start()
111+
plot_images(imgs, targets, paths, f)
113112
if self.wandb and ni == 10:
114113
files = sorted(self.save_dir.glob('train*.jpg'))
115114
self.wandb.log({'Mosaics': [wandb.Image(str(f), caption=f.name) for f in files if f.exists()]})
@@ -132,7 +131,7 @@ def on_val_end(self):
132131

133132
def on_fit_epoch_end(self, vals, epoch, best_fitness, fi):
134133
# Callback runs at the end of each fit (train+val) epoch
135-
x = {k: v for k, v in zip(self.keys, vals)} # dict
134+
x = dict(zip(self.keys, vals))
136135
if self.csv:
137136
file = self.save_dir / 'results.csv'
138137
n = len(x) + 1 # number of cols
@@ -171,7 +170,7 @@ def on_train_end(self, last, best, plots, epoch, results):
171170
self.tb.add_image(f.stem, cv2.imread(str(f))[..., ::-1], epoch, dataformats='HWC')
172171

173172
if self.wandb:
174-
self.wandb.log({k: v for k, v in zip(self.keys[3:10], results)}) # log best.pt val results
173+
self.wandb.log(dict(zip(self.keys[3:10], results)))
175174
self.wandb.log({"Results": [wandb.Image(str(f), caption=f.name) for f in files]})
176175
# Calling wandb.log. TODO: Refactor this into WandbLogger.log_model
177176
if not self.opt.evolve:

utils/plots.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from PIL import Image, ImageDraw, ImageFont
2020

2121
from utils.general import (CONFIG_DIR, FONT, LOGGER, Timeout, check_font, check_requirements, clip_coords,
22-
increment_path, is_ascii, try_except, xywh2xyxy, xyxy2xywh)
22+
increment_path, is_ascii, threaded, try_except, xywh2xyxy, xyxy2xywh)
2323
from utils.metrics import fitness
2424

2525
# Settings
@@ -32,9 +32,9 @@ class Colors:
3232
# Ultralytics color palette https://ultralytics.com/
3333
def __init__(self):
3434
# hex = matplotlib.colors.TABLEAU_COLORS.values()
35-
hex = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB',
36-
'2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7')
37-
self.palette = [self.hex2rgb('#' + c) for c in hex]
35+
hexs = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB',
36+
'2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7')
37+
self.palette = [self.hex2rgb(f'#{c}') for c in hexs]
3838
self.n = len(self.palette)
3939

4040
def __call__(self, i, bgr=False):
@@ -100,7 +100,7 @@ def box_label(self, box, label='', color=(128, 128, 128), txt_color=(255, 255, 2
100100
if label:
101101
tf = max(self.lw - 1, 1) # font thickness
102102
w, h = cv2.getTextSize(label, 0, fontScale=self.lw / 3, thickness=tf)[0] # text width, height
103-
outside = p1[1] - h - 3 >= 0 # label fits outside box
103+
outside = p1[1] - h >= 3
104104
p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3
105105
cv2.rectangle(self.im, p1, p2, color, -1, cv2.LINE_AA) # filled
106106
cv2.putText(self.im,
@@ -184,6 +184,7 @@ def output_to_target(output):
184184
return np.array(targets)
185185

186186

187+
@threaded
187188
def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=1920, max_subplots=16):
188189
# Plot image grid with labels
189190
if isinstance(images, torch.Tensor):
@@ -420,7 +421,7 @@ def plot_results(file='path/to/results.csv', dir=''):
420421
ax = ax.ravel()
421422
files = list(save_dir.glob('results*.csv'))
422423
assert len(files), f'No results.csv files found in {save_dir.resolve()}, nothing to plot.'
423-
for fi, f in enumerate(files):
424+
for f in files:
424425
try:
425426
data = pd.read_csv(f)
426427
s = [x.strip() for x in data.columns]

val.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
import os
2424
import sys
2525
from pathlib import Path
26-
from threading import Thread
2726

2827
import numpy as np
2928
import torch
@@ -255,10 +254,8 @@ def run(
255254

256255
# Plot images
257256
if plots and batch_i < 3:
258-
f = save_dir / f'val_batch{batch_i}_labels.jpg' # labels
259-
Thread(target=plot_images, args=(im, targets, paths, f, names), daemon=True).start()
260-
f = save_dir / f'val_batch{batch_i}_pred.jpg' # predictions
261-
Thread(target=plot_images, args=(im, output_to_target(out), paths, f, names), daemon=True).start()
257+
plot_images(im, targets, paths, save_dir / f'val_batch{batch_i}_labels.jpg', names) # labels
258+
plot_images(im, output_to_target(out), paths, save_dir / f'val_batch{batch_i}_pred.jpg', names) # pred
262259

263260
callbacks.run('on_val_batch_end')
264261

0 commit comments

Comments
 (0)