Start setup for improved W&B integration (#1948)
Browse files* Add helper functions for wandb and artifacts
* cleanup
* Reorganize files
* Update wandb_utils.py
* Update log_dataset.py
We can remove this code, as the giou hyp has been deprecated for a while now.
* Reorganize and update dataloader call
* yaml.SafeLoader
* PEP8 reformat
* remove redundant checks
* Add helper functions for wandb and artifacts
* cleanup
* Reorganize files
* Update wandb_utils.py
* Update log_dataset.py
We can remove this code, as the giou hyp has been deprecated for a while now.
* Reorganize and update dataloader call
* yaml.SafeLoader
* PEP8 reformat
* remove redundant checks
* Update util files
* Update wandb_utils.py
* Remove word size
* Change path of labels.zip
* remove unused imports
* remove --rect
* log_dataset.py cleanup
* log_dataset.py cleanup2
* wandb_utils.py cleanup
* remove redundant id_count
* wandb_utils.py cleanup2
* rename cls
* use pathlib for zip
* rename dataloader to dataset
* Change import order
* Remove redundant code
* remove unused import
* remove unused imports
Co-authored-by: Glenn Jocher <[email protected]>
- utils/datasets.py +2 -1
- utils/wandb_logging/__init__.py +0 -0
- utils/wandb_logging/log_dataset.py +39 -0
- utils/wandb_logging/wandb_utils.py +145 -0
@@ -348,7 +348,8 @@ class LoadImagesAndLabels(Dataset): # for training/testing
|
|
348 |
self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
|
349 |
self.mosaic_border = [-img_size // 2, -img_size // 2]
|
350 |
self.stride = stride
|
351 |
-
|
|
|
352 |
try:
|
353 |
f = [] # image files
|
354 |
for p in path if isinstance(path, list) else [path]:
|
|
|
348 |
self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
|
349 |
self.mosaic_border = [-img_size // 2, -img_size // 2]
|
350 |
self.stride = stride
|
351 |
+
self.path = path
|
352 |
+
|
353 |
try:
|
354 |
f = [] # image files
|
355 |
for p in path if isinstance(path, list) else [path]:
|
File without changes
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
from pathlib import Path
|
3 |
+
|
4 |
+
import yaml
|
5 |
+
|
6 |
+
from wandb_utils import WandbLogger
|
7 |
+
from utils.datasets import LoadImagesAndLabels
|
8 |
+
|
9 |
+
WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
|
10 |
+
|
11 |
+
|
12 |
+
def create_dataset_artifact(opt):
|
13 |
+
with open(opt.data) as f:
|
14 |
+
data = yaml.load(f, Loader=yaml.SafeLoader) # data dict
|
15 |
+
logger = WandbLogger(opt, '', None, data, job_type='create_dataset')
|
16 |
+
nc, names = (1, ['item']) if opt.single_cls else (int(data['nc']), data['names'])
|
17 |
+
names = {k: v for k, v in enumerate(names)} # to index dictionary
|
18 |
+
logger.log_dataset_artifact(LoadImagesAndLabels(data['train']), names, name='train') # trainset
|
19 |
+
logger.log_dataset_artifact(LoadImagesAndLabels(data['val']), names, name='val') # valset
|
20 |
+
|
21 |
+
# Update data.yaml with artifact links
|
22 |
+
data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(opt.project) / 'train')
|
23 |
+
data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(opt.project) / 'val')
|
24 |
+
path = opt.data if opt.overwrite_config else opt.data.replace('.', '_wandb.') # updated data.yaml path
|
25 |
+
data.pop('download', None) # download via artifact instead of predefined field 'download:'
|
26 |
+
with open(path, 'w') as f:
|
27 |
+
yaml.dump(data, f)
|
28 |
+
print("New Config file => ", path)
|
29 |
+
|
30 |
+
|
31 |
+
if __name__ == '__main__':
|
32 |
+
parser = argparse.ArgumentParser()
|
33 |
+
parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path')
|
34 |
+
parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset')
|
35 |
+
parser.add_argument('--project', type=str, default='YOLOv5', help='name of W&B Project')
|
36 |
+
parser.add_argument('--overwrite_config', action='store_true', help='overwrite data.yaml')
|
37 |
+
opt = parser.parse_args()
|
38 |
+
|
39 |
+
create_dataset_artifact(opt)
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import shutil
|
3 |
+
import sys
|
4 |
+
from datetime import datetime
|
5 |
+
from pathlib import Path
|
6 |
+
|
7 |
+
import torch
|
8 |
+
|
9 |
+
sys.path.append(str(Path(__file__).parent.parent.parent)) # add utils/ to path
|
10 |
+
from utils.general import colorstr, xywh2xyxy
|
11 |
+
|
12 |
+
try:
|
13 |
+
import wandb
|
14 |
+
except ImportError:
|
15 |
+
wandb = None
|
16 |
+
print(f"{colorstr('wandb: ')}Install Weights & Biases for YOLOv5 logging with 'pip install wandb' (recommended)")
|
17 |
+
|
18 |
+
WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
|
19 |
+
|
20 |
+
|
21 |
+
def remove_prefix(from_string, prefix):
|
22 |
+
return from_string[len(prefix):]
|
23 |
+
|
24 |
+
|
25 |
+
class WandbLogger():
|
26 |
+
def __init__(self, opt, name, run_id, data_dict, job_type='Training'):
|
27 |
+
self.wandb = wandb
|
28 |
+
self.wandb_run = wandb.init(config=opt, resume="allow",
|
29 |
+
project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem,
|
30 |
+
name=name,
|
31 |
+
job_type=job_type,
|
32 |
+
id=run_id) if self.wandb else None
|
33 |
+
|
34 |
+
if job_type == 'Training':
|
35 |
+
self.setup_training(opt, data_dict)
|
36 |
+
if opt.bbox_interval == -1:
|
37 |
+
opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else opt.epochs
|
38 |
+
if opt.save_period == -1:
|
39 |
+
opt.save_period = (opt.epochs // 10) if opt.epochs > 10 else opt.epochs
|
40 |
+
|
41 |
+
def setup_training(self, opt, data_dict):
|
42 |
+
self.log_dict = {}
|
43 |
+
self.train_artifact_path, self.trainset_artifact = \
|
44 |
+
self.download_dataset_artifact(data_dict['train'], opt.artifact_alias)
|
45 |
+
self.test_artifact_path, self.testset_artifact = \
|
46 |
+
self.download_dataset_artifact(data_dict['val'], opt.artifact_alias)
|
47 |
+
self.result_artifact, self.result_table, self.weights = None, None, None
|
48 |
+
if self.train_artifact_path is not None:
|
49 |
+
train_path = Path(self.train_artifact_path) / 'data/images/'
|
50 |
+
data_dict['train'] = str(train_path)
|
51 |
+
if self.test_artifact_path is not None:
|
52 |
+
test_path = Path(self.test_artifact_path) / 'data/images/'
|
53 |
+
data_dict['val'] = str(test_path)
|
54 |
+
self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
|
55 |
+
self.result_table = wandb.Table(["epoch", "id", "prediction", "avg_confidence"])
|
56 |
+
if opt.resume_from_artifact:
|
57 |
+
modeldir, _ = self.download_model_artifact(opt.resume_from_artifact)
|
58 |
+
if modeldir:
|
59 |
+
self.weights = Path(modeldir) / "best.pt"
|
60 |
+
opt.weights = self.weights
|
61 |
+
|
62 |
+
def download_dataset_artifact(self, path, alias):
|
63 |
+
if path.startswith(WANDB_ARTIFACT_PREFIX):
|
64 |
+
dataset_artifact = wandb.use_artifact(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias)
|
65 |
+
assert dataset_artifact is not None, "'Error: W&B dataset artifact doesn\'t exist'"
|
66 |
+
datadir = dataset_artifact.download()
|
67 |
+
labels_zip = Path(datadir) / "data/labels.zip"
|
68 |
+
shutil.unpack_archive(labels_zip, Path(datadir) / 'data/labels', 'zip')
|
69 |
+
print("Downloaded dataset to : ", datadir)
|
70 |
+
return datadir, dataset_artifact
|
71 |
+
return None, None
|
72 |
+
|
73 |
+
def download_model_artifact(self, name):
|
74 |
+
model_artifact = wandb.use_artifact(name + ":latest")
|
75 |
+
assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist'
|
76 |
+
modeldir = model_artifact.download()
|
77 |
+
print("Downloaded model to : ", modeldir)
|
78 |
+
return modeldir, model_artifact
|
79 |
+
|
80 |
+
def log_model(self, path, opt, epoch):
|
81 |
+
datetime_suffix = datetime.today().strftime('%Y-%m-%d-%H-%M-%S')
|
82 |
+
model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={
|
83 |
+
'original_url': str(path),
|
84 |
+
'epoch': epoch + 1,
|
85 |
+
'save period': opt.save_period,
|
86 |
+
'project': opt.project,
|
87 |
+
'datetime': datetime_suffix
|
88 |
+
})
|
89 |
+
model_artifact.add_file(str(path / 'last.pt'), name='last.pt')
|
90 |
+
model_artifact.add_file(str(path / 'best.pt'), name='best.pt')
|
91 |
+
wandb.log_artifact(model_artifact)
|
92 |
+
print("Saving model artifact on epoch ", epoch + 1)
|
93 |
+
|
94 |
+
def log_dataset_artifact(self, dataset, class_to_id, name='dataset'):
|
95 |
+
artifact = wandb.Artifact(name=name, type="dataset")
|
96 |
+
image_path = dataset.path
|
97 |
+
artifact.add_dir(image_path, name='data/images')
|
98 |
+
table = wandb.Table(columns=["id", "train_image", "Classes"])
|
99 |
+
class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()])
|
100 |
+
for si, (img, labels, paths, shapes) in enumerate(dataset):
|
101 |
+
height, width = shapes[0]
|
102 |
+
labels[:, 2:] = (xywh2xyxy(labels[:, 2:].view(-1, 4)))
|
103 |
+
labels[:, 2:] *= torch.Tensor([width, height, width, height])
|
104 |
+
box_data = []
|
105 |
+
img_classes = {}
|
106 |
+
for cls, *xyxy in labels[:, 1:].tolist():
|
107 |
+
cls = int(cls)
|
108 |
+
box_data.append({"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
|
109 |
+
"class_id": cls,
|
110 |
+
"box_caption": "%s" % (class_to_id[cls]),
|
111 |
+
"scores": {"acc": 1},
|
112 |
+
"domain": "pixel"})
|
113 |
+
img_classes[cls] = class_to_id[cls]
|
114 |
+
boxes = {"ground_truth": {"box_data": box_data, "class_labels": class_to_id}} # inference-space
|
115 |
+
table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), json.dumps(img_classes))
|
116 |
+
artifact.add(table, name)
|
117 |
+
labels_path = 'labels'.join(image_path.rsplit('images', 1))
|
118 |
+
zip_path = Path(labels_path).parent / (name + '_labels.zip')
|
119 |
+
if not zip_path.is_file(): # make_archive won't check if file exists
|
120 |
+
shutil.make_archive(zip_path.with_suffix(''), 'zip', labels_path)
|
121 |
+
artifact.add_file(str(zip_path), name='data/labels.zip')
|
122 |
+
wandb.log_artifact(artifact)
|
123 |
+
print("Saving data to W&B...")
|
124 |
+
|
125 |
+
def log(self, log_dict):
|
126 |
+
if self.wandb_run:
|
127 |
+
for key, value in log_dict.items():
|
128 |
+
self.log_dict[key] = value
|
129 |
+
|
130 |
+
def end_epoch(self):
|
131 |
+
if self.wandb_run and self.log_dict:
|
132 |
+
wandb.log(self.log_dict)
|
133 |
+
self.log_dict = {}
|
134 |
+
|
135 |
+
def finish_run(self):
|
136 |
+
if self.wandb_run:
|
137 |
+
if self.result_artifact:
|
138 |
+
print("Add Training Progress Artifact")
|
139 |
+
self.result_artifact.add(self.result_table, 'result')
|
140 |
+
train_results = wandb.JoinedTable(self.testset_artifact.get("val"), self.result_table, "id")
|
141 |
+
self.result_artifact.add(train_results, 'joined_result')
|
142 |
+
wandb.log_artifact(self.result_artifact)
|
143 |
+
if self.log_dict:
|
144 |
+
wandb.log(self.log_dict)
|
145 |
+
wandb.run.finish()
|