Ayush Chaurasia
commited on
Improve docstrings and run names (#4174)
Browse files- utils/loggers/__init__.py +1 -1
- utils/loggers/wandb/wandb_utils.py +132 -13
utils/loggers/__init__.py
CHANGED
@@ -57,7 +57,7 @@ class Loggers():
|
|
57 |
assert 'wandb' in self.include and wandb
|
58 |
run_id = torch.load(self.weights).get('wandb_id') if self.opt.resume else None
|
59 |
self.opt.hyp = self.hyp # add hyperparameters
|
60 |
-
self.wandb = WandbLogger(self.opt,
|
61 |
except:
|
62 |
self.wandb = None
|
63 |
|
|
|
57 |
assert 'wandb' in self.include and wandb
|
58 |
run_id = torch.load(self.weights).get('wandb_id') if self.opt.resume else None
|
59 |
self.opt.hyp = self.hyp # add hyperparameters
|
60 |
+
self.wandb = WandbLogger(self.opt, run_id, self.data_dict)
|
61 |
except:
|
62 |
self.wandb = None
|
63 |
|
utils/loggers/wandb/wandb_utils.py
CHANGED
@@ -99,7 +99,19 @@ class WandbLogger():
|
|
99 |
https://docs.wandb.com/guides/integrations/yolov5
|
100 |
"""
|
101 |
|
102 |
-
def __init__(self, opt,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
# Pre-training routine --
|
104 |
self.job_type = job_type
|
105 |
self.wandb, self.wandb_run = wandb, None if not wandb else wandb.run
|
@@ -129,7 +141,7 @@ class WandbLogger():
|
|
129 |
resume="allow",
|
130 |
project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem,
|
131 |
entity=opt.entity,
|
132 |
-
name=name,
|
133 |
job_type=job_type,
|
134 |
id=run_id,
|
135 |
allow_val_change=True) if not wandb.run else wandb.run
|
@@ -145,6 +157,15 @@ class WandbLogger():
|
|
145 |
self.data_dict = self.check_and_upload_dataset(opt)
|
146 |
|
147 |
def check_and_upload_dataset(self, opt):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
148 |
assert wandb, 'Install wandb to upload dataset'
|
149 |
config_path = self.log_dataset_artifact(check_file(opt.data),
|
150 |
opt.single_cls,
|
@@ -155,6 +176,19 @@ class WandbLogger():
|
|
155 |
return wandb_data_dict
|
156 |
|
157 |
def setup_training(self, opt, data_dict):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
158 |
self.log_dict, self.current_epoch = {}, 0
|
159 |
self.bbox_interval = opt.bbox_interval
|
160 |
if isinstance(opt.resume, str):
|
@@ -185,12 +219,22 @@ class WandbLogger():
|
|
185 |
self.val_table = self.val_artifact.get("val")
|
186 |
if self.val_table_path_map is None:
|
187 |
self.map_val_table_path()
|
188 |
-
wandb.log({"validation dataset": self.val_table})
|
189 |
if opt.bbox_interval == -1:
|
190 |
self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1
|
191 |
return data_dict
|
192 |
|
193 |
def download_dataset_artifact(self, path, alias):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
194 |
if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX):
|
195 |
artifact_path = Path(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias)
|
196 |
dataset_artifact = wandb.use_artifact(artifact_path.as_posix().replace("\\", "/"))
|
@@ -200,6 +244,12 @@ class WandbLogger():
|
|
200 |
return None, None
|
201 |
|
202 |
def download_model_artifact(self, opt):
|
|
|
|
|
|
|
|
|
|
|
|
|
203 |
if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
|
204 |
model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + ":latest")
|
205 |
assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist'
|
@@ -212,6 +262,16 @@ class WandbLogger():
|
|
212 |
return None, None
|
213 |
|
214 |
def log_model(self, path, opt, epoch, fitness_score, best_model=False):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
215 |
model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={
|
216 |
'original_url': str(path),
|
217 |
'epochs_trained': epoch + 1,
|
@@ -226,6 +286,19 @@ class WandbLogger():
|
|
226 |
print("Saving model artifact on epoch ", epoch + 1)
|
227 |
|
228 |
def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
229 |
with open(data_file, encoding='ascii', errors='ignore') as f:
|
230 |
data = yaml.safe_load(f) # data dict
|
231 |
check_dataset(data)
|
@@ -257,12 +330,27 @@ class WandbLogger():
|
|
257 |
return path
|
258 |
|
259 |
def map_val_table_path(self):
|
|
|
|
|
|
|
|
|
260 |
self.val_table_path_map = {}
|
261 |
print("Mapping dataset")
|
262 |
for i, data in enumerate(tqdm(self.val_table.data)):
|
263 |
self.val_table_path_map[data[3]] = data[0]
|
264 |
|
265 |
def create_dataset_table(self, dataset, class_to_id, name='dataset'):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
266 |
# TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging
|
267 |
artifact = wandb.Artifact(name=name, type="dataset")
|
268 |
img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None
|
@@ -294,6 +382,14 @@ class WandbLogger():
|
|
294 |
return artifact
|
295 |
|
296 |
def log_training_progress(self, predn, path, names):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
297 |
class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()])
|
298 |
box_data = []
|
299 |
total_conf = 0
|
@@ -316,25 +412,45 @@ class WandbLogger():
|
|
316 |
)
|
317 |
|
318 |
def val_one_image(self, pred, predn, path, names, im):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
319 |
if self.val_table and self.result_table: # Log Table if Val dataset is uploaded as artifact
|
320 |
self.log_training_progress(predn, path, names)
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
|
332 |
def log(self, log_dict):
|
|
|
|
|
|
|
|
|
|
|
|
|
333 |
if self.wandb_run:
|
334 |
for key, value in log_dict.items():
|
335 |
self.log_dict[key] = value
|
336 |
|
337 |
def end_epoch(self, best_result=False):
|
|
|
|
|
|
|
|
|
|
|
|
|
338 |
if self.wandb_run:
|
339 |
with all_logging_disabled():
|
340 |
if self.bbox_media_panel_images:
|
@@ -352,6 +468,9 @@ class WandbLogger():
|
|
352 |
self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
|
353 |
|
354 |
def finish_run(self):
|
|
|
|
|
|
|
355 |
if self.wandb_run:
|
356 |
if self.log_dict:
|
357 |
with all_logging_disabled():
|
|
|
99 |
https://docs.wandb.com/guides/integrations/yolov5
|
100 |
"""
|
101 |
|
102 |
+
def __init__(self, opt, run_id, data_dict, job_type='Training'):
|
103 |
+
'''
|
104 |
+
- Initialize WandbLogger instance
|
105 |
+
- Upload dataset if opt.upload_dataset is True
|
106 |
+
- Setup trainig processes if job_type is 'Training'
|
107 |
+
|
108 |
+
arguments:
|
109 |
+
opt (namespace) -- Commandline arguments for this run
|
110 |
+
run_id (str) -- Run ID of W&B run to be resumed
|
111 |
+
data_dict (Dict) -- Dictionary conataining info about the dataset to be used
|
112 |
+
job_type (str) -- To set the job_type for this run
|
113 |
+
|
114 |
+
'''
|
115 |
# Pre-training routine --
|
116 |
self.job_type = job_type
|
117 |
self.wandb, self.wandb_run = wandb, None if not wandb else wandb.run
|
|
|
141 |
resume="allow",
|
142 |
project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem,
|
143 |
entity=opt.entity,
|
144 |
+
name=opt.name if opt.name != 'exp' else None,
|
145 |
job_type=job_type,
|
146 |
id=run_id,
|
147 |
allow_val_change=True) if not wandb.run else wandb.run
|
|
|
157 |
self.data_dict = self.check_and_upload_dataset(opt)
|
158 |
|
159 |
def check_and_upload_dataset(self, opt):
|
160 |
+
'''
|
161 |
+
Check if the dataset format is compatible and upload it as W&B artifact
|
162 |
+
|
163 |
+
arguments:
|
164 |
+
opt (namespace)-- Commandline arguments for current run
|
165 |
+
|
166 |
+
returns:
|
167 |
+
Updated dataset info dictionary where local dataset paths are replaced by WAND_ARFACT_PREFIX links.
|
168 |
+
'''
|
169 |
assert wandb, 'Install wandb to upload dataset'
|
170 |
config_path = self.log_dataset_artifact(check_file(opt.data),
|
171 |
opt.single_cls,
|
|
|
176 |
return wandb_data_dict
|
177 |
|
178 |
def setup_training(self, opt, data_dict):
|
179 |
+
'''
|
180 |
+
Setup the necessary processes for training YOLO models:
|
181 |
+
- Attempt to download model checkpoint and dataset artifacts if opt.resume stats with WANDB_ARTIFACT_PREFIX
|
182 |
+
- Update data_dict, to contain info of previous run if resumed and the paths of dataset artifact if downloaded
|
183 |
+
- Setup log_dict, initialize bbox_interval
|
184 |
+
|
185 |
+
arguments:
|
186 |
+
opt (namespace) -- commandline arguments for this run
|
187 |
+
data_dict (Dict) -- Dataset dictionary for this run
|
188 |
+
|
189 |
+
returns:
|
190 |
+
data_dict (Dict) -- contains the updated info about the dataset to be used for training
|
191 |
+
'''
|
192 |
self.log_dict, self.current_epoch = {}, 0
|
193 |
self.bbox_interval = opt.bbox_interval
|
194 |
if isinstance(opt.resume, str):
|
|
|
219 |
self.val_table = self.val_artifact.get("val")
|
220 |
if self.val_table_path_map is None:
|
221 |
self.map_val_table_path()
|
|
|
222 |
if opt.bbox_interval == -1:
|
223 |
self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1
|
224 |
return data_dict
|
225 |
|
226 |
def download_dataset_artifact(self, path, alias):
|
227 |
+
'''
|
228 |
+
download the model checkpoint artifact if the path starts with WANDB_ARTIFACT_PREFIX
|
229 |
+
|
230 |
+
arguments:
|
231 |
+
path -- path of the dataset to be used for training
|
232 |
+
alias (str)-- alias of the artifact to be download/used for training
|
233 |
+
|
234 |
+
returns:
|
235 |
+
(str, wandb.Artifact) -- path of the downladed dataset and it's corresponding artifact object if dataset
|
236 |
+
is found otherwise returns (None, None)
|
237 |
+
'''
|
238 |
if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX):
|
239 |
artifact_path = Path(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias)
|
240 |
dataset_artifact = wandb.use_artifact(artifact_path.as_posix().replace("\\", "/"))
|
|
|
244 |
return None, None
|
245 |
|
246 |
def download_model_artifact(self, opt):
|
247 |
+
'''
|
248 |
+
download the model checkpoint artifact if the resume path starts with WANDB_ARTIFACT_PREFIX
|
249 |
+
|
250 |
+
arguments:
|
251 |
+
opt (namespace) -- Commandline arguments for this run
|
252 |
+
'''
|
253 |
if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
|
254 |
model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + ":latest")
|
255 |
assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist'
|
|
|
262 |
return None, None
|
263 |
|
264 |
def log_model(self, path, opt, epoch, fitness_score, best_model=False):
|
265 |
+
'''
|
266 |
+
Log the model checkpoint as W&B artifact
|
267 |
+
|
268 |
+
arguments:
|
269 |
+
path (Path) -- Path of directory containing the checkpoints
|
270 |
+
opt (namespace) -- Command line arguments for this run
|
271 |
+
epoch (int) -- Current epoch number
|
272 |
+
fitness_score (float) -- fitness score for current epoch
|
273 |
+
best_model (boolean) -- Boolean representing if the current checkpoint is the best yet.
|
274 |
+
'''
|
275 |
model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={
|
276 |
'original_url': str(path),
|
277 |
'epochs_trained': epoch + 1,
|
|
|
286 |
print("Saving model artifact on epoch ", epoch + 1)
|
287 |
|
288 |
def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False):
|
289 |
+
'''
|
290 |
+
Log the dataset as W&B artifact and return the new data file with W&B links
|
291 |
+
|
292 |
+
arguments:
|
293 |
+
data_file (str) -- the .yaml file with information about the dataset like - path, classes etc.
|
294 |
+
single_class (boolean) -- train multi-class data as single-class
|
295 |
+
project (str) -- project name. Used to construct the artifact path
|
296 |
+
overwrite_config (boolean) -- overwrites the data.yaml file if set to true otherwise creates a new
|
297 |
+
file with _wandb postfix. Eg -> data_wandb.yaml
|
298 |
+
|
299 |
+
returns:
|
300 |
+
the new .yaml file with artifact links. it can be used to start training directly from artifacts
|
301 |
+
'''
|
302 |
with open(data_file, encoding='ascii', errors='ignore') as f:
|
303 |
data = yaml.safe_load(f) # data dict
|
304 |
check_dataset(data)
|
|
|
330 |
return path
|
331 |
|
332 |
def map_val_table_path(self):
|
333 |
+
'''
|
334 |
+
Map the validation dataset Table like name of file -> it's id in the W&B Table.
|
335 |
+
Useful for - referencing artifacts for evaluation.
|
336 |
+
'''
|
337 |
self.val_table_path_map = {}
|
338 |
print("Mapping dataset")
|
339 |
for i, data in enumerate(tqdm(self.val_table.data)):
|
340 |
self.val_table_path_map[data[3]] = data[0]
|
341 |
|
342 |
def create_dataset_table(self, dataset, class_to_id, name='dataset'):
|
343 |
+
'''
|
344 |
+
Create and return W&B artifact containing W&B Table of the dataset.
|
345 |
+
|
346 |
+
arguments:
|
347 |
+
dataset (LoadImagesAndLabels) -- instance of LoadImagesAndLabels class used to iterate over the data to build Table
|
348 |
+
class_to_id (dict(int, str)) -- hash map that maps class ids to labels
|
349 |
+
name (str) -- name of the artifact
|
350 |
+
|
351 |
+
returns:
|
352 |
+
dataset artifact to be logged or used
|
353 |
+
'''
|
354 |
# TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging
|
355 |
artifact = wandb.Artifact(name=name, type="dataset")
|
356 |
img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None
|
|
|
382 |
return artifact
|
383 |
|
384 |
def log_training_progress(self, predn, path, names):
|
385 |
+
'''
|
386 |
+
Build evaluation Table. Uses reference from validation dataset table.
|
387 |
+
|
388 |
+
arguments:
|
389 |
+
predn (list): list of predictions in the native space in the format - [xmin, ymin, xmax, ymax, confidence, class]
|
390 |
+
path (str): local path of the current evaluation image
|
391 |
+
names (dict(int, str)): hash map that maps class ids to labels
|
392 |
+
'''
|
393 |
class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()])
|
394 |
box_data = []
|
395 |
total_conf = 0
|
|
|
412 |
)
|
413 |
|
414 |
def val_one_image(self, pred, predn, path, names, im):
|
415 |
+
'''
|
416 |
+
Log validation data for one image. updates the result Table if validation dataset is uploaded and log bbox media panel
|
417 |
+
|
418 |
+
arguments:
|
419 |
+
pred (list): list of scaled predictions in the format - [xmin, ymin, xmax, ymax, confidence, class]
|
420 |
+
predn (list): list of predictions in the native space - [xmin, ymin, xmax, ymax, confidence, class]
|
421 |
+
path (str): local path of the current evaluation image
|
422 |
+
'''
|
423 |
if self.val_table and self.result_table: # Log Table if Val dataset is uploaded as artifact
|
424 |
self.log_training_progress(predn, path, names)
|
425 |
+
|
426 |
+
if len(self.bbox_media_panel_images) < self.max_imgs_to_log and self.current_epoch > 0:
|
427 |
+
if self.current_epoch % self.bbox_interval == 0:
|
428 |
+
box_data = [{"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
|
429 |
+
"class_id": int(cls),
|
430 |
+
"box_caption": "%s %.3f" % (names[cls], conf),
|
431 |
+
"scores": {"class_score": conf},
|
432 |
+
"domain": "pixel"} for *xyxy, conf, cls in pred.tolist()]
|
433 |
+
boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
|
434 |
+
self.bbox_media_panel_images.append(wandb.Image(im, boxes=boxes, caption=path.name))
|
435 |
|
436 |
def log(self, log_dict):
|
437 |
+
'''
|
438 |
+
save the metrics to the logging dictionary
|
439 |
+
|
440 |
+
arguments:
|
441 |
+
log_dict (Dict) -- metrics/media to be logged in current step
|
442 |
+
'''
|
443 |
if self.wandb_run:
|
444 |
for key, value in log_dict.items():
|
445 |
self.log_dict[key] = value
|
446 |
|
447 |
def end_epoch(self, best_result=False):
|
448 |
+
'''
|
449 |
+
commit the log_dict, model artifacts and Tables to W&B and flush the log_dict.
|
450 |
+
|
451 |
+
arguments:
|
452 |
+
best_result (boolean): Boolean representing if the result of this evaluation is best or not
|
453 |
+
'''
|
454 |
if self.wandb_run:
|
455 |
with all_logging_disabled():
|
456 |
if self.bbox_media_panel_images:
|
|
|
468 |
self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
|
469 |
|
470 |
def finish_run(self):
|
471 |
+
'''
|
472 |
+
Log metrics if any and finish the current W&B run
|
473 |
+
'''
|
474 |
if self.wandb_run:
|
475 |
if self.log_dict:
|
476 |
with all_logging_disabled():
|