Skip to content

Commit 0322bb3

Browse files
New global TQDM_BAR_FORMAT (#10211)
* New global TQDM_BAR_FORMAT * [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 74b3886 commit 0322bb3

File tree

9 files changed

+35
-33
lines changed

9 files changed

+35
-33
lines changed

classify/train.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,8 @@
4040
from models.experimental import attempt_load
4141
from models.yolo import ClassificationModel, DetectionModel
4242
from utils.dataloaders import create_classification_dataloader
43-
from utils.general import (DATASETS_DIR, LOGGER, WorkingDirectory, check_git_status, check_requirements, colorstr,
44-
download, increment_path, init_seeds, print_args, yaml_save)
43+
from utils.general import (DATASETS_DIR, LOGGER, TQDM_BAR_FORMAT, WorkingDirectory, check_git_status,
44+
check_requirements, colorstr, download, increment_path, init_seeds, print_args, yaml_save)
4545
from utils.loggers import GenericLogger
4646
from utils.plots import imshow_cls
4747
from utils.torch_utils import (ModelEMA, model_info, reshape_classifier_output, select_device, smart_DDP,
@@ -174,7 +174,7 @@ def train(opt, device):
174174
trainloader.sampler.set_epoch(epoch)
175175
pbar = enumerate(trainloader)
176176
if RANK in {-1, 0}:
177-
pbar = tqdm(enumerate(trainloader), total=len(trainloader), bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}')
177+
pbar = tqdm(enumerate(trainloader), total=len(trainloader), bar_format=TQDM_BAR_FORMAT)
178178
for i, (images, labels) in pbar: # progress bar
179179
images, labels = images.to(device, non_blocking=True), labels.to(device)
180180

classify/val.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@
3636

3737
from models.common import DetectMultiBackend
3838
from utils.dataloaders import create_classification_dataloader
39-
from utils.general import LOGGER, Profile, check_img_size, check_requirements, colorstr, increment_path, print_args
39+
from utils.general import (LOGGER, TQDM_BAR_FORMAT, Profile, check_img_size, check_requirements, colorstr,
40+
increment_path, print_args)
4041
from utils.torch_utils import select_device, smart_inference_mode
4142

4243

@@ -100,7 +101,7 @@ def run(
100101
n = len(dataloader) # number of batches
101102
action = 'validating' if dataloader.dataset.root.stem == 'val' else 'testing'
102103
desc = f"{pbar.desc[:-36]}{action:>36}" if pbar else f"{action}"
103-
bar = tqdm(dataloader, desc, n, not training, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}', position=0)
104+
bar = tqdm(dataloader, desc, n, not training, bar_format=TQDM_BAR_FORMAT, position=0)
104105
with torch.cuda.amp.autocast(enabled=device.type != 'cpu'):
105106
for images, labels in bar:
106107
with dt[0]:

segment/train.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,10 @@
4646
from utils.autobatch import check_train_batch_size
4747
from utils.callbacks import Callbacks
4848
from utils.downloads import attempt_download, is_url
49-
from utils.general import (LOGGER, check_amp, check_dataset, check_file, check_git_status, check_img_size,
50-
check_requirements, check_suffix, check_yaml, colorstr, get_latest_run, increment_path,
51-
init_seeds, intersect_dicts, labels_to_class_weights, labels_to_image_weights, one_cycle,
52-
print_args, print_mutation, strip_optimizer, yaml_save)
49+
from utils.general import (LOGGER, TQDM_BAR_FORMAT, check_amp, check_dataset, check_file, check_git_status,
50+
check_img_size, check_requirements, check_suffix, check_yaml, colorstr, get_latest_run,
51+
increment_path, init_seeds, intersect_dicts, labels_to_class_weights,
52+
labels_to_image_weights, one_cycle, print_args, print_mutation, strip_optimizer, yaml_save)
5353
from utils.loggers import GenericLogger
5454
from utils.plots import plot_evolve, plot_labels
5555
from utils.segment.dataloaders import create_dataloader
@@ -277,7 +277,7 @@ def train(hyp, opt, device, callbacks): # hyp is path/to/hyp.yaml or hyp dictio
277277
LOGGER.info(('\n' + '%11s' * 8) %
278278
('Epoch', 'GPU_mem', 'box_loss', 'seg_loss', 'obj_loss', 'cls_loss', 'Instances', 'Size'))
279279
if RANK in {-1, 0}:
280-
pbar = tqdm(pbar, total=nb, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar
280+
pbar = tqdm(pbar, total=nb, bar_format=TQDM_BAR_FORMAT) # progress bar
281281
optimizer.zero_grad()
282282
for i, (imgs, targets, paths, _, masks) in pbar: # batch ------------------------------------------------------
283283
# callbacks.run('on_train_batch_start')

segment/val.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,9 @@
4242
from models.common import DetectMultiBackend
4343
from models.yolo import SegmentationModel
4444
from utils.callbacks import Callbacks
45-
from utils.general import (LOGGER, NUM_THREADS, Profile, check_dataset, check_img_size, check_requirements, check_yaml,
46-
coco80_to_coco91_class, colorstr, increment_path, non_max_suppression, print_args,
47-
scale_boxes, xywh2xyxy, xyxy2xywh)
45+
from utils.general import (LOGGER, NUM_THREADS, TQDM_BAR_FORMAT, Profile, check_dataset, check_img_size,
46+
check_requirements, check_yaml, coco80_to_coco91_class, colorstr, increment_path,
47+
non_max_suppression, print_args, scale_boxes, xywh2xyxy, xyxy2xywh)
4848
from utils.metrics import ConfusionMatrix, box_iou
4949
from utils.plots import output_to_target, plot_val_study
5050
from utils.segment.dataloaders import create_dataloader
@@ -237,7 +237,7 @@ def run(
237237
loss = torch.zeros(4, device=device)
238238
jdict, stats = [], []
239239
# callbacks.run('on_val_start')
240-
pbar = tqdm(dataloader, desc=s, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar
240+
pbar = tqdm(dataloader, desc=s, bar_format=TQDM_BAR_FORMAT) # progress bar
241241
for batch_i, (im, targets, paths, shapes, masks) in enumerate(pbar):
242242
# callbacks.run('on_val_batch_start')
243243
with dt[0]:

train.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,11 @@
4747
from utils.callbacks import Callbacks
4848
from utils.dataloaders import create_dataloader
4949
from utils.downloads import attempt_download, is_url
50-
from utils.general import (LOGGER, check_amp, check_dataset, check_file, check_git_status, check_img_size,
51-
check_requirements, check_suffix, check_yaml, colorstr, get_latest_run, increment_path,
52-
init_seeds, intersect_dicts, labels_to_class_weights, labels_to_image_weights, methods,
53-
one_cycle, print_args, print_mutation, strip_optimizer, yaml_save)
50+
from utils.general import (LOGGER, TQDM_BAR_FORMAT, check_amp, check_dataset, check_file, check_git_status,
51+
check_img_size, check_requirements, check_suffix, check_yaml, colorstr, get_latest_run,
52+
increment_path, init_seeds, intersect_dicts, labels_to_class_weights,
53+
labels_to_image_weights, methods, one_cycle, print_args, print_mutation, strip_optimizer,
54+
yaml_save)
5455
from utils.loggers import Loggers
5556
from utils.loggers.comet.comet_utils import check_comet_resume
5657
from utils.loss import ComputeLoss
@@ -275,7 +276,7 @@ def train(hyp, opt, device, callbacks): # hyp is path/to/hyp.yaml or hyp dictio
275276
pbar = enumerate(train_loader)
276277
LOGGER.info(('\n' + '%11s' * 7) % ('Epoch', 'GPU_mem', 'box_loss', 'obj_loss', 'cls_loss', 'Instances', 'Size'))
277278
if RANK in {-1, 0}:
278-
pbar = tqdm(pbar, total=nb, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar
279+
pbar = tqdm(pbar, total=nb, bar_format=TQDM_BAR_FORMAT) # progress bar
279280
optimizer.zero_grad()
280281
for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
281282
callbacks.run('on_train_batch_start')

utils/autoanchor.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from tqdm import tqdm
1212

1313
from utils import TryExcept
14-
from utils.general import LOGGER, colorstr
14+
from utils.general import LOGGER, TQDM_BAR_FORMAT, colorstr
1515

1616
PREFIX = colorstr('AutoAnchor: ')
1717

@@ -153,7 +153,7 @@ def print_results(k, verbose=True):
153153

154154
# Evolve
155155
f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
156-
pbar = tqdm(range(gen), bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar
156+
pbar = tqdm(range(gen), bar_format=TQDM_BAR_FORMAT) # progress bar
157157
for _ in pbar:
158158
v = np.ones(sh)
159159
while (v == 1).all(): # mutate until a change occurs (prevent duplicates)

utils/dataloaders.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,17 +29,16 @@
2929
from tqdm import tqdm
3030

3131
from utils.augmentations import (Albumentations, augment_hsv, classify_albumentations, classify_transforms, copy_paste,
32-
cutout, letterbox, mixup, random_perspective)
33-
from utils.general import (DATASETS_DIR, LOGGER, NUM_THREADS, check_dataset, check_requirements, check_yaml, clean_str,
34-
cv2, is_colab, is_kaggle, segments2boxes, unzip_file, xyn2xy, xywh2xyxy, xywhn2xyxy,
35-
xyxy2xywhn)
32+
letterbox, mixup, random_perspective)
33+
from utils.general import (DATASETS_DIR, LOGGER, NUM_THREADS, TQDM_BAR_FORMAT, check_dataset, check_requirements,
34+
check_yaml, clean_str, cv2, is_colab, is_kaggle, segments2boxes, unzip_file, xyn2xy,
35+
xywh2xyxy, xywhn2xyxy, xyxy2xywhn)
3636
from utils.torch_utils import torch_distributed_zero_first
3737

3838
# Parameters
3939
HELP_URL = 'See https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
4040
IMG_FORMATS = 'bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp', 'pfm' # include image suffixes
4141
VID_FORMATS = 'asf', 'avi', 'gif', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'ts', 'wmv' # include video suffixes
42-
BAR_FORMAT = '{l_bar}{bar:10}{r_bar}{bar:-10b}' # tqdm bar format
4342
LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html
4443
RANK = int(os.getenv('RANK', -1))
4544
PIN_MEMORY = str(os.getenv('PIN_MEMORY', True)).lower() == 'true' # global pin_memory for dataloaders
@@ -494,7 +493,7 @@ def __init__(self,
494493
nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupt, total
495494
if exists and LOCAL_RANK in {-1, 0}:
496495
d = f"Scanning {cache_path}... {nf} images, {nm + ne} backgrounds, {nc} corrupt"
497-
tqdm(None, desc=prefix + d, total=n, initial=n, bar_format=BAR_FORMAT) # display cache results
496+
tqdm(None, desc=prefix + d, total=n, initial=n, bar_format=TQDM_BAR_FORMAT) # display cache results
498497
if cache['msgs']:
499498
LOGGER.info('\n'.join(cache['msgs'])) # display warnings
500499
assert nf > 0 or not augment, f'{prefix}No labels found in {cache_path}, can not start training. {HELP_URL}'
@@ -576,7 +575,7 @@ def __init__(self,
576575
self.im_hw0, self.im_hw = [None] * n, [None] * n
577576
fcn = self.cache_images_to_disk if cache_images == 'disk' else self.load_image
578577
results = ThreadPool(NUM_THREADS).imap(fcn, range(n))
579-
pbar = tqdm(enumerate(results), total=n, bar_format=BAR_FORMAT, disable=LOCAL_RANK > 0)
578+
pbar = tqdm(enumerate(results), total=n, bar_format=TQDM_BAR_FORMAT, disable=LOCAL_RANK > 0)
580579
for i, x in pbar:
581580
if cache_images == 'disk':
582581
b += self.npy_files[i].stat().st_size
@@ -612,7 +611,7 @@ def cache_labels(self, path=Path('./labels.cache'), prefix=''):
612611
pbar = tqdm(pool.imap(verify_image_label, zip(self.im_files, self.label_files, repeat(prefix))),
613612
desc=desc,
614613
total=len(self.im_files),
615-
bar_format=BAR_FORMAT)
614+
bar_format=TQDM_BAR_FORMAT)
616615
for im_file, lb, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar:
617616
nm += nm_f
618617
nf += nf_f

utils/general.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
DATASETS_DIR = Path(os.getenv('YOLOv5_DATASETS_DIR', ROOT.parent / 'datasets')) # global datasets directory
5151
AUTOINSTALL = str(os.getenv('YOLOv5_AUTOINSTALL', True)).lower() == 'true' # global auto-install mode
5252
VERBOSE = str(os.getenv('YOLOv5_VERBOSE', True)).lower() == 'true' # global verbose mode
53+
TQDM_BAR_FORMAT = '{l_bar}{bar:10}| {n_fmt}/{total_fmt} {elapsed}' # tqdm bar format
5354
FONT = 'Arial.ttf' # https://ultralytics.com/assets/Arial.ttf
5455

5556
torch.set_printoptions(linewidth=320, precision=5, profile='long')

val.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,9 @@
3838
from models.common import DetectMultiBackend
3939
from utils.callbacks import Callbacks
4040
from utils.dataloaders import create_dataloader
41-
from utils.general import (LOGGER, Profile, check_dataset, check_img_size, check_requirements, check_yaml,
42-
coco80_to_coco91_class, colorstr, increment_path, non_max_suppression, print_args,
43-
scale_boxes, xywh2xyxy, xyxy2xywh)
41+
from utils.general import (LOGGER, TQDM_BAR_FORMAT, Profile, check_dataset, check_img_size, check_requirements,
42+
check_yaml, coco80_to_coco91_class, colorstr, increment_path, non_max_suppression,
43+
print_args, scale_boxes, xywh2xyxy, xyxy2xywh)
4444
from utils.metrics import ConfusionMatrix, ap_per_class, box_iou
4545
from utils.plots import output_to_target, plot_images, plot_val_study
4646
from utils.torch_utils import select_device, smart_inference_mode
@@ -193,7 +193,7 @@ def run(
193193
loss = torch.zeros(3, device=device)
194194
jdict, stats, ap, ap_class = [], [], [], []
195195
callbacks.run('on_val_start')
196-
pbar = tqdm(dataloader, desc=s, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar
196+
pbar = tqdm(dataloader, desc=s, bar_format=TQDM_BAR_FORMAT) # progress bar
197197
for batch_i, (im, targets, paths, shapes) in enumerate(pbar):
198198
callbacks.run('on_val_batch_start')
199199
with dt[0]:

0 commit comments

Comments
 (0)